diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 44ecf5d92..9a2d3aee5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -24,7 +24,7 @@ concurrency: jobs: build: - name: Build under Build Wrapper + name: Compilation database for SonarQube Cloud runs-on: ubuntu-24.04 permissions: contents: read @@ -73,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. @@ -105,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 b62bb8321..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" @@ -370,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 }} @@ -379,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 @@ -412,6 +507,7 @@ jobs: with: packages: >- build-essential + ccache pkg-config libasound2-dev libpulse-dev @@ -475,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 \ @@ -488,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 @@ -557,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: @@ -581,6 +766,7 @@ jobs: path: dist/maszyna-windows-x64 - name: Download Windows build (no AVX2) + if: needs.changes.outputs.noavx2 == 'true' uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-windows-x64-noavx2-${{ env.CONFIG_WIN }} @@ -593,6 +779,7 @@ jobs: path: dist/maszyna-linux-x64 - name: Download Linux build (no AVX2) + if: needs.changes.outputs.noavx2 == 'true' uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-linux-x64-noavx2-${{ env.CONFIG_LINUX }} @@ -604,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/* @@ -611,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 @@ -628,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 2e9a9c4b4..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: 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 69a7de615..eb71a765d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -56,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" @@ -79,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") @@ -164,16 +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" "model/eu07m/eu07m_convert.cpp" @@ -215,6 +264,7 @@ set(SOURCES "input/drivermouseinput.cpp" "utilities/translation.cpp" "model/material.cpp" +"model/materialdata.cpp" "stdafx.cpp" "input/messaging.cpp" "scene/scene.cpp" @@ -395,6 +445,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" @@ -746,16 +797,33 @@ add_library(eu07_settings INTERFACE) # 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 "audio/startsample.cpp" -"McZapkie/friction.cpp" -"McZapkie/hamulce.cpp" -"McZapkie/Mover.cpp" -"McZapkie/couplerphysics.cpp" -"McZapkie/derailment.cpp" -"McZapkie/collision.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" -"McZapkie/Oerlikon_ESt.cpp" +"physics/oerlikonest.cpp" "utilities/logfiles.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" @@ -843,7 +911,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" diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h deleted file mode 100644 index d5847cbc1..000000000 --- a/McZapkie/MOVER.h +++ /dev/null @@ -1,3269 +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 -#include "hamulce.h" -#include "couplerphysics.h" -#include "derailment.h" -#include "collision.h" -#include "scripting/ladderlogic.h" -#include "vehicle/derailmotion.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 - /// 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) - -/*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 - /// 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 -}; -/// 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 circuit of the power coupling given, nullptr for a coupling which isn't one - power_coupling *power(coupling const Coupling) - { - switch (Coupling) - { - 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 Coupling) const - { - switch (Coupling) - { - 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; - } -}; - -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 - }; - - // 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 - 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 - // 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; - 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; - // the holding brake (StopBrakeDecc) of a unit with the MED lets go only once power has been demanded for this long (SBDReleaseDelay, s); - // 0 lets it go at the first demand - double StopBrakeReleaseDelay = 0.0; - double StopBrakeReleaseTimer = 0.0; // how long power has been demanded without a break, s - 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*/ - // 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 FieldShuntSwitch = false; - 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)*/ - // 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 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 */ - // the criteria of derailment (physics.derailment new), and the distance travelled since they were checked [m] - derailment::monitor derailment_monitor; - double derailment_distance = 0.0; - // 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 derailment_reports = 0; - 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*/ - bool ScndPipeCouplersPending{false}; // the main reservoir pipe stepped, its air exchange through the hoses is yet to come (UpdatePipeCouplers()) - double BrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych*/ - double BrakePressRate = 0.0; // how fast BrakePress changes, averaged over about a second [bar/s], see accelerating() - 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*/ - bool PipeCouplersPending{false}; // the brake pipe stepped, its air exchange through the hoses is yet to come (UpdatePipeCouplers()) - 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; - 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 TractionMode{traction_mode::catenary}; - bool GensetSelected() const { return TractionMode == traction_mode::genset; } - 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}; - // config, .fiz Engine:PressureSwitchBrakeCylinder. whether 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 PressureSwitchBrakeCylinder{true}; - // config, .fiz 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 (PantographsRequireMains) they drop with it (EP05). - // 0: an emergency application leaves the line breaker alone - double EmergencyBrakeMainOffPressure{0.0}; - 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 - // pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): the vehicle is prepared for being hauled dead in a - // train, see PulleeModeSwitch() - bool PulleeMode{false}; - 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; - // 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}; // SpringBrake.SBP - int manual{0}; // ManualBrakePos - double local{0.0}; // LocalBrakePosA - } sleep_brakes; - - /*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); - // 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 dtrain_out 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 Derailed{derailment::outcome::none}; - // 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 DerailCause{derail_motion::cause::off_rails}; - double DerailAcceleration{0.0}; - int DerailSide{0}; - // 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(int End) const; - double buffer_height_at(int 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 CollisionDerail{NONE}; - // physics.collisions monitor: how many crushes the log told of, of the hits of this vehicle on the others - int crush_reports{0}; - // 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(int 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 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 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(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; - // 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(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); - // the parts of RunCommand(), by the area of the commands - bool RunControllerCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunRelaysCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunCabCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunBrakeCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunBrakeEquipmentCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunAuxiliariesCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunPumpsCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunBlowersCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunPowerCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - bool RunDoorsCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, bool &OK); - void DoorPermitCommand(double CValue1, double CValue2); - void DoorRemoteCommand(bool Open, double CValue1, double CValue2); - bool RunLoadCommand(std::string const &Command, double CValue1, double CValue2, int Couplertype, 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(); - 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(int const End, double dt); - void CouplerStretchCheck(int 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(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 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 EmergencyBrakeMainOffPressure > 0.0 && PipePress < EmergencyBrakeMainOffPressure && 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 == 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 - 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 Coupling); - // the parts of PowerCouplersCheck() - double LocalPowerVoltage(coupling Coupling); - void PowerCouplersVoltage(coupling Coupling, double abslocalvoltage, bool localpowersource); - void PowerCouplersCurrent(coupling Coupling, bool localpowersource); - double *PowerCircuitCurrent(coupling 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 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 - 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); - // 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(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 - // 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 (StopBrakeDecc) 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 StopBrakeReleaseDelay. 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 dizel_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(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; - // the parts of update_doors() - // not const: the door they change is one of Doors.instances - void update_door_requests(basic_door &door, bool localopencontrol, bool remoteopencontrol, bool localclosecontrol, bool remoteclosecontrol); - void move_door(basic_door &door, double Deltatime); - bool door_open_request(basic_door const &door, bool localopencontrol, bool remoteopencontrol) const; - bool door_close_request(basic_door const &door, bool localclosecontrol, bool remoteclosecontrol) const; - bool doors_powered() const; - bool door_step_folding(basic_door const &door) const; - float door_open_duration(basic_door const &door, bool localopencontrol, bool remoteopencontrol) const; - void update_door_timers(double Deltatime); - - /* 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: - 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 -}; - -// 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 7ee85203a..000000000 --- a/McZapkie/Mover.cpp +++ /dev/null @@ -1,15912 +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 "vehicle/fieldshunting.h" - -#include -#include -#include -#include -#include -#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; -} - -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(TMoverParameters const &Vehicle) -{ - return Global.collisions == global_settings::collision_model::physical && TestFlag(Vehicle.CategoryFlag, 1) && TestFlag(Vehicle.DamageFlag, dtrain_out) && - Vehicle.Derailed == derailment::outcome::none; -} - -// a derailed vehicle tears its brake hoses: the brake pipe vents and the rest of the train brakes in emergency -void tear_brake_hoses(TMoverParameters &Vehicle) -{ - if (std::any_of(std::begin(Vehicle.Couplers), std::end(Vehicle.Couplers), [](auto const &Coupler) { return (Coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose; })) - { - Vehicle.AlarmChainFlag = true; - } -} - -} // namespace - -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 Mn; // przujmuje int, ale dla poprawnosci obliczeń - double Bn; - - UpdateSeriesMotorDynamicBrakeFlag(); - - 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... - MotorCurrent = SeriesMotorCurrent(n, U, R, Mn); - } - // 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; - - 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 TMoverParameters::UpdateSeriesMotorDynamicBrakeFlag() -{ - // 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"); - } -} - -// 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 TMoverParameters::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 (DynamicBrakeFlag) // 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 (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 = 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 TMoverParameters::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 TMoverParameters::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 (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*/ - } -} - -// ************************************************************************************************* -// 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 - - PantPressureSwitchCheck(); - } - else - { // a tu coś dla SM42 i SM31, aby pokazywać na manometrze - PantPress = CntrlPipePress; - } -}; - -// 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 TMoverParameters::PantPressureSwitchCheck() -{ - if (PantPress < EnginePowerSource.CollectorParameters.MinPress) - { - // 3.5 wg http://www.transportszynowy.pl/eu06-07pneumat.php - if (true == PantPressSwitchActive) - { - PantPressureSwitchTrip(); - } - } - 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; - } - } -} - -// the pantographs' pressure switch tripped by the low pressure: the line breaker opened, unless the voltage comes from -// elsewhere, or the converter of a unit locked; spent until primed again -void TMoverParameters::PantPressureSwitchTrip() -{ - // 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 - // (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 == 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; -} - -void TMoverParameters::UpdateBatteryVoltage(double dt) -{ // przeliczenie obciążenia baterii - using enum TEngineType; - if (BatteryVoltage > 0 && EngineType != DieselEngine && EngineType != 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 == DieselElectric && true == Mains) || (EngineType == DieselEngine && true == Mains)}; - - BatteryVoltage -= BatteryDrain(dt, converteractive); - if (NominalBatteryVoltage / BatteryVoltage > 1.57 && MainSwitch(false) && EngineType != DieselEngine && EngineType != 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; - } -}; - -// the drop of the battery's voltage in dt, by what draws from it, or its rise by the converter charging it -double TMoverParameters::BatteryDrain(double dt, bool const converteractive) const -{ - if (NominalBatteryVoltage / BatteryVoltage < 1.22 && Battery) - { // 110V - return BatteryDrainCharged(dt, converteractive); - } - if (NominalBatteryVoltage / BatteryVoltage >= 1.22 && Battery) - { // 90V - return BatteryDrainLow(dt, converteractive); - } - if (!Battery) - { - return BatteryDrainSwitchedOff(dt); - } - return 0.0; -} - -// the drain of a battery at its voltage, the converter charging it -double TMoverParameters::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 (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; - return sn1 + sn2 + sn3 + sn4 + sn5; -} - -// the drain of a battery run down to 90 V, the converter charging it -double TMoverParameters::BatteryDrainLow(double dt, bool const converteractive) const -{ - double sn1; - double sn2; - double sn3; - double sn4; - double sn5; - 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; - return sn1 + sn2 + sn3 + sn4 + sn5; -} - -// the drain of a battery switched off, very slow -double TMoverParameters::BatteryDrainSwitchedOff(double dt) const -{ - double sn1; - double sn2; - double sn3; - double sn4; - double sn5; - 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 - return sn1 + sn2 + sn3 + sn4 + sn5; -} - -/* 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)}; - // 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{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; - } - } - - // 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::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}; - // 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::faux}; - auto const wall = [crushing, coupled](TMoverParameters const &Vehicle) { - return TestFlag(Vehicle.DamageFlag, dtrain_out) && (false == crushing || (Vehicle.Derailed == derailment::outcome::none && false == coupled)); - }; - if (false == wall(*this)) - { - auto const accelerationchange{(velocity - V) / dt}; - AccS += accelerationchange * accelerationspike; - V = velocity; - } - if (false == wall(*othervehicle)) - { - 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"); -} - -// ************************************************************************************************* -// physics.collisions new: the collisions past the buffers, see collision.h -// ************************************************************************************************* -collision::vehicle_kind TMoverParameters::collision_kind() const -{ - auto const powered{EngineType != TEngineType::None && EngineType != TEngineType::Dumb}; - auto const unit{(TrainType & (dt_EZT | dt_DMU)) != 0}; - 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 && HeatingPower > 0.0), false); -} - -collision::crush_curve TMoverParameters::crush_curve_at(int const End) const -{ - return collision::crush_of(Couplers[End].collision, collision_kind()); -} - -double TMoverParameters::buffer_height_at(int const End) const -{ - auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 0.0}; - return collision::buffer_height(Couplers[End].collision, collision_kind(), loadshare); -} - -void TMoverParameters::derail_in_collision(DerailReason const Reason, std::string const &Why) -{ - if (false == SetFlag(DamageFlag, dtrain_out)) - { - return; - } - // upright, it slides on the sleepers and keeps passing the forces on - Derailed = 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 - nrot = 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(int const End) -{ - return End == end::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"; - } -} - -// the force pressing the end in, of the coupling or of the buffers touching [N]: forwards at the front pulls -double compression_at(TCoupling const &Coupler, int const End) -{ - return std::max(0.0, (End == end::front ? -1.0 : 1.0) * Coupler.CForce); -} - -// 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 TMoverParameters::crush_hit(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 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::faux}; - auto const wall{false == coupled && TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none}; - auto const otherwall{false == coupled && TestFlag(othervehicle->DamageFlag, dtrain_out) && othervehicle->Derailed == 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; - ++crush_reports; - 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 == end::front ? -1.0 : 1.0}; - if (false == wall) - { - V += apart * hit.impulse / mass; - } - if (false == otherwall) - { - othervehicle->V -= 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 = [&](TMoverParameters const &Vehicle, int const VehicleEnd, 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(VehicleEnd), 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::faux && std::max(thiscoupler.crush, othercoupler.crush) >= collision::draw_gear_crush) - { - auto const hose{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; - damage_coupler(End); - if (hose) - { - othervehicle->AlarmChainFlag = true; - } - } - else if (thiscoupler.CouplingFlag == coupling::faux) - { - 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 = [&](TMoverParameters const &Climber, TMoverParameters 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 TMoverParameters::check_pushed_off(double const dt, double const Distance) -{ - if (Global.collisions != global_settings::collision_model::physical || false == Global.crash_damage || TestFlag(DamageFlag, dtrain_out) || 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{static_cast(end::front)}; - for (int end = end::front; end <= end::rear; ++end) - { - auto const *other{Neighbours[end].vehicle}; - if (other == nullptr) - { - continue; - } - auto const &coupler{Couplers[end]}; - collision::pushed_end pushed; - pushed.other_length = other->MoverParameters->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[end::front], end::front) / 1000.0, - compression_at(Couplers[end::rear], end::rear) / 1000.0, Couplers[end::front].hit_force / 1000.0, Couplers[end::rear].hit_force / 1000.0, - Couplers[end::front].crush, Couplers[end::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(TMoverParameters &Vehicle, TCoupling &Coupler) -{ - Coupler.broken = false; - Coupler.stretch_duration = 0.f; - Coupler.physics_state.couple(); - restore_end(Coupler); - 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; -} - -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 TMoverParameters::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 - Mass - Mred}; - auto const loadshare{MaxLoad > 0.f ? LoadAmount / MaxLoad : 1.0}; - return derailment::loaded_centre_of_gravity(empty, Mass, loadmass, loadshare, Floor, Dim.H); -} - -void TMoverParameters::check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double const Distance) -{ - if (TestFlag(DamageFlag, dtrain_out) || 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 (int end = end::front; end <= end::rear; ++end) - { - 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[end].compression = (end == end::front ? -1.0 : 1.0) * Couplers[end].CForce; - vehicle.ends[end].other_length = other->MoverParameters->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, V, Distance)}; - if (verdict.result == derailment::outcome::none) - { - return; - } - if (Global.derailment == global_settings::derailment_model::physical) - { - derail(verdict, vehicle, track, Track.Name); - return; - } - // physics.derailment monitor: the legacy draw decides, the log tells what the criteria would do, once on a track - if (derailment_reported.has_value() && *derailment_reported == Track.Name) - { - return; - } - derailment_reported = Track.Name; - ++derailment_reports; - WriteLog("derailment monitor: " + Name + " " + derailment::report(verdict, vehicle, track, V, Track.Name != nullptr ? *Track.Name : std::string{})); -} - -void TMoverParameters::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName) -{ - if (false == SetFlag(DamageFlag, dtrain_out)) - { - return; - } - Derailed = 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, V, 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 TMoverParameters::rerail() -{ - ClearFlag(DamageFlag, dtrain_out); - Derailed = 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(); - derailment_distance = 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 TMoverParameters::repair_damage() -{ - DamageFlag = 0; - EngDmgFlag = 0; - WheelFlat = 0.0; - AlarmChainFlag = false; - // the crushed ends rebuilt - for (auto &coupler : Couplers) - { - restore_end(coupler); - } - rerail(); -} - -void TMoverParameters::Derail(DerailReason const Reason) -{ - if (SetFlag(DamageFlag, dtrain_out)) - { - EventFlag = true; - MainSwitch(false, range_t::local); - - auto const velocity{V}; - AccS *= 0.65; - V *= 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(V - velocity); - } - RunningShape.R = 0; - if (Vel < 5.0) - { - // HACK: prevent permanent axle spin in static vehicle after a collision - nrot = 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)) - { - Derailed = 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 `TMoverParameters::CollisionDetect()` - else if (Reason == TRAILED_SWITCH) - ErrorLog("Bad driving: " + Name + " derailed trailing through a switch with a movable nose set the other way"); - } -} - -bool TMoverParameters::leaves_track() const -{ - return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out) && Derailed != derailment::outcome::none && - false == OffTrack.active(); -} - -void TMoverParameters::pull_off(int const Side, double const Acceleration, std::string const &Why) -{ - if (Global.derailment != global_settings::derailment_model::physical || false == SetFlag(DamageFlag, dtrain_out)) - { - return; - } - // upright, its flange climbs the rail the coupling pulls it over - Derailed = 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)); -} - -void TMoverParameters::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 (int end = end::front; end <= end::rear; ++end) - { - auto const &coupler{vehicle->Couplers[end]}; - auto *other{coupler.Connected}; - if (other == nullptr || coupler.CouplingFlag == coupling::faux || std::any_of(train.begin(), train.end(), [other](auto const &Entry) { return Entry.first == other; })) - { - continue; - } - auto const otherdirection{direction * DirPatch(end, coupler.ConnectedNr)}; - other->V += Change * otherdirection; - train.emplace_back(other, otherdirection); - } - } -} - -// ************************************************************************************************* -// 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 - } - 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) && 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) - - // 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 (TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) - AccS = -Sign(V) * 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{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && V == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; - if (stuck) - AccS = 0.0; - - // 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 (stuck) - V = 0.0; - 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); - // 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 * V - 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, derailment_distance + std::abs(dL)); - } - derailment_distance = 0.0; - // 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 !!! - 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 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) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this)) - AccS = -Sign(V) * g * 1; // * random(0.0, 0.1) - auto const stuck{(Derailed != derailment::outcome::none || legacy_derailed_slides(*this)) && V == 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{V}; - V += (3.0 * AccS - AccSprev) * dt / 2.0; // przyrost predkosci - if (stuck) - V = 0.0; - 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; - - // 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 == TestFlag(DamageFlag, dtrain_out) && Derailed == derailment::outcome::none && false == legacy_derailed_slides(*this) && Vel < 1.0) - { - V = 0.0; - AccS = 0.0; - } - - dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha - // the criteria of derailment go by the distance, checked in the full step which ends the frame - derailment_distance += std::abs(dL); - // 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 !!! - 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 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); - GensetCheck(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; - } - } - 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 || (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; - } - - // an emergency brake application made under power opens the line breaker, where the vehicle has such an interlock - if (Mains && EmergencyBrakeHoldsMainOff()) - { - MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); - } -} - -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 const localvoltage{LocalPowerVoltage(Coupling)}; - - auto const abslocalvoltage{std::abs(localvoltage)}; - auto const localpowersource{(abslocalvoltage > 1.0)}; - - // przekazywanie napiec - PowerCouplersVoltage(Coupling, abslocalvoltage, localpowersource); - - // przekazywanie pradow - PowerCouplersCurrent(Coupling, localpowersource); -} - -// the current the vehicle draws from the circuit of the power coupling given -double *TMoverParameters::PowerCircuitCurrent(coupling const Coupling) -{ - switch (Coupling) - { - 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 TMoverParameters::LocalPowerVoltage(coupling const Coupling) -{ - auto localvoltage{0.0}; - - // local power sources - // the results could be kept in the 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 - // (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 (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; - } - } - - return localvoltage; -} - -// the voltage passed through the vehicle to the coupler at its other end, from the coupled vehicle or its own source -void TMoverParameters::PowerCouplersVoltage(coupling const Coupling, double const abslocalvoltage, bool const localpowersource) -{ - if (Couplers[end::front].power(Coupling) == nullptr) - { - // not a power coupling, there's no voltage to pass - return; - } - 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 = thiscoupler.power(Coupling); - auto *oppositecoupling = oppositecoupler.power(Coupling); - - // 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(Coupling); - 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 TMoverParameters::PowerCouplersCurrent(coupling const Coupling, bool const localpowersource) -{ - auto const *frontcoupling{Couplers[end::front].power(Coupling)}; - auto const *rearcoupling{Couplers[end::rear].power(Coupling)}; - auto *totalcurrent{PowerCircuitCurrent(Coupling)}; - 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(Coupling); - - 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 = connectedothercoupler.power(Coupling); - 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() ? TractionSupplyVoltage() : 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++; - } -} - -// 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 TMoverParameters::GensetCheck(double const Deltatime) -{ - if (false == Genset.fitted()) - { - return; - } - auto &genset{Genset}; - auto const wasactive{genset.is_active}; - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; - 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() && Mains ? std::clamp(eimv_pr, 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 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) - { - 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("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; -} - -// a notch up, as the kind of the engine takes it; returns whether the controller moved -bool TMoverParameters::IncMainCtrlByEngine(int const CtrlSpeed) -{ - bool OK = false; - 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) - { - SpeedCtrlSwitch(false); - SpeedCtrlUnit.IsActive = false; - } - break; - } - - case TEngineType::ElectricSeriesMotor: - { - OK = IncMainCtrlSeriesMotor(CtrlSpeed); - 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 - return OK; -} - -// 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 TMoverParameters::IncMainCtrlSeriesMotor(int const CtrlSpeed) -{ - bool OK = false; - if (DirActive == 0) - { - return false; - } - - if (CtrlSpeed > 1) - { - // szybkie przejœcie na bezoporow¹ - if (TrainType == dt_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=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; - } - 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 - 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("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; -} - -// a notch down, as the kind of the engine takes it; returns whether the controller moved -bool TMoverParameters::DecMainCtrlByEngine(int const CtrlSpeed) -{ - bool OK = false; - switch (EngineType) - { - case TEngineType::None: - case TEngineType::Dumb: - case TEngineType::DieselElectric: - case TEngineType::ElectricInductionMotor: - { - if (CtrlSpeed == 1) - { - MainCtrlPos--; - OK = true; - if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos) - { - SpeedCtrlSwitch(false); - SpeedCtrlUnit.IsActive = false; - } - } - else if (CtrlSpeed > 1) - OK = DecMainCtrl(1) && DecMainCtrl(CtrlSpeed - 1); // CtrlSpeed-1); - break; - } - - case TEngineType::ElectricSeriesMotor: - { - OK = DecMainCtrlSeriesMotor(CtrlSpeed); - 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 - return OK; -} - -// a notch down of the series motors' controller: CtrlSpeed over 1 runs it down to the first position without resistors -bool TMoverParameters::DecMainCtrlSeriesMotor(int const CtrlSpeed) -{ - bool OK = false; - 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} - } - 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 (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("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; - if (PulleeMode && State) - { - // the battery of a vehicle prepared for hauling stays off - return false; - } - 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; - wake_for_brake(); - 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; - wake_for_brake(); - return true; - } - else - return false; -} - -// ************************************************************************************************* -// 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 TMoverParameters::PulleeModeSwitch(bool const State) -{ - if (PulleeMode == State || (State && CabActive != 0)) - { - return false; - } - PulleeMode = State; - if (PulleeMode) - { - DecManualBrakeLevel(ManualBrakePosNo); - SpringBrake.Activate = false; - SecuritySystem.set_enabled(false); - Battery = false; - } - return true; -} - -// ************************************************************************************************* -// 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; - } - } - 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) && 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) && false == EmergencyBrakeHoldsMainOff(); -} - -// ************************************************************************************************* -// 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; -} - -// the traction selector of a dual-mode vehicle: moves only with the line breaker open, and only where a genset is -bool TMoverParameters::TractionModeSwitch(traction_mode const Mode, range_t const Notify) -{ - auto const initialstate{TractionMode}; - // refused with the line breaker closed, and then not passed on either, so the train stays on one source - auto const accepted{false == Mains}; - - if (Genset.fitted() && accepted) - { - TractionMode = Mode; - } - - if (Notify != range_t::local && accepted) - { - SendCtrlToNext("TractionMode", Mode == traction_mode::genset ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return TractionMode != initialstate; -} - -// 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 TMoverParameters::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("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 TMoverParameters::TractionSourceVoltage() const -{ - return GensetSelected() ? Genset.voltage : PantographVoltage; -} - -// the voltage the traction circuit gets: from the vehicle's own source, or through the train's high voltage line -double TMoverParameters::TractionSupplyVoltage() const -{ - return std::max(GetTrainsetHighVoltage(), TractionSourceVoltage()); -} - -// below it the undervoltage trip opens the line breaker -double TMoverParameters::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 TMoverParameters::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 TMoverParameters::CatenaryCurrent() const -{ - if (GensetSelected()) - { - return HeatingPowerSource.SourceType == TPowerSource::CurrentCollector ? TotalCurrent : 0.0; - } - return (DynamicBrakeFlag && ResistorsFlag ? 0 : std::abs(Itot) * IsVehicleEIMBrakingFactor()) + TotalCurrent; -} - -// returns voltage of defined main engine power source -double TMoverParameters::EnginePowerSourceVoltage() const -{ - - return EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? TractionSupplyVoltage() : - 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() >= TractionSupplyMinVoltage(); -} - -// ************************************************************************************************* -// 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); - wake_for_brake(); - 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); - wake_for_brake(); - 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--; - } - wake_for_brake(); - 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--; - } - wake_for_brake(); - 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 - - auto const brakepress{BrakePress}; - BrakePress = Hamulec->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(BrakePress - brakepress) / dt}; - BrakePressRate += (rate - BrakePressRate) * std::min(1.0, dt / 1.0); - } - // 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) - { - - UpdateLocalBrakeValve(dt); - UpdateMainValve(dt); - } - - UpdateEmergencyValve(dt); - - // 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; - - UpdateDistributorSettings(); - - if ((BrakeHandle == TBrakeHandle::FVel6 || BrakeHandle == TBrakeHandle::FVE408) && CabOccupied != 0) - { - UpdateEPBrake(); - } - 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)); - // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() - PipeCouplersPending = true; - - 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; -} - -// the flow of the local brake valve, by the handle, the TRAXX's timed one, the integrated controller or the parking -void TMoverParameters::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 = 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(PulleeMode ? 0.0 : 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(PulleeMode ? 0.0 : std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, 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 TMoverParameters::UpdateMainValve(double dt) -{ - auto const temp{MainValveSupply()}; - Handle->SetReductor(BrakeCtrlPos2); - - if (PulleeMode) - { - // the driver's valve of a vehicle prepared for hauling is cut out, whatever its handle shows - dpMainValve = 0; - } - else 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)) - { - dpMainValve = Handle->GetPF(MainValveHandlePosition(), 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); - } -} - -// the pressure the driver's handle is fed from: the main pipe's, or the brake pipe's own with the pipe locked -double TMoverParameters::MainValveSupply() -{ - 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) - { - return PipePress + 0.00001; - } - return ScndPipePress; -} - -// the position the driver's handle works at: its own, or the one the speed control's brake intervention sets -double TMoverParameters::MainValveHandlePosition() const -{ - 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); - } - return pos; -} - -void TMoverParameters::UpdateEmergencyValve(double dt) -{ - // 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. - // 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 && LocalBrakePosA >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || - (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) || - (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)}; - if (AlarmChainFlag || (ownemergency && false == PulleeMode)) - { - EmergencyValveFlow = PF(0, PipePress, 0.15) * dt; - } - dpMainValve += EmergencyValveFlow; -} - -// what the distributor valve gets of the local brake and the load, by its kind -void TMoverParameters::UpdateDistributorSettings() -{ - 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 -} - -// the ep brake of the FVel6 and FVE408 handles, passed along the unit -void TMoverParameters::UpdateEPBrake() -{ - 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); -} - -// ************************************************************************************************* -// Q: 20160713 -// Aktualizacja ciśnienia w przewodzie zasilającym -// ************************************************************************************************* -void TMoverParameters::UpdateScndPipePressure(double dt) -{ - if (ScndPipePress > 1.0) - { - Pipe2->Flow(-ScndPipePress*AirLeakRate * dt); - Pipe2->Act(); - } - - const double Spz = 0.5067; - - UpdateSpringBrake(dt); - - 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 ) */) - { - double const dV = PF(Compressor, ScndPipePress, Spz) * dt; - CompressedVolume += dV / 1000.0; - Pipe2->Flow(-dV); - } - // the air the main reservoir hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() - ScndPipeCouplersPending = true; - 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(); -} - -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 &Pipe) -{ - if (Flow * Flow <= 0.00000000000001) - return false; - return (Global.physics_pipewake <= 0.f) - || (std::abs(Pressure - Pipe.P_pending()) > Global.physics_pipewake) - || (std::abs(Pipe.P_pending() - Pipe.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(TMoverParameters const &Neighbour, double const Pressure, TReservoir const &Pipe) -{ - if ((Global.physics_pipewake <= 0.f) || Neighbour.PhysicActivation) - return Pressure; - return Pipe.P_pending(); -} -} // namespace - -// ************************************************************************************************* -// 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, neighbour_pipe_pressure(*c, c->PipePress, *c->Pipe), 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, neighbour_pipe_pressure(*c, c->PipePress, *c->Pipe), 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; -} - -// ************************************************************************************************* -// 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 TMoverParameters::GetScndDVc(double dt) -{ - const double Spz = 0.5067; - TMoverParameters *c; - double dv1 = 0; - double 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, neighbour_pipe_pressure(*c, c->ScndPipePress, *c->Pipe2), 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, neighbour_pipe_pressure(*c, c->ScndPipePress, *c->Pipe2), 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)) - { - double const 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); - } - return dv1 + dv2; -} - -namespace -{ - -// a pipe along the train, whose air the hoses between the vehicles carry (TMoverParameters::UpdatePipeCouplers()) -struct train_pipe -{ - std::shared_ptr TMoverParameters::*reservoir; - double TMoverParameters::*pressure; - bool TMoverParameters::*pending; // the vehicle stepped the pipe, the exchange through its hoses is yet to come - int hose; // the coupling flag of the pipe's hose - double (TMoverParameters::*exchange)(double); // the air the hoses carry in a step, the neighbours' share sent to them - double (*area)(TMoverParameters const &); // the cross-section of the hose, as the exchange takes it -}; - -// the brake pipe, GetDVc() -train_pipe const brake_pipe{&TMoverParameters::Pipe, - &TMoverParameters::PipePress, - &TMoverParameters::PipeCouplersPending, - ctrain_pneumatic, - &TMoverParameters::GetDVc, - [](TMoverParameters const &Vehicle) { return Vehicle.Spg / (1.0 + 0.015 / Vehicle.Spg * Vehicle.Dim.L); }}; -// the main reservoir pipe, GetScndDVc() -train_pipe const main_reservoir_pipe{&TMoverParameters::Pipe2, - &TMoverParameters::ScndPipePress, - &TMoverParameters::ScndPipeCouplersPending, - ctrain_scndpneumatic, - &TMoverParameters::GetScndDVc, - [](TMoverParameters 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(TMoverParameters const &Vehicle, train_pipe const &Pipe, double const dt) -{ - auto substeps{1}; - auto const area{Pipe.area(Vehicle)}; - auto const capacity{(Vehicle.*Pipe.reservoir)->GetCap()}; - for (auto const &hose : Vehicle.Couplers) - { - if (hose.Connected == nullptr || false == TestFlag(hose.CouplingFlag, Pipe.hose)) - { - continue; - } - auto const &other{*hose.Connected}; - auto const othercapacity{(other.*Pipe.reservoir)->GetCap()}; - // the flow per bar of the difference, at small differences, where it's the largest - auto const pressure{std::max(Vehicle.*Pipe.pressure, other.*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 &Pipe) -{ - 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]->*Pipe.pending) - { - byaddress.emplace_back(Vehicles[index], index); - } - } - std::ranges::sort(byaddress); - auto const find = [&byaddress](TMoverParameters 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]->*Pipe.pending || 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 == TestFlag(hose.CouplingFlag, Pipe.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 &Pipe, double const dt) -{ - auto const trains{hose_trains(Vehicles, Pipe)}; - std::vector substeps; - for (std::size_t index = 0; index < Vehicles.size(); ++index) - { - if (false == Vehicles[index]->*Pipe.pending) - { - continue; - } - if (substeps.size() <= trains[index]) - { - substeps.resize(trains[index] + 1, 1); - } - substeps[trains[index]] = std::max(substeps[trains[index]], hose_substeps(*Vehicles[index], Pipe, 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]->*Pipe.pending || trains[index] != train) - { - continue; - } - auto *vehicle{Vehicles[index]}; - auto &pipe{*(vehicle->*Pipe.reservoir)}; - pipe.Act(); // what the neighbours have sent in the meantime - vehicle->*Pipe.pressure = pipe.P(); - pipe.Flow((vehicle->*Pipe.exchange)(substep)); - pipe.Act(); - vehicle->*Pipe.pressure = pipe.P(); - } - } - } - for (auto *vehicle : Vehicles) - { - vehicle->*Pipe.pending = 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 TMoverParameters::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 TMoverParameters::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 TMoverParameters::UpdatePipeCouplers(std::vector const &Vehicles, double const dt) -{ - exchange_through_hoses(Vehicles, brake_pipe, dt); - exchange_through_hoses(Vehicles, main_reservoir_pipe, dt); -} - -// ************************************************************************************************* -// 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 - { - // 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 || 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)) - { - if (Derailed != 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(Derailed)}; - 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(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 ? TractionSupplyVoltage() : 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) - { - // 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->MoverParameters, Neighbours[end].vehicle_end) * DirF(end); - Couplers[end].CForce = CouplerForce(end, dt); - FTrain += Couplers[end].CForce; - // 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 += 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(); - } - - // the spring brake of a vehicle prepared for hauling (PulleeMode) is released by hand: no force, whatever its cylinder has - if (SpringBrake.IsReady && false == PulleeMode) - 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 const &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)}; - - // 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::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; - } - 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::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; -} - -// a coupler stretched with more than its strength for over a second breaks, the more likely the longer, with crash damage on -void TMoverParameters::CouplerStretchCheck(int 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 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; - } - // 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 &= ~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, 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::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; - // 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; -} - -// ************************************************************************************************* -// Q: 20160714 -// oblicza sile trakcyjna lokomotywy (dla elektrowozu tez calkowity prad) -// ************************************************************************************************* -double TMoverParameters::TractionForce(double dt) -{ - using enum TEngineType; - Ft = 0; - double dtrans{0.0}; - double dmoment{0.0}; - auto const revolutions{UpdateEngineRevolutions(dt, dtrans, dmoment)}; - - 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 - UpdateVentilators(dt); - auto const PosRatio{UpdateEnginePower()}; - VoltageRelaysCheck(); - - if (EngineType == DieselElectric && DEDynamicBrake.source != diesel_electric_dynamic_brake::control::none) - { - update_dieselelectric_dynamic_brake(dt); - } - - if (DirActive != 0) - switch (EngineType) - { - case Dumb: - { - DumbTractionForce(PosRatio); - break; - } - case WheelsDriven: - { - WheelsDrivenTractionForce(dt); - break; - } - case ElectricSeriesMotor: - { - SeriesMotorTractionForce(dt); - break; - } - case DieselEngine: - { - DieselEngineTractionForce(dt, dmoment, dtrans); - break; - } - case DieselElectric: // youBy - { - DieselElectricTractionForce(revolutions); - if (DEDynamicBrake.level > 0.0) - { - // braking: no power asked for, so the drive above gave no force - apply_dieselelectric_dynamic_brake(dt); - } - break; - } - case ElectricInductionMotor: - { - InductionMotorTractionForce(dt); - break; - } - case None: - default: - { - break; - } - } // case EngineType - - if (EngineType == DieselElectric) - { - // rough approximation of extra effort to overcome friction etc - EnginePower += EngineRPMRatio() * 0.15 * DElist[MainCtrlPosNo].GenPower; - } - - return Ft; -} - -// 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 TMoverParameters::UpdateEngineRevolutions(double dt, double &dtrans, double &dmoment) -{ - double tmp{0.0}; - // youBy - switch (EngineType) - { - case TEngineType::DieselElectric: - { - if (true == Mains && true == FuelPump.is_active) - { - tmp = DieselElectricTargetRevolutions(); - } - 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; - } - } - - return tmp; -} - -// the revolutions a diesel-electric's engine aims at [1/s], by the controller and the heating; the fill shown by the smoke -double TMoverParameters::DieselElectricTargetRevolutions() -{ - double tmp; - - 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); - return tmp; -} - -// the starting resistors' blowers, and the diesels' radiator fans -void TMoverParameters::UpdateVentilators(double dt) -{ - switch (EngineType) - { - - case TEngineType::ElectricSeriesMotor: - { - if (MainCircuitPowered()) - { - UpdateResistorBlowers(dt); - } // 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; - } - } -} - -// the starting resistors' blowers of the series motors with the line breaker closed, worked by hand or by the current -void TMoverParameters::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 (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 -} - -// the power of a dumb or diesel engine; returns the ratio of the power a dumb engine is set to -double TMoverParameters::UpdateEnginePower() -{ - double PosRatio{0.0}; - 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; - } - } - - return PosRatio; -} - -// the line breaker opened by a voltage out of the motors' range, and the line contactors of a diesel-electric -void TMoverParameters::VoltageRelaysCheck() -{ - 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) - // (the source by the traction selector of a dual-mode vehicle: the pantographs or the genset) - if (Mains && ((TractionSupplyVoltage() < TractionSupplyMinVoltage() && false == PantographsRequireMains) || - TractionSupplyVoltage() > 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; - } - } -} - -void TMoverParameters::DumbTractionForce(double const PosRatio) -{ - 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; - } -} - -void TMoverParameters::WheelsDrivenTractionForce(double dt) -{ - 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); -} - -void TMoverParameters::SeriesMotorTractionForce(double dt) -{ - // 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) - { - SeriesMotorDynamicBrake(dt); - } - - 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 -} - -// the automatic dynamic brake of the series motors: the excitation current, by the stages of the ep brake (TUHEX) -void TMoverParameters::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; - 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); -} - -void TMoverParameters::DieselEngineTractionForce(double dt, double const dmoment, double const dtrans) -{ - 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; -} - -// tmp: the revolutions the engine aims at [1/s], see UpdateEngineRevolutions() -void TMoverParameters::DieselElectricTractionForce(double tmp) -{ - double PosRatio; - // tmpV:=V*CabActive*DirActive; - auto const tmpV{nrot * 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 == Heating) - { - power -= HeatingPower; - } - 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 == StLinFlag) - 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 - Mm = Mw / Transmision.Ratio; // moment silnika trakcyjnego - - Im = dieselelectric_motor_current(Mm); - - 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 == StLinFlag || 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 TMoverParameters::DieselElectricShuntForce(double const tmpV, double &tmp) -{ - 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; - } -} - -// 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 TMoverParameters::DieselElectricDigitalForce(double const tmpV, double &tempUmax, double &tempImax) -{ - 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); - auto const tempPmax = DElist[MainCtrlPosNo].GenPower * std::min(eimic_positive, rpmratio); - if (true == StLinFlag) - 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 TMoverParameters::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 TMoverParameters::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 TMoverParameters::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, 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 ) ); - } - */ -} - -// 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 TMoverParameters::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 TMoverParameters::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 TMoverParameters::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 TMoverParameters::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 TMoverParameters::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 TMoverParameters::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 TMoverParameters::ShuntFieldRelaysType46Up() -{ - if (ScndCtrlPos % 2 == 0) - { - if (MPTRelay[ScndCtrlPos].Iup > Im) - { - ++ScndCtrlPos; - } - } - else - { - if (MPTRelay[ScndCtrlPos - 1].Iup > Im && MPTRelay[ScndCtrlPos].Iup < Vel) - { - ++ScndCtrlPos; - } - } -} - -void TMoverParameters::InductionMotorTractionForce(double dt) -{ - if (MainCircuitPowered() && !SecuritySystem.is_engine_blocked()) - { - double PosRatio; - double tmp; - 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); - } - 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; - eimv_pr = 0; - } - - eimv_pr += std::max(std::min(PosRatio - eimv_pr, 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 TMoverParameters::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("SpeedCntrl", 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 TMoverParameters::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 TMoverParameters::InductionMotorBrakeBlending(double const ActiveInverters, double &PosRatio, double &tmp) -{ - InductionMotorDynamicBrakeFlag(); - auto const edBCP{Hamulec->GetEDBCP() * eimc[eimc_p_abed]}; // stala napedu - if (DynamicBrakeFlag) - { - PosRatio = InductionMotorBrakeRatio(ActiveInverters, edBCP); - 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 - } -} - -// 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 TMoverParameters::InductionMotorDynamicBrakeFlag() -{ - double const 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; -} - -// 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 TMoverParameters::InductionMotorBrakeRatio(double const ActiveInverters, double const edBCP) -{ - double PosRatio; - // 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])); - } - } - return PosRatio; -} - -// the model of the induction motors and their inverters: voltage, frequency, currents, moment and force -void TMoverParameters::InductionMotorDrive(double dt) -{ - double tmp; - if (DynamicBrakeFlag) - tmp = eimc[eimc_f_Uzh]; - else - tmp = eimc[eimc_f_Uzmax]; - - auto f_cfu{DynamicBrakeFlag ? eimc[eimc_f_cfuH] : eimc[eimc_f_cfu]}; - - eimv[eimv_Uzsmax] = std::min(EngineVoltage - eimc[eimc_f_DU], tmp); - eimv[eimv_fkr] = eimv[eimv_Uzsmax] / f_cfu; - if (eimv_pr < 0) - { - eimv[eimv_Pmax] = eimc[eimc_p_Ph]; - } - else - { - eimv[eimv_Pmax] = std::min(eimc[eimc_p_Pmax], 0.001 * EngineVoltage * (eimc[eimc_p_Imax] - eimc[eimc_f_I0]) * Pirazy2 * eimc[eimc_s_cim] / eimc[eimc_s_p] / eimc[eimc_s_cfu]); - if (GensetSelected()) - { - // on the genset of a dual-mode vehicle the traction takes no more than the genset gives - eimv[eimv_Pmax] = std::min(eimv[eimv_Pmax], GensetTractionPowerLimit()); - } - } - eimv[eimv_FMAXMAX] = 0.001 * - square(std::min(1.0, eimv[eimv_fkr] / std::max(abs(enrot) * eimc[eimc_s_p] + eimc[eimc_s_dfmax] * eimv[eimv_ks], eimc[eimc_s_dfmax])) * f_cfu / eimc[eimc_s_cfu]) * - (eimc[eimc_s_dfmax] * eimc[eimc_s_dfic] * eimc[eimc_s_cim]) * Transmision.Ratio * NPoweredAxles * 2.0 / WheelDiameter; - InductionMotorForceLimits(); - for (auto &inv : Inverters) - { - inv.Request = inv.IsActive ? eimv_pr : 0.0; - inv.Error = inv.Failure_Const || (inv.Failure_Drive && inv.Request != 0); - inv.IsActive = inv.Activate && !inv.Error; - } - eimv[eimv_ks] = eimv[eimv_Fr] / eimv[eimv_FMAXMAX]; - eimv[eimv_df] = eimv[eimv_ks] * eimc[eimc_s_dfmax]; - eimv[eimv_fp] = DirAbsolute * enrot * eimc[eimc_s_p] + eimv[eimv_df]; // do przemyslenia dzialanie pp z tmpV - // eimv[eimv_U]:=std::max(eimv[eimv_Uzsmax],std::min(eimc[eimc_f_cfu]*eimv[eimv_fp],eimv[eimv_Uzsmax])); - // eimv[eimv_pole]:=eimv[eimv_U]/(eimv[eimv_fp]*eimc[eimc_s_cfu]); - if (abs(eimv[eimv_fp]) <= eimv[eimv_fkr]) - eimv[eimv_pole] = f_cfu / eimc[eimc_s_cfu]; - else - eimv[eimv_pole] = eimv[eimv_Uzsmax] / eimc[eimc_s_cfu] / abs(eimv[eimv_fp]); - eimv[eimv_U] = eimv[eimv_pole] * eimv[eimv_fp] * eimc[eimc_s_cfu]; - eimv[eimv_Ic] = (eimv[eimv_fp] - DirAbsolute * enrot * eimc[eimc_s_p]) * eimc[eimc_s_dfic] * eimv[eimv_pole]; - eimv[eimv_If] = eimv[eimv_Ic] * eimc[eimc_s_icif]; - eimv[eimv_M] = eimv[eimv_pole] * eimv[eimv_Ic] * eimc[eimc_s_cim]; - eimv[eimv_Ipoj] = eimv[eimv_Ic] * NPoweredAxles * InvertersRatio * eimv[eimv_U] / (EngineVoltage - eimc[eimc_f_DU]) + eimc[eimc_f_I0]; - eimv[eimv_Pm] = DirActive * eimv[eimv_M] * NPoweredAxles * InvertersRatio * enrot * Pirazy2 / 1000; - eimv[eimv_Pe] = eimv[eimv_Ipoj] * EngineVoltage / 1000; - eimv[eimv_eta] = eimv[eimv_Pm] / eimv[eimv_Pe]; - - Im = eimv[eimv_If]; - if (eimv[eimv_Ipoj] >= 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 = eimv[eimv_Ipoj] * (0.01 + std::min(0.99, 0.99 - Vadd)); - - EnginePower = abs(eimv[eimv_Ic] * eimv[eimv_U] * NPoweredAxles) / 1000; - // power inverters - UpdateInverterFrequency(); - - 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; -} - -// the force the motors give at full and at the setting (eimv_pr), braking within the power and the force of the -// electrodynamic brake, driving within the power and the starting force -void TMoverParameters::InductionMotorForceLimits() -{ - if (eimv_pr < 0) - { - eimv[eimv_Fful] = std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(eimc[eimc_p_Fh], eimv[eimv_FMAXMAX])); - eimv[eimv_Fmax] = -Sign(V) * DirAbsolute*std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-eimc[eimc_p_Fh] * eimv_pr, eimv[eimv_FMAXMAX])); - double pr = eimv_pr; - if (EIMCLogForce) - pr = -log(1 - 4 * pr) / log(5); - eimv[eimv_Fr] = -Sign(V) * DirAbsolute*std::min(eimc[eimc_p_Ph] * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-eimc[eimc_p_Fh] * pr, eimv[eimv_FMAXMAX])); - if (InvertersRatio < 1.0) - eimv[eimv_Fful] = 0; - //*std::min(1,(Vel-eimc[eimc_p_Vh0])/(eimc[eimc_p_Vh1]-eimc[eimc_p_Vh0])) - } - else - { - eimv[eimv_Fful] = std::min(std::min(3.6 * eimv[eimv_Pmax] / std::max(Vel, 1.), eimc[eimc_p_F0] - Vel * eimc[eimc_p_a1]), eimv[eimv_FMAXMAX]); - // if(not Flat)then - eimv[eimv_Fmax] = eimv[eimv_Fful] * eimv_pr; - // else - // eimv[eimv_Fmax]:=std::min(eimc[eimc_p_F0]*eimv_pr,eimv[eimv_Fful]); - double pr = eimv_pr; - if (EIMCLogForce) - pr = log(1 + 4 * pr) / log(5); - eimv[eimv_Fr] = eimv[eimv_Fful] * pr; - } -} - -// the frequency of the inverters at the motors' slip frequency, from the list of the drive or of its brake -void TMoverParameters::UpdateInverterFrequency() -{ - 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; - } -} - -// the induction motor drive without power, or blocked by the security system -void TMoverParameters::InductionMotorOff() -{ - 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); -} - -// the current of a diesel-electric vehicle's traction motors giving the moment [N m] of one motor -double TMoverParameters::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 TMoverParameters::dieselelectric_dynamic_brake_demand() const -{ - switch (DEDynamicBrake.source) - { - case diesel_electric_dynamic_brake::control::controller: - return std::clamp(-eimic_real, 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 TMoverParameters::dieselelectric_dynamic_brake_limit() const -{ - auto const &brake{DEDynamicBrake}; - auto limit{brake.max_force}; - if (brake.max_power > 0.0 && std::abs(V) > 0.0) - { - limit = std::min(limit, brake.max_power / std::abs(V)); - } - 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 TMoverParameters::update_dieselelectric_dynamic_brake(double const dt) -{ - auto &brake{DEDynamicBrake}; - auto const nopower{brake.source == diesel_electric_dynamic_brake::control::controller ? eimic_real <= 0.0 : IsMainCtrlNoPowerPos()}; - if (Mains && 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(); - DynamicBrakeFlag = 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) - Hamulec->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 TMoverParameters::apply_dieselelectric_dynamic_brake(double const dt) -{ - auto const force{dt > 0.0 ? std::min(DEDynamicBrake.force, TotalMass * std::abs(V) / dt) : DEDynamicBrake.force}; - Ft = V > 0.0 ? -force : V < 0.0 ? force : 0.0; - Fw = Ft / NPoweredAxles; - Mw = Fw * WheelDiameter / 2.0; - Mm = Mw / Transmision.Ratio; - Im = dieselelectric_motor_current(Mm); - EngineVoltage = 0.0; - EnginePower = 0.0; -} - -// ************************************************************************************************* -// 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; - 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 - OK = AutoRelayShuntStep(ARFASI2); - } - else - { // zmieniaj mainctrlactualpos - OK = AutoRelayMainStep(ARFASI); - } - } - else // not StLinFlag - { - OK = AutoRelayLineContactorsStep(motorconnectorsoff); - } - if (OK) - LastRelayTime = 0; - - return OK; - } -} - -// a step of the shunt field on a position without resistors, up or down to the second controller -bool TMoverParameters::AutoRelayShuntStep(bool const ARFASI2) -{ - bool OK = false; - // 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; - 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 TMoverParameters::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 != 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))) - { - OK = AutoRelayMainUp(ARFASI); - } - else if (RList[MainCtrlActualPos].Relay > MainCtrlPos) - { - OK = AutoRelayMainDown(); - } - 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; - 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 TMoverParameters::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 (LastRelayTime > 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 TMoverParameters::AutoRelayMainNotchUp() -{ - bool OK = false; - // 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); - } - } - return OK; -} - -// a step of the main relays down to the controller's position; returns whether they moved -bool TMoverParameters::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 (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); - } - } - return OK; -} - -// the line contactors closed at the first position, or, open, the camshaft run back to zero -bool TMoverParameters::AutoRelayLineContactorsStep(bool const motorconnectorsoff) -{ - bool 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)) - { - 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 TMoverParameters::CamshaftRunDown() -{ - bool OK = false; - - if (CoupledCtrl) - { - - if (TrainType == dt_EZT) - { - OK = CamshaftRunDownEMU(); - } - else if (LastRelayTime > CtrlDownDelay) // wal kulakowy dwukierunkowy - { - 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; - } - return OK; -} - -// the one way camshaft of the EN57 run on to its end and round to zero; returns whether it moved -bool TMoverParameters::CamshaftRunDownEMU() -{ - bool OK = false; - // 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; - } - } - return OK; -} - -bool TMoverParameters::MotorConnectorsCheck() -{ - - // hunter-111211: wylacznik cisnieniowy - // (on some vehicles it watches the brake pipe alone) - ControlPressureSwitch = HasControlPressureSwitch && ((PressureSwitchBrakeCylinder && 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: - EIMICFromController(brakeDemand, offset, multiplier); - break; - case 1: - EIMICFromSteps(dt); - break; - case 2: - EIMICFromFourPositions(dt); - break; - case 3: - EIMICFromUniversalController(dt, brakeDemand); - break; - } - if (LocHandleTimeTraxx) - { - EIMICTraxxLocalBrake(dt); - } - - EIMICLimit(); -} - -// the controller (EIMCtrlType 0): the position of the main controller, or the analog one, or the brake asked -void TMoverParameters::EIMICFromController(double const brakeDemand, double const offset, double const multiplier) -{ - 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); -} - -// EIMCtrlType 1: the positions B+ to TMax move the value at a steady pace -void TMoverParameters::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 TMoverParameters::EIMICFromFourPositions(double dt) -{ - 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; - } -} - -// EIMCtrlType 3: the universal controller of UniCtrlList, with the train brake built in or not -void TMoverParameters::EIMICFromUniversalController(double dt, double const brakeDemand) -{ - if (UniCtrlIntegratedBrakePNCtrl) - { - UniversalControllerTrainBrake(); - } - - 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; - } -} - -// 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 TMoverParameters::UniversalControllerTrainBrake() -{ - 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); -} - -// the local brake of the TRAXX locomotives, by time: released, held or applied, which cuts the drive off -void TMoverParameters::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, 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; -} - -// the value limited by the power, the spring brake, the pipe lock, the direction and the doors' permits -void TMoverParameters::EIMICLimit() -{ - 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); -} - -bool TMoverParameters::UpdateStopBrakeRelease(double const Demand, double const Dt) -{ - if (Demand <= 0.0) - { - StopBrakeReleaseTimer = 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{StopBrakeReleaseTimer >= StopBrakeReleaseDelay}; - StopBrakeReleaseTimer += Dt; - return released; -} - -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) - { - SpeedCtrlRegulator(dt, accfactor); - } - 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) - { - SpeedCtrlSwitch(false); - SpeedCtrlUnit.IsActive = false; - } - } - else - { - eimicSpeedCtrl = 1; - eimicSpeedCtrlIntegral = 0; - SpeedCtrlUnit.Parking = false; - SendCtrlToNext("SpeedCtrlUnit.Parking", 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 TMoverParameters::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 && 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; - } -} - -bool TMoverParameters::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 TMoverParameters::IsSpeedCtrlEngaged() const -{ - return IsSpeedCtrlSeparate() ? SpeedCtrlUnit.IsActive : ScndCtrlPos > 0; -} - -bool TMoverParameters::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 TMoverParameters::SpeedCtrlButton(int button) -{ - if (SpeedCtrl && IsSpeedCtrlEngaged()) - { - SpeedCtrlValue = SpeedCtrlButtons[button]; - } -} - -void TMoverParameters::SpeedCtrlInc() -{ - if (SpeedCtrl && IsSpeedCtrlEngaged()) - { - double x = floor(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) + 1.0; - SpeedCtrlValue = std::min(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MaxVelocity); - } -} - -void TMoverParameters::SpeedCtrlDec() -{ - if (SpeedCtrl && IsSpeedCtrlEngaged()) - { - double x = ceil(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) - 1.0; - SpeedCtrlValue = std::max(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MinVelocity); - } -} - -bool TMoverParameters::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 TMoverParameters::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; -} - -// ************************************************************************************************* -// 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) - { - OK = dizel_GearShiftCheck(VelUp, VelDown); - } - - if (Mains) - { - 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 TMoverParameters::dizel_GearShiftCheck(double const VelUp, double const VelDown) -{ - auto OK{false}; - if (RList[MainCtrlPos].Mn == 0 && !hydro_TC) - { - if (dizel_engagestate > 0) - dizel_EngageSwitch(0); - if (IsMainCtrlNoPowerPos() && ScndCtrlActualPos > 0) - dizel_automaticgearstatus = -1; - } - else - { - OK = dizel_GearShiftRequest(VelUp, VelDown); - } - if (dizel_engage < 0.1 && dizel_automaticgearstatus != 0) - { - if (dizel_automaticgearstatus == 1) - ScndCtrlActualPos++; - else - ScndCtrlActualPos--; - dizel_automaticgearstatus = 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 TMoverParameters::dizel_GearShiftRequest(double const VelUp, double const VelDown) -{ - auto OK{false}; - 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; - } - } - } - return OK; -} - -// the pressure in the clutch's cylinder, by the controller's position or the integrated controller -void TMoverParameters::dizel_ClutchCheck() -{ - if (EIMCtrlType > 0) // sterowanie komputerowe - { - dizel_ClutchByIntegratedController(); - } - else if (dizel_automaticgearstatus == 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 TMoverParameters::dizel_ClutchByController() -{ - 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); - } -} - -// the clutch of the integrated controller: in with the converter filled or the power asked, half in for the retarder -void TMoverParameters::dizel_ClutchByIntegratedController() -{ - 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); -} - -// 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 = dizel_DigitalFill(dt); - } - else - { - dizel_nreg_max = dizel_nmax; - realfill = RList[mcp].R; - } - } - if (dizel_nmax_cutoff > 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 TMoverParameters::dizel_DigitalFill(double dt) -{ - double realfill; - 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; - } - return realfill; -} - -// the fill cut off over the revolutions the governor allows at the controller's position, or full under the idle ones -double TMoverParameters::dizel_GovernorFill(int const mcp, double realfill) const -{ - auto nreg{0.0}; - if (EIMCtrlType > 0) - nreg = eimic_real > 0.005 ? dizel_nreg_max : dizel_nmin; - else - nreg = dizel_GovernorRevolutions(mcp, realfill); - 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 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 TMoverParameters::dizel_GovernorRevolutions(int const mcp, double &realfill) const -{ - auto nreg{0.0}; - 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; - } - return nreg; -} - -// ************************************************************************************************* -// 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; - - hydro_TCFillCheck(dt); - - // obliczanie momentow poszczegolnych sprzegiel - // sprzeglo glowne (skrzynia biegow) - TorqueC = dizel_engageMaxForce * dizel_engage * dizel_engageDia * friction; - - if (hydro_TC) // jesli hydro - { - hydro_TCTorque(); - 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; -} - -// the torque converter filled and emptied, and its lockup clutch engaged and released, by the power and the speed -void TMoverParameters::hydro_TCFillCheck(double dt) -{ - 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; - } -} - -// the torque converter's moments on its input and output shafts, by their revolutions and its fill -void TMoverParameters::hydro_TCTorque() -{ - 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; - } - } -} - -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) - { - update_door_requests(door, localopencontrol, remoteopencontrol, localclosecontrol, remoteclosecontrol); - move_door(door, 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(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 { 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 ); - } - } - } - */ -} - -// the permit, the state and the requests of a door, and whether it and its step open or close -void TMoverParameters::update_door_requests(basic_door &door, 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 == 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 openrequest{door_open_request(door, localopencontrol, remoteopencontrol)}; - auto const closerequest{door_close_request(door, localclosecontrol, remoteclosecontrol)}; - auto const ispowered{doors_powered()}; - - 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_folding(door); - - if (true == door.is_opening) - { - door.auto_timer = door_open_duration(door, localopencontrol, remoteopencontrol); - } -} - -// whether the door is asked to open, by the passengers, from afar or by itself -bool TMoverParameters::door_open_request(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const -{ - auto const autoopenrequest{Doors.open_control == control_t::autonomous && (false == Doors.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 TMoverParameters::door_close_request(basic_door const &door, bool const localclosecontrol, bool const remoteclosecontrol) const -{ - 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)}; - return (door.remote_close && remoteclosecontrol) || (door.local_close && localclosecontrol) || (autocloserequest && door.is_open); -} - -// whether the doors have the voltage they work on -bool TMoverParameters::doors_powered() const -{ - if (Doors.voltage == 0) - { - return true; - } - if (Doors.voltage == 24) - { - return Power24vIsAvailable || Power110vIsAvailable; - } - return Doors.voltage == 110 && Power110vIsAvailable; -} - -// 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 TMoverParameters::door_step_folding(basic_door const &door) const -{ - auto const unfolded{door.step_position > 0.f}; - auto const mayfold{false == Doors.step_enabled || (Doors.permit_needed ? false == door.open_permit : door.is_closing)}; - return unfolded && mayfold && (door.close_delay > Doors.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 TMoverParameters::door_open_duration(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const -{ - if (localopencontrol && door.local_open) - { - return Doors.auto_duration; - } - if (remoteopencontrol && door.remote_open && Doors.auto_include_remote) - { - return Doors.auto_duration; - } - return -1.f; -} - -// a door and its step moved as they open or close -void TMoverParameters::move_door(basic_door &door, double const Deltatime) -{ - // 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)); - } - } -} - -// the timers of the open doors which close after a while, kept running while the load is exchanged -void TMoverParameters::update_door_timers(double const Deltatime) -{ - // 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; - } - } -} - -// ************************************************************************************************* -// 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. 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) && BrakePressRate <= 0.05}; - return false == held; -} - -void TMoverParameters::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 TMoverParameters::brakes_changed_asleep() const -{ - if (PhysicActivation) - return false; - constexpr double pressure_change{0.05}; // [bar] - return std::abs(BrakePress - sleep_brakes.cylinder) > pressure_change || std::abs(SpringBrake.SBP - sleep_brakes.spring) > pressure_change || - ManualBrakePos != sleep_brakes.manual || std::abs(LocalBrakePosA - sleep_brakes.local) > 0.01; -} - -// ************************************************************************************************* -// 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); - } - else - { - // what the brake force of the last step came from, which it keeps while asleep (brakes_changed_asleep()) - sleep_brakes = {BrakePress, SpringBrake.SBP, ManualBrakePos, LocalBrakePosA}; - } - - 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) -{ - 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 (!enableModernDimmer) - { - 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 TMoverParameters::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 TMoverParameters::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 TMoverParameters::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 TMoverParameters::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; - } -} - -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, ""); - // 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 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; -} - -// 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 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); - } - - // 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 (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) -{ - - 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 TMoverParameters::LoadFIZ_CntrlBrakes(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) - { - 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)); - LocalBrake = lookup != localbrakes.end() ? lookup->second : NoBrake; - } - // mbrake - extract_value(MBrake, "ManualBrake", line, ""); -} - -// Cntrl.: of a vehicle with a train brake, its positions, delays, modes, handles, load weighing and anti-slip brake -void TMoverParameters::LoadFIZ_CntrlTrainBrake(std::string const &line) -{ - 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 - 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 TMoverParameters::LoadFIZ_CntrlAntiSlipBrake(std::string_view const asb) -{ - if (asb == "yes") - { - ASBType = 128; - } - else if (BrakeCtrlPosNo > 0 && asb == "manual") - { - ASBType = 1; - } - else if (BrakeCtrlPosNo > 0 && asb == "automatic") - { - ASBType = 2; - } -} - -// Cntrl.: the controllers, their delays, the cab and the switches of the driver's desk -void TMoverParameters::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)); - 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; - } - // 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(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(StopBrakeReleaseDelay, "SBDReleaseDelay", line, ""); // the holding brake waits for the power demand this long, s - 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, ""); -} - -// Cntrl.: how the devices start (MainStart, BatteryStart, ...) and their relays -void TMoverParameters::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(MainsInitTime, "MainInitTime", line, ""); - { - auto lookup = starts.find(extract_value("MainStart", line)); - MainsStart = lookup != starts.end() ? lookup->second : manual; - } - extract_value(PantographsRequireMains, "PantRequiresMain", line, ""); - // the brake pipe pressure of an emergency brake application, which opens the line breaker under power - extract_value(EmergencyBrakeMainOffPressure, "EmergencyBrakeMainOff", line, ""); - EmergencyBrakeMainOffPressure = std::max(0.0, EmergencyBrakeMainOffPressure); - // battery - { - auto lookup = starts.find(extract_value("BatteryStart", line)); - BatteryStart = lookup != starts.end() ? lookup->second : manual; - } - // converter - { - auto lookup = starts.find(extract_value("ConverterStart", line)); - ConverterStart = lookup != starts.end() ? lookup->second : 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 : manual; - } - // pantograph compressor - { - auto lookup = starts.find(extract_value("PantCompressorStart", line)); - PantographCompressorStart = lookup != starts.end() ? lookup->second : 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 : 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 : 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[end::rear].start_type = lookup != starts.end() ? lookup->second : 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 : automatic; // legacy behaviour - } - // ground relay - { - auto lookup = starts.find(extract_value("GroundRelayStart", line)); - auto const defaultstart{TrainType == dt_EZT ? automatic : 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 ? converter : 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; - } - 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 TMoverParameters::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 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: - { - 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[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"); - // its brake cylinder half; the brake pipe one stays - extract_value(PressureSwitchBrakeCylinder, "PressureSwitchBrakeCylinder", Input, ""); -} - -// Engine: of a diesel engine, its revolutions, gears, hydraulic transmission and retarder -void TMoverParameters::LoadFIZ_EngineDiesel(std::string const &Input) -{ - - 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, ""); - } - } -} - -// Engine: of a diesel-electric -void TMoverParameters::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(EngineHeatingRPM, "HeatingRPM", Input, ""); - extract_value(dizel_AIM, "AIM", Input, "1.25"); - extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); - LoadFIZ_DieselElectricDynamicBrake(Input); -} - -// Engine: of an induction motor drive -void TMoverParameters::LoadFIZ_EngineInductionMotor(std::string const &Input) -{ - - 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, ""); - if (false == extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, "")) - { - // without its own figure the dynamic brake takes the one of the traction - eimc[eimc_f_cfuH] = 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); - }*/ -} - -// Engine: what both kinds of diesels have, their heat among it -void TMoverParameters::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(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; -} - -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, ""); -} - -// the dynamic brake of a diesel-electric vehicle, from its Engine section: none without EDBrake -void TMoverParameters::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 - SplitEDPneumaticBrake = true; - } -} - -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)); - - CreateBrakeValve(); - - CreateBrakeHandles(); - - CreateBrakePipes(); - - if (LightsPosNo > 0) - LightsPos = LightsDefPos; - - // set default wiper switch position - wiperSwitchPos = WiperDefaultPos; - - if (CompressorListPosNo > 0) - CompressorListPos = CompressorListDefPos; - - // 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 && HeatingPower > 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; - 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; -} - -// the distributor valve of the vehicle's kind -void TMoverParameters::CreateBrakeValve() -{ - 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); -} - -// the driver's handle and the local brake handle of the vehicle's kinds -void TMoverParameters::CreateBrakeHandles() -{ - 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(); - } -} - -// the brake pipe, the main pipe and the spring brake's cylinder -void TMoverParameters::CreateBrakePipes() -{ - 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); - } -} - -// the pressure of the main pipe at the start: the main reservoir's, or HosePressure fed through a main hose, or none -double TMoverParameters::InitialScndPipePress(double const HosePressure) const -{ - if (VeselVolume > 0.0) - { - return CompressedVolume / VeselVolume; - } - if ((Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 || (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0) - { - return HosePressure; - } - return 0.0; -} - -// the air and the controls of a vehicle ready to depart -void TMoverParameters::SetReadyToDepart() -{ - WriteLog("Ready to depart"); - CompressedVolume = VeselVolume * MinCompressor * 9.8 / 10.0; - ScndPipePress = InitialScndPipePress(5.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; -} - -// the air and the brakes of a vehicle standing braked -void TMoverParameters::SetBraked() -{ - WriteLog("Braked"); - Volume = BrakeVVolume * MaxBrakePress[3]; - CompressedVolume = VeselVolume * MinCompressor * 0.55; - /* - ScndPipePress = 5.1; - */ - ScndPipePress = InitialScndPipePress(5.1); - 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; - } -} - -// ************************************************************************************************* -// 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) -{ - // 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, Couplertype, 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 TMoverParameters::RunControllerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - 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 - { - return false; - } - return true; -} - -// RunCommand() for the direction, the automatic start and the current relays; returns whether the command is one of them -bool TMoverParameters::RunRelaysCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - if (Command == "Direction") - { - DirActive = static_cast(floor(CValue1)); - DirAbsolute = DirActive * CabActive; - 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 == "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 - { - return false; - } - return true; -} - -// RunCommand() for the cab and the speed control; returns whether the command is one of them -bool TMoverParameters::RunCabCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - 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; - } - } - 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 == "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 - { - return false; - } - return true; -} - -// RunCommand() for the train brake, the releaser and the emergency brake; returns whether the command is one of them -bool TMoverParameters::RunBrakeCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - 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 == "Emergency_brake") - { - 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 TMoverParameters::RunBrakeEquipmentCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - 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 == "SpringBrakeActivate") - { - if (Power24vIsAvailable || Power110vIsAvailable) - { - SpringBrake.Activate = CValue1 > 0; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else - OK = true; - } - - 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 - { - return false; - } - return true; -} - -// RunCommand() for the heating, the converter, the battery and the compressor; returns whether the command is one of them -bool TMoverParameters::RunAuxiliariesCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - if (Command == "HeatingSwitch") - { - HeatingSwitch_(CValue1 > 0.0); - 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*/ - { - // the battery of a vehicle prepared for hauling (PulleeMode) stays off - if (BatteryStart == start_t::manual && (false == PulleeMode || CValue1 <= 0.0)) - { - 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 - { - 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 TMoverParameters::RunPumpsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - 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 - { - return false; - } - return true; -} - -// RunCommand() for the motor blowers and the compartment lights; returns whether the command is one of them -bool TMoverParameters::RunBlowersCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - 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 - { - return false; - } - return true; -} - -// RunCommand() for the line breaker, the relays and the pantographs; returns whether the command is one of them -bool TMoverParameters::RunPowerCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - if (Command == "MainSwitch") - { - MainSwitch_(CValue1 > 0.0); - 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 == "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 == "TractionMode") - { - TractionModeSwitch(CValue1 > 0.5 ? traction_mode::genset : traction_mode::catenary, range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "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 TMoverParameters::RunDoorsCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype, bool &OK) -{ - if (Command == "DoorPermit") - { - DoorPermitCommand(CValue1, CValue2); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorOpen" || Command == "DoorClose") /*NBMX*/ - { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - DoorRemoteCommand(Command == "DoorOpen", CValue1, CValue2); - 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 - { - 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 TMoverParameters::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_(side::right, CValue1 > 0); - } - if (std::abs(static_cast(CValue1)) & leftside) - { - PermitDoors_(side::left, CValue1 > 0); - } -} - -// the doors opened or closed from afar on the sides the command names, unless they're only worked locally -void TMoverParameters::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 == Power24vIsAvailable && false == Power110vIsAvailable)) - { - return; - } - auto const leftside{CValue2 > 0 ? 1 : 2}; - if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) - { - Doors.instances[side::right].remote_open = Open; - Doors.instances[side::right].remote_close = false == Open; - } - if (static_cast(CValue1) & leftside) - { - Doors.instances[side::left].remote_open = Open; - Doors.instances[side::left].remote_close = false == Open; - } -} - -// RunCommand() for the load and the damage; returns whether the command is one of them -bool TMoverParameters::RunLoadCommand(std::string const &Command, double CValue1, double CValue2, int const /*Couplertype*/, bool &OK) -{ - 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 == "SetDamage") - { - if (CValue2 == 1) - OK = SetFlag(DamageFlag, static_cast(floor(CValue1))); - if (CValue2 == -1) - { - auto const derailed{TestFlag(DamageFlag, dtrain_out)}; - OK = SetFlag(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 == TestFlag(DamageFlag, dtrain_out)) - rerail(); - } - } - else - { - return false; - } - return true; -} - -// ************************************************************************************************* -// 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/application/application.cpp b/application/application.cpp index 563cba5c1..fa74c3d7d 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -47,6 +47,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "utilities/translation.h" +#include "physics/vehicle.h" #if WITH_DISCORD_RPC #include "ref/discord-rpc/include/discord_rpc.h" @@ -102,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 @@ -825,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)}) { diff --git a/application/consistviews.cpp b/application/consistviews.cpp index 49815f6e8..55da9ca81 100644 --- a/application/consistviews.cpp +++ b/application/consistviews.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Camera.h" #include "vehicle/Driver.h" #include "vehicle/DynObj.h" +#include "physics/vehicle.h" namespace { @@ -28,17 +29,17 @@ cameraviews::vehicle_pose pose_of(TDynamicObject const *Vehicle) { cameraviews::vehicle_pose pose; pose.position = Vehicle->GetPosition(); pose.front = Vehicle->VectorFront(); - pose.length = Vehicle->MoverParameters->Dim.L; - pose.width = Vehicle->MoverParameters->Dim.W; - pose.height = Vehicle->MoverParameters->Dim.H; + 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 : {end::front, end::rear}) { - if (Vehicle->MoverParameters->Neighbours[side].vehicle == Other) { - return side; + for (auto const side : VehicleEnds) { + if (Vehicle->physics->Neighbours[side].vehicle == Other) { + return NumberOf(side); } } return -1; @@ -53,25 +54,25 @@ int outer_end(TDynamicObject const *Vehicle, TDynamicObject const *Inner, int co return inner < 0 ? Alone : 1 - inner; } -cameraviews::coupler coupler_of(TDynamicObject const *Vehicle, int const End) { +cameraviews::coupler coupler_of(TDynamicObject const *Vehicle, VehicleEnd const End) { cameraviews::coupler coupler; - coupler.position = Vehicle->CouplerPosition(static_cast(End)); - coupler.outward = Vehicle->VectorFront() * (End == end::front ? 1.0 : -1.0); - coupler.width = Vehicle->MoverParameters->Dim.W; + 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->MoverParameters->CabOccupied < 0 ? -1 : 1}; - auto const direction{Driven->MoverParameters->DirActive < 0 ? -1 : 1}; + 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(end::front)}; - auto const rear{Vehicle->CouplerPosition(end::rear)}; + auto const front{Vehicle->CouplerPosition(VehicleEnd::front)}; + auto const rear{Vehicle->CouplerPosition(VehicleEnd::rear)}; return glm::dot(front - rear, Way) >= 0.0 ? front : rear; } @@ -102,7 +103,7 @@ std::vector consist_views::train_of(TDynamicObject *Driven) { return train; } auto const *controller{Driven->Mechanik != nullptr ? Driven->Mechanik : Driven->ctOwner}; - auto *first{controller != nullptr ? controller->Vehicle(end::front) : nullptr}; + auto *first{controller != nullptr ? controller->Vehicle(VehicleEnd::front) : nullptr}; if (first == nullptr) { first = Driven; } @@ -141,9 +142,9 @@ TDynamicObject *consist_views::pick(std::vector const &Train, return m_vehicle; } -double consist_views::gap_beyond(TDynamicObject const *Vehicle, int const End) { - auto const &neighbour{Vehicle->MoverParameters->Neighbours[End]}; - if (neighbour.vehicle == nullptr || Vehicle->MoverParameters->Couplers[End].CouplingFlag != 0) { +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) { @@ -162,23 +163,23 @@ consist_views::coupling_place consist_views::coupling_at(std::vectorCouplerPosition(static_cast(behindend < 0 ? end::front : behindend)); + 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, front ? end::front : end::rear)}; + auto const outer{outer_end(vehicle, inner, NumberOf(front ? VehicleEnd::front : VehicleEnd::rear))}; place.vehicle = vehicle; - place.coupler = coupler_of(vehicle, outer); - auto const &neighbour{vehicle->MoverParameters->Neighbours[outer]}; - place.gap = gap_beyond(vehicle, outer); - if (place.gap >= 0.0 && (neighbour.vehicle_end == end::front || neighbour.vehicle_end == end::rear)) { + 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(static_cast(neighbour.vehicle_end)); + place.otherposition = neighbour.vehicle->CouplerPosition(neighbour.FacingEnd()); } return place; } @@ -207,7 +208,7 @@ cameraviews::train_motion consist_views::motion_of(std::vector 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->MoverParameters->Dim.W; + 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)); @@ -231,10 +232,10 @@ cameraviews::placement consist_views::place_shunting(TCamera const &Camera, std: auto const pose{pose_of(m_vehicle)}; auto length{0.0}; for (auto const *vehicle : Train) { - length += vehicle->MoverParameters->Dim.L; + 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->MoverParameters->CabOccupied)}; + auto const facing{cameraviews::driving_facing(m_vehicle->VectorFront(), Driven->VectorFront(), Driven->physics->CabOccupied())}; return cameraviews::topdown_placement(m_topdown, pose, facing); } diff --git a/application/consistviews.h b/application/consistviews.h index 1c86345c0..d5bf6641e 100644 --- a/application/consistviews.h +++ b/application/consistviews.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include "physics/vehicletypes.h" #include "vehicle/cameraviews.h" @@ -51,7 +52,7 @@ private: // 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, int End); + 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); diff --git a/application/driverhints.cpp b/application/driverhints.cpp index cd1967aa2..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,7 @@ 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: { @@ -795,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 } @@ -805,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; @@ -835,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 ) { @@ -850,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 ) { @@ -866,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 } @@ -884,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(); @@ -898,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(); @@ -960,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 @@ -1026,257 +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( AIControllFlag ) { - mvOccupied->PermitDoorStep( true ); + if( aiControlled ) { + occupied->PermitDoorStep( true ); } remove_hint( driver_hint::doorstepoff ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->Doors.step_enabled == true; } ); + return occupied->Doors.step_enabled == true; } ); break; } case driver_hint::doorstepoff: { - if( AIControllFlag ) { - mvOccupied->PermitDoorStep( false ); + if( aiControlled ) { + occupied->PermitDoorStep( false ); } remove_hint( driver_hint::doorstepon ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->Doors.step_enabled == false; } ); + 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 ); @@ -1284,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 ); @@ -1297,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 ); @@ -1314,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 ); @@ -1343,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/drivermode.cpp b/application/drivermode.cpp index e76baec1c..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 } @@ -786,7 +789,7 @@ void driver_mode::update_camera(double const Deltatime) { // 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)) @@ -798,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(); @@ -806,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()))}; @@ -866,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; @@ -874,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(); } @@ -1191,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) @@ -1202,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; @@ -1241,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; @@ -1255,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 @@ -1271,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; @@ -1285,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 @@ -1299,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; @@ -1313,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 @@ -1381,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/driveruipanels.cpp b/application/driveruipanels.cpp index d7d9d6bca..ede3f887e 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -34,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" @@ -54,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 }; } @@ -81,12 +82,12 @@ 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_movers( - *mover, + auto const readout { drivingaid::compute( drivingaid::from_vehicles( + *physics, *vehicledriver->Controlling(), drivingaid::cab_controls { train->ggLocalBrake.SubModel != nullptr, @@ -97,7 +98,7 @@ drivingaid_panel::update() { 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(), @@ -121,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() ); @@ -133,9 +134,9 @@ drivingaid_panel::update() { STR_C("Throttle: %3d+%d %c%s"), readout.throttle_first, readout.throttle_second, - mover->SpeedCtrlUnit.IsActive ? 'T' : - mover->DirActive > 0 ? 'D' : - mover->DirActive < 0 ? 'R' : + physics->SpeedCtrlUnit.IsActive ? 'T' : + physics->DirActive > 0 ? 'D' : + physics->DirActive < 0 ? 'R' : 'N', expandedtext.c_str()); @@ -148,8 +149,8 @@ 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(); } if( readout.ed_percent ) { @@ -166,7 +167,7 @@ drivingaid_panel::update() { STR_C("Brakes: %5.1f+%-2.0f%c%s"), readout.brake_first, readout.local_brake, - mover->SlippingWheels ? '!' : ' ', + physics->SlippingWheels() ? '!' : ' ', expandedtext.c_str() ); } else { @@ -175,7 +176,7 @@ drivingaid_panel::update() { m_buffer.data(), m_buffer.size(), STR_C("Brakes: %5.1f%c%s"), readout.brake_first, - mover->SlippingWheels ? '!' : ' ', + physics->SlippingWheels() ? '!' : ' ', expandedtext.c_str() ); } @@ -205,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 ); } @@ -221,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); @@ -231,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(); @@ -385,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(), @@ -451,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 ) : @@ -536,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 @@ -617,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()); } @@ -787,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 ); @@ -815,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 ); @@ -887,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() }; @@ -908,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(); } @@ -922,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(); } @@ -961,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, @@ -979,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 @@ -1006,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(); } @@ -1032,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 ) { @@ -1053,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; @@ -1073,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; } } @@ -1085,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 += @@ -1109,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 ); } @@ -1144,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 ) { @@ -1165,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 @@ -1217,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 ) { @@ -1252,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 ); @@ -1262,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 ); @@ -1613,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( @@ -1631,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 { @@ -1669,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; @@ -1744,7 +1740,7 @@ 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; 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 d9b1d4311..7531d5d2b 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -22,6 +22,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 @@ -5868,7 +5870,7 @@ bool editor_mode::enter_cab(TDynamicObject &Vehicle) if ((Vehicle.mdKabina == nullptr) || (Vehicle.mdKabina == Vehicle.mdModel)) return false; // in the seat of the driver, looking ahead from the cab taken - auto const side{Vehicle.MoverParameters->CabOccupied < 0 ? -1.0 : 1.0}; + auto const side{Vehicle.OccupiedCab() < 0 ? -1.0 : 1.0}; auto const look{Vehicle.VectorFront() * side}; Camera.Pos = Vehicle.GetWorldPosition(train->pMechSittingPosition); Camera.Angle = glm::vec3(0.0f, static_cast(std::atan2(-look.x, -look.z)), 0.0f); @@ -7721,7 +7723,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; 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/editormodeselftestscene.cpp b/application/editormodeselftestscene.cpp index bf3419574..2f1c2554c 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/editoruimodel.cpp b/application/editoruimodel.cpp index b2f80a48b..f71da8046 100644 --- a/application/editoruimodel.cpp +++ b/application/editoruimodel.cpp @@ -2419,7 +2419,7 @@ void eu07m_model_panel::fly_to_vehicle(TDynamicObject const &Vehicle) const { if (focus != nullptr) { - focus(Vehicle.GetPosition(), std::max(5.0, Vehicle.MoverParameters->Dim.L * vehicle_focus)); + focus(Vehicle.GetPosition(), std::max(5.0, Vehicle.GetLength() * vehicle_focus)); } } diff --git a/audio/sound.cpp b/audio/sound.cpp index 426ee3cc4..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 ) diff --git a/directoryDescription.md b/directoryDescription.md index 77d571771..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)| diff --git a/docs/eu07m-format.md b/docs/eu07m-format.md index 6a89e9d7b..87bd5f515 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -201,11 +201,18 @@ of the game, the folders of a family are 7% to 38% of their size with their shar packed with zstd when it saves an eighth, and the index: entries of 40 B (`u64 × 2` id, `u64` offset, `u32` size in the file, `u32` size unpacked, `u32` flags (0x1 zstd), `u32` 0), sorted by the id. - **In a model file,** `GREF` names the primitives kept in the store. The writer leaves their vertex and index ranges out of the - streams of the file; the reader takes their blocks from the store, checks the id and the counts of each, and puts them back in - their places, so the model in memory always has its whole streams and nothing past the reader knows the difference. A model - with references and no store, or a block which isn't the one referred to, is refused with the reason in the log. `GREF` is a + streams of the file; the reader takes their blocks from the store by their ids, checks the counts of each, and puts them back + in their places, so the model in memory always has its whole streams and nothing past the reader knows the difference. The + bytes of a block are hashed again and compared with its id only when the content of the file is checked too (`verify_hash`, + the tools); the game goes by the id and the counts. A model with references and no store, or a block which isn't the one + referred to, is refused with the reason in the log. `GREF` is a required section, so a reader which doesn't know it refuses the file rather than reading short streams. -- **The game** opens the store of a folder once and keeps it, reading the blocks from it as the models ask for them. +- **The game** keeps the store of a folder open, with the size and the time of its file, and reads the blocks from it as the + models ask for them; a store whose file changed (packed again while the game runs) is opened again. A store which can't be + opened is logged once per folder, with the reason. +- **Settled before the data is packed:** the id of a block (two FNV-1a 64) is part of the format. A change of it is a new major + version and a repack of every store, so it is to be decided before the stores go into the SVN; the order of the blocks in a + store (now by id) and reading a model's blocks at once are free to change, as the index finds a block wherever it lies. - **The tools.** `eu07 -eu07m pack [minimum bytes]` moves every block of at least the minimum (4096 by default) which occurs more than once in the models of the folder into its store, made anew from all of them, and writes the models again referring to it; each model is read back and compared with what it was before it's replaced. `eu07 -eu07m unpack ` @@ -367,7 +374,11 @@ parts of a node without a track stay as in its TRS. nodes, as apart from what an instance sets as it's drawn the nodes are kept by the submodels all the instances share. Each time the instance is drawn, `RaPrepare()` samples the clips and sets the transforms of the nodes (`TSubModel::SetClipTransform()`, the animation `at_Clip`) before the animations of the events: an animation event of the scenery moving a node (`rotate`, - `translate`...) takes it over from a clip, one which ended or was stopped included. The nodes the clips move are flagged + `translate`...) takes it over from a clip, one which ended or was stopped included. The takeover is for good: the container + of such an event sets its node again at every draw for as long as it lives, so a clip or a channel started later on that node + doesn't show for that instance. Leave the nodes a model's clips and channels move to them, and the others to the events of the + scenery. A node whose matrix (`XFRM`) is sheared loses the shear once a clip moves it, as a node's TRS can't hold one; keep the + nodes the tracks of a clip move free of shear. The nodes the clips move are flagged animated at load, so a model with clips isn't instanced. A clip moving the joints of a skin bends the skinned parts (see "Skinning"). - The TRS fields of a node with a matrix (`XFRM`) are only an approximation of it: the parts the tracks of a clip don't move are 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/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/ubo.h b/gl/ubo.h index 17f13e927..c31016021 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; @@ -691,13 +737,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 @@ -716,10 +781,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}; @@ -735,7 +814,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 @@ -758,14 +840,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/drivermouseinput.cpp b/input/drivermouseinput.cpp index 47105ac22..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 }; @@ -32,7 +34,7 @@ mouse_slider::bind( user_command const &Command ) { 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: @@ -61,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 @@ -69,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; 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 fed6a38c5..e9673d1b0 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -15904,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)" diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 21f52b2b9..2522970ce 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -27,6 +27,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; @@ -581,6 +582,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 b39e4d927..83cd73e33 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" #include @@ -127,6 +128,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.h b/model/Model3d.h index 743274cb6..df9f6c8d8 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 "model/skinning.h" #include "model/clip.h" @@ -288,7 +287,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/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/model/skinning.cpp b/model/skinning.cpp index 4e346b8f4..3333072a7 100644 --- a/model/skinning.cpp +++ b/model/skinning.cpp @@ -119,10 +119,17 @@ glm::vec3 direction(glm::mat3 const &Rotation, glm::vec3 const &Vector) // what moves the normals: the inverse transpose of the rotation, here as its cofactors (the same direction, without the // division), with the sign of the determinant so a mirroring matrix keeps the normals facing out. the rotation itself would // tilt the normals of a part squashed by a scale -glm::mat3 normal_matrix(glm::mat3 const &Rotation) +glm::mat3 normal_matrix(glm::mat3 const &Rotation, bool const Mirrors) { glm::mat3 const cofactors{glm::cross(Rotation[1], Rotation[2]), glm::cross(Rotation[2], Rotation[0]), glm::cross(Rotation[0], Rotation[1])}; - return glm::dot(Rotation[0], cofactors[0]) < 0.f ? -cofactors : cofactors; + return Mirrors ? -cofactors : cofactors; +} + +// the rotation turns the space inside out (a negative determinant): the normals take the sign, and so does the handedness of +// the tangent frame, or the bitangent rebuilt from the normal and the tangent points the other way +bool mirrors(glm::mat3 const &Rotation) +{ + return glm::dot(Rotation[0], glm::cross(Rotation[1], Rotation[2])) < 0.f; } } // namespace @@ -142,8 +149,9 @@ void skin_vertices(std::span const Rest, std::span -#include "MOVER.h" +#include "physics/vehicle.h" #include "utilities/utilities.h" //---FUNKCJE OGOLNE--- diff --git a/McZapkie/hamulce.h b/physics/brakes.h similarity index 99% rename from McZapkie/hamulce.h rename to physics/brakes.h index 2b08e1f63..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*/ diff --git a/McZapkie/collision.cpp b/physics/collision.cpp similarity index 99% rename from McZapkie/collision.cpp rename to physics/collision.cpp index 2fb085e69..2dd3af62c 100644 --- a/McZapkie/collision.cpp +++ b/physics/collision.cpp @@ -8,13 +8,13 @@ http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" -#include "collision.h" +#include "physics/collision.h" #include #include #include -#include "derailment.h" +#include "physics/derailment.h" namespace collision { diff --git a/McZapkie/collision.h b/physics/collision.h similarity index 99% rename from McZapkie/collision.h rename to physics/collision.h index 01239a3cd..9b9258169 100644 --- a/McZapkie/collision.h +++ b/physics/collision.h @@ -12,11 +12,11 @@ http://mozilla.org/MPL/2.0/. #include #include -#include "couplerphysics.h" -#include "derailment.h" +#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 -// TMoverParameters::CollisionDetect()), as plain functions of the vehicles and the hit: +// 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 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..a3819786f --- /dev/null +++ b/physics/components/fizparser.cpp @@ -0,0 +1,1341 @@ +/* +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; + } + parser >> WiperList[idx].byteSum >> WiperList[idx].WiperSpeed >> WiperList[idx].interval >> WiperList[idx].outBackDelay; + 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 99% rename from McZapkie/couplerphysics.cpp rename to physics/couplerphysics.cpp index 31afd26fe..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 diff --git a/McZapkie/couplerphysics.h b/physics/couplerphysics.h similarity index 99% rename from McZapkie/couplerphysics.h rename to physics/couplerphysics.h index 8d7f9b06e..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 diff --git a/McZapkie/derailment.cpp b/physics/derailment.cpp similarity index 87% rename from McZapkie/derailment.cpp rename to physics/derailment.cpp index e9cfa452e..b6962caaf 100644 --- a/McZapkie/derailment.cpp +++ b/physics/derailment.cpp @@ -8,7 +8,7 @@ http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" -#include "derailment.h" +#include "physics/derailment.h" #include #include @@ -282,4 +282,43 @@ std::string report(verdict const &Verdict, vehicle_state const &Vehicle, track_s 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/McZapkie/derailment.h b/physics/derailment.h similarity index 82% rename from McZapkie/derailment.h rename to physics/derailment.h index 50a3d84cb..d29fbc852 100644 --- a/McZapkie/derailment.h +++ b/physics/derailment.h @@ -16,7 +16,7 @@ http://mozilla.org/MPL/2.0/. // 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 TMoverParameters::check_derailment()). two ways off the rails: +// (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. @@ -112,7 +112,7 @@ struct vehicle_state { std::array ends{}; }; -// the dtrack_* flags of the track (MOVER.h) the criteria look at +// 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}; @@ -226,4 +226,33 @@ std::optional climbing_speed(vehicle_state const &Vehicle, track_state c // 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/rendering/common/locallights.cpp b/rendering/common/locallights.cpp index ff6b1465e..3a7349209 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 @@ -266,6 +267,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); } @@ -280,6 +284,7 @@ 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 *) @@ -373,7 +378,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; @@ -737,7 +742,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() @@ -751,6 +756,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/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/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 033df86ba..10064734d 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -187,16 +187,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( @@ -289,19 +289,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 ) { @@ -1989,8 +1989,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) @@ -2015,8 +2015,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 }, {} ); @@ -2249,6 +2249,37 @@ gfx::geometry_handle scene_walk::submodel_geometry(TSubModel *Submodel) return gfx::skin_cache::instance().geometry(*Submodel, *TSubModel::pRoot, m_framestamp); } +// 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"); @@ -2420,7 +2451,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) { @@ -3225,8 +3256,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 174d96bca..443bfa9e9 100644 --- a/rendering/common/scenewalk.h +++ b/rendering/common/scenewalk.h @@ -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" @@ -165,6 +166,8 @@ class scene_walk void Render(TSubModel *Submodel); // the geometry a submodel is drawn with: its own, or for a skinned one that of the instance drawn (gfx::skin_cache) gfx::geometry_handle submodel_geometry(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. @@ -180,7 +183,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); diff --git a/rendering/common/scenewalkindirect.cpp b/rendering/common/scenewalkindirect.cpp index 4cba1742c..c4c74551a 100644 --- a/rendering/common/scenewalkindirect.cpp +++ b/rendering/common/scenewalkindirect.cpp @@ -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(); @@ -867,9 +868,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/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/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/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 6dabd2c7b..1d4b55fe9 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" @@ -30,7 +31,20 @@ http://mozilla.org/MPL/2.0/. #include "rendering/screenshot.h" #include "rendering/editoroverlay.h" #include "rendering/common/skincache.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 @@ -1683,16 +1697,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]) { @@ -1701,10 +1776,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 @@ -1712,14 +1789,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 @@ -1730,11 +1809,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) @@ -1804,16 +1897,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) { @@ -1913,6 +2008,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); @@ -2124,7 +2220,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()); } @@ -2271,6 +2367,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; @@ -2298,6 +2398,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 @@ -2316,6 +2420,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"); @@ -2352,6 +2460,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) @@ -3284,7 +3393,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) @@ -3519,6 +3640,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]); @@ -4087,8 +4226,11 @@ opengl46_renderer::indirect_counts opengl46_renderer::Render_Instances_Indirect_ ++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() ) ) : @@ -4100,7 +4242,8 @@ 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; } multidrawprogram->bind(); @@ -4111,8 +4254,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; @@ -4177,7 +4322,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() ) ); @@ -4189,6 +4341,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 @@ -4256,8 +4437,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 ); @@ -5168,28 +5350,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() @@ -6041,6 +6304,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) { @@ -6762,7 +7026,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}; @@ -6854,7 +7118,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); @@ -6870,6 +7140,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); diff --git a/rendering/opengl46/opengl46renderer.h b/rendering/opengl46/opengl46renderer.h index 5f5ec776a..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: @@ -413,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 @@ -651,6 +659,9 @@ 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 @@ -864,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; @@ -874,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/opengl46water.cpp b/rendering/opengl46/opengl46water.cpp index a48b9edfb..980e779df 100644 --- a/rendering/opengl46/opengl46water.cpp +++ b/rendering/opengl46/opengl46water.cpp @@ -10,6 +10,7 @@ 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" @@ -25,64 +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 namespace { -// the programs of the passes, in their order (opengl46_windscreen_water::pass) -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"}; +// 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 + { + gl::shader shader(PROGRAM_NAMES[Index]); + m_programs[Index] = std::make_unique(std::vector>{shader}); + return true; + } + catch (gl::shader_exception const &e) + { + 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"); - auto const missing{std::ranges::find_if(m_programs, [](std::unique_ptr const &Program) { return Program == nullptr; })}; - if (missing == m_programs.end()) - return false; - auto const index{static_cast(std::distance(m_programs.begin(), missing))}; - try + for (std::size_t index = 0; index < PROGRAM_NAMES.size(); ++index) { - gl::shader shader(PROGRAM_NAMES[index]); - *missing = std::make_unique(std::vector>{shader}); + 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)); } - catch (gl::shader_exception const &e) + // 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) { - // left to gpu_init(), which tells of it and goes without the simulation - ErrorLog("windscreen water: " + std::string(PROGRAM_NAMES[index]) + " not made ahead: " + std::string(e.what())); - return false; + make_rain_cells_program(); + return true; } - return true; + return false; } bool opengl46_windscreen_water::gpu_init() { - try + // the ones made ahead (prepare_next()) are kept + for (std::size_t i = 0; i < PROGRAM_NAMES.size(); ++i) { - // 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)) { - if (m_programs[i]) - continue; - gl::shader shader(PROGRAM_NAMES[i]); - m_programs[i] = std::make_unique(std::vector>{shader}); + ErrorLog("windscreen water: can't use the programs of the simulation"); + return false; } } - catch (gl::shader_exception const &e) - { - ErrorLog("windscreen water: can't use the programs of the simulation: " + std::string(e.what())); - 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) @@ -96,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); } @@ -104,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); @@ -117,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) @@ -133,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 f609291c9..db914fb93 100644 --- a/rendering/opengl46/opengl46water.h +++ b/rendering/opengl46/opengl46water.h @@ -25,18 +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; } + 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 @@ -51,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/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/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/vulkan14context.h b/rendering/vulkan14/vulkan14context.h index b0adb8392..6bef028aa 100644 --- a/rendering/vulkan14/vulkan14context.h +++ b/rendering/vulkan14/vulkan14context.h @@ -521,6 +521,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; diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 1bc026f4b..3ad8b3f60 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -393,7 +393,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); } @@ -1136,6 +1137,10 @@ void vulkan14_renderer::render_scene() 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()); @@ -1565,16 +1570,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]) { @@ -1583,10 +1649,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 @@ -1594,14 +1662,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 @@ -1668,7 +1738,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})))}; @@ -1718,6 +1789,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) @@ -1753,6 +1825,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); @@ -1970,8 +2043,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()}; @@ -2451,6 +2525,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)}); @@ -2474,6 +2552,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)}); } @@ -2498,6 +2579,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) { @@ -2662,6 +2747,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 @@ -3798,10 +3884,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) @@ -4161,7 +4250,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}; diff --git a/rendering/vulkan14/vulkan14indirect.cpp b/rendering/vulkan14/vulkan14indirect.cpp index 48f5d5d5d..e6536bd84 100644 --- a/rendering/vulkan14/vulkan14indirect.cpp +++ b/rendering/vulkan14/vulkan14indirect.cpp @@ -664,7 +664,11 @@ 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)}; + // 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) @@ -678,12 +682,24 @@ vulkan14_renderer::indirect_counts vulkan14_renderer::draw_indirect_shadow(vk14: { // 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); } 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/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index c28460167..bf2f4dedc 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -432,6 +432,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); @@ -576,6 +578,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 diff --git a/rendering/vulkan14/vulkan14scene.cpp b/rendering/vulkan14/vulkan14scene.cpp index 7ccf9599f..cffe8029f 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -24,6 +24,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/color.h" #include "utilities/utilities.h" +#include "vehicle/DynObj.h" #include #include @@ -192,6 +193,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: @@ -1104,6 +1106,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; @@ -1139,6 +1142,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])); @@ -1465,10 +1469,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 @@ -1477,10 +1485,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) @@ -1684,6 +1733,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 @@ -1693,6 +1748,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) { diff --git a/rendering/vulkan14/vulkan14shaders.cpp b/rendering/vulkan14/vulkan14shaders.cpp index b0101f9eb..7f6326901 100644 --- a/rendering/vulkan14/vulkan14shaders.cpp +++ b/rendering/vulkan14/vulkan14shaders.cpp @@ -898,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); @@ -930,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); @@ -969,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/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/scene.cpp b/scene/scene.cpp index 506b52d67..03b10d8f1 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -24,6 +24,8 @@ http://mozilla.org/MPL/2.0/. #include "rendering/renderer.h" #include "widgets/map_objects.h" #include "vehicle/aiwire.h" +#include "physics/vehicle.h" +#include "vehicle/DynObj.h" #include @@ -129,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 ); 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/scenenode.cpp b/scene/scenenode.cpp index afe87cf83..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 ) { @@ -124,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 ); } @@ -318,6 +349,8 @@ shape_node::import_from( 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; } @@ -776,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 d0246adc1..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 { @@ -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/sceneterrain.cpp b/scene/sceneterrain.cpp index 585912a2b..4248d4592 100644 --- a/scene/sceneterrain.cpp +++ b/scene/sceneterrain.cpp @@ -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/scripting/lua.cpp b/scripting/lua.cpp index 2011413b5..93e542742 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -7,6 +7,7 @@ #include "simulation/simulation.h" #include "scripting/luasandbox.h" #include "utilities/utilities.h" +#include "physics/vehicle.h" lua::lua() { @@ -350,7 +351,7 @@ 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; } 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 b24be60dc..724e1d9b8 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; @@ -373,6 +384,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/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_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/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 9eb2fcdf7..fab9b129b 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/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_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/skin.comp b/shaders/vk14/skin.comp index 7f5d8846e..ce2e8e5b6 100644 --- a/shaders/vk14/skin.comp +++ b/shaders/vk14/skin.comp @@ -65,10 +65,14 @@ void main() vec3 position = (blended * vec4(source.position_u.xyz, 1.0)).xyz; mat3 rotation = mat3(blended); // the normals by the cofactors of the rotation (the direction of its inverse transpose), with the sign of its determinant, - // as skinning::skin_vertices() moves them on the cpu + // as skinning::skin_vertices() moves them on the cpu; a mirroring rotation turns the handedness of the tangent frame as well mat3 cofactors = mat3(cross(rotation[1], rotation[2]), cross(rotation[2], rotation[0]), cross(rotation[0], rotation[1])); + float handedness = source.tangent.w; if (dot(rotation[0], cofactors[0]) < 0.0) + { cofactors = -cofactors; + handedness = -handedness; + } vec3 normal = skin_direction(cofactors, source.normal_v.xyz); vec3 tangent = skin_direction(rotation, source.tangent.xyz); uint target = (skin_counts.y + index) * 12u; @@ -83,5 +87,5 @@ void main() skin_output[target + 8u] = tangent.x; skin_output[target + 9u] = tangent.y; skin_output[target + 10u] = tangent.z; - skin_output[target + 11u] = source.tangent.w; + skin_output[target + 11u] = handedness; } 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/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 e4161ce61..15c326a49 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/physicslog.h" #include "utilities/utilities.h" #include "world/stationnames.h" +#include "physics/vehicle.h" #include #include @@ -65,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: @@ -108,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 @@ -119,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 @@ -205,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; @@ -224,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; } @@ -414,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}; @@ -423,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); } @@ -527,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; @@ -581,7 +582,7 @@ void blackbox_recorder::look_at_derailments() { for (auto *vehicle : simulation::Vehicles.sequence()) { if (false == vehicle->bEnabled) continue; - auto const &motion{vehicle->MoverParameters->OffTrack}; + auto const &motion{vehicle->physics->OffTrack}; auto const id{vehicle_id(vehicle)}; auto &entry{m_vehicles[vehicle]}; if (false == motion.active()) { @@ -597,7 +598,7 @@ void blackbox_recorder::look_at_derailments() { 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->MoverParameters->V * 3.6); + 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()); @@ -616,12 +617,12 @@ void blackbox_recorder::look_at_couplers() { 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}; @@ -645,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; @@ -763,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; } diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 2eb0a3c89..a63ddfc03 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 { @@ -243,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(); } } @@ -311,7 +312,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,11 +436,11 @@ void state_manager::process_commands() { while (vehicle) { // no damage, back on the rails with the state of the derailment cleared - vehicle->MoverParameters->repair_damage(); - vehicle->MoverParameters->V = 0.000001; // HACK: force vehicle position re-calculation - vehicle->MoverParameters->DistCounter = 0.0; - vehicle->MoverParameters->OffsetTrackH = 0.0; - vehicle->MoverParameters->OffsetTrackV = 0.0; + 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 ) { @@ -460,13 +461,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) { @@ -496,7 +497,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(); } @@ -509,7 +510,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 c1fad53ae..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; } @@ -578,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 ); } } @@ -1477,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( @@ -1624,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 @@ -1691,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 f6e2a4a39..a247918aa 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -188,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/tests/scenarios/README.md b/tests/scenarios/README.md index 529fefea6..9712b2f46 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -395,6 +395,15 @@ on level ground, on an embankment 4 m high and in a cutting, made of triangle st 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 @@ -613,8 +622,8 @@ 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 | -| `baltyk_skm1_roj55321_departure` | #525 | passes, with three seeds: the unit in the platform leaves at 10:34 | +| `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 | diff --git a/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json b/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json index 98b9c8119..3a820f17a 100644 --- a/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json +++ b/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json @@ -1,8 +1,8 @@ { - "description": "eu07/maszyna#525, Baltyk skm1, the mission that starts in the platform of Baltyk Glowny (EN71-014ra, ROJ55321, departure 10:34): the exit signal has to clear and the unit has to leave. Standing for 10 minutes ends the test as standstill.", + "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": "EN71-014ra", + "vehicle": "EN57AL-1230ra", "slow": true, "physicslog": false, "ini": [ diff --git a/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json b/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json index a8fa0e7cc..343b431d4 100644 --- a/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json +++ b/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json @@ -1,8 +1,8 @@ { - "description": "eu07/maszyna#525, Baltyk skm1, the mission that starts on the siding of Baltyk Towarowy next to the shunter (EN90-009A, ROJ55324): 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.", + "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": "EN90-009A", + "vehicle": "ED78-019A", "slow": true, "physicslog": false, "ini": [ 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/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/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 347e359e6..44684b79b 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -47,6 +47,17 @@ add_executable(${UNIT_TESTS_NAME} # 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) diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index 71870c892..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`. @@ -95,7 +95,7 @@ The per-file table further down is from the run before the tests of the parser, | 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 | @@ -153,7 +153,7 @@ The tests are written for the first two columns, and for what the game doesn't c **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()`. @@ -163,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`). 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 1f22632e6..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); } } @@ -84,8 +84,8 @@ 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) { @@ -96,11 +96,11 @@ void consist::step(track const &Track, double Dt) { void consist::update_brake_pipes(double Dt) const { // vehicle_table::update_brake_pipes() - std::vector movers; + std::vector vehicles; for (auto const &vehicle : m_vehicles) { - movers.push_back(&vehicle->mover()); + vehicles.push_back(&vehicle->physics()); } - TMoverParameters::UpdatePipeCouplers(movers, Dt); + physics::Vehicle::UpdatePipeCouplers(vehicles, Dt); } void consist::run(double Seconds, track const &Track, double Dt) { @@ -111,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 2c982e446..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(); } @@ -49,7 +49,7 @@ private: 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/drive.cpp b/tests/unit/drive.cpp index 02fc74c03..524a9e39a 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -4,7 +4,7 @@ #include "golden.h" #include "doctest.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include "vehicle/fieldshunting.h" namespace test { @@ -15,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(); } } @@ -62,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); @@ -74,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); } @@ -85,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 { @@ -108,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 @@ -131,7 +131,7 @@ 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 } } @@ -140,16 +140,16 @@ void close_line_breaker(driven const &Driven) { // 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(TMoverParameters &Cab) { +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)) { + if (Cab.EngineType == TEngineType::DieselElectric && fieldshunting::has_switch(Cab.AutoRelayType(), Cab.FieldShuntSwitch())) { Cab.AutoRelaySwitch(true); } } @@ -174,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(); @@ -184,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 { @@ -210,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); @@ -248,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/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 index d8444d7e5..c3ecc2fb0 100644 --- a/tests/unit/test_6dg_power_steps.cpp +++ b/tests/unit/test_6dg_power_steps.cpp @@ -27,17 +27,17 @@ definition shipped() { void move_to(vehicle &Loco, int const Position) { // one notch at a time, as far as the controller goes - while (Loco->MainCtrlPos < Position) { + while (Loco->MainCtrlPos() < Position) { if (false == Loco->IncMainCtrl(1)) { break; } } - while (Loco->MainCtrlPos > Position) { + while (Loco->MainCtrlPos() > Position) { if (false == Loco->DecMainCtrl(1)) { break; } } - REQUIRE(Loco->MainCtrlPos == Position); + REQUIRE(Loco->MainCtrlPos() == Position); } // the 6Dg started up (engine running), its brakes released and its direction set, its controller holding no power @@ -52,17 +52,17 @@ void get_ready(vehicle &Loco, test::track const &Track) { 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->BrakePress > 0.1; ++second) { + for (int second = 0; second < 180 && Loco->brakes.cylinderPressure > 0.1; ++second) { test::drive(driven, Track, 1.0); } - REQUIRE(Loco->BrakePress <= 0.1); + 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->Mains); // the engine running - REQUIRE(Loco->StLinFlag); // the line contactors closed + 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)); } @@ -100,7 +100,7 @@ TEST_CASE("6Dg: the shipped definition sets the controller's power demand in ste 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)); + 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}; @@ -120,7 +120,7 @@ TEST_CASE("6Dg: the shipped definition sets the controller's power demand in ste CAPTURE(i); CHECK(loco->eimic == doctest::Approx(std::min(top, before + 0.05))); CHECK(loco->eimic <= top + 1e-9); - CHECK(loco->eimic_real == doctest::Approx(loco->eimic)); // the demand reaching the drive + 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); @@ -178,9 +178,9 @@ TEST_CASE("6Dg: the diesel-electric drive follows the stepped demand") { loco.step(line); } REQUIRE(loco->eimic == doctest::Approx(0.05 * taps)); - REQUIRE(loco->eimic_real == 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->eimic_real, loco->enrot, std::abs(loco->Ft), loco->EnginePower, std::abs(loco.speed())); + 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 @@ -200,7 +200,7 @@ TEST_CASE("6Dg: the diesel-electric drive follows the stepped demand") { 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); + REQUIRE(loco->UniCtrlValStep() == 0.0); get_ready(loco, line); // a tap moves it by 0.01 only tap(loco, raise, line); 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_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_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 f74edfc03..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); @@ -281,12 +281,12 @@ struct st113_sample { std::vector st113_run() { test::reseed_random(); vehicle real{definition::fiz("en57_v1/6bai")}; - REQUIRE(real->BrakeHandle == TBrakeHandle::St113); - REQUIRE(real->Handle != nullptr); - real.hold_main_reservoir(std::max(real->MaxCompressor, 8.0)); - auto &handle{*real->Handle}; + 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->PipePress, real->BrakePress, handle.GetEP()}); }}; + 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) { diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp index 664f7262d..e1281992b 100644 --- a/tests/unit/test_brake_pipe.cpp +++ b/tests/unit/test_brake_pipe.cpp @@ -1,12 +1,12 @@ #include "stdafx.h" #include "doctest.h" -#include "McZapkie/MOVER.h" -#include "McZapkie/hamulce.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 (TMoverParameters::UpdatePipeCouplers()). +// 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 @@ -22,8 +22,8 @@ void freight_train(test::consist &Train, int const Wagons) { for (int i = 0; i < Wagons; ++i) { auto &wagon{Train.add(definition::fiz("3wl_v2/3wl"))}; wagon->BrakeDelaySwitch(bdelay_G); - REQUIRE(wagon->BrakeValve == TBrakeValve::ESt3); - REQUIRE(wagon->Spg == doctest::Approx(0.792)); // the pipe of a freight wagon + 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 } @@ -33,7 +33,7 @@ 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->Spg == doctest::Approx(0.507)); // the pipe of a passenger car + REQUIRE(car->brakes.config.pipeSection == doctest::Approx(0.507)); // the pipe of a passenger car } Train[0].hold_brake_pipe(5.0); } @@ -42,10 +42,10 @@ void passenger_train(test::consist &Train, int const Cars) { // 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->PipePress}; + auto const start{last->brakePipe.Pressure()}; Train[0].hold_brake_pipe(Pressure); auto time{0.0}; - while (last->PipePress > start - 0.5 && time < 60.0) { + while (last->brakePipe.Pressure() > start - 0.5 && time < 60.0) { Train.step({}, Dt); time += Dt; } @@ -70,13 +70,13 @@ TEST_CASE("brake pipe: the distributors of a standing freight train see the pres train.run(300.0); for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); - auto &wagon{train[i].mover()}; + 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.Hamulec->GetVRP() - wagon.PipePress) < 0.005); - CHECK(wagon.PipePress > 4.9); + 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.Hamulec->GetBrakeStatus() & (b_on | b_hld)) == 0); - CHECK(wagon.BrakePress < 0.1); + 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); @@ -105,10 +105,10 @@ TEST_CASE("brake pipe: a passenger train, whose exchange was stable in one step, train.run(300.0); for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); - auto &car{train[i].mover()}; - CHECK(std::abs(car.Hamulec->GetVRP() - car.PipePress) < 0.005); - CHECK((car.Hamulec->GetBrakeStatus() & (b_on | b_hld)) == 0); - CHECK(car.BrakePress < 0.1); + 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)}; diff --git a/tests/unit/test_brake_setting.cpp b/tests/unit/test_brake_setting.cpp index 39b0e2117..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,58 +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(Shunt, false)); - CHECK(brake_setting::inspects_train(Loose_shunt, false)); - CHECK(brake_setting::inspects_train(Obey_train, false)); - CHECK(brake_setting::inspects_train(Bank, false)); + 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(Connect, false)); - CHECK(brake_setting::inspects_train(Connect | Change_direction, false)); + 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(Connect, true)); - CHECK(false == brake_setting::inspects_train(Connect | Change_direction, true)); + 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(Obey_train | Connect, true)); - CHECK(brake_setting::inspects_train(Shunt, true)); + 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(Wait_for_orders, false)); - CHECK(false == brake_setting::inspects_train(Prepare_engine, false)); - CHECK(false == brake_setting::inspects_train(Release_engine, false)); - CHECK(false == brake_setting::inspects_train(Change_direction, false)); - CHECK(false == brake_setting::inspects_train(Disconnect, false)); - CHECK(false == brake_setting::inspects_train(Jump_to_first_order, false)); + 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") { @@ -506,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 cd2a95a3c..bd93b8ca6 100644 --- a/tests/unit/test_brakes.cpp +++ b/tests/unit/test_brakes.cpp @@ -17,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") { @@ -36,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)}; @@ -55,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); } } @@ -102,42 +102,42 @@ 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); } } @@ -165,16 +165,16 @@ TEST_CASE("brakes: a wagon standing braked on a gradient sleeps while the brakes wagon->DecManualBrakeLevel(ManualBrakePosNo); wagon.hold_brake_pipe(3.5); wagon.run(30.0, slope); - REQUIRE(wagon->BrakePress > 1.0); + REQUIRE(wagon->brakes.cylinderPressure > 1.0); CHECK(std::abs(wagon.speed()) < 0.01); - CHECK_FALSE(wagon->PhysicActivation); + 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}; + auto const asleep{false == wagon->PhysicActivation()}; wagon.step(slope); - if (asleep && wagon->PhysicActivation) { + if (asleep && wagon->PhysicActivation()) { ++wakes; } } @@ -184,10 +184,10 @@ TEST_CASE("brakes: a wagon standing braked on a gradient sleeps while the brakes // 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->BrakePress < 0.1); - CHECK(wagon->Fb < 1.0); + CHECK(wagon->brakes.cylinderPressure < 0.1); + CHECK(wagon->Fb() < 1.0); CHECK(std::abs(wagon.speed()) > 1.0); - CHECK(wagon->PhysicActivation); + 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") { @@ -197,15 +197,15 @@ TEST_CASE("brakes: a wagon held by its hand brake on a gradient wakes and rolls slope.gradient = 0.01; vehicle wagon{definition::load("wagon")}; // made standing, it has the hand brake on (SetBraked()) - REQUIRE(wagon->ManualBrakePos == ManualBrakePosNo); + REQUIRE(wagon->brakes.HandBrakePosition() == ManualBrakePosNo); wagon.hold_brake_pipe(5.0); wagon.run(90.0, slope); - REQUIRE(wagon->BrakePress < 0.1); + REQUIRE(wagon->brakes.cylinderPressure < 0.1); CHECK(std::abs(wagon.speed()) < 0.01); - CHECK_FALSE(wagon->PhysicActivation); + CHECK_FALSE(wagon->PhysicActivation()); wagon->DecManualBrakeLevel(ManualBrakePosNo); wagon.run(30.0, slope); - CHECK(wagon->Fb < 1.0); + 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 6bcf92fc7..f542ec27c 100644 --- a/tests/unit/test_braking_curve.cpp +++ b/tests/unit/test_braking_curve.cpp @@ -228,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 index 684fadb56..c0a75978d 100644 --- a/tests/unit/test_camera.cpp +++ b/tests/unit/test_camera.cpp @@ -9,6 +9,7 @@ #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 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_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 index 6aee28e98..e63cb6c71 100644 --- a/tests/unit/test_collisions.cpp +++ b/tests/unit/test_collisions.cpp @@ -3,8 +3,8 @@ #include "consist.h" #include "drive.h" #include "vehicle.h" -#include "McZapkie/collision.h" -#include "McZapkie/MOVER.h" +#include "physics/collision.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include @@ -12,7 +12,7 @@ #include #include -// collisions past the buffers with physics.collisions new (McZapkie/collision.h): the crush of the ends, the override, +// 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; @@ -111,12 +111,12 @@ cl::crush_curve const locomotive_curve{cl::default_crush(cl::vehicle_kind::locom // ---- trains of real vehicles -bool derailed(TMoverParameters const &Vehicle) { - return TestFlag(Vehicle.DamageFlag, dtrain_out); +bool derailed(physics::Vehicle const &Vehicle) { + return Vehicle.DamageFlag.HasAll(VehicleDamage::derailed); } -double crush_of(TMoverParameters const &Vehicle) { - return std::max(Vehicle.Couplers[end::front].crush, Vehicle.Couplers[end::rear].crush); +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 @@ -125,8 +125,8 @@ 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, int const Coupling, double const Velocity, double const Gap) { - auto &wagon{Train.add(mixed_wagon(Index), 0, Coupling, Velocity, Gap)}; +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(); @@ -162,7 +162,7 @@ crash_outcome freight_crash(double const Speed, double const Radius, double cons } 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::faux, Speed, 1.0); + 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); } @@ -170,9 +170,9 @@ crash_outcome freight_crash(double const Speed, double const Radius, double cons crash_outcome result; for (std::size_t i = 0; i < train.size(); ++i) { - auto const &vehicle{train[i].mover()}; + 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 : {end::front, end::rear}) { + for (auto const end : VehicleEnds) { if (vehicle.Couplers[end].crush >= cl::crush_mark) { ++result.crushed; } @@ -180,17 +180,17 @@ crash_outcome freight_crash(double const Speed, double const Radius, double cons 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.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"); + 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[end::rear].broken; + result.broken += train[i]->Couplers[VehicleEnd::rear].broken; } return result; } @@ -202,24 +202,24 @@ double locomotive_into_wagon(double const Speed, double const Dt) { 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::faux, Speed, 0.5)}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, Speed, 0.5)}; train.run(3.0, {}, Dt); - return wagon->Couplers[end::rear].crush + locomotive->Couplers[end::front].crush; + 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(TMoverParameters const &First, int const FirstEnd, TMoverParameters const &Second, int const SecondEnd) { +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(TMoverParameters const &First, int const FirstEnd, TMoverParameters const &Second, int const SecondEnd) { +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(TMoverParameters const &First, TMoverParameters const &Second, double const Velocity) { - auto const mass{First.TotalMass * Second.TotalMass / (First.TotalMass + Second.TotalMass)}; +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; } @@ -235,13 +235,13 @@ struct contact_outcome { 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::faux, Speed, Gap)}; + auto &back{train.add(Back, 0, Coupling::none, Speed, Gap)}; train.run(Seconds, {}, Dt); contact_outcome result; - result.crush = front->Couplers[end::rear].crush + back->Couplers[end::front].crush; - result.energy = crush_energy(front.mover(), end::rear, back.mover(), end::front); - result.available = std::max(0.0, relative_energy(front.mover(), back.mover(), Speed * kmh) - capacity_of(front.mover(), end::rear, back.mover(), end::front)); - result.derailed = derailed(front.mover()) || derailed(back.mover()); + 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; } @@ -251,23 +251,23 @@ definition coach(double const 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(TMoverParameters const &Vehicle, int const End, double const OtherLength, double const Radius) { +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.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; + 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 == end::front ? -1.0 : 1.0) * Vehicle.Couplers[End].CForce); + 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, int const Coupling, double const Velocity, double const Gap) { - auto &wagon{Train.add(definition::fiz("430w_v2/430w"), 0, Coupling, Velocity, Gap)}; +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; @@ -473,11 +473,11 @@ TEST_CASE("collisions: an empty two-axle wagon between loaded ones in a curve of 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.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; + 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; @@ -502,11 +502,11 @@ TEST_CASE("collisions: an empty two-axle wagon between loaded ones in a curve of // the loaded wagon, four axles, takes it cl::pushed_vehicle heavy; - heavy.mass = loaded->TotalMass - loaded->Mred + 59.5e3; - heavy.axles = loaded->NAxles; + 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; + heavy.pivots = loaded->BDist(); + heavy.axle_base = loaded->ADist(); end.force = 600.0e3; CHECK(cl::pushed_ratio(heavy, end, 150.0) < 0.5); @@ -579,24 +579,24 @@ TEST_CASE("collisions: a locomotive at its starting effort against a braked trai train[i].hold_brake_pipe(0.0); } train.run(30.0, line); - auto &locomotive{train.add(definition::fiz("st44_v2/m62-1151"), 1, coupling::faux, 0.0, 0.0)}; - test::driven const driver{locomotive.mover(), locomotive.mover(), locomotive.mover(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; + 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.mover()); + 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 const start{empty->DistCounter()}; auto pushed{0.0}; auto worst{0.0}; auto const watch = [&]() { - pushed = std::max(pushed, -locomotive->Couplers[end::front].CForce); - worst = std::max(worst, pushed_ratio_of(empty.mover(), end::rear, locomotive->Dim.L, line.radius)); + 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->StLinFlag; ++i) { + 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) { @@ -608,12 +608,12 @@ TEST_CASE("collisions: a locomotive at its starting effort against a braked trai test::drive(driver, line, 1.0); watch(); } - auto const rolled{(empty->DistCounter - start) * 1000.0}; + 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.mover())); - CHECK(empty->CollisionDerail == NONE); + 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") { @@ -625,14 +625,14 @@ TEST_CASE("collisions: a locomotive running onto an empty wagon at 9 km/h doesn' 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::faux, 9.0, 0.5)}; + 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[end::rear].CForce); - auto const ratio{pushed_ratio_of(empty.mover(), end::rear, locomotive->Dim.L, curve.radius)}; + 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; } @@ -640,8 +640,8 @@ TEST_CASE("collisions: a locomotive running onto an empty wagon at 9 km/h doesn' empty.speed())); REQUIRE(worst >= derailment::climbing_limit); REQUIRE(over >= 5); - CHECK_FALSE(derailed(empty.mover())); - CHECK_FALSE(derailed(locomotive.mover())); + 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") { @@ -661,16 +661,16 @@ TEST_CASE("collisions: a train propelling an empty wagon into a braked one in a train[i].hold_brake_pipe(0.0); } train.run(30.0, curve); - auto &empty{train.add(definition::fiz("3wl_v2/3wl"), 0, coupling::faux, 15.0, 1.0)}; + 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}; + auto const start{empty->DistCounter()}; train.run(10.0, curve); - MESSAGE(std::format("the empty 3WL: derailed {}, {}, rolled {:.2f} m", derailed(empty.mover()), empty->CollisionDerail == COLLISION_PUSHED_OFF ? "pushed off" : "not pushed off", - (empty->DistCounter - start) * 1000.0)); - CHECK(empty->CollisionDerail == COLLISION_PUSHED_OFF); + 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 @@ -681,20 +681,20 @@ TEST_CASE("collisions: a repaired vehicle has its ends rebuilt and is back on th 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::faux, 0.0, 0.0)}; - auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 30.0, 0.5)}; + 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[end::rear].crush + locomotive->Couplers[end::front].crush > cl::override_crush); - REQUIRE((derailed(wagon.mover()) || derailed(locomotive.mover()))); + 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 &mover{vehicle->mover()}; - mover.repair_damage(); - CHECK(mover.DamageFlag == 0); - CHECK(mover.Derailed == derailment::outcome::none); - CHECK(mover.CollisionDerail == NONE); - CHECK(mover.pushed_off_monitor.distance() == 0.0); - CHECK(mover.pushed_off_monitor.time() == 0.0); - for (auto const &coupler : mover.Couplers) { + 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); @@ -708,27 +708,27 @@ TEST_CASE("collisions: a repaired vehicle has its ends rebuilt and is back on th 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[end::rear]}; + auto &coupler{wagon->Couplers[VehicleEnd::rear]}; coupler.crush = 0.3; coupler.broken = true; coupler.hit_force = 2.0e6; - SetFlag(wagon->DamageFlag, dtrain_coupling); - REQUIRE(wagon->repair_coupler(end::rear)); + 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(TestFlag(wagon->DamageFlag, dtrain_coupling)); + 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("SetDamage", dtrain_out, -1); - CHECK(wagon->CollisionDerail == NONE); - CHECK(wagon->Derailed == derailment::outcome::none); - CHECK_FALSE(TestFlag(wagon->DamageFlag, dtrain_out)); + 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 @@ -764,11 +764,11 @@ TEST_CASE("collisions: the legacy rule with physics.collisions old, the crush wi model_setting const setting{model}; consist train; train.add(definition::fiz(front)); - train.add(definition::fiz(back), 0, coupling::faux, speed, 20.0); + train.add(definition::fiz(back), 0, Coupling::none, speed, 20.0); train.run(10.0); - CHECK(derailed(train[0].mover()) == (physical ? frontout_new : frontout_old)); - CHECK(derailed(train[1].mover()) == (physical ? backout_new : backout_old)); - auto const crush{train[0]->Couplers[end::rear].crush + train[1]->Couplers[end::front].crush}; + 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); @@ -776,7 +776,7 @@ TEST_CASE("collisions: the legacy rule with physics.collisions old, the crush wi else { CHECK(crush == 0.0); } - CHECK(train[0]->crush_reports + train[1]->crush_reports == (model == global_settings::collision_model::monitor ? monitored : 0)); + CHECK(train[0]->crush_reports() + train[1]->crush_reports() == (model == global_settings::collision_model::monitor ? monitored : 0)); } } } @@ -805,10 +805,10 @@ TEST_CASE("collisions: the model of the collisions goes apart from the one of th model_setting const setting{collisions}; consist train; train.add(definition::fiz("4e_v1/4e")); - train.add(definition::fiz("4e_v1/4e"), 0, coupling::faux, 25.0, 20.0); + 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[end::rear].crush + train[1]->Couplers[end::front].crush}; + 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)); } } @@ -844,33 +844,33 @@ TEST_CASE("collisions: the crush of a locomotive hitting a wagon doesn't depend 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)}; + 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, end::front, standing, end::rear, 1.0}; + 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(end::front, standing.mover(), end::rear)}; + auto const closing{moving->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::rear)}; pair.step(); - fast = fast || (pair.coupled() && false == coupled && closing > TMoverParameters::SafeCollisionVelocity); + fast = fast || (pair.coupled() && false == coupled && closing > physics::Vehicle::SafeCollisionVelocity); coupled = coupled || pair.coupled(); } - auto const crush{moving->Couplers[end::front].crush + standing->Couplers[end::rear].crush}; - MESSAGE(speed, " km/h: crush ", crush, " m, derailed ", derailed(moving.mover()), " ", derailed(standing.mover()), ", coupled later ", 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[end::front].crush, standing->Couplers[end::rear].crush) >= cl::draw_gear_crush) { + if (std::max(moving->Couplers[VehicleEnd::front].crush, standing->Couplers[VehicleEnd::rear].crush) >= cl::draw_gear_crush) { CHECK_FALSE(coupled); - CHECK((moving->Couplers[end::front].broken || standing->Couplers[end::rear].broken)); + 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.mover()) == derailed(standing.mover())); - CHECK(derailed(moving.mover()) == (crush > cl::override_both)); + CHECK(derailed(moving.physics()) == derailed(standing.physics())); + CHECK(derailed(moving.physics()) == (crush > cl::override_both)); } } @@ -882,13 +882,13 @@ TEST_CASE("collisions: road vehicles keep the legacy rule") { model_setting const setting{model}; consist road; road.add(definition::fiz("road/man/nl293")); - road.add(definition::fiz("road/man/nl293"), 0, coupling::faux, 40.0, 5.0); + road.add(definition::fiz("road/man/nl293"), 0, Coupling::none, 40.0, 5.0); road.run(5.0); - CHECK(derailed(road[0].mover())); - CHECK(derailed(road[1].mover())); - CHECK(road[0]->Couplers[end::rear].crush == 0.0); - CHECK(road[1]->CollisionDerail == NONE); - CHECK(road[0]->crush_reports + road[1]->crush_reports == 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); } } @@ -897,13 +897,13 @@ TEST_CASE("collisions: a vehicle off the rails by the new model stays in the cha 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::faux, 10.0, 0.5)}; + 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.mover())); - auto const before{wagon->TotalMass * wagon->V + locomotive->TotalMass * locomotive->V}; + 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}; + 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); @@ -946,7 +946,7 @@ TEST_CASE("collisions: identical units built to EN 15227 at 36 km/h") { consist train; train.add(unit(Anticlimbers, 1.040)); train.add(unit(Anticlimbers, 1.040)); - train.add(unit(Anticlimbers, 1.040 + Offset), 0, coupling::faux, Speed, 1.0); + 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 { @@ -954,10 +954,10 @@ TEST_CASE("collisions: identical units built to EN 15227 at 36 km/h") { double inner; int derailed; bool higher; - } result{train[1]->Couplers[end::rear].crush + train[2]->Couplers[end::front].crush, std::max(crush_of(train[0].mover()), crush_of(train[3].mover())), 0, - derailed(train[2].mover())}; + } 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].mover()); + result.derailed += derailed(train[i].physics()); } return result; }; @@ -997,9 +997,9 @@ TEST_CASE("collisions: the buffers of EN 15551 of an end take in their energy, o 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[end::front].collision.buffers.has_value()); - CHECK(*wagon->Couplers[end::front].collision.buffers == cl::buffer_category::B); - CHECK(cl::buffer_capacity(wagon->Couplers[end::rear].collision, wagon->collision_kind()) == doctest::Approx(100.0e3)); + 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") { @@ -1136,7 +1136,7 @@ TEST_CASE("collisions: two locomotives (117 t and 84 t) touching at walking spee auto const sm42{definition::fiz("sm42_v1/6d1")}; { vehicle check{su45}; - CHECK(check->TotalMass == doctest::Approx(117.0e3).epsilon(0.02)); + CHECK(check->TotalMass() == doctest::Approx(117.0e3).epsilon(0.02)); } for (auto const physics : {false, true}) { CAPTURE(physics); @@ -1184,8 +1184,8 @@ TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor 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)); + 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); @@ -1204,11 +1204,11 @@ TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor consist train; auto &wall{train.add(light)}; wall->Derail(END_OF_TRACK); - REQUIRE(derailed(wall.mover())); - auto &running{train.add(heavy, 0, coupling::faux, 5.0, gap)}; + REQUIRE(derailed(wall.physics())); + auto &running{train.add(heavy, 0, Coupling::none, 5.0, gap)}; train.run(5.0); - CHECK(wall->Couplers[end::rear].crush + running->Couplers[end::front].crush == 0.0); - CHECK(running->CollisionDerail == NONE); + CHECK(wall->Couplers[VehicleEnd::rear].crush + running->Couplers[VehicleEnd::front].crush == 0.0); + CHECK(running->CollisionDerail() == NONE); } } @@ -1231,10 +1231,10 @@ TEST_CASE("collisions: a locomotive pushing a standing braked train at full powe } 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::faux, 0.0, 0.0)}; - test::driven const driver{locomotive.mover(), locomotive.mover(), locomotive.mover(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; + 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.mover()); + test::release_brakes(locomotive.physics()); for (int i = 0; i < 3 && locomotive->DirActive <= 0; ++i) { locomotive->DirectionForward(); } @@ -1242,13 +1242,13 @@ TEST_CASE("collisions: a locomotive pushing a standing braked train at full powe 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[end::front].CForce)}; + 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->StLinFlag; ++i) { + 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) { @@ -1265,8 +1265,8 @@ TEST_CASE("collisions: a locomotive pushing a standing braked train at full powe CHECK(seconds >= 55); for (std::size_t i = 0; i < train.size(); ++i) { CAPTURE(i); - CHECK(crush_of(train[i].mover()) == 0.0); - CHECK_FALSE(derailed(train[i].mover())); + CHECK(crush_of(train[i].physics()) == 0.0); + CHECK_FALSE(derailed(train[i].physics())); } } } @@ -1298,16 +1298,16 @@ TEST_CASE("collisions: the monitor goes by the energy of the hit as well") { CAPTURE(gap); consist train; train.add(definition::fiz("sm42_v1/6d1")); - train.add(definition::fiz("su45_v2/301d"), 0, coupling::faux, 5.8, gap); + 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); + 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::faux, 25.0, 20.0); + 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); + 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 @@ -1326,17 +1326,17 @@ struct train_damage { train_damage damage_of(consist &Train) { train_damage result; for (std::size_t i = 0; i < Train.size(); ++i) { - auto const &vehicle{Train[i].mover()}; + auto const &vehicle{Train[i].physics()}; result.crush = std::max(result.crush, crush_of(vehicle)); - for (auto const end : {end::front, end::rear}) { + for (auto const end : VehicleEnds) { result.energy += vehicle.crush_curve_at(end).energy(0.0, vehicle.Couplers[end].crush); } - result.derailed += vehicle.CollisionDerail != NONE; + result.derailed += vehicle.CollisionDerail() != NONE; if (i + 1 < Train.size()) { - result.broken += vehicle.Couplers[end::rear].broken; + 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" : ""); + 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; @@ -1346,7 +1346,7 @@ train_damage damage_of(consist &Train) { 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; + energy += 0.5 * Train[i]->TotalMass() * Train[i]->V() * Train[i]->V(); } return energy; } @@ -1370,7 +1370,7 @@ TEST_CASE("collisions: the cut of the speed of the legacy derailment is no hit i for (auto const reason : {TOO_HIGH_SPEED, END_OF_TRACK}) { CAPTURE(reason); consist train; - auto &locomotive{train.add(definition::fiz(path), 0, coupling::faux, speed)}; + 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); } @@ -1382,7 +1382,7 @@ TEST_CASE("collisions: the cut of the speed of the legacy derailment is no hit i locomotive->Derail(reason); } train.step(); - REQUIRE(derailed(locomotive.mover())); + REQUIRE(derailed(locomotive.physics())); // the train loses the speed with it for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); @@ -1415,7 +1415,7 @@ TEST_CASE("collisions: the train behind a vehicle that ran off the end of the tr auto const speed{pushed ? 33.0 : 30.0}; consist train; if (false == pushed) { - train.add(definition::fiz("st44_v2/m62-1151"), 0, coupling::faux, speed); + train.add(definition::fiz("st44_v2/m62-1151"), 0, Coupling::none, speed); } constexpr int wagons{6}; for (int i = 0; i < wagons; ++i) { @@ -1432,7 +1432,7 @@ TEST_CASE("collisions: the train behind a vehicle that ran off the end of the tr auto const kinetic{kinetic_of(train)}; train[0].damage_track(dtrack_norail); train.run(20.0); - REQUIRE(derailed(train[0].mover())); + 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)); @@ -1442,7 +1442,7 @@ TEST_CASE("collisions: the train behind a vehicle that ran off the end of the tr CHECK(damage.broken == 0); for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); - CHECK_FALSE(derailed(train[i].mover())); + CHECK_FALSE(derailed(train[i].physics())); } } } @@ -1477,7 +1477,7 @@ TEST_CASE("collisions: a pair parting at the start of the step isn't crushed (l0 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::faux, parting ? -3.0 : 0.0, -0.3)}; + 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}; @@ -1487,16 +1487,16 @@ TEST_CASE("collisions: a pair parting at the start of the step isn't crushed (l0 for (auto *vehicle : {&front, &back}) { vehicle->forces(dt); } - REQUIRE((front->Couplers[end::rear].closing < 0.0) == parting); - back->V = 25.0 * kmh; + 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); + vehicle->move({}, dt, (*vehicle)->Loc(), 5.0); } - auto const crush{front->Couplers[end::rear].crush + back->Couplers[end::front].crush}; + 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); + CHECK(back->V() < 25.0 * kmh); } else { // closing in from a stand, the knock is a hit past the energy of the buffers 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 index bff60e440..8724a135b 100644 --- a/tests/unit/test_compartment_lights.cpp +++ b/tests/unit/test_compartment_lights.cpp @@ -20,32 +20,32 @@ void lights_check(vehicle &Car) { 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->Power24vIsAvailable = false; - car->Power110vIsAvailable = false; + 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->Power110vIsAvailable = true; // converter on + car->lowVoltage.Set110vAvailableForTest(true); // converter on lights_check(car); CHECK(car->CompartmentLights.is_active); CHECK(car->CompartmentLights.intensity == doctest::Approx(1.0)); - car->Power110vIsAvailable = false; // battery only: the lights stay on, dimmed - car->Power24vIsAvailable = true; + 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->Power24vIsAvailable = false; // no power at all + 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->Power110vIsAvailable = true; + car->lowVoltage.Set110vAvailableForTest(true); lights_check(car); CHECK_FALSE(car->CompartmentLights.is_active); // manual start: off until switched on @@ -68,13 +68,13 @@ TEST_CASE("compartment lights: the off switch turns the lights off, the on switc 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->Power24vIsAvailable = false; - car->Power110vIsAvailable = false; + car->lowVoltage.Set24vAvailableForTest(false); + car->lowVoltage.Set110vAvailableForTest(false); lights_check(car); CHECK_FALSE(car->CompartmentLights.is_active); - car->Power110vIsAvailable = true; + 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 index b9ba78398..0433c1d1f 100644 --- a/tests/unit/test_compartment_lights_switch.cpp +++ b/tests/unit/test_compartment_lights_switch.cpp @@ -117,7 +117,7 @@ void toggle(vehicle &Car, cab_controls const &Cab) { // 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->Power110vIsAvailable = true; + Car->lowVoltage.Set110vAvailableForTest(true); lights_check(Car); REQUIRE_FALSE(Car->CompartmentLights.is_active); } 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 ba9404482..4f754d0fc 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -3,7 +3,7 @@ #include "scenario.h" #include "drive.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include "utilities/Globals.h" #include "utilities/utilities.h" @@ -33,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); } @@ -43,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); @@ -62,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; } @@ -100,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); @@ -136,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(); @@ -177,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(); } @@ -211,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)); @@ -222,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)); @@ -241,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)); @@ -259,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")); @@ -301,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); @@ -320,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(); } @@ -337,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); @@ -368,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(); } @@ -395,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)); @@ -403,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 @@ -437,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"); @@ -456,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(); } @@ -477,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(); @@ -508,14 +508,14 @@ TEST_CASE("controls: a locomotive running into a standing wagon") { 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(); } @@ -552,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(); } @@ -600,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 19421c52b..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 @@ -70,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") { @@ -85,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") { @@ -95,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") { @@ -105,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 @@ -116,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") { @@ -134,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") { @@ -162,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 @@ -183,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 @@ -218,7 +218,7 @@ TEST_CASE("couplers: a wagon hitting a standing one too fast doesn't couple, nor 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}; @@ -227,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; } } @@ -253,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(); @@ -285,7 +285,7 @@ TEST_CASE("couplers: a hit a little too fast for the couplers bounces the vehicl 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)); @@ -301,7 +301,7 @@ TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over t 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)); @@ -309,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)); @@ -317,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)); @@ -325,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)); @@ -339,7 +339,7 @@ TEST_CASE("couplers: wagons running head-on into each other couple only up to th 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)); @@ -347,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)); @@ -358,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); @@ -366,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)); @@ -380,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(); @@ -398,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); @@ -415,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)); } } @@ -451,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); } } @@ -487,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)); @@ -511,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); @@ -531,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); @@ -560,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 @@ -581,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"}}; @@ -597,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); } } @@ -638,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); }; @@ -646,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); } @@ -664,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 cbe002bb1..a98d9bd08 100644 --- a/tests/unit/test_couplers_trains.cpp +++ b/tests/unit/test_couplers_trains.cpp @@ -33,79 +33,79 @@ private: 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") { @@ -115,51 +115,51 @@ 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") { @@ -184,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 index d70cbfb4e..74edbe7ce 100644 --- a/tests/unit/test_crew.cpp +++ b/tests/unit/test_crew.cpp @@ -3,7 +3,7 @@ #include "consist.h" #include "drive.h" -#include "McZapkie/hamulce.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 @@ -31,10 +31,10 @@ void get_under_way(consist &Train, int const Position, double const Seconds) { } test::drive(driver, line, 20.0); driver.controlling.IncMainCtrl(1); - for (int i = 0; i < 90 && false == driver.controlling.StLinFlag; ++i) { + 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) { + for (int i = 0; i < 60 && driver.controlling.MainCtrlPos() < Position; ++i) { driver.controlling.IncMainCtrl(1); test::drive(driver, line, 1.0); } @@ -191,29 +191,29 @@ TEST_CASE("crew: a locomotive under power left by its driver stops and stays bra consist train; train.add(definition::fiz("4e_v1/4e"), 1); get_under_way(train, 20, 30.0); - auto &eu07{train[0].mover()}; + auto &eu07{train[0].physics()}; REQUIRE(train[0].speed() > 20.0); - REQUIRE(eu07.MainCtrlPos > 0); - REQUIRE(eu07.Mains); + REQUIRE(eu07.MainCtrlPos() > 0); + REQUIRE(eu07.lineBreaker.IsClosed()); crew::secure(eu07, eu07); - CHECK(eu07.MainCtrlPos == eu07.MainCtrlNoPowerPos()); - CHECK(eu07.ScndCtrlPos == 0); - CHECK(eu07.BrakeCtrlPos == static_cast(eu07.Handle->GetPos(bh_EB))); + 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); + 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.PipePress < 1.0); // vented by the emergency position - CHECK(eu07.BrakePress > 2.0); + 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.Mains); + CHECK(eu07.lineBreaker.IsClosed()); CHECK(eu07.Im == doctest::Approx(0.0)); } @@ -221,17 +221,17 @@ 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->WarningSignal = 1; + cab->SetWarningSignal(1); cab->signal_departure(true); cab->Sandbox(true); - REQUIRE(cab->DepartureSignal); - REQUIRE(cab->SandDose); + REQUIRE(cab->DepartureSignal()); + REQUIRE(cab->SandDose()); - crew::secure(cab.mover(), cab.mover()); + crew::secure(cab.physics(), cab.physics()); - CHECK(cab->WarningSignal == 0); - CHECK_FALSE(cab->DepartureSignal); - CHECK_FALSE(cab->SandDose); + 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") { @@ -241,10 +241,10 @@ TEST_CASE("crew: a train left by its driver is braked through the whole of it") 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].mover()}; - auto &last{train[2].mover()}; + auto &eu07{train[0].physics()}; + auto &last{train[2].physics()}; REQUIRE(train[0].speed() > 15.0); - REQUIRE(last.BrakePress < 0.1); + REQUIRE(last.brakes.cylinderPressure < 0.1); crew::secure(eu07, eu07); @@ -252,8 +252,8 @@ TEST_CASE("crew: a train left by its driver is braked through the whole of it") CAPTURE(stoppedafter); CHECK(std::abs(train[0].speed()) <= 0.01); CHECK(std::abs(train[2].speed()) <= 0.01); - CHECK(last.PipePress < 1.0); - CHECK(last.BrakePress > 1.0); + 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") { @@ -263,18 +263,18 @@ TEST_CASE("crew: a standing locomotive left by its driver is braked too") { auto driver{test::driving(train)}; REQUIRE(test::start_up(driver, line)); test::release_brakes(driver.cab); - auto &eu07{train[0].mover()}; + 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.BrakePress >= 0.1; ++i) { + for (int i = 0; i < 180 && eu07.brakes.cylinderPressure >= 0.1; ++i) { test::drive(driver, line, 1.0); } - REQUIRE(eu07.BrakePress < 0.1); + 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.BrakePress > 2.0); + CHECK(eu07.brakes.cylinderPressure > 2.0); CHECK(std::abs(train[0].speed()) <= 0.01); } @@ -284,30 +284,30 @@ TEST_CASE("crew: the power an integrated handle asked for goes when the driver l // 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->MainCtrlPos = impuls->MainCtrlPosNo; + impuls->SetMainCtrlPos(impuls->MainCtrlPosNo); impuls->eimic = 0.8; - impuls->eimic_real = 0.8; + impuls->SetEimicReal(0.8); - crew::secure(impuls.mover(), impuls.mover()); + crew::secure(impuls.physics(), impuls.physics()); - CHECK(impuls->MainCtrlPos == impuls->MainCtrlNoPowerPos()); + CHECK(impuls->MainCtrlPos() == impuls->MainCtrlNoPowerPos()); CHECK(impuls->eimic == 0.0); - CHECK(impuls->eimic_real == 0.0); - CHECK(impuls->BrakeCtrlPos == static_cast(impuls->Handle->GetPos(bh_EB))); - CHECK(impuls->CabOccupied == 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->BrakeSystem == TBrakeSystem::Individual); - REQUIRE(bus->LocalBrakePosA == 0.0); + REQUIRE(bus->brakes.config.kind == TBrakeSystem::Individual); + REQUIRE(bus->brakes.IndependentPosition() == 0.0); bus->CabActivisation(); - crew::secure(bus.mover(), bus.mover()); + crew::secure(bus.physics(), bus.physics()); - CHECK(bus->LocalBrakePosA == 1.0); - CHECK(bus->MainCtrlPos == bus->MainCtrlNoPowerPos()); + 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 index 5423f2400..2d3a7f1af 100644 --- a/tests/unit/test_derail_motion.cpp +++ b/tests/unit/test_derail_motion.cpp @@ -2,8 +2,8 @@ #include "doctest.h" #include "vehicle.h" #include "vehicle/derailmotion.h" -#include "McZapkie/derailment.h" -#include "McZapkie/MOVER.h" +#include "physics/derailment.h" +#include "physics/vehicle.h" #include "utilities/Globals.h" #include @@ -14,7 +14,7 @@ #include // a vehicle off the rails moving on the ground by itself (physics.derailment new): vehicle/derailmotion.h, and what -// the vehicle of TMoverParameters makes of it +// the vehicle of physics::Vehicle makes of it using test::definition; using test::vehicle; @@ -102,7 +102,7 @@ struct outcome { double lying_at{-1.0}; // the time it came to lie on its side, -1 never }; -// the vehicle slides as TMoverParameters drives it: its speed along the heading falls with the friction of the motion +// 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; @@ -416,49 +416,49 @@ TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment n 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); + 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); + 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}; + auto const start{eu07vehicle->V()}; for (int step = 0; step < 20; ++step) { eu07vehicle.step(curve); } - auto const deceleration{(start - eu07vehicle->V) / 0.2}; + 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); + 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(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); - CHECK(eu07vehicle->Derailed == dr::outcome::off_rails); - CHECK(eu07vehicle->DerailCause == dm::cause::end_of_track); + 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(TestFlag(pulled->DamageFlag, dtrain_out)); - CHECK(pulled->Derailed == dr::outcome::off_rails); - CHECK(pulled->DerailCause == dm::cause::pulled_off); - CHECK(pulled->DerailSide == -1); + 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); + CHECK(pulled->DerailCause() == dm::cause::off_rails); + CHECK(pulled->DerailAcceleration() == 0.0); + CHECK(pulled->DerailSide() == 0); } } @@ -473,22 +473,22 @@ TEST_CASE("derail motion: with physics.derailment monitor and old the vehicle st for (int step = 0; step < 600; ++step) { fast.step(curve); } - REQUIRE(TestFlag(fast->DamageFlag, dtrain_out)); - CHECK(fast->Derailed == dr::outcome::none); + 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)); + 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(TestFlag(ending->DamageFlag, dtrain_out)); - CHECK(ending->Derailed == dr::outcome::none); + 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(TestFlag(pulled->DamageFlag, dtrain_out)); + CHECK_FALSE(pulled->DamageFlag.HasAll(VehicleDamage::derailed)); } } @@ -522,7 +522,7 @@ struct car { double gap{0.0}; // of the coupling behind it }; -// the train of bodies off the track on level ground as TMoverParameters and TDynamicObject drive it: their buffers and +// 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) { @@ -838,7 +838,7 @@ TEST_CASE("derail motion: the scatter") { namespace { -// a body off the track and the speed its vehicle goes with along its heading, as TMoverParameters keeps it +// 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}; diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp index 3afca6a26..cb23a5c5e 100644 --- a/tests/unit/test_derailment.cpp +++ b/tests/unit/test_derailment.cpp @@ -1,11 +1,11 @@ #include "stdafx.h" #include "doctest.h" -#include "McZapkie/derailment.h" +#include "physics/derailment.h" #include #include -// the criteria of derailment (McZapkie/derailment.h): overturning by the lateral acceleration the cant doesn't +// 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; @@ -343,3 +343,159 @@ TEST_CASE("derailment: the report of the log") { 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 index 99b6c0417..9a3e857f1 100644 --- a/tests/unit/test_derailment_vehicle.cpp +++ b/tests/unit/test_derailment_vehicle.cpp @@ -1,14 +1,14 @@ #include "stdafx.h" #include "doctest.h" #include "vehicle.h" -#include "McZapkie/derailment.h" -#include "McZapkie/MOVER.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 McZapkie/derailment.h checked by -// TMoverParameters::check_derailment(), and what the vehicle comes to off the rails +// 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; @@ -47,8 +47,8 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { for (int step = 0; step < 300; ++step) { eu07vehicle.step(curve); } - CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); - CHECK(eu07vehicle->Derailed == dr::outcome::none); + 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}; @@ -57,21 +57,21 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { for (int step = 0; step < 10; ++step) { eu07vehicle.step(curve); } - REQUIRE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); - CHECK(eu07vehicle->Derailed == dr::outcome::overturned); - CHECK_FALSE(eu07vehicle->Mains); + 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}; + 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}; + 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)); + 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}; @@ -79,7 +79,7 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { for (int step = 0; step < 50; ++step) { high.step(curve); } - CHECK(high->Derailed == dr::outcome::overturned); + 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}) { @@ -89,12 +89,12 @@ TEST_CASE("derailment: a vehicle too fast in a curve") { for (auto step = 0; step < steps; ++step) { eu07vehicle.step(curve, dt); } - CHECK(eu07vehicle->Derailed == dr::outcome::overturned); + 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); + CHECK(slower->Derailed() == dr::outcome::none); } } SUBCASE("a load raises the centre of gravity") { @@ -116,7 +116,7 @@ TEST_CASE("derailment: the model of eu07.ini") { for (int step = 0; step < 300; ++step) { eu07vehicle.step(curve); } - CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + 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}; @@ -125,23 +125,23 @@ TEST_CASE("derailment: the model of eu07.ini") { eu07vehicle.step(curve); } // far over its threshold the draw comes out at once - CHECK(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); - CHECK(eu07vehicle->Derailed == dr::outcome::none); - CHECK(eu07vehicle->V == doctest::Approx(0.0).epsilon(0.01)); + 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[end::rear].CouplingFlag = coupling::coupler | coupling::brakehose; + 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->AlarmChainFlag); + REQUIRE(eu07vehicle->Derailed() == dr::outcome::overturned); + CHECK(eu07vehicle->brakes.alarmChain); } TEST_CASE("derailment: a stopped derailed vehicle stays put on a gradient") { @@ -155,12 +155,12 @@ TEST_CASE("derailment: a stopped derailed vehicle stays put on a gradient") { for (int step = 0; step < 2000; ++step) { eu07vehicle.step(curve); } - REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); - REQUIRE(eu07vehicle->V == 0.0); + 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; + still = still && eu07vehicle->V() == 0.0 && eu07vehicle->AccS() == 0.0; } CHECK(still); } @@ -177,24 +177,24 @@ TEST_CASE("derailment: a repaired vehicle is back on the rails") { for (int step = 0; step < 2000; ++step) { repaired.step(curve); } - REQUIRE(repaired->Derailed == dr::outcome::overturned); - REQUIRE(repaired->V == 0.0); + REQUIRE(repaired->Derailed() == dr::outcome::overturned); + REQUIRE(repaired->V() == 0.0); repaired->repair_damage(); - CHECK(repaired->DamageFlag == 0); - CHECK(repaired->Derailed == dr::outcome::none); - CHECK(repaired->derailment_distance == 0.0); - CHECK(repaired->OffsetTrackH == 0.0); - CHECK(repaired->OffsetTrackV == 0.0); + 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->V = fresh->V; - repaired->AccS = 0.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(repaired->Derailed() == dr::outcome::none); + auto const start{fresh->V()}; REQUIRE(start > 10.0); for (int step = 0; step < 150; ++step) { repaired.step(straight); @@ -202,8 +202,8 @@ TEST_CASE("derailment: a repaired vehicle is back on the rails") { } // 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)); + 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 @@ -212,16 +212,16 @@ TEST_CASE("derailment: a repaired vehicle is back on the rails") { 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); + 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->V = 150.0 * kmh; + 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); + CHECK(repaired->Derailed() == dr::outcome::overturned); } } @@ -233,14 +233,14 @@ TEST_CASE("derailment: SetDamage taking the derailment off puts the vehicle back for (int step = 0; step < 20; ++step) { eu07vehicle.step(curve); } - REQUIRE(eu07vehicle->Derailed == dr::outcome::overturned); + REQUIRE(eu07vehicle->Derailed() == dr::outcome::overturned); // another flag taken off leaves it derailed - eu07vehicle->RunCommand("SetDamage", dtrain_engine, 1); - eu07vehicle->RunCommand("SetDamage", dtrain_engine, -1); - CHECK(eu07vehicle->Derailed == dr::outcome::overturned); - CHECK(eu07vehicle->RunCommand("SetDamage", dtrain_out, -1)); - CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); - CHECK(eu07vehicle->Derailed == dr::outcome::none); + 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") { @@ -253,13 +253,13 @@ TEST_CASE("derailment: monitor tells again on the same track after a repair") { for (int step = 0; step < 100; ++step) { eu07vehicle.step(curve); } - REQUIRE(eu07vehicle->derailment_reports == 1); + 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); + CHECK(eu07vehicle->derailment_reports() == 2); } TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what the criteria would do") { @@ -274,10 +274,10 @@ TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what t for (int step = 0; step < 100; ++step) { eu07vehicle.step(curve); } - CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); - CHECK(eu07vehicle->Derailed == dr::outcome::none); + 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); + CHECK(eu07vehicle->derailment_reports() == 1); REQUIRE(eu07vehicle->derailment_reported.has_value()); CHECK(*eu07vehicle->derailment_reported == &curve.name); // and once more on the next one @@ -286,24 +286,24 @@ TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what t for (int step = 0; step < 100; ++step) { eu07vehicle.step(next); } - CHECK(eu07vehicle->derailment_reports == 2); - CHECK_FALSE(TestFlag(eu07vehicle->DamageFlag, dtrain_out)); + 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); + 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(TestFlag(faster->DamageFlag, dtrain_out)); - CHECK(faster->Derailed == dr::outcome::none); - CHECK(faster->V == doctest::Approx(0.0).epsilon(0.01)); + CHECK(faster->DamageFlag.HasAll(VehicleDamage::derailed)); + CHECK(faster->Derailed() == dr::outcome::none); + CHECK(faster->V() == doctest::Approx(0.0).epsilon(0.01)); } } @@ -326,3 +326,94 @@ TEST_CASE("derailment: the names of the models in eu07.ini") { } 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 9eff62441..12eae8193 100644 --- a/tests/unit/test_door_wings.cpp +++ b/tests/unit/test_door_wings.cpp @@ -5,7 +5,7 @@ #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 @@ -79,7 +79,7 @@ TEST_CASE("door wings: the kinds of animation are named as DoorOpenMethod of the // 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 TMoverParameters::door_data::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); diff --git a/tests/unit/test_drivingaid.cpp b/tests/unit/test_drivingaid.cpp index b6ae1cc9d..438100981 100644 --- a/tests/unit/test_drivingaid.cpp +++ b/tests/unit/test_drivingaid.cpp @@ -4,7 +4,7 @@ #include "real_vehicles.h" #include "vehicle/drivingaid.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include #include @@ -27,16 +27,16 @@ 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_movers(Vehicle.mover(), Vehicle.mover(), 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(TMoverParameters const &Mover) { +drivingaid::readout before(physics::Vehicle const &Physics) { drivingaid::readout result; - result.throttle_first = Mover.EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * Mover.eimic_real)) : Mover.MainCtrlPos; - result.throttle_second = Mover.EIMCtrlType > 0 ? Mover.MainCtrlPos : Mover.ScndCtrlPos; - result.brake_first = Mover.UniCtrlIntegratedBrakeCtrl ? std::max(0.0, -100.0 * Mover.eimic_real) : Mover.fBrakeCtrlPos; - result.local_brake = Mover.LocalBrakePosA * LocalBrakePosNo; + 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; } @@ -46,13 +46,13 @@ test::track const line{0.15, 0.0, test::catenary_3kv}; 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->SplitEDPneumaticBrake); - REQUIRE(vectron->DynamicBrakeCtrlPosNo == 15); + 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(idle.throttle_first == vectron->MainCtrlPos()); CHECK_FALSE(idle.ed_percent.has_value()); CHECK(idle.show_local_brake); @@ -64,11 +64,11 @@ TEST_CASE("driving aid: the Vectron's ED lever shows as a negative throttle step 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->eimic_real == doctest::Approx(-0.4)); + 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->fBrakeCtrlPos)); + CHECK(braking.brake_first == doctest::Approx(vectron->brakes.HandlePositionSmooth())); CHECK(braking.show_local_brake); CHECK(braking.local_brake == doctest::Approx(0.0)); @@ -79,16 +79,16 @@ TEST_CASE("driving aid: the Vectron's ED lever shows as a negative throttle step 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->SplitEDPneumaticBrake); + REQUIRE_FALSE(traxx->brakes.electrodynamic.splitFromPneumatic); CHECK_FALSE(read(traxx, lever_cab).ed_percent.has_value()); // B+: the braking demand ramps towards full - traxx->MainCtrlPos = 0; + traxx->SetMainCtrlPos(0); traxx.run(3.0, line); - REQUIRE(traxx->eimic_real < -0.2); + 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->eimic_real)); + 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); @@ -99,25 +99,25 @@ TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, 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->LocalBrake == TLocalBrake::PneumaticBrake); + 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->MainCtrlPos = 0; + elf->SetMainCtrlPos(0); elf.run(2.0, line); - REQUIRE(elf->eimic_real < -0.1); + 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->eimic_real)); + 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->LocalBrakePosA = 0.3; + 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)); @@ -125,11 +125,11 @@ TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, 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->MainCtrlPos = 5; - eu07->LocalBrakePosA = 0.2; + 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.throttle_second == eu07->ScndCtrlPos()); CHECK(readout.local_brake == doctest::Approx(2.0)); CHECK(readout.show_local_brake); CHECK_FALSE(readout.ed_percent.has_value()); @@ -161,11 +161,11 @@ TEST_CASE("driving aid: every real vehicle with a local brake control shows the 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->MainCtrlPos = std::min(mainctrl, real->MainCtrlPosNo); - real->LocalBrakePosA = localbrake; - real->eimic_real = eimic; + 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.mover())}; + 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)); diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp index fc3f30f27..d936ea5d1 100644 --- a/tests/unit/test_dynamic_brake_diesel.cpp +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -4,7 +4,7 @@ #include "drive.h" #include "real_vehicles.h" -#include "McZapkie/hamulce.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 @@ -22,9 +22,9 @@ 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.DynamicBrakeFlag ? 1.0 : 0.0; }}, - {"eimic_real", [](auto const &M) { return M.eimic_real; }}, - {"DynamicBrakeCtrlPos", [](auto const &M) { return M.DynamicBrakeCtrlPos; }}, + {"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; }}, }; } @@ -51,17 +51,17 @@ definition st44_braking() { } // the force of the brakes above at full effort at the speed of the vehicle -double br285_limit(TMoverParameters 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 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(TMoverParameters const &Vehicle) { - return std::min(120000.0, 1200000.0 / std::abs(Vehicle.V)) * std::clamp(Vehicle.Vel / 40.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(TMoverParameters &Locomotive, int Position) { - while (Locomotive.MainCtrlPos > Position && Locomotive.DecMainCtrl(1)) {} - while (Locomotive.MainCtrlPos < Position && Locomotive.IncMainCtrl(1)) {} +void controller_to(physics::Vehicle &Locomotive, int Position) { + while (Locomotive.MainCtrlPos() > Position && Locomotive.DecMainCtrl(1)) {} + while (Locomotive.MainCtrlPos() < Position && Locomotive.IncMainCtrl(1)) {} } } // namespace @@ -71,7 +71,7 @@ TEST_CASE("diesel-electric dynamic brake: none without its definition") { for (auto const &path : test::real_vehicles()) { CAPTURE(path); test::vehicle vehicle{definition::fiz(path)}; - CHECK(vehicle->DEDynamicBrake.source == TMoverParameters::diesel_electric_dynamic_brake::control::none); + 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); @@ -84,9 +84,9 @@ TEST_CASE("diesel-electric dynamic brake: none without its definition") { scenario.act("braking range"); controller_to(locomotive, 0); scenario.wait(15.0); - CHECK(locomotive.eimic_real == doctest::Approx(-1.0)); - CHECK(locomotive.Ft == doctest::Approx(0.0)); - CHECK_FALSE(locomotive.DynamicBrakeFlag); + 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(); @@ -99,7 +99,7 @@ TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { 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 == TMoverParameters::diesel_electric_dynamic_brake::control::controller); + 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()); @@ -110,27 +110,27 @@ TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { scenario.act("EB+"); controller_to(locomotive, 0); scenario.wait(10.0); - CHECK(locomotive.eimic_real == doctest::Approx(-1.0)); + CHECK(locomotive.EimicReal() == doctest::Approx(-1.0)); CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); - CHECK(locomotive.DynamicBrakeFlag); + CHECK(locomotive.brakes.electrodynamic.on); REQUIRE(locomotive.Vel > 6.0); - CHECK(-locomotive.Ft == doctest::Approx(br285_limit(locomotive)).epsilon(0.01)); + 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.BrakePress < 0.1); + CHECK(locomotive.brakes.cylinderPressure < 0.1); scenario.act("EB- to half"); controller_to(locomotive, 2); - for (int i = 0; i < 20 && locomotive.eimic_real < -0.5; ++i) { + 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.eimic_real}; + auto const held{locomotive.EimicReal()}; CHECK(held == doctest::Approx(-0.5).epsilon(0.35)); scenario.wait(5.0); - CHECK(locomotive.eimic_real == doctest::Approx(held)); + CHECK(locomotive.EimicReal() == doctest::Approx(held)); CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(-held).epsilon(0.01)); scenario.act("EB+ to the stop"); @@ -141,17 +141,17 @@ TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { // 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)); + 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); + 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.DynamicBrakeFlag); + 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(); @@ -164,9 +164,9 @@ TEST_CASE("diesel-electric dynamic brake: a resistor brake with its own lever") 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 == TMoverParameters::diesel_electric_dynamic_brake::control::lever); - CHECK(locomotive.SplitEDPneumaticBrake); - CHECK(locomotive.DynamicBrakeCtrlPosNo == 8); + 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); @@ -177,34 +177,34 @@ TEST_CASE("diesel-electric dynamic brake: a resistor brake with its own lever") 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.DynamicBrakeFlag); + 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.DynamicBrakeFlag); - CHECK(-locomotive.Ft == doctest::Approx(st44_limit(locomotive)).epsilon(0.01)); + 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.DynamicBrakeCtrlPos == doctest::Approx(0.5)); + 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)); + 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.DynamicBrakeFlag); + CHECK(locomotive.Ft() == doctest::Approx(0.0)); + CHECK_FALSE(locomotive.brakes.electrodynamic.on); scenario.check(); } @@ -223,12 +223,12 @@ TEST_CASE("diesel-electric dynamic brake: blended with the locomotive's air brak scenario.notch_back(0); scenario.act("dynamic and train brake"); locomotive.DynamicBrakeLevelSet(1.0); - locomotive.BrakeLevelSet(locomotive.Handle->GetPos(bh_FB)); + 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.PipePress < 4.6); - CHECK((locomotive.BrakePress < 0.2) == blending); + CHECK(locomotive.brakePipe.Pressure() < 4.6); + CHECK((locomotive.brakes.cylinderPressure < 0.2) == blending); scenario.check(); } } @@ -249,15 +249,15 @@ TEST_CASE("diesel-electric dynamic brake: without a fade it brings the vehicle t scenario.act("EB+ to the stop"); controller_to(locomotive, 0); - for (int i = 0; i < 120 && locomotive.V != 0.0; ++i) { + for (int i = 0; i < 120 && locomotive.V() != 0.0; ++i) { scenario.wait(1.0); } - CHECK(locomotive.BrakePress < 0.1); + 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.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_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index bb7d34b74..f3b9a21c6 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -3,7 +3,7 @@ #include "consist.h" #include "drive.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include #include @@ -56,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); } @@ -94,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); } } @@ -158,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") { @@ -191,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") { @@ -205,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); } } @@ -235,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); } } @@ -257,14 +257,14 @@ 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: TMoverParameters::UpdateStopBrakeRelease() of the cab with its demand after every step and, where the +// 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 { @@ -281,37 +281,37 @@ template double release_time(elf &Unit, double Seconds, Action auto const time{i * step_time}; Act(time); Unit.unit.step(Unit.line); - if (cab.UpdateStopBrakeRelease(cab.eimic_real, step_time)) { + if (cab.UpdateStopBrakeRelease(cab.EimicReal(), step_time)) { return time; } } return -1.0; } -// the holding brake of TDynamicObject::Update() at standstill: StopBrakeDecc times the mass of the train, shared out +// 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; + mass += Unit.car(i).TotalMass(); + axles += Unit.car(i).NAxles(); } - auto const force{Unit.cab().StopBrakeDecc * mass}; + 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.P2FTrans * car.MaxBrakePress[0] - car.BrakeCylSpring) * car.BrakeCylMult[0] - car.BrakeSlckAdj) * car.BrakeCylNo * car.BrakeRigEff}; - auto const fmax{nmax * car.Hamulec->GetFC(nmax / (car.NAxles * car.NBpA), car.MED_Vref) * 1000}; - auto position{Hold ? force * car.NAxles / axles / fmax : 0.0}; + 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.BrakeSlckAdj / car.BrakeCylMult[0] + car.BrakeCylSpring) / (car.P2FTrans * car.MaxBrakePress[0])}; + 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.LocalBrakePosAEIM = position; + car.brakes.SetIndependentPositionEim(position); } } @@ -332,21 +332,21 @@ template start start_off(elf &Unit, double Seconds, Action Act hold(Unit, true); Unit.wait(10.0); start result; - result.pressure = cab.BrakePress; + 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.eimic_real, step_time)}; + 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.eimic_real; + result.demand = cab.EimicReal(); } if (cab.Vel > 0.5 && result.moving < 0.0) { result.moving = time; @@ -366,8 +366,8 @@ void flick(elf &Unit, double Time) { 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->StopBrakeDecc == doctest::Approx(0.6)); - CHECK(car->StopBrakeReleaseDelay == 0.0); + 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)); @@ -378,7 +378,7 @@ TEST_CASE("elf holding brake: without SBDReleaseDelay it lets go at the first de 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->StopBrakeReleaseDelay == doctest::Approx(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)) { @@ -387,7 +387,7 @@ TEST_CASE("elf holding brake: SBDReleaseDelay holds it for that long of a demand 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->StopBrakeReleaseTimer == 0.0); + CHECK(car->brakes.holding.releaseTimer == 0.0); CHECK_FALSE(car->UpdateStopBrakeRelease(0.01, step_time)); } @@ -397,7 +397,7 @@ TEST_CASE("elf holding brake: the controller held at power") { 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().eimic_real == doctest::Approx(0.01)); + 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}; @@ -405,10 +405,10 @@ TEST_CASE("elf holding brake: the controller held at power") { 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.eimic_real}; + auto const demand{cab.EimicReal()}; // the step the ramp of the demand starts at auto rampstart{release}; - while (cab.eimic_real < 0.0101 && rampstart < 5.0) { + while (cab.EimicReal() < 0.0101 && rampstart < 5.0) { rampstart += step_time; unit.unit.step(unit.line); } @@ -425,10 +425,10 @@ TEST_CASE("elf holding brake: the controller flicked to power once and back to h 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.eimic_real); + 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.eimic_real == doctest::Approx(0.01).epsilon(0.02)); + 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") { @@ -439,7 +439,7 @@ TEST_CASE("elf holding brake: a demand dropped to zero before the delay starts t 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.eimic_real > 0.0); + CHECK(cab.EimicReal() > 0.0); } TEST_CASE("elf holding brake: it comes back when the demand drops to zero at standstill") { @@ -451,8 +451,8 @@ TEST_CASE("elf holding brake: it comes back when the demand drops to zero at sta // 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.eimic_real <= 0.0); - CHECK_FALSE(cab.UpdateStopBrakeRelease(cab.eimic_real, step_time)); + 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)); @@ -521,16 +521,16 @@ TEST_CASE("elf holding brake: the force of the motors at 1% against the holding 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; + 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.StopBrakeDecc * mass}; - MESSAGE("mass " << mass << " kg, holding " << holding << " N, cars with motors " << powered << ", demand " << cab.eimic_real << ", cab car Ft " << cab.Ft - << " N, Fful " << cab.eimv[eimv_Fful] << " kN, speed " << cab.Vel << " km/h after 5 s"); - CHECK(cab.eimic_real == doctest::Approx(0.01).epsilon(0.02)); - CHECK(cab.Ft * powered < 0.1 * holding); + 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 index 63296901b..b3f730558 100644 --- a/tests/unit/test_est3al2_relay.cpp +++ b/tests/unit/test_est3al2_relay.cpp @@ -2,7 +2,7 @@ #include "doctest.h" #include "vehicle.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include #include @@ -64,28 +64,28 @@ struct times { times measure(int const Delay, int const Lever) { test::reseed_random(); vehicle wagon{fas_413s()}; - REQUIRE(wagon->BrakeValve == TBrakeValve::ESt3AL2); - if (wagon->BrakeDelayFlag != Delay) { + 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 (TMoverParameters::CheckLocomotiveParameters) - REQUIRE(wagon->LoadFlag == 1); - while (wagon->LoadFlag < Lever) { + // 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->LoadFlag == Lever); + REQUIRE(wagon->brakes.loadSetting == Lever); times result{}; wagon.hold_brake_pipe(5.0); wagon.run(180.0); - result.charged = wagon->BrakePress; + 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->BrakePress); + cylinder.push_back(wagon->brakes.cylinderPressure); } result.applied = cylinder.back(); result.fill = -1.0; @@ -100,7 +100,7 @@ times measure(int const Delay, int const Lever) { result.release = -1.0; for (int i = 0; i < 18000; ++i) { wagon.step(); - if (wagon->BrakePress <= 0.4) { + if (wagon->brakes.cylinderPressure <= 0.4) { result.release = static_cast(i + 1) * step; break; } diff --git a/tests/unit/test_fcfuh_default.cpp b/tests/unit/test_fcfuh_default.cpp index 437164060..bd5120915 100644 --- a/tests/unit/test_fcfuh_default.cpp +++ b/tests/unit/test_fcfuh_default.cpp @@ -19,7 +19,7 @@ using test::vehicle; namespace { -// a figure read from a line the way TMoverParameters::LoadFIZ_EngineInductionMotor() reads fcfu +// 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, ""); @@ -142,12 +142,12 @@ TEST_CASE("fcfuH: the loader gives the dynamic brake the traction's figure when CAPTURE(fcfu); // the EU47's definition has fcfu only vehicle eu47{definition::fiz("e186_v2/eu47").set("Engine", "fcfu", fcfu)}; - CHECK(eu47->eimc[eimc_f_cfu] == read_fcfu(fcfu)); - CHECK(bits(eu47->eimc[eimc_f_cfuH]) == bits(eu47->eimc[eimc_f_cfu])); - CHECK(bits(eu47->eimc[eimc_f_cfuH]) == bits(fcfuh_before(read_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->eimc[eimc_f_cfu] == read_fcfu(fcfu)); - CHECK(own->eimc[eimc_f_cfuH] == read_fcfu("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 index 55816af43..50a7441de 100644 --- a/tests/unit/test_feed_pipe.cpp +++ b/tests/unit/test_feed_pipe.cpp @@ -1,12 +1,12 @@ #include "stdafx.h" #include "doctest.h" -#include "McZapkie/MOVER.h" -#include "McZapkie/hamulce.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 (TMoverParameters::UpdatePipeCouplers()). +// 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 @@ -48,7 +48,7 @@ double off_pressure(test::consist &Train, double const Pressure, double const Se 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]->ScndPipePress - Pressure)); + off = std::max(off, std::abs(Train[i]->mainPipe.Pressure() - Pressure)); } } return off; @@ -66,37 +66,37 @@ evening_out even_out(Builder Train, int const Count, double const Pressure, doub test::consist train; Train(train, Count); for (std::size_t i = 0; i < train.size(); ++i) { - auto &mover{train[i].mover()}; - REQUIRE(mover.VeselVolume > 0.0); + auto &physics{train[i].physics()}; + REQUIRE(physics.air.config.mainReservoirVolume > 0.0); auto const pressure{i == 0 ? Pressure : Pressure - 1.0}; - mover.CompressedVolume = pressure * mover.VeselVolume; - mover.Compressor = pressure; - mover.Pipe2->CreatePress(pressure); - mover.Pipe2->Act(); - mover.ScndPipePress = pressure; + 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].mover()}; - auto const &last{train[train.size() - 1].mover()}; + 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]->ScndPipePress; + 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]->ScndPipePress - previous[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]->ScndPipePress; + previous[i] = train[i]->mainPipe.Pressure(); } - if (std::abs(first.Compressor - last.Compressor) < 0.05) { + if (std::abs(first.air.MainReservoirPressure() - last.air.MainReservoirPressure()) < 0.05) { result.time = time; break; } @@ -112,16 +112,16 @@ double charging_time(Builder Train, int const Count, double const Pressure, doub Train(train, Count); train[0].hold_main_reservoir(Pressure); for (std::size_t i = 1; i < train.size(); ++i) { - auto &mover{train[i].mover()}; - REQUIRE(mover.VeselVolume == 0.0); - mover.Pipe2->CreatePress(0.0); - mover.Pipe2->Act(); - mover.ScndPipePress = 0.0; + 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].mover()}; - auto const &last{train[train.size() - 1].mover()}; + auto const &first{train[0].physics()}; + auto const &last{train[train.size() - 1].physics()}; auto time{0.0}; - while ((last.ScndPipePress < 1.0 || std::abs(last.ScndPipePress - first.ScndPipePress) > 0.2) && time < 60.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; } diff --git a/tests/unit/test_field_shunting.cpp b/tests/unit/test_field_shunting.cpp index e61783b0e..4c9793294 100644 --- a/tests/unit/test_field_shunting.cpp +++ b/tests/unit/test_field_shunting.cpp @@ -46,30 +46,30 @@ TEST_CASE("field shunting: the SU45 with its switch, off at full power and switc scenario.add("bdhpumn_v3/bdhpumn"); REQUIRE(scenario.start_up()); auto &su45{scenario.driver().controlling}; - REQUIRE(su45.AutoRelayType == 2); - REQUIRE(su45.FieldShuntSwitch); + REQUIRE(su45.AutoRelayType() == 2); + REQUIRE(su45.FieldShuntSwitch()); // the driver switches it on as the AI does, getting the locomotive ready - CHECK(su45.AutoRelayFlag); + 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.StLinFlag); - CHECK(su45.ScndCtrlPos == 0); + CHECK(su45.lineContactors.IsClosed()); + CHECK(su45.ScndCtrlPos() == 0); CHECK_FALSE(su45.IncScndCtrl(1)); scenario.wait(1.0); - CHECK(su45.ScndCtrlPos == 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); + 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); + CHECK(su45.ScndCtrlPos() == 0); scenario.check(); } @@ -81,19 +81,19 @@ TEST_CASE("field shunting: a diesel-electric with AutoRelay=Optional alone shunt 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); + 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.StLinFlag); + 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); + CHECK(su45.ScndCtrlPos() == 0); scenario.act("field shunting by hand"); CHECK(su45.IncScndCtrl(1)); scenario.wait(1.0); - CHECK(su45.ScndCtrlPos == 1); + 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_genset.cpp b/tests/unit/test_genset.cpp index c3b4f3015..b6211fa35 100644 --- a/tests/unit/test_genset.cpp +++ b/tests/unit/test_genset.cpp @@ -4,7 +4,7 @@ #include "drive.h" #include "golden.h" -#include "McZapkie/hamulce.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 @@ -14,7 +14,7 @@ using test::consist; using test::definition; using test::track; using test::vehicle; -using traction_mode = TMoverParameters::traction_mode; +using traction_mode = physics::Vehicle::traction_mode; namespace { @@ -40,7 +40,7 @@ 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(TMoverParameters &Cab) { +void wake(physics::Vehicle &Cab) { Cab.BatterySwitch(true); Cab.CabActivisation(); for (int i = 0; i < 3 && Cab.DirActive <= 0; ++i) { @@ -49,7 +49,7 @@ void wake(TMoverParameters &Cab) { } // the vigilance and the cab signalling acknowledged, as test::drive() does once a second -void attend(TMoverParameters &Cab) { +void attend(physics::Vehicle &Cab) { if (Cab.SecuritySystem.is_cabsignal_blinking() && Cab.SecuritySystem.has_separate_acknowledge()) { Cab.SecuritySystem.cabsignal_reset(); } @@ -63,7 +63,7 @@ void run(vehicle &Vehicle, double const Seconds, track const &Track = no_wire) { } // the line breaker closed, which it does only with the controller at zero, and after the relays are reset -void close_line_breaker(TMoverParameters &Cab) { +void close_line_breaker(physics::Vehicle &Cab) { while (Cab.DecMainCtrl(2)) { // down to zero } @@ -75,12 +75,12 @@ void close_line_breaker(TMoverParameters &Cab) { // 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.mover()}; + auto &cab{Vehicle.physics()}; for (auto second = 0; second < Seconds; ++second) { wake(cab); cab.TractionModeSwitch(traction_mode::genset); cab.GensetSwitch(true); - if (false == cab.Mains) { + if (false == cab.lineBreaker.IsClosed()) { if (cab.MainSwitchCheck()) { close_line_breaker(cab); } @@ -90,34 +90,34 @@ bool start_on_genset(vehicle &Vehicle, track const &Track = no_wire, double cons cab.CompressorSwitch(true); } run(Vehicle, 1.0, Track); - if (cab.Mains && cab.ConverterFlag && cab.ScndPipePress >= 4.5) { + 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.BrakePress > 0.05; ++wait) { + for (auto wait = 0; wait < 120 && cab.brakes.cylinderPressure > 0.05; ++wait) { run(Vehicle, 1.0, Track); } - return cab.BrakePress <= 0.05; + return cab.brakes.cylinderPressure <= 0.05; } } return false; } // the main controller to its full power position -void notch_up(TMoverParameters &Cab) { +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(TMoverParameters const &Vehicle) { - return std::abs(Vehicle.Ft * Vehicle.V) / 1000.0; +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.mover()); + attend(Vehicle.physics()); } Vehicle.step(Track); } @@ -126,15 +126,15 @@ void step(vehicle &Vehicle, long const Step, track const &Track = no_wire) { 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.mover()}; + 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(cab.TractionMode() == traction_mode::catenary); CHECK_FALSE(cab.GensetSelected()); REQUIRE(test::start_up(test::driving(dragon6), wire)); - CHECK(cab.PantographVoltage > 2900.0); - CHECK(cab.TractionSupplyVoltage() == std::max(cab.GetTrainsetHighVoltage(), cab.PantographVoltage)); + 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 @@ -142,7 +142,7 @@ TEST_CASE("genset: a vehicle without the keys has none and stays on the catenary run(dragon6, 20.0, wire); CHECK_FALSE(cab.Genset.is_active); CHECK(cab.Genset.voltage == 0.0); - CHECK(cab.TractionMode == traction_mode::catenary); + CHECK(cab.TractionMode() == traction_mode::catenary); } TEST_CASE("genset: the keys reach the vehicle") { @@ -157,7 +157,7 @@ TEST_CASE("genset: the keys reach the vehicle") { 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); + 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); @@ -185,30 +185,30 @@ TEST_CASE("genset: the keys are ignored on other than induction motor vehicles") 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); + 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.mover()}; + auto &cab{dragon6.physics()}; REQUIRE(test::start_up(test::driving(dragon6), wire)); - REQUIRE(cab.Mains); + REQUIRE(cab.lineBreaker.IsClosed()); CHECK_FALSE(cab.TractionModeSwitch(traction_mode::genset)); - CHECK(cab.TractionMode == traction_mode::catenary); + CHECK(cab.TractionMode() == traction_mode::catenary); run(dragon6, 2.0, wire); - CHECK(cab.Mains); + CHECK(cab.lineBreaker.IsClosed()); cab.MainSwitch(false); - REQUIRE_FALSE(cab.Mains); + 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); + 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.mover()}; + auto &cab{dragon6.physics()}; wake(cab); REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); cab.GensetSwitch(true); @@ -223,32 +223,32 @@ TEST_CASE("genset: started, it closes the line breaker without a catenary") { 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.Mains; ++second) { + for (auto second = 0; second < 10 && false == cab.lineBreaker.IsClosed(); ++second) { if (cab.MainSwitchCheck()) { close_line_breaker(cab); } run(dragon6, 1.0); } - REQUIRE(cab.Mains); - CHECK(cab.PantographVoltage == 0.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.Mains); + 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.mover()}; + 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(cab.TractionMode() == traction_mode::catenary); CHECK_FALSE(cab.MainSwitchCheck()); close_line_breaker(cab); - CHECK_FALSE(cab.Mains); + CHECK_FALSE(cab.lineBreaker.IsClosed()); dragon6.step(no_wire); CHECK(cab.EngineVoltage == 0.0); CHECK(cab.TractionSupplyVoltage() == 0.0); @@ -258,13 +258,13 @@ TEST_CASE("genset: on the catenary position the genset feeds nothing") { TEST_CASE("genset: on the genset position the catenary feeds nothing") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + 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.PantographVoltage > 2900.0); - CHECK_FALSE(cab.Mains); + REQUIRE(cab.pantographCircuit.SupplyVoltage() > 2900.0); + CHECK_FALSE(cab.lineBreaker.IsClosed()); CHECK_FALSE(cab.MainSwitchCheck()); dragon6.step(wire); CHECK(cab.EngineVoltage == 0.0); @@ -273,14 +273,14 @@ TEST_CASE("genset: on the genset position the catenary feeds nothing") { TEST_CASE("genset: the power at the wheels stays within the genset's") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + 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.Mains; ++step_count) { + 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); @@ -291,7 +291,7 @@ TEST_CASE("genset: the power at the wheels stays within the genset's") { } CAPTURE(step_count); CAPTURE(peak); - CHECK(cab.Mains); + CHECK(cab.lineBreaker.IsClosed()); CHECK(cab.Vel >= 80.0); CHECK(over == 0); CHECK(peak <= genset_traction_power * 1.02); @@ -301,7 +301,7 @@ TEST_CASE("genset: the power at the wheels stays within the genset's") { TEST_CASE("genset: the revolutions follow the demand, so the power builds up") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + 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)); @@ -309,11 +309,11 @@ TEST_CASE("genset: the revolutions follow the demand, so the power builds up") { 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.eimv_pr < 0.99; ++step_count) { + for (; step_count < 3000 && cab.inductionMotor.forceShare < 0.99; ++step_count) { step(dragon6, step_count); } CAPTURE(step_count); - REQUIRE(cab.eimv_pr >= 0.99); + REQUIRE(cab.inductionMotor.forceShare >= 0.99); run(dragon6, 3.0); auto const after3{cab.Genset.available_power()}; CAPTURE(after3); @@ -341,11 +341,11 @@ TEST_CASE("genset: running from the catenary is the same with the keys") { }; auto const record = [](values &Values) { return std::vector{ - {"Ft", [&Values](TMoverParameters const &Vehicle) { Values.force.push_back(Vehicle.Ft); return Vehicle.Ft; }}, - {"V", [&Values](TMoverParameters const &Vehicle) { Values.speed.push_back(Vehicle.V); return Vehicle.V; }}, - {"EngineVoltage", [&Values](TMoverParameters const &Vehicle) { Values.voltage.push_back(Vehicle.EngineVoltage); return Vehicle.EngineVoltage; }}, - {"Itot", [&Values](TMoverParameters const &Vehicle) { Values.current.push_back(Vehicle.Itot); return Vehicle.Itot; }}, - {"eimv_pr", [&Values](TMoverParameters const &Vehicle) { Values.demand.push_back(Vehicle.eimv_pr); return Vehicle.eimv_pr; }}, + {"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) { @@ -377,18 +377,18 @@ TEST_CASE("genset: running from the catenary is the same with the keys") { TEST_CASE("genset: stopped, it opens the line breaker") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + 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.Mains; ++step_count) { + 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.Mains); + 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 @@ -396,7 +396,7 @@ TEST_CASE("genset: stopped, it opens the line breaker") { close_line_breaker(cab); run(dragon6, 1.0); } - CHECK_FALSE(cab.Mains); + 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); @@ -404,7 +404,7 @@ TEST_CASE("genset: stopped, it opens the line breaker") { TEST_CASE("genset: automatic start follows the selector") { vehicle dragon6{dragon_genset().set("Cntrl", "GensetStart", "Automatic"), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; wake(cab); run(dragon6, 10.0); CHECK_FALSE(cab.Genset.is_cranking); @@ -425,12 +425,12 @@ TEST_CASE("genset: automatic start follows the selector") { TEST_CASE("genset: no battery, no start") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + auto &cab{dragon6.physics()}; cab.BatterySwitch(false); REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); cab.GensetSwitch(true); run(dragon6, 20.0); - CHECK_FALSE(cab.Power24vIsAvailable); + CHECK_FALSE(cab.lowVoltage.Is24vAvailable()); CHECK_FALSE(cab.Genset.is_cranking); CHECK_FALSE(cab.Genset.is_active); CHECK(cab.Genset.revolutions == 0.0); @@ -443,23 +443,21 @@ TEST_CASE("genset: no battery, no start") { 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.mover()}; + auto &cab{dragon6.physics()}; REQUIRE(start_on_genset(dragon6)); - cab.PantPressSwitchActive = true; - cab.PantPress = 0.0; + cab.pantographAir.SetForTest(0.0, true); cab.PantPressureSwitchCheck(); - CHECK(cab.Mains); + 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.mover()}; + auto &cab{dragon6.physics()}; REQUIRE(test::start_up(test::driving(dragon6), wire)); - REQUIRE(cab.Mains); + REQUIRE(cab.lineBreaker.IsClosed()); // the pressure switch looks at the voltage through the couplers, not the pantographs' - cab.PantPressSwitchActive = true; - cab.PantPress = 0.0; + cab.pantographAir.SetForTest(0.0, true); cab.PantPressureSwitchCheck(); - CHECK_FALSE(cab.Mains); + CHECK_FALSE(cab.lineBreaker.IsClosed()); } } @@ -475,7 +473,7 @@ struct 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.mover()}; + 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); @@ -486,13 +484,13 @@ braking brake_from_60(vehicle &Dragon, track const &Track) { } run(Dragon, 2.0, Track); cab.DynamicBrakeSwitch(true); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_FB)); + 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.eimv_pr < 0.0 && cab.eimv[eimv_Ipoj] < 0.0; + result.electrodynamic |= cab.inductionMotor.forceShare < 0.0 && cab.inductionMotor.state.lineCurrent < 0.0; } result.speed_lost = speed - cab.Vel; return result; @@ -508,12 +506,12 @@ TEST_CASE("genset: braking electrodynamically on the genset sends nothing back") REQUIRE(braked.electrodynamic); CHECK(braked.lowest_current >= -1e-6); CHECK(braked.speed_lost > 5.0); - CHECK(dragon6->Mains); + 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.mover()); + test::release_brakes(dragon6.physics()); run(dragon6, 5.0, wire); auto const braked{brake_from_60(dragon6, wire)}; REQUIRE(braked.electrodynamic); @@ -525,9 +523,9 @@ TEST_CASE("genset: braking electrodynamically on the genset sends nothing back") 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).mover()}; - auto &second{train.add(dragon().set("BuffCoupl", "AllowedFlag", 47)).mover()}; - REQUIRE((first.Couplers[end::rear].CouplingFlag & coupling::highvoltage) != 0); + 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); @@ -536,28 +534,28 @@ TEST_CASE("genset: one genset feeds the next car through the high voltage coupli train.run(10.0, no_wire); REQUIRE(first.Genset.is_active); CHECK(second.GetTrainsetHighVoltage() > 2900.0); - CHECK(second.PantographVoltage == 0.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.Mains); + 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.Mains); + 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}; + auto const coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control}; consist train; - auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; - auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; - REQUIRE((first.Couplers[end::rear].CouplingFlag & coupling::control) != 0); + 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)); @@ -575,15 +573,15 @@ TEST_CASE("genset: the selector command travels along the train") { } 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}; + auto const coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control}; consist train; - auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).mover()}; - auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; + 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.Mains); + 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.Mains); + REQUIRE_FALSE(second.lineBreaker.IsClosed()); CHECK_FALSE(first.TractionModeSwitch(traction_mode::genset, range_t::consist)); CHECK_FALSE(first.GensetSelected()); CHECK_FALSE(second.GensetSelected()); @@ -595,10 +593,10 @@ TEST_CASE("genset: a selector command refused with the line breaker closed isn't } 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}; + 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).mover()}; - auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).mover()}; + 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 @@ -612,7 +610,7 @@ TEST_CASE("genset: a lead which starts its genset on its own passes the start sw 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.mover()}; + auto &cab{dragon6.physics()}; REQUIRE(start_on_genset(dragon6)); notch_up(cab); run(dragon6, 10.0); @@ -627,7 +625,7 @@ TEST_CASE("genset: on the genset the pantographs carry no traction current") { } 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.mover()}; + auto &cab{dragon6.physics()}; REQUIRE(test::start_up(test::driving(dragon6), wire)); test::release_brakes(cab); run(dragon6, 5.0, wire); @@ -644,19 +642,19 @@ TEST_CASE("genset: on the genset the pantographs carry no traction current") { TEST_CASE("genset: a scenery command reaches the selector") { vehicle dragon6{dragon_genset(), 0.0, "test", 1}; - auto &cab{dragon6.mover()}; + 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); + cab.PutCommand("TractionMode", 1, 0, cab.Loc()); dragon6.step(no_wire); CHECK(cab.GensetSelected()); - CHECK(cab.CommandIn.Command.empty()); - cab.PutCommand("GensetSwitch", 1, 0, cab.Loc); + 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); + 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_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_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 9b36b817f..55f637bf9 100644 --- a/tests/unit/test_linebreaker.cpp +++ b/tests/unit/test_linebreaker.cpp @@ -16,7 +16,7 @@ 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; + physics::Vehicle &physics; state breaker{state::open}; // as TTrain::m_linebreakerstate bool on{false}; @@ -27,7 +27,7 @@ struct lever { break; case linebreaker::toggle::open: on = false; - if (breaker == state::closed && mover.MainSwitch(false)) { + if (breaker == state::closed && physics.MainSwitch(false)) { breaker = state::open; } break; @@ -37,14 +37,14 @@ struct lever { } // TTrain::Update() void update() { - if (breaker == state::open && mover.Mains) { + if (breaker == state::open && physics.lineBreaker.IsClosed()) { breaker = state::closed; } - if (breaker == state::closed && false == mover.Mains) { + if (breaker == state::closed && false == physics.lineBreaker.IsClosed()) { breaker = state::open; } - if (on && breaker == state::open && mover.MainSwitchCheck()) { - breaker = mover.MainSwitch(true) ? state::closed : state::open; + if (on && breaker == state::open && physics.MainSwitchCheck()) { + breaker = physics.MainSwitch(true) ? state::closed : state::open; } } }; @@ -67,20 +67,20 @@ TEST_CASE("line breaker: a press of the toggle closes an open breaker and opens 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); + 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_FALSE(ep05.lineBreaker.IsClosed()); REQUIRE(ws.breaker == state::open); CHECK(ws.on); // with the relay tripped the breaker doesn't close @@ -93,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); @@ -101,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(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_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 index 5d44c7331..8226fad46 100644 --- a/tests/unit/test_motor_param_bounds.cpp +++ b/tests/unit/test_motor_param_bounds.cpp @@ -11,7 +11,7 @@ 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 (TMoverParameters::Momentum(), MomentumF(), TController::ESMVelocity()) +// .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 { diff --git a/tests/unit/test_odometer.cpp b/tests/unit/test_odometer.cpp index b3da8d792..ffb420bc3 100644 --- a/tests/unit/test_odometer.cpp +++ b/tests/unit/test_odometer.cpp @@ -68,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()); } 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 ee82aca9a..58f3bb980 100644 --- a/tests/unit/test_parser.cpp +++ b/tests/unit/test_parser.cpp @@ -698,7 +698,7 @@ TEST_CASE("parser: read line by line, a line starting with include is the direct namespace { -// the lines of a file, read the way the vehicle's .fiz is (TMoverParameters::LoadFIZ_Parse): line by line while the +// 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; diff --git a/tests/unit/test_pressure_switch.cpp b/tests/unit/test_pressure_switch.cpp index 65672b252..1a50a0931 100644 --- a/tests/unit/test_pressure_switch.cpp +++ b/tests/unit/test_pressure_switch.cpp @@ -2,7 +2,7 @@ #include "doctest.h" #include "drive.h" -#include "McZapkie/hamulce.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 @@ -45,27 +45,27 @@ 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->ControlPressureSwitch; ++i) { + for (int i = 0; i < 120 && Loco->protection.PressureSwitchTripped(); ++i) { test::drive(Driven, line, 1.0); } - REQUIRE_FALSE(Loco->ControlPressureSwitch); - REQUIRE(Loco->Mains); - REQUIRE(Loco->Pantographs[end::rear].is_active); + 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)) { + while (Loco->MainCtrlPos() < Position && Loco->IncMainCtrl(1)) { test::drive(Driven, line, 1.0); } test::drive(Driven, line, 2.0); - REQUIRE(Loco->MainCtrlPos == Position); + 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->StLinFlag); + REQUIRE(Loco->lineContactors.IsClosed()); REQUIRE(std::abs(Loco->Im) > 10.0); } @@ -73,28 +73,28 @@ void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const void apply_independent_brake(test::vehicle &Loco, test::driven const &Driven) { Loco->IncLocalBrakeLevel(LocalBrakePosNo); test::drive(Driven, line, 20.0); - REQUIRE(Loco->BrakePress == doctest::Approx(3.8).epsilon(0.03)); - REQUIRE(Loco->PipePress > 4.8); + 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->Handle->GetPos(bh_EB)); + Loco->BrakeLevelSet(Loco->brakes.driverValve->GetPos(bh_EB)); test::drive(Driven, line, 10.0); - REQUIRE(Loco->PipePress < 1.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->HasControlPressureSwitch); - CHECK(loco->PressureSwitchBrakeCylinder); - CHECK(loco->EmergencyBrakeMainOffPressure == 0.0); + 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->HasControlPressureSwitch); - CHECK_FALSE(changed->PressureSwitchBrakeCylinder); - CHECK(changed->EmergencyBrakeMainOffPressure == doctest::Approx(emergency_pressure)); + 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") { @@ -102,14 +102,14 @@ TEST_CASE("pressure switch: with the brake cylinders at 3.8 bar the EP05 takes n auto driven{test::driving(loco)}; get_ready(loco, driven); apply_independent_brake(loco, driven); - CHECK(loco->ControlPressureSwitch); + CHECK(loco->protection.PressureSwitchTripped()); CHECK_FALSE(loco->MainCircuitLampsEnabled()); notch_up(loco, driven, 3); - CHECK_FALSE(loco->StLinFlag); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->Im == 0.0); - CHECK(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); + 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") { @@ -117,16 +117,16 @@ TEST_CASE("pressure switch: without its brake cylinder half the EP05 takes curre auto driven{test::driving(loco)}; get_ready(loco, driven); apply_independent_brake(loco, driven); - CHECK_FALSE(loco->ControlPressureSwitch); + 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->StLinFlag); + CHECK(loco->lineContactors.IsClosed()); CHECK(loco->MainCtrlActualPos == 3); CHECK(std::abs(loco->Im) > 100.0); - CHECK(loco->BrakePress == doctest::Approx(3.8).epsilon(0.03)); + 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"); } @@ -136,20 +136,20 @@ TEST_CASE("pressure switch: without its brake cylinder half the brake pipe still get_under_power(loco, driven, 5); SUBCASE("a service application") { - loco->BrakeLevelSet(loco->Handle->GetPos(bh_FB)); + loco->BrakeLevelSet(loco->brakes.driverValve->GetPos(bh_FB)); test::drive(driven, line, 15.0); - REQUIRE(loco->PipePress < 3.6); - REQUIRE(loco->PipePress > 3.0); + REQUIRE(loco->brakePipe.Pressure() < 3.6); + REQUIRE(loco->brakePipe.Pressure() > 3.0); } SUBCASE("an emergency application") { emergency_application(loco, driven); } - CHECK(loco->ControlPressureSwitch); - CHECK_FALSE(loco->StLinFlag); + CHECK(loco->protection.PressureSwitchTripped()); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->Im == 0.0); // nothing else lets go without the other key - CHECK(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); + 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") { @@ -158,26 +158,26 @@ TEST_CASE("pressure switch: an emergency application with the master controller get_under_power(loco, driven, 5); SUBCASE("made with the brake handle") { - loco->BrakeLevelSet(loco->Handle->GetPos(bh_EB)); + 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->PipePress < emergency_pressure); - REQUIRE(loco->MainCtrlPos == 5); - CHECK_FALSE(loco->Mains); - CHECK_FALSE(loco->Pantographs[end::front].is_active); - CHECK_FALSE(loco->Pantographs[end::rear].is_active); - CHECK(loco->PantographVoltage == 0.0); - CHECK_FALSE(loco->StLinFlag); + 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->Mains); - CHECK_FALSE(loco->Pantographs[end::rear].is_active); + 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") { @@ -188,19 +188,19 @@ TEST_CASE("pressure switch: an emergency application with the master controller // down to zero } test::drive(driven, line, 2.0); - REQUIRE(loco->MainCtrlPos == 0); + REQUIRE(loco->MainCtrlPos() == 0); emergency_application(loco, driven); - CHECK(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); - CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + 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->Mains); - CHECK_FALSE(loco->Pantographs[end::rear].is_active); + 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") { @@ -210,18 +210,18 @@ TEST_CASE("pressure switch: a service application with the master controller on // the last service position of the FV4a, 2.8 bar in the pipe loco->BrakeLevelSet(5.0); - auto lowest{loco->PipePress}; + auto lowest{loco->brakePipe.Pressure()}; for (int second = 0; second < 60; ++second) { test::drive(driven, line, 1.0); - lowest = std::min(lowest, loco->PipePress); + 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->Mains); - CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->lineBreaker.IsClosed()); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); // the pressure switch has cut the motors off - CHECK_FALSE(loco->StLinFlag); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->Im == 0.0); } @@ -231,27 +231,27 @@ TEST_CASE("pressure switch: without the key an emergency application leaves the get_under_power(loco, driven, 5); emergency_application(loco, driven); - REQUIRE(loco->MainCtrlPos == 5); - CHECK(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); - CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + 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->ControlPressureSwitch); - CHECK_FALSE(loco->StLinFlag); + 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->PantographsRequireMains); + REQUIRE_FALSE(loco->lineBreaker.config.pantographsRequireIt); auto driven{test::driving(loco)}; get_under_power(loco, driven, 5); emergency_application(loco, driven); - CHECK_FALSE(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); - CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); - CHECK_FALSE(loco->StLinFlag); + 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); } @@ -263,33 +263,33 @@ TEST_CASE("pressure switch: after the emergency application the driver's start-u auto driven{test::driving(loco)}; get_under_power(loco, driven, 5); emergency_application(loco, driven); - REQUIRE_FALSE(loco->Mains); - REQUIRE_FALSE(loco->Pantographs[end::rear].is_active); - REQUIRE(loco->Pantographs[end::rear].valve.is_enabled); + 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->Mains); - CHECK(loco->Pantographs[end::rear].is_active); - CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); - REQUIRE(loco->PipePress < emergency_pressure); + 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->Mains); - CHECK(loco->Pantographs[end::rear].is_active); + 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->ControlPressureSwitch; ++i) { - loco->BrakeReleaser(loco->PipePress < 3.0 ? 1 : 0); + 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->ControlPressureSwitch); + REQUIRE_FALSE(loco->protection.PressureSwitchTripped()); notch_up(loco, driven, 3); - CHECK(loco->Mains); - CHECK(loco->StLinFlag); + 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 index 7e2742f7a..8a8388aae 100644 --- a/tests/unit/test_pullee.cpp +++ b/tests/unit/test_pullee.cpp @@ -11,14 +11,14 @@ 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, TMoverParameters::PulleeModeSwitch(). the trains here are an EU07 and the vehicle behind it, coupled with +// 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 int hook_and_brake_hose{coupling::coupler | coupling::brakehose}; +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, @@ -40,16 +40,16 @@ struct hauled_train { }; // no air in the main reservoir and the feed pipe, as after standing dead for some hours -void drain_feed_air(TMoverParameters &Vehicle) { - Vehicle.Pipe2->CreatePress(0.0); - Vehicle.Pipe2->Act(); - Vehicle.CompressedVolume = 0.0; +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[end::front].CouplerType != TCouplerType::NoCoupler; + return (probe->CategoryFlag & 1) != 0 && probe->Couplers[VehicleEnd::front].CouplerType != TCouplerType::NoCoupler; } } // namespace @@ -76,20 +76,20 @@ TEST_CASE("pullee: a dead Vectron vents the brake pipe of the train hauling it, SUBCASE("as it is") { hauled_train train{vectron, 60.0, false}; REQUIRE((train.hauled->InactiveCabFlag & activation::emergencybrake) != 0); - REQUIRE_FALSE(train.hauled->PulleeMode); + REQUIRE_FALSE(train.hauled->PulleeMode()); train.run(120.0); - CHECK(train.hauled->EmergencyValveFlow > 0.0); - CHECK(train.locomotive->PipePress < 4.95); // the pipe sags although the locomotive keeps feeding it - CHECK(train.hauled->BrakePress > 0.4); + 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->EmergencyValveFlow == 0.0); - CHECK(train.locomotive->PipePress > 4.99); - CHECK(train.hauled->BrakePress < 0.1); - CHECK(train.hauled->Fb < 1.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 } } @@ -114,16 +114,16 @@ TEST_CASE("pullee: an EU07 with a driver can't release the brakes of a dead Vect 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->Battery); - CHECK(locomotive->PipePress < 1.0); - CHECK(locomotive->BrakePress > 3.0); - CHECK(hauled->BrakePress > 3.0); + 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->Battery); - CHECK(locomotive->PipePress > 4.9); - CHECK(locomotive->BrakePress < 0.1); - CHECK(hauled->BrakePress < 0.1); + 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(); @@ -147,18 +147,18 @@ TEST_CASE("pullee: the spring brake of a dead locomotive without air stops the t CAPTURE(pullee); test::reseed_random(); hauled_train train{definition::fiz(path), 60.0, pullee}; - auto const &hauled{train.hauled.mover()}; - REQUIRE(hauled.SpringBrake.MaxBrakeForce > 0.0); - drain_feed_air(train.hauled.mover()); + 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.SpringBrake.SBP < 0.1); + REQUIRE(hauled.brakes.spring.pressure < 0.1); if (pullee) { - CHECK(hauled.Fb < 1.0); + CHECK(hauled.Fb() < 1.0); CHECK(train.hauled.speed() > 45.0); } else { - CHECK(hauled.Fb > 30000.0); + CHECK(hauled.Fb() > 30000.0); CHECK(std::abs(train.hauled.speed()) < 1.0); } } @@ -171,21 +171,21 @@ TEST_CASE("pullee: a dead EU47 starts to drag once its main reservoir has leaked CAPTURE(pullee); test::reseed_random(); hauled_train train{definition::fiz("e186_v2/eu47"), 0.0, pullee}; - auto &hauled{train.hauled.mover()}; + auto &hauled{train.hauled.physics()}; // what the driver of the train does on its inspection, TController::AutoRewident() hauled.DecManualBrakeLevel(ManualBrakePosNo); - hauled.SpringBrake.Activate = false; + hauled.brakes.spring.activate = false; train.run(180.0); // charged and released: nothing holds it yet - CHECK(hauled.BrakePress < 0.1); - CHECK(hauled.Fb < 1.0); + CHECK(hauled.brakes.cylinderPressure < 0.1); + CHECK(hauled.Fb() < 1.0); train.run(1020.0); // 20 minutes since the start - CHECK(hauled.ScndPipePress < hauled.SpringBrake.MinForcePressure); + CHECK(hauled.mainPipe.Pressure() < hauled.brakes.spring.minForcePressure); if (pullee) { - CHECK(hauled.Fb < 1.0); + CHECK(hauled.Fb() < 1.0); } else { - CHECK(hauled.Fb > 5000.0); + CHECK(hauled.Fb() > 5000.0); } } } @@ -199,22 +199,22 @@ TEST_CASE("pullee: a vehicle prepared for hauling brakes and releases with the t CAPTURE(feedair); test::reseed_random(); hauled_train train{definition::fiz(path), 60.0, true}; - auto const &hauled{train.hauled.mover()}; + auto const &hauled{train.hauled.physics()}; if (false == feedair) { - drain_feed_air(train.hauled.mover()); + drain_feed_air(train.hauled.physics()); } train.run(30.0); - CHECK(hauled.BrakePress < 0.1); + CHECK(hauled.brakes.cylinderPressure < 0.1); // a full service application train.locomotive.hold_brake_pipe(3.5); train.run(20.0); - CHECK(hauled.BrakePress > 2.0); - CHECK(hauled.Fb > 30000.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.BrakePress < 0.1); - CHECK(hauled.Fb < 1.0); - CHECK(hauled.EmergencyValveFlow == 0.0); + CHECK(hauled.brakes.cylinderPressure < 0.1); + CHECK(hauled.Fb() < 1.0); + CHECK(hauled.brakes.emergencyValve.flow == 0.0); } } } @@ -227,19 +227,19 @@ TEST_CASE("pullee: the spring brake of an Impuls prepared for hauling doesn't ca CAPTURE(pullee); test::reseed_random(); hauled_train train{impuls, 60.0, pullee}; - auto const &hauled{train.hauled.mover()}; + auto const &hauled{train.hauled.physics()}; REQUIRE(hauled.InactiveCabFlag == 0); - REQUIRE(hauled.SpringBrakeDriveEmergencyVel == doctest::Approx(2.0)); - drain_feed_air(train.hauled.mover()); + 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.SpringBrake.IsActive); + REQUIRE(hauled.brakes.spring.isActive); if (pullee) { - CHECK(hauled.EmergencyValveFlow == 0.0); - CHECK(hauled.BrakePress < 0.1); + CHECK(hauled.brakes.emergencyValve.flow == 0.0); + CHECK(hauled.brakes.cylinderPressure < 0.1); } else { - CHECK(hauled.EmergencyValveFlow > 0.0); + CHECK(hauled.brakes.emergencyValve.flow > 0.0); } } } @@ -261,29 +261,29 @@ TEST_CASE("pullee: the brake valves in the cab of a vehicle prepared for hauling // the local brake a driver keeps a standing vehicle on is let go driven->DecLocalBrakeLevel(LocalBrakePosNo); driven.run(20.0); - REQUIRE(driven->BrakePress < 0.1); - auto const charged{driven->PipePress}; + REQUIRE(driven->brakes.cylinderPressure < 0.1); + auto const charged{driven->brakePipe.Pressure()}; // full service braking with the driver's valve - driven->BrakeLevelSet(driven->Handle->GetPos(bh_FB)); + driven->BrakeLevelSet(driven->brakes.driverValve->GetPos(bh_FB)); driven.run(10.0); if (pullee) { - CHECK(driven->dpMainValve == 0.0); - CHECK(driven->PipePress > charged - 0.1); - CHECK(driven->BrakePress < 0.1); + CHECK(driven->brakes.driverValveFlow == 0.0); + CHECK(driven->brakePipe.Pressure() > charged - 0.1); + CHECK(driven->brakes.cylinderPressure < 0.1); } else { - CHECK(driven->PipePress < charged - 0.5); - CHECK(driven->BrakePress > 1.0); + CHECK(driven->brakePipe.Pressure() < charged - 0.5); + CHECK(driven->brakes.cylinderPressure > 1.0); } // and the emergency position - driven->BrakeLevelSet(driven->Handle->GetPos(bh_EB)); + driven->BrakeLevelSet(driven->brakes.driverValve->GetPos(bh_EB)); driven.run(10.0); if (pullee) { - CHECK(driven->dpMainValve == 0.0); - CHECK(driven->PipePress > charged - 0.1); + CHECK(driven->brakes.driverValveFlow == 0.0); + CHECK(driven->brakePipe.Pressure() > charged - 0.1); } else { - CHECK(driven->PipePress < 1.0); + CHECK(driven->brakePipe.Pressure() < 1.0); } } } @@ -304,13 +304,13 @@ TEST_CASE("pullee: the local brake of a vehicle prepared for hauling stays relea // 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->LocalBrakePosAEIM = 1.0; + driven->brakes.SetIndependentPositionEim(1.0); driven.run(20.0); if (pullee) { - CHECK(driven->BrakePress < 0.1); + CHECK(driven->brakes.cylinderPressure < 0.1); } else { - CHECK(driven->BrakePress > 1.0); + CHECK(driven->brakes.cylinderPressure > 1.0); } } } @@ -319,25 +319,25 @@ TEST_CASE("pullee: the local brake of a vehicle prepared for hauling stays relea 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->SpringBrake.Activate); - REQUIRE_FALSE(vectron->PulleeMode); + REQUIRE(vectron->brakes.spring.activate); + REQUIRE_FALSE(vectron->PulleeMode()); CHECK(vectron->PulleeModeSwitch(true)); - CHECK(vectron->PulleeMode); - CHECK_FALSE(vectron->SpringBrake.Activate); + 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->ManualBrakePos > 0); + REQUIRE(en57->brakes.HandBrakePosition() > 0); CHECK(en57->PulleeModeSwitch(true)); - CHECK(en57->ManualBrakePos == 0); + 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->Battery); + REQUIRE(vectron->lowVoltage.IsBatteryOn()); CHECK(vectron->PulleeModeSwitch(true)); - CHECK_FALSE(vectron->Battery); + CHECK_FALSE(vectron->lowVoltage.IsBatteryOn()); } } @@ -345,24 +345,24 @@ TEST_CASE("pullee: the battery and the cabs of a vehicle prepared for hauling st vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.0, "test", 1}; REQUIRE(vectron->PulleeModeSwitch(true)); CHECK_FALSE(vectron->BatterySwitch(true)); - CHECK_FALSE(vectron->Battery); + 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->EmergencyValveFlow == 0.0); + CHECK(vectron->brakes.emergencyValve.flow == 0.0); REQUIRE(vectron->PulleeModeSwitch(false)); - CHECK_FALSE(vectron->PulleeMode); + CHECK_FALSE(vectron->PulleeMode()); CHECK(vectron->BatterySwitch(true)); - CHECK(vectron->Battery); + 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); + CHECK_FALSE(vectron->PulleeMode()); } TEST_CASE("pullee: a cab activated on a dead battery calls the emergency brake, which the mode keeps from happening") { @@ -378,7 +378,7 @@ TEST_CASE("pullee: a cab activated on a dead battery calls the emergency brake, CHECK(vectron->CabActivisation() == (false == pullee)); vectron.run(0.5); CHECK(vectron->SecuritySystem.is_braking() == (false == pullee)); - CHECK((vectron->EmergencyValveFlow > 0.0) == (false == pullee)); + CHECK((vectron->brakes.emergencyValve.flow > 0.0) == (false == pullee)); } } @@ -394,14 +394,14 @@ TEST_CASE("pullee: the battery and cab commands of the train's driver pass a veh if (pullee) { REQUIRE(hauled->PulleeModeSwitch(true)); } - REQUIRE_FALSE(hauled->Battery); + REQUIRE_FALSE(hauled->lowVoltage.IsBatteryOn()); locomotive->BatterySwitch(true); locomotive->CabActivisation(); train.run(2.0); - CHECK(hauled->Battery == (false == pullee)); + CHECK(hauled->lowVoltage.IsBatteryOn() == (false == pullee)); CHECK(hauled->CabActive == (pullee ? 0 : 1)); // the vehicle behind it gets them either way - CHECK(last->Battery); + CHECK(last->lowVoltage.IsBatteryOn()); CHECK(last->CabActive == 1); } } @@ -415,13 +415,13 @@ TEST_CASE("pullee: every real vehicle prepared for hauling runs free behind a lo } test::reseed_random(); hauled_train train{definition::fiz(path), 60.0, true}; - auto const &hauled{train.hauled.mover()}; - drain_feed_air(train.hauled.mover()); + auto const &hauled{train.hauled.physics()}; + drain_feed_air(train.hauled.physics()); train.run(60.0); - CHECK(hauled.EmergencyValveFlow == 0.0); - CHECK(hauled.BrakePress < 0.1); - CHECK(hauled.Fb < 1.0); - CHECK(train.locomotive->PipePress > 4.99); + 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); } } @@ -436,14 +436,14 @@ TEST_CASE("pullee: every real vehicle standing braked releases once prepared for 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.mover()}; - CHECK(hauled.ManualBrakePos == 0); - CHECK_FALSE(hauled.SpringBrake.Activate); - CHECK_FALSE(hauled.Battery); + 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.EmergencyValveFlow == 0.0); - CHECK(hauled.BrakePress < 0.1); + 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); + 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_skinning.cpp b/tests/unit/test_skinning.cpp index 9c57c01b9..498c335d2 100644 --- a/tests/unit/test_skinning.cpp +++ b/tests/unit/test_skinning.cpp @@ -159,10 +159,13 @@ TEST_CASE("skinning: the normals of a part scaled unevenly stay square to its su std::vector out(1); skinning::skin_vertices(rest, weights, palette, out); CHECK(close_to(out[0].normal, glm::normalize(glm::vec3{0.5f, 1.f, 0.f}))); - // a mirroring joint keeps the normal facing out + CHECK(out[0].tangent.w == doctest::Approx(vertex.tangent.w)); + // a mirroring joint keeps the normal facing out, and turns the handedness of the tangent frame, so the bitangent rebuilt + // from the normal and the tangent mirrors with the surface std::vector const mirror{glm::scale(glm::mat4{1.f}, glm::vec3{-1.f, 1.f, 1.f})}; skinning::skin_vertices(rest, weights, mirror, out); CHECK(close_to(out[0].normal, glm::normalize(glm::vec3{-1.f, 1.f, 0.f}))); + CHECK(out[0].tangent.w == doctest::Approx(-vertex.tangent.w)); } TEST_CASE("skinning: a joint turned moves its vertices, blended by the weights") { 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 index 3f8a9a9ec..5878fb64d 100644 --- a/tests/unit/test_speed_control.cpp +++ b/tests/unit/test_speed_control.cpp @@ -21,8 +21,8 @@ std::vector cruise() { {"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.eimic_real; }}, + {"eimicSpeedCtrl", [](auto const &M) { return M.eimicSpeedCtrl(); }}, + {"eimic_real", [](auto const &M) { return M.EimicReal(); }}, }; } @@ -32,14 +32,14 @@ constexpr int dg_lower{4}; constexpr int dg_hold{5}; constexpr int dg_raise{6}; -void move_to(TMoverParameters &Vehicle, int const Position) { - while (Vehicle.MainCtrlPos < Position && Vehicle.IncMainCtrl(1)) { +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)) { + while (Vehicle.MainCtrlPos() > Position && Vehicle.DecMainCtrl(1)) { // all the work is done in the condition } - REQUIRE(Vehicle.MainCtrlPos == Position); + REQUIRE(Vehicle.MainCtrlPos() == Position); } // the 6Dg started up, its brakes released, its controller through the no power and lowering positions to holding, @@ -49,15 +49,15 @@ void get_6dg_going(scenario &Scenario) { REQUIRE(Scenario.start_up()); Scenario.get_going(); move_to(loco, dg_no_power); - for (int second = 0; second < 180 && loco.BrakePress > 0.1; ++second) { + for (int second = 0; second < 180 && loco.brakes.cylinderPressure > 0.1; ++second) { Scenario.wait(1.0); } - REQUIRE(loco.BrakePress <= 0.1); + 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.StLinFlag); + REQUIRE(loco.lineContactors.IsClosed()); } } // namespace @@ -73,23 +73,23 @@ TEST_CASE("speed control: the field shunting of the vehicles without a cruise co 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_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); + CHECK(loco.ScndCtrlPos() == 1); scenario.wait(10.0); CHECK(loco.Vel > speed); - CHECK(loco.ScndCtrlPos == 1); + 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); + CHECK(loco.ScndCtrlPos() == 0); scenario.wait(5.0); CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); scenario.check(); @@ -99,24 +99,24 @@ TEST_CASE("speed control: the field shunting of the vehicles without a cruise co 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_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); + most = std::max(most, loco.ScndCtrlPos()); } - CHECK(most == loco.ScndCtrlPosNo); + 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); + CHECK(loco.ScndCtrlPos() == 0); scenario.check(); } } @@ -126,14 +126,14 @@ TEST_CASE("speed control: the vehicles whose secondary controller is the cruise 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(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.ScndCtrlPos() == 1); CHECK(unit.SpeedCtrlUnit.IsActive); CHECK(unit.SpeedCtrlValue == doctest::Approx(unit.Vel)); auto const held{unit.SpeedCtrlValue}; @@ -141,7 +141,7 @@ TEST_CASE("speed control: the vehicles whose secondary controller is the cruise CHECK(unit.Vel == doctest::Approx(held).epsilon(0.05)); scenario.act("cruise control off"); CHECK(unit.DecScndCtrl(2)); - CHECK(unit.ScndCtrlPos == 0); + CHECK(unit.ScndCtrlPos() == 0); CHECK_FALSE(unit.SpeedCtrlUnit.IsActive); CHECK(unit.SpeedCtrlValue == 0.0); scenario.wait(5.0); @@ -151,22 +151,22 @@ TEST_CASE("speed control: the vehicles whose secondary controller is the cruise 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(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)) { + while (loco.ScndCtrlPos() < 3 && loco.IncScndCtrl(1)) { // all the work is done in the condition } - REQUIRE(loco.ScndCtrlPos == 3); + REQUIRE(loco.ScndCtrlPos() == 3); scenario.wait(10.0); - CHECK(loco.NewSpeed > 0.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.SpeedCtrlValue == doctest::Approx(loco.NewSpeed())); CHECK(loco.SpeedCtrlUnit.IsActive); scenario.full_power(60.0); CHECK(loco.Vel == doctest::Approx(loco.SpeedCtrlValue).epsilon(0.1)); @@ -185,21 +185,21 @@ TEST_CASE("speed control: the field shunting of the vehicles with a cruise contr 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); + 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); + CHECK(loco.ScndCtrlPos() == 0); scenario.wait(110.0); CHECK(loco.Vel > 100.0); - CHECK(loco.ScndCtrlPos == 1); + CHECK(loco.ScndCtrlPos() == 1); CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); - CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); + CHECK(loco.EimicReal() == doctest::Approx(loco.eimic)); // the driver can't move the shunt CHECK_FALSE(loco.IncScndCtrl(1)); CHECK_FALSE(loco.DecScndCtrl(2)); @@ -209,8 +209,8 @@ TEST_CASE("speed control: the field shunting of the vehicles with a cruise contr 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(loco.SpeedCtrl()); + REQUIRE(loco.AutoRelayFlag()); REQUIRE(scenario.start_up()); scenario.get_going(); scenario.full_power(5.0); @@ -219,12 +219,12 @@ TEST_CASE("speed control: the field shunting of the vehicles with a cruise contr auto most{0}; for (int i = 0; i < 9; ++i) { scenario.wait(10.0); - most = std::max(most, loco.ScndCtrlPos); + most = std::max(most, loco.ScndCtrlPos()); } CHECK(loco.Vel > 130.0); CHECK(most == 0); CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); - CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); + CHECK(loco.EimicReal() == doctest::Approx(loco.eimic)); // the speed buttons do nothing with the cruise control off loco.SpeedCtrlButton(4); loco.SpeedCtrlInc(); @@ -260,10 +260,10 @@ TEST_CASE("speed control apart: which vehicles' cruise control has a switch of i 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, TMoverParameters const &Vehicle, int const Seconds, int &Shunted, int &Unshunted) { +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); + ++(Vehicle.ScndCtrlPos() > 0 ? Shunted : Unshunted); } } @@ -278,7 +278,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the move_to(loco, dg_raise); scenario.wait(30.0); REQUIRE(loco.Vel > 50.0); - REQUIRE(loco.ScndCtrlPos == 1); // the shunt in + 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); @@ -292,7 +292,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the 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 + 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}; @@ -300,7 +300,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the count_shunting(scenario, loco, 60, shunted, unshunted); CHECK(loco.Vel == doctest::Approx(held).epsilon(0.03)); CHECK_FALSE(loco.SpeedCtrlUnit.Standby); - CHECK(loco.eimic_real < loco.eimic); // the cruise control holding the power back + CHECK(loco.EimicReal() < loco.eimic); // the cruise control holding the power back scenario.act("two steps up"); loco.SpeedCtrlInc(); @@ -309,7 +309,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the 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.StLinFlag); + CHECK(loco.lineContactors.IsClosed()); CHECK(shunted > 0); CHECK(unshunted > 0); CHECK_FALSE(loco.IncScndCtrl(1)); // still not the driver's @@ -321,15 +321,15 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the // 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.StLinFlag); + 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.StLinFlag); + CHECK(loco.lineContactors.IsClosed()); CHECK(loco.Vel == doctest::Approx(30.0).epsilon(0.05)); - CHECK(loco.ScndCtrlPos == 0); // out at this speed + CHECK(loco.ScndCtrlPos() == 0); // out at this speed scenario.act("cruise control off"); CHECK(loco.SpeedCtrlSwitch(false)); @@ -337,7 +337,7 @@ TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); CHECK(loco.SpeedCtrlValue == 0.0); scenario.wait(5.0); - CHECK(loco.eimic_real == doctest::Approx(loco.eimic)); // the controller's demand again + CHECK(loco.EimicReal() == doctest::Approx(loco.eimic)); // the controller's demand again scenario.check(); } @@ -356,7 +356,7 @@ TEST_CASE("speed control apart: the ST45's cruise control on its own switch, wit CHECK(loco.SpeedCtrlValue == doctest::Approx(60.0)); scenario.wait(90.0); CHECK(loco.Vel == doctest::Approx(60.0).epsilon(0.03)); - CHECK(loco.StLinFlag); + CHECK(loco.lineContactors.IsClosed()); scenario.act("step up, power down"); loco.SpeedCtrlInc(); CHECK(loco.SpeedCtrlValue == doctest::Approx(65.0)); @@ -364,7 +364,7 @@ TEST_CASE("speed control apart: the ST45's cruise control on its own switch, wit CHECK(loco.SpeedCtrlUnit.DesiredPower == doctest::Approx(0.9)); scenario.wait(60.0); CHECK(loco.Vel == doctest::Approx(65.0).epsilon(0.03)); - CHECK(loco.eimic_real <= 0.9 + 1e-9); + CHECK(loco.EimicReal() <= 0.9 + 1e-9); scenario.act("cruise control off"); CHECK(loco.SpeedCtrlSwitch(false)); // off, its buttons do nothing @@ -373,7 +373,7 @@ TEST_CASE("speed control apart: the ST45's cruise control on its own switch, wit CHECK_FALSE(loco.SpeedCtrlPowerInc()); CHECK(loco.SpeedCtrlValue == 0.0); scenario.wait(5.0); - CHECK(loco.ScndCtrlPos == 0); + CHECK(loco.ScndCtrlPos() == 0); scenario.check(); } @@ -387,13 +387,13 @@ TEST_CASE("speed control apart: the switch of a cruise control without one of it scenario.full_power(20.0); scenario.act("cruise control on"); CHECK(railbus.SpeedCtrlSwitch(true)); - CHECK(railbus.ScndCtrlPos == 1); + 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(railbus.ScndCtrlPos() == 0); CHECK_FALSE(railbus.SpeedCtrlUnit.IsActive); CHECK_FALSE(railbus.IsSpeedCtrlEngaged()); scenario.wait(5.0); 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 index a41aafcce..dff4ec6e4 100644 --- a/tests/unit/test_timetable.cpp +++ b/tests/unit/test_timetable.cpp @@ -2,7 +2,7 @@ #include "doctest.h" #include "vehicle.h" -#include "McZapkie/MOVER.h" +#include "physics/vehicle.h" #include "utilities/utilities.h" #include "vehicle/timetableservice.h" #include "world/timetablereader.h" @@ -269,20 +269,20 @@ TEST_CASE("timetable: the AI opens the doors from the cab as the vehicle and the auto const notcentral{flags(no, unset, unset, unset)}; unit->Doors.open_control = control_t::driver; - CHECK(timetable::opens_doors(unit.mover(), {})); - CHECK(timetable::opens_doors(unit.mover(), notcentral)); // the driver's doors open only from the cab + 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.mover(), {})); + 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.mover(), {})); - CHECK_FALSE(timetable::opens_doors(unit.mover(), notcentral)); - CHECK(timetable::opens_doors(unit.mover(), central)); + 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.mover(), central)); + CHECK_FALSE(timetable::opens_doors(unit.physics(), central)); unit->Doors.open_control = control_t::autonomous; - CHECK_FALSE(timetable::opens_doors(unit.mover(), central)); + CHECK_FALSE(timetable::opens_doors(unit.physics(), central)); } TEST_CASE("timetable: the doorsteps, the conductor and the brake test as the timetable says") { diff --git a/tests/unit/test_track_buckle_derailment.cpp b/tests/unit/test_track_buckle_derailment.cpp index 2f5d99592..98583743e 100644 --- a/tests/unit/test_track_buckle_derailment.cpp +++ b/tests/unit/test_track_buckle_derailment.cpp @@ -1,6 +1,6 @@ #include "stdafx.h" #include "doctest.h" -#include "McZapkie/derailment.h" +#include "physics/derailment.h" #include "world/TrackBuckle.h" #include 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_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_utilities.cpp b/tests/unit/test_utilities.cpp index 1b12f1b9a..d9309fa46 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -7,6 +7,7 @@ #include "utilities/Globals.h" #include "utilities/utilities.h" +#include "utilities/uuid.hpp" #include #include @@ -297,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) { 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/vehicle.cpp b/tests/unit/vehicle.cpp index afbac8680..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 { @@ -175,17 +175,18 @@ TTrackShape shape_of(track const &Track) { 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; } @@ -194,71 +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)}; + auto param{parameters_of(Track, *m_physics)}; param.DamageFlag = m_trackdamage; - return m_mover->FastComputeMovement(Dt, shape_of(Track), param, Location, TRotation{0.0, 0.0, 0.0}); + 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 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; } @@ -271,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 @@ -279,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; } @@ -291,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(); } } @@ -311,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(); } } @@ -334,11 +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() - TMoverParameters::UpdatePipeCouplers({&m_vehicles[0].owner->mover(), &m_vehicles[1].owner->mover()}, Dt); + physics::Vehicle::UpdatePipeCouplers({&m_vehicles[0].owner->physics(), &m_vehicles[1].owner->physics()}, Dt); } void pair::run(double Seconds, track const &Track, double Dt) { @@ -350,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 05c03dbf6..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); @@ -68,6 +73,7 @@ struct track { 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 }; @@ -83,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 @@ -112,10 +118,10 @@ 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}; @@ -129,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; @@ -148,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/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/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 ae90ad075..0ebb66791 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -1075,7 +1075,7 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& if (token == "physics.derailment") { - // new: the physical criteria (McZapkie/derailment.h), old: the legacy draw, off: no derailment from the speed, + // 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); @@ -1083,6 +1083,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.derailment.trustlimits") + { + ParseOne(Parser, derailment_trust_limits, 1); + return true; + } + if (token == "physics.trackcheck") { ParseOne(Parser, track_check, 1); @@ -1091,7 +1097,7 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& if (token == "physics.collisions") { - // new: the crush of the ends past the buffers (McZapkie/collision.h), old: the legacy rule, monitor: the legacy + // 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); @@ -1494,6 +1500,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; @@ -2294,6 +2306,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 ); @@ -2531,6 +2557,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 ); @@ -2577,6 +2604,7 @@ global_settings::export_as_text( std::ostream &Output ) const { } 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 ); @@ -2870,6 +2898,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 ); diff --git a/utilities/Globals.h b/utilities/Globals.h index c427d7535..52b0db797 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -148,10 +148,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{ false }; // vehicles standing still and held by their brakes let their physics sleep, see TMoverParameters::accelerating() + 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 @@ -361,14 +362,14 @@ struct global_settings { // 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 (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 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 McZapkie/derailment.h held over 2 m, and slides on with the friction of the ballast; old, the + // 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. @@ -376,8 +377,13 @@ struct global_settings { // 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 (McZapkie/collision.h); old, the legacy rule of the safe + // 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 }; @@ -495,7 +501,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; @@ -652,6 +662,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 }; 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/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/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/translation.cpp b/utilities/translation.cpp index 58c9746ab..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() { @@ -419,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/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/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 554d304cc..000000000 --- a/vehicle/Driver.cpp +++ /dev/null @@ -1,9657 +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/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 - -// 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; - } - bSeenAhead = signal_passing::seen_ahead_on_update( fDist, bSeenAhead ); - 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 -} - -bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders 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 ); - 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. - // 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() & 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(), mvOccupied->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 ? 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 -{ - // 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, TestFlag( Point.iFlags, spElapsed ), Point.bSeenAhead ) - || ( 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; - // 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.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 ); - // 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 - 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() - && true == timetable::has_conductor( m_stopflags ) ) { - // 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 (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 - 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; - // 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; -} - -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( brake_setting::inspects_train( OrderCurrentGet(), user == Connect ) ) { - // 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(); - } - - 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->EnginePowerSource.SourceType == TPowerSource::CurrentCollector - && mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { - // if our pantograph unit isn't a pantograph-devoid fallback - 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; - // 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->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 ); - } - } - control_field_shunting(); - // 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->Vel < EU07_AI_NOMOVEMENT ) { - // standing: the locomotive brake first, then the pipe is filled - secure_standing_train(); - } - else if( ( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_RP ) ) - && ( ( false == mvOccupied->Handle->Time ) - || ( mvOccupied->Handle->GetCP() < mvOccupied->HighPipePress - 0.05 ) ) ) { - cue_action( driver_hint::trainbrakerelease ); - } - // sync spring brake state across consist - 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; -} - -// 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 = mvOccupied->Vel < EU07_AI_NOMOVEMENT; - if( mvPantographUnit->PantPress >= Pantographpressure ) { - state.pantographs_up = - mvPantographUnit->Pantographs[ end::front ].is_active - || mvPantographUnit->Pantographs[ end::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->MoverParameters == mvPantographUnit ) { - auto const pantographcount { std::min( carrier->iAnimType[ ANIM_PANTS ], static_cast( carrier->MoverParameters->Pantographs.size() ) ) }; - for( auto index { 0 }; index < pantographcount; ++index ) { - if( true == carrier->MoverParameters->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( AIControllFlag ? 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( 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( brake_charge::holds_application( - bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) { - // the order to go came while the train still charges: released now, the wagons let go as their - // reservoirs fill and the train stands on a locomotive brake that doesn't hold it. the locomotive - // brake stays on with it - break; - } - if (deltaAcc < 0 && /*GBH mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) { - OK = /*mvOccupied->*/ BrakeLevelAdd(-0.25); - // 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); - } - // standing, the locomotive brake holds the train until its brakes are charged: off before, a train - // released on a gradient rolls with no air to brake with. nor through DecBrakeEIM(), which takes it off - // as well (the locomotive brake of a vehicle without the integrated handle) - auto const holdlocomotive { - ( false == IsConsistCharged ) - && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) }; - if( ( !OK ) && ( false == holdlocomotive ) ) { - OK = mvOccupied->DecLocalBrakeLevel(2); - } - if( ( !OK ) && ( false == holdlocomotive ) ) { - 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->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("SpeedCntrl", 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("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->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 == 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; - // doorsteps as the timetable asks, before the doors open (eu07/maszyna#95) - if( auto const doorstep { timetable::doorstep( m_stopflags ) }; - doorstep.has_value() && mvOccupied->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->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 - // 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->MoverParameters, 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() ) { - 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(); - 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 == 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(); - // the flags of the first station until the train stops there - m_stopflags = TrainParams.stop_flags(); - 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 - // 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 - 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 }; - auto chargelevel { std::numeric_limits::max() }; // the lowest pipe or auxiliary reservoir pressure of a working brake - while (p) - { // sprawdzenie odhamowania wszystkich połączonych pojazdów - auto *vehicle { p->MoverParameters }; - auto const bp { std::max( 0.0, vehicle->BrakePress - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->MaxBrakePress[ 0 ] * vehicle->StopBrakeDecc : 0.0 ) ) }; - momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); - mostapplied = std::max( bp, mostapplied ); - if( ( vehicle->BrakeSystem != TBrakeSystem::Individual ) - && ( vehicle->MaxBrakePress[ 3 ] > 0.0 ) - && ( false == TestFlag( vehicle->Hamulec->GetBrakeStatus(), b_dmg ) ) ) { // a brake cut out doesn't count - chargelevel = std::min( { chargelevel, vehicle->PipePress, vehicle->Hamulec->GetBRP() } ); - } - auto const wasready { Ready }; - if( released || Ready ) { - // bo jak coś nie odhamowane, to dalej nie ma co sprawdzać - 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 ); - // standing, the train starts only with its brakes charged: released alone, a train prepared from cold has no air to - // brake with while its auxiliary reservoirs fill. with the train brake applied (held for an uphill start, a light - // application while charging) they charge to what the head of the pipe has. - // only the start the charge is in question for: the first after the train was prepared standing, or one with the - // pipe near empty (after an emergency application, brake_charge::empty_level). after an ordinary stop the - // reservoirs refill as the brake releases, and waiting for the last tenths of a bar there only delays the train and - // those behind it. - // and only the pneumatic brake: multiple units with the electro-pneumatic one start as before - if( mvOccupied->Vel > 1.0 ) { - // the start is made. a shunting engine coupling wagons moves at a walking pace: a higher speed would leave its - // every start the first, waiting for each cut of wagons placed cold to charge - bBrakeChargeStart = false; - bBrakeChargeHold = false; - bHasRun = true; - } - auto const chargeable { - ( BrakeSystem == TBrakeSystem::Pneumatic ) - && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) - && ( chargelevel < std::numeric_limits::max() ) }; - if( chargeable && ( chargelevel < brake_charge::empty_level ) ) { - bBrakeChargeStart = true; - } - if( chargeable && bBrakeChargeStart ) { - if( ( VelDesired <= 0.0 ) || ( AccDesired <= EU07_AI_NOACCELERATION ) ) { - // to stand: the next start is checked anew - BrakeCharge.going = false; - } - auto const trainbrakeapplied { - AIControllFlag ? - BrakeCtrlPosition > 0.0 : - // a human driver's handle, which BrakeCtrlPosition doesn't follow - mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 }; - auto const reference { - brake_charge::reference( mvOccupied->PipePress, std::min( mvOccupied->Handle->GetRP(), 5.0 ), trainbrakeapplied ) }; - // air to charge with: the engine prepared, the main reservoir above what the pipe charges to, and the driver's - // brake valve feeding the pipe at the head of the train. a train still being prepared from cold can't charge, - // nor one whose pipe is locked (unlocked by control_releaser()): it waits without that counting as a stall, held - // by its brakes as it can't release them either - auto const supplied { - iEngineActive - && ( std::max( mvControlling->Compressor, mvOccupied->Compressor ) > reference ) - && ( mvOccupied->PipePress >= reference - brake_charge::margin ) }; - auto const wasstalled { BrakeCharge.stalled }; - IsConsistCharged = brake_charge::charged( BrakeCharge, chargelevel, reference, ElapsedTime, supplied ); - if( BrakeCharge.stalled && ( false == wasstalled ) ) { - WriteLog( - "AI: " + mvOccupied->Name + " stopped charging its brakes at " + to_string( chargelevel, 2 ) - + " bar of " + to_string( reference, 2 ) + ", starting all the same" ); - } - if( false == IsConsistCharged ) { - // a human driver is told to wait as the ai does, the locomotive brake applied - cue_action( driver_hint::waitbrakecharge ); - } - } - else { - IsConsistCharged = true; - BrakeCharge = {}; - } - if( AIControllFlag - && ( false == IsConsistCharged ) - && ( false == heldforstart ) ) { - Ready = false; - } - auto const departblocked { - AIControllFlag - && mvOccupied->Vel < EU07_AI_NOMOVEMENT - && 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() { - // 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( mvOccupied->Vel ) }; - if( mvControlling->SlippingWheels - && velocity < EU07_AI_SANDEDSTARTVELOCITY - && false == mvControlling->IsMainCtrlNoPowerPos() - && mvControlling->Sand > 0.0 ) { - bSandedStart = true; - } - else if( velocity >= EU07_AI_SANDEDSTARTVELOCITY - || ( velocity < EU07_AI_NOMOVEMENT && VelDesired == 0.0 ) ) { - bSandedStart = false; - } - // wheel slip - if( mvControlling->SlippingWheels ) { - cue_action( driver_hint::sandingon ); // piasku! - if( false == bSandedStart ) { - cue_action( driver_hint::tractiveforcedecrease ); - cue_action( driver_hint::antislip ); - } - else if( ElapsedTime - fSandedStartDecreaseTime >= 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 ); - fSandedStartDecreaseTime = ElapsedTime; - } - cue_action( driver_hint::brakingforcedecrease ); - ++iDriverFailCount; - } - else if( ( std::fabs( mvControlling->Im ) > 0.75 * mvControlling->ImaxHi ) - || ( bSandedStart && 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( 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 ] }; - // 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 - ( mvOccupied->LocalBrake == TLocalBrake::PneumaticBrake || mvOccupied->LocalBrake == TLocalBrake::HydraulicBrake ) ? - mvOccupied->LocalBrakePosA : - 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( ( DynamicBrakeTest == 0 ) - && ( 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( 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 -} - -// 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( AIControllFlag - && 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 )*/ || mvOccupied->SpeedCtrlUnit.IsActive && velocity < mvOccupied->SpeedCtrlUnit.FullPowerVelocity) && - false == TestFlag(iDrivigFlags, movePress) && - // starting uphill against the releasing brake, no more power than holds the train - uphill_start::may_add_power( bUphillRelease, fUphillTractiveForce, 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; - } - 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; - 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 = fUphillTractiveForce, - .grade_force = fUphillHoldingForce, - .consist_released = IsConsistReleased, - .consist_charged = IsConsistCharged }; - if( false == bUphillStart ) { - if( false == uphill_start::begins( now ) ) { - return; - } - bUphillStart = true; - bUphillRelease = false; - UphillTopUp = {}; - fUphillStartTime = 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; - } - 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( uphill_start::power_holds( now, ElapsedTime - fUphillStartTime ) ) { - // 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( uphill_start::released( now, ElapsedTime - fUphillReleaseTime ) ) { - end_uphill_start(); - } -} - -// the locomotive brake comes off only once the brake of the rest of the train holds the train on its own: a train -// stopped on a light application stands on the locomotive brake too, and rolls back as soon as it is off. until then -// the train brake is applied further, a step at a time; true while it is -bool TController::uphill_brake_top_up() { - - auto trainbrakeforce { 0.0 }; - auto haswagons { false }; - for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - if( vehicle->MoverParameters->Power < 0.01 ) { - trainbrakeforce += vehicle->MoverParameters->Fb; - haswagons = true; - } - } - if( false == haswagons ) { - return false; - } - auto const action { uphill_start::brake_top_up( - UphillTopUp, trainbrakeforce, fUphillHoldingForce, BrakeCtrlPosition, fBrakeHeldTime, - mvOccupied->BrakeDelay[ mvOccupied->BrakeDelayFlag > bdelay_G ? 1 : 3 ] ) }; - if( action == uphill_start::top_up_action::none ) { - return false; - } - // the time for the power to hold the train starts once the brake does - fUphillStartTime = ElapsedTime; - if( action == uphill_start::top_up_action::step ) { - BrakeLevelAdd( BrakingLevelIncrease ); - } - return true; -} - -void TController::end_uphill_start() { - - bUphillStart = false; - bUphillRelease = false; - bUphillBrakeTopUp = false; -} - -// standing, a train is prepared as a driver does it: the locomotive brake first, then the brake pipe is filled. the pipe -// filled at once releases the distributors while the auxiliary reservoirs are still empty: the train has no brake left, -// and on a gradient rolls away as it releases. where the locomotive brake alone doesn't hold the train, the train brake -// is applied lightly, so the reservoirs charge with the train held. the locomotive brake comes off only once the train -// is charged and to start (DecBrake()) -void TController::secure_standing_train() { - - if( BrakeSystem != TBrakeSystem::Pneumatic ) { - // the electro-pneumatic brake of a multiple unit is released as before: nothing there takes the locomotive - // brake off again when the unit starts - cue_action( driver_hint::trainbrakerelease ); - return; - } - // the first start of a train that hasn't run yet waits for the brakes to charge. one that has run, prepared again - // (a change of direction, an engine started anew), has its reservoirs charged from the run and starts as before - if( false == bHasRun ) { - bBrakeChargeStart = true; - } - if( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) { - cue_action( driver_hint::independentbrakeapply ); - } - if( false == brake_charge::locomotive_brake_holds( locomotive_brake_force(), fMass * fAccGravity ) ) { - // the first service position: the pipe and the reservoirs charge to a little below the working pressure, the - // distributors keep a light application. a stronger application already there is left as it is, but not - // the emergency one or an empty pipe's, which don't charge - if( AIControllFlag - && ( ( BrakeCtrlPosition < 1.0 ) || ( BrakeCtrlPosition > uphill_start::top_up_position ) ) ) { - BrakeLevelSet( 1.0 ); - } - bBrakeChargeHold = true; - return; - } - bBrakeChargeHold = false; - cue_action( driver_hint::trainbrakerelease ); -} - -// the brake force of the locomotive brake at full application [N]. of the occupied vehicle alone: its handle acts on -// no other, not on a second section or a locomotive in multiple control either, let alone one hauled dead -double TController::locomotive_brake_force() const { - - if( ( mvOccupied->LocalBrake == TLocalBrake::ManualBrake ) - || ( mvOccupied->MaxBrakePress[ 0 ] <= 0.0 ) ) { - return 0.0; - } - return brake_charge::locomotive_brake_force( - mvOccupied->BrakeForceP( mvOccupied->MaxBrakePress[ 0 ], 0.0 ), - mvOccupied->TotalMassxg ); -} - -void TController::increase_tractive_force() { - - 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 - // a human driver standing with the train not charged yet keeps the locomotive brake on, told so by the - // waitbrakecharge hint; the ai is held back in DecBrake() - && ( AIControllFlag - || ( false == brake_charge::release_waits( - IsConsistCharged, - mvOccupied->Vel < EU07_AI_NOMOVEMENT, - mvOccupied->fBrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) + 0.2 ) ) ) ) { // the human driver's handle - // jak hamuje, to nie tykaj kranu za często - // yB: luzuje hamulec dopiero przy różnicy opóźnień rzędu 0.2 - // przy odłączaniu nie zwalniamy tu hamulca - // 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; } - - brake_releaser::conditions state; - state.acceleration_desired = AccDesired; - state.pipe_pressure = mvOccupied->PipePress; - state.cylinder_pressure = mvOccupied->BrakePress; - state.control_pressure = mvOccupied->Hamulec->GetCRP(); - state.velocity = mvOccupied->Vel; - state.uphill_start = bUphillStart; - state.pressing = TestFlag( iDrivigFlags, movePress ); - // stage 3 of uncoupling (UpdateDisconnect), from the direction change until the coupler lets go - state.compressing_buffers = - state.pressing && ( OrderCurrentGet() & Disconnect ) != 0 && iVehicleCount >= 0 && iDirection == iDirectionOrder; - // a train prepared standing charges its brakes before its first start. a pipe left below the lock of the driver's - // brake valve (a train placed cold, as after an emergency application) is unlocked as the train stands, not only - // once it is to go: else it charges only after the order to go, and starts on what the reservoirs got by then. - // a handle which has to be moved to unlock is left where it holds the train with the train brake - state.charging_standing = - bBrakeChargeStart - && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) - && ( ( mvOccupied->HandleUnlock == -3 ) || ( BrakeCtrlPosition <= 0.0 ) ); - auto const wanted { brake_releaser::decide( state ) }; - auto const actuate { wanted.actuate }; - auto isbrakehandleinrightposition { true }; - - // some vehicles require brake handle to be moved to specific position to fill up the brake pipe - if( wanted.fill_pipe - && mvOccupied->HandleUnlock != -3 ) { - cue_action( driver_hint::trainbrakesetpipeunlock ); - isbrakehandleinrightposition = ( BrakeCtrlPosition == mvOccupied->HandleUnlock ); - } - - 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 - // standing to charge before the first start, as in control_releaser() - || ( bBrakeChargeStart && ( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) ) ) - && 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() ) ) ) - // the light application a charging train stands on stays, as in DecBrake() - && ( false == brake_charge::holds_application( - bBrakeChargeHold, IsConsistCharged, mvOccupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) ) { - cue_action( driver_hint::trainbrakerelease ); - } - } -} - -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 0fc445ce3..c58ce134b 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -13,7 +13,8 @@ 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" @@ -33,25 +34,8 @@ auto const EU07_AI_UPHILLGRAVITY = -0.025; // [m/s2] about 2.5 per mille up: the 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, @@ -60,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 @@ -131,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 @@ -165,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 @@ -176,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(); @@ -189,11 +186,11 @@ class TSpeedPos UpdateDistance( double dist ) { fDist -= dist; } // 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, TOrders order = Wait_for_orders, bool Standing = false); - void Set(TTrack *t, double d, int f); + 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); }; //---------------------------------------------------------------------------- @@ -216,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 ); @@ -240,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 @@ -264,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 @@ -288,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; @@ -323,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; @@ -332,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; @@ -407,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(); @@ -423,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 @@ -435,30 +508,20 @@ 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 - bool bSandedStart = false; // the wheels slipped while starting: sand while under power until the train is under way - double fSandedStartDecreaseTime = -1.0; // when the power was last taken down a step for a slip while starting - double fUphillStartTime = 0.0; // when the uphill start began - bool bUphillRelease = false; // starting uphill, the power holds the train and the train brake is being released - bool bUphillBrakeTopUp = false; // starting uphill, the train brake is applied further before the locomotive brake comes off - uphill_start::top_up UphillTopUp; // starting uphill, what has been done to apply the train brake further - double fUphillReleaseTime = 0.0; // when the release began - double fUphillTractiveForce = 0.0; // the tractive force of the consist while starting uphill [N] - double fUphillHoldingForce = 0.0; // the grade force on the consist while starting uphill [N] + 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 @@ -488,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; @@ -511,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) @@ -538,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 @@ -565,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 @@ -621,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 { @@ -635,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; @@ -682,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(); @@ -706,7 +754,7 @@ 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) @@ -736,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 @@ -780,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; @@ -792,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 b7acdc262..000000000 --- a/vehicle/DynObj.cpp +++ /dev/null @@ -1,10611 +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/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" - -// 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( 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(); - } -} - -} // 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 ); - } - } -} - -// 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( *MoverParameters, pAnim ), MoverParameters->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( MoverParameters->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 { 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 - // 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( MoverParameters->CabOccupied, MoverParameters->DirAbsolute, followsdirection ) }; - btMechanik1.Turn( figure > 0 ); - btMechanik2.Turn( figure < 0 ); - if( figure != 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(); - } - // the parts the editor holds, over what the vehicle has set - if( apply_held_parts() ) { - btnOn = true; - } - // 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 && MoverParameters->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 && ( MoverParameters->OffTrack.active() || dynamic->MoverParameters->OffTrack.active() ) && false == in_line_with( *dynamic ) ) { - continue; - } -/* - 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; - } - // the stretches the criteria of derailment held over were on the track the vehicle left (consistteleport) - MoverParameters->derailment_monitor.reset(); - MoverParameters->derailment_distance = 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 - 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( hauled ) { - // once the vehicle has its starting state: the hand brake and the spring brake of a standing one let go, battery off - MoverParameters->PulleeModeSwitch( true ); - } - - 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) -{ - if( MoverParameters->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 (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 - } -} - -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 (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 - } -*/ - } - } - } -} - -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; -} - -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, int const End ) { - auto const facing { End == end::front ? 1.0 : -1.0 }; - auto const &motion { Vehicle.MoverParameters->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.MoverParameters->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( TMoverParameters const &Vehicle, int const End ) { - return ( End == end::front ? -1.0 : 1.0 ) * Vehicle.Couplers[ End ].CForce; -} - -// 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; - -double seconds_since( off_track_clock::time_point const Start ) { - return std::chrono::duration( off_track_clock::now() - Start ).count(); -} - -std::string_view side_name( int const Side ) { - if( Side > 0 ) { - return "left"; - } - return Side < 0 ? "right" : "none"; -} - -} // namespace - -double TDynamicObject::off_track_gap( int const End ) const { - - auto const *neighbour { MoverParameters->Neighbours[ End ].vehicle }; - if( neighbour == nullptr ) { - return 0.0; - } - return derail_motion::meet( end_point_of( *this, End ), end_point_of( *neighbour, MoverParameters->Neighbours[ End ].vehicle_end ) ).gap; -} - -double TDynamicObject::off_track_offset() const { - - if( false == MoverParameters->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, McZapkie/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 MoverParameters->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 &mover { *MoverParameters }; - auto const &position { mover.OffTrack.active() ? mover.OffTrack.current().position : vPosition }; - // as far as it may slide, and some - auto const slide { derail_motion::stopping_distance( mover.V, derailment::off_rails_friction ).value_or( 0.0 ) }; - auto const reach { std::min( slide + mover.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( mover.OffTrack.active() ) { - heading = mover.OffTrack.heading(); - } - auto const length { glm::length( heading ) }; - auto const stop { length > 1e-6 ? position + heading * ( std::copysign( std::max( reach - mover.Dim.L - 50.0, 0.0 ), mover.V ) / length ) : position }; - auto const margin { mover.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", MoverParameters->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 { 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, MoverParameters->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 { MoverParameters->OffTrack.current().position }; - auto const reach { 0.5 * MoverParameters->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() { - - auto &mover { *MoverParameters }; - derail_motion::vehicle_shape shape; - shape.length = mover.Dim.L; - shape.width = mover.Dim.W > 0.5 ? mover.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 = mover.Dim.H > 2.0 ? mover.Dim.H : 4.0; - shape.centre_of_gravity = mover.centre_of_gravity(); - shape.contact_spacing = derailment::contact_spacing( mover.TrackW ); - shape.base = std::max( static_cast( fAxleDist ), 1.0 ); - shape.mass = mover.TotalMass; - - derail_motion::start start; - start.position = vPosition; - start.front = vFront; - start.line = track_front(); - start.speed = mover.V; - start.reason = mover.DerailCause; - start.outward = ( mover.DerailSide != 0 ? mover.DerailSide : outward_side() ); - start.acceleration = mover.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, mover.Name ) ) }; - mover.OffTrack.begin( start, shape, m_offtracksite, scatter ); - m_pulledoff = {}; - m_offtracklogdue = 0.0; - m_offtrackslowdue = 0.0; - m_offtrackaxles = 0.0; - m_offtrackfrom = mover.OffTrack.current().position; - - auto const heading { mover.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", - mover.Name, std::abs( mover.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}{}", - mover.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 { MoverParameters->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( int end = end::front; end <= end::rear; ++end ) { - auto const *neighbour { MoverParameters->Neighbours[ end ].vehicle }; - auto const compression { compression_of( *MoverParameters, end ) }; - if( neighbour == nullptr || compression == 0.0 ) { - continue; - } - ends[ end ] = derail_motion::force_on( - derail_motion::meet( end_point_of( *this, end ), end_point_of( *neighbour, MoverParameters->Neighbours[ end ].vehicle_end ) ), compression ); - } - auto const reversals { motion.reversals() }; - motion.step( time, Distance, MoverParameters->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 - MoverParameters->V = -MoverParameters->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( Distance ); - - // what it cost: a frame of the vehicle off the track should take well under a millisecond - auto const took { 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", MoverParameters->Name, took * 1000.0, time ) ); - } -} - -void TDynamicObject::place_off_track() { - - auto const &pose { MoverParameters->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 * MoverParameters->Dim.L * vFront }; - vCoulpler[ end::front ] = vPosition + half; - vCoulpler[ end::rear ] = vPosition - half; - m_offtrackplaced = true; -} - -void TDynamicObject::pull_neighbours( double const Distance ) { - - for( int end = end::front; end <= end::rear; ++end ) { - auto const &coupler { MoverParameters->Couplers[ end ] }; - auto *neighbour { MoverParameters->Neighbours[ end ].vehicle }; - if( coupler.CouplingFlag == coupling::faux || neighbour == nullptr || neighbour->MoverParameters->OffTrack.active() - || TestFlag( neighbour->MoverParameters->DamageFlag, dtrain_out ) ) { - m_pulledoff[ end ].reset(); - continue; - } - auto &other { *neighbour->MoverParameters }; - auto const otherend { MoverParameters->Neighbours[ end ].vehicle_end }; - 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 ) }; - if( false == m_pulledoff[ end ].update( ratio >= derailment::climbing_limit, Distance ) ) { - 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", MoverParameters->Name, glm::degrees( angle ), magnitude / 1000.0 ) ); - m_pulledoff[ end ].reset(); - } -} - -void TDynamicObject::update_off_track( double const Deltatime ) { - - auto const &motion { MoverParameters->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{}", - MoverParameters->Name, resting ? "came to rest" : "off the track", motion.travelled(), off_track_offset(), std::abs( MoverParameters->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" : "" ) ); -} - -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 - // 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 { 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->MoverParameters->Name, took * 1000.0, frame ) ); - } - } - private: - TDynamicObject *vehicle; - double frame; - off_track_clock::time_point started {}; - }; - off_track_watch const watch { MoverParameters->OffTrack.active() ? this : nullptr, dt1 }; - if( m_offtrackterrain != nullptr && false == MoverParameters->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 (!MoverParameters->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( MoverParameters->OffTrack.active() && false == MoverParameters->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 - - 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 - // 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( MoverParameters->ADist ) + Axle1.BuckleCurvature( MoverParameters->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(); - - // 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 - && false == MoverParameters->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: " + 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); - } - // the holding brake lets go once power has been demanded for its delay (SBDReleaseDelay, none by default) - auto const holdingbrakereleased { MoverParameters->UpdateStopBrakeRelease( eimic, dt1 ) }; - if (MoverParameters->ShuntMode && false == holdingbrakereleased || 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 ); - } - // physics.derailment new: derailed, the vehicle leaves the track and goes on the ground - if( MoverParameters->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(); - - 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 - // 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 = MoverParameters->CatenaryCurrent(); - // 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 - // held by the editor, the pantograph goes where it was put, whatever the air and the switches - if( ( i < static_cast( m_heldpantographs.size() ) ) - && ( m_heldpantographs[ i ] != pantograph_hold::none ) ) { - move_pantograph( *p, m_heldpantographs[ i ] == pantograph_hold::up, dt1 ); - continue; - } - 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 - - // 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( MoverParameters->OffTrack.active() && false == MoverParameters->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( 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; -} - -namespace { - -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 " + 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 - 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, - MoverParameters->Doors.type, - MoverParameters->Doors.range, - MoverParameters->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( 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:" ) { - 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; - 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 + 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; - } - else { - read_driver_position( parser, token, cabplaces ); - } - - } while( token != "" ); - - SingleDesk = driver_figure::single_desk( JointCabs, cabplaces[ 0 ], cabplaces[ 1 ] ); - - } // 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 ); - if( MoverParameters->OffTrack.active() || neighbour.vehicle->MoverParameters->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) - neighbour.distance = off_track_gap( end ); - } - // 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 }; - // 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( 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->MoverParameters->CategoryFlag == 2 ? 50 : 100) ) { - // at short distances (re)calculate range between couplers directly - neighbour.distance = TMoverParameters::CouplerDist( MoverParameters, neighbour.vehicle->MoverParameters ); - if( MoverParameters->OffTrack.active() || neighbour.vehicle->MoverParameters->OffTrack.active() ) { - // physics.derailment new: the ends where they are, as for a coupled pair - neighbour.distance = off_track_gap( end ); - } - // 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; - } - } - } -} - -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 * ( MoverParameters->Dim.W + Other.MoverParameters->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 { ( 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, 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 { 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 - 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 + '@' + 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 - // 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->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( 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 ); - } - 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 &mover { *Vehicle.MoverParameters }; - derail_motion::pose pose; - if( mover.OffTrack.active() ) { - pose = mover.OffTrack.current(); - } - else { - pose.position = Vehicle.GetPosition(); - pose.front = Vehicle.VectorFront(); - pose.left = Vehicle.VectorLeft(); - pose.up = Vehicle.VectorUp(); - } - auto const &shape { mover.OffTrack.shape() }; - return derail_motion::footprint_of( - pose, mover.Dim.L, - mover.OffTrack.active() ? shape.width : ( mover.Dim.W > 0.5 ? mover.Dim.W : 3.0 ), - mover.OffTrack.active() ? shape.height : ( mover.Dim.H > 2.0 ? mover.Dim.H : 4.0 ) ); -} - -// the vehicle as a body in a contact -derail_motion::contact_body contact_body_of( TDynamicObject const &Vehicle ) { - - auto const &mover { *Vehicle.MoverParameters }; - derail_motion::contact_body body; - body.mass = mover.TotalMass; - if( mover.OffTrack.active() ) { - body.base = mover.OffTrack.base(); - body.velocity = mover.OffTrack.velocity(); - body.yaw_rate = mover.OffTrack.yaw_rate(); - body.gyration = mover.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 * mover.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.MoverParameters->OffTrack.active() && Second.MoverParameters->OffTrack.active() }; - for( int end = end::front; end <= end::rear; ++end ) { - if( First.MoverParameters->Couplers[ end ].Connected == Second.MoverParameters - && First.MoverParameters->Couplers[ end ].CouplingFlag != coupling::faux ) { - return offtrack ? "coupled, both off the track" : "coupled, one on the rails"; - } - if( First.MoverParameters->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 ]->MoverParameters->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->MoverParameters->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->MoverParameters->OffTrack.active() }; - if( otheroff && otherplace < place ) { - continue; - } - // the bounding circles first - auto const apart { other->GetPosition() - vehicle->GetPosition() }; - auto const otherreach { 0.5 * other->MoverParameters->Dim.L + std::max( other->MoverParameters->Dim.W, other->MoverParameters->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->MoverParameters->Name, other->MoverParameters->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->MoverParameters->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->MoverParameters->V = 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->MoverParameters->OffTrack }; - if( glm::length( impulse ) > 0.0 ) { - othermotion.kick( othervelocity, otheryawrate ); - other->MoverParameters->V = 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 &othermover { *other->MoverParameters }; - othermover.V += glm::dot( impulse, otherbody.guide ) / std::max( othermover.TotalMass, 1.0 ); - if( TestFlag( othermover.DamageFlag, dtrain_out ) ) { - continue; - } - glm::dvec3 const otherleft { otherbody.guide.z, 0.0, -otherbody.guide.x }; - auto const across { glm::dot( impulse, otherleft ) / Deltatime }; - auto const mass { othermover.TotalMass - othermover.Mred }; - auto const ratio { derail_motion::pull_ratio( std::abs( across ), 0.5 * std::numbers::pi, mass, othermover.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 ) { - othermover.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->MoverParameters->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 { 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->MoverParameters->PipeCouplersPending ) - || ( true == vehicle->MoverParameters->ScndPipeCouplersPending ) ) { - m_brakepipes.push_back( vehicle->MoverParameters ); - } - } - TMoverParameters::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->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 ); }; - // 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 *mover { m_items[ index ]->MoverParameters }; - if( mover->PipeCouplersPending || mover->ScndPipeCouplersPending ) { - pipes.push_back( mover ); - } - } - TMoverParameters::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->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; -} - -std::array const &TDynamicObject::held_part_table() { - static std::array const table { { - { "coupler1", &TDynamicObject::btCoupler1 }, - { "coupler2", &TDynamicObject::btCoupler2 }, - { "cpneumatic1", &TDynamicObject::btCPneumatic1 }, - { "cpneumatic1r", &TDynamicObject::btCPneumatic1r }, - { "cpneumatic2", &TDynamicObject::btCPneumatic2 }, - { "cpneumatic2r", &TDynamicObject::btCPneumatic2r }, - { "pneumatic1", &TDynamicObject::btPneumatic1 }, - { "pneumatic1r", &TDynamicObject::btPneumatic1r }, - { "pneumatic2", &TDynamicObject::btPneumatic2 }, - { "pneumatic2r", &TDynamicObject::btPneumatic2r }, - { "headlamp11", &TDynamicObject::m_headlamp11 }, - { "headlamp12", &TDynamicObject::m_headlamp12 }, - { "headlamp13", &TDynamicObject::m_headlamp13 }, - { "highbeam12", &TDynamicObject::m_highbeam12 }, - { "highbeam13", &TDynamicObject::m_highbeam13 }, - { "headsignal12", &TDynamicObject::m_headsignal12 }, - { "headsignal13", &TDynamicObject::m_headsignal13 }, - { "headlamp21", &TDynamicObject::m_headlamp21 }, - { "headlamp22", &TDynamicObject::m_headlamp22 }, - { "headlamp23", &TDynamicObject::m_headlamp23 }, - { "highbeam22", &TDynamicObject::m_highbeam22 }, - { "highbeam23", &TDynamicObject::m_highbeam23 }, - { "headsignal22", &TDynamicObject::m_headsignal22 }, - { "headsignal23", &TDynamicObject::m_headsignal23 } } }; - return table; -} - -char const *TDynamicObject::held_part_name( std::size_t const Part ) { - return held_part_table()[ Part ].name; -} - -bool TDynamicObject::held_part_present( std::size_t const Part ) const { - return ( this->*( held_part_table()[ Part ].part ) ).Active(); -} - -std::size_t TDynamicObject::part_of( TSubModel const *Submodel ) const { - auto const &table { held_part_table() }; - for( auto const *submodel { Submodel }; submodel != nullptr; submodel = submodel->Parent ) { - auto const found { std::ranges::find_if( table, [ this, submodel ]( held_part_entry const &Entry ) { return ( this->*( Entry.part ) ).is_part( submodel ); } ) }; - if( found != table.end() ) { - return static_cast( std::distance( table.begin(), found ) ); - } - } - return held_part_total; -} - -bool TDynamicObject::apply_held_parts() { - auto held { false }; - auto const &table { held_part_table() }; - for( std::size_t idx = 0; idx < table.size(); ++idx ) { - auto &part { this->*( table[ idx ].part ) }; - switch( m_heldparts[ idx ] ) { - case part_hold::off: { part.TurnOff(); break; } - case part_hold::on: { part.TurnOn(); break; } - case part_hold::xon: { part.TurnxOn(); break; } - default: { continue; } - } - held = true; - } - return held; -} - -int TDynamicObject::pantograph_count() const { - return std::min( iAnimType[ ANIM_PANTS ], static_cast( m_heldpantographs.size() ) ); -} - -void TDynamicObject::hold_pantograph( int const Pantograph, pantograph_hold const Hold ) { - if( ( Pantograph < 0 ) || ( Pantograph >= pantograph_count() ) ) { - return; - } - m_heldpantographs[ Pantograph ] = Hold; -} - -void TDynamicObject::step_held_pantographs( double const Timedelta ) { - if( pants == nullptr ) { - return; - } - for( int idx = 0; idx < pantograph_count(); ++idx ) { - if( ( m_heldpantographs[ idx ] != pantograph_hold::none ) && ( pants[ idx ].fParamPants != nullptr ) ) { - move_pantograph( *pants[ idx ].fParamPants, m_heldpantographs[ idx ] == pantograph_hold::up, Timedelta ); - } - } -} - -int TDynamicObject::pantograph_of( TSubModel const *Submodel ) const { - if( pants == nullptr ) { - return -1; - } - for( auto const *submodel { Submodel }; submodel != nullptr; submodel = submodel->Parent ) { - for( int idx = 0; idx < pantograph_count(); ++idx ) { - auto const *arms { pants[ idx ].smElement }; - if( ( arms != nullptr ) && std::ranges::find( arms, arms + 5, submodel ) != arms + 5 ) { - return idx; - } - } - } - return -1; -} - -void TDynamicObject::move_pantograph( TAnimPant &Pantograph, bool const Up, double const Timedelta ) { - // the upper arm follows the lower one, and the height follows both, as the pantograph moves in Update() - auto const upper = [ &Pantograph ]( double const Lower ) { - return std::acos( std::clamp( ( Pantograph.fLenL1 * std::cos( Lower ) + Pantograph.fHoriz ) / Pantograph.fLenU1, -1.0, 1.0 ) ); }; - auto const height = [ &Pantograph, &upper ]( double const Lower ) { - return Pantograph.fLenL1 * std::sin( Lower ) + Pantograph.fLenU1 * std::sin( upper( Lower ) ) + Pantograph.fHeight; }; - // the angle of the lower arm it goes to: down at rest, up at the wire it has, or without one 1.6 m over its rest, and no - // further than the arms reach - auto target { Pantograph.fAngleL0 }; - if( Up ) { - auto const top { Pantograph.hvPowerWire != nullptr ? Pantograph.PantTraction : height( target ) + 1.6 }; - constexpr double step { 0.002 }; - while( ( height( target ) < top ) && ( target + step + upper( target + step ) < std::numbers::pi ) ) { - target += step; - } - } - // a few seconds from the rest to the wire, a little slower down, as the air moves it - auto const pace { ( Up ? 0.3 : 0.2 ) * std::max( 0.0, Timedelta ) }; - auto lower { Pantograph.fAngleL }; - lower = lower < target ? std::min( lower + pace, target ) : std::max( lower - pace, target ); - Pantograph.fAngleL = lower; - Pantograph.fAngleU = upper( lower ); - Pantograph.PantWys = height( lower ); -} diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 2b9edb861..6025868cd 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" @@ -30,6 +34,7 @@ http://mozilla.org/MPL/2.0/. #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 @@ -137,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 { @@ -187,16 +192,6 @@ 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; @@ -207,7 +202,7 @@ public: //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 @@ -227,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(); @@ -423,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 { @@ -484,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 { @@ -517,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, @@ -606,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 }; @@ -644,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! @@ -668,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); @@ -698,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 @@ -750,6 +756,26 @@ 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); @@ -758,7 +784,7 @@ private: 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( int End ) const; + double off_track_gap( VehicleEnd End ) const; private: // the axles moved along their tracks by the distance void move_axles( double Distance ); @@ -775,14 +801,14 @@ private: 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 (McZapkie/derailment.h); on a straight track out of the turn of + // 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, the step - // having travelled the distance - void pull_neighbours( double Distance ); + // 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 ); @@ -803,14 +829,37 @@ private: // 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 - std::array m_pulledoff; // the distance the coupling of an end pulled the vehicle coupled there over the climbing limit + 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 @@ -822,7 +871,7 @@ public: // 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 ? @@ -850,12 +899,27 @@ public: 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 + int OccupiedCab() const; // the cab the crew is in: 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; @@ -864,6 +928,39 @@ public: // 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. @@ -884,17 +981,17 @@ public: 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 ]; } // the hold of the editor on parts of the vehicle (the EU07M model window): the lamps, the coupler hooks and the hoses shown in // a state of its choice, and the pantographs held up or down, whatever the vehicle does with them. nothing is held at first enum class part_hold : std::uint8_t { none, off, on, xon }; @@ -916,6 +1013,8 @@ public: void step_held_pantographs( double Timedelta ); // the pantograph the submodel is an arm of, or is in; -1 when it's none int pantograph_of( TSubModel const *Submodel ) const; + // every hold let go of: the parts and the pantographs are the vehicle's own again (the editor closed, another vehicle picked) + void release_holds(); private: struct held_part_entry { char const *name; @@ -931,9 +1030,9 @@ public: 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 @@ -952,11 +1051,11 @@ public: 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); @@ -981,13 +1080,10 @@ public: 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 @@ -1090,25 +1186,25 @@ private: 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_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 @@ -1117,16 +1213,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 0944fe83b..48b21ac1c 100644 --- a/vehicle/Gauge.cpp +++ b/vehicle/Gauge.cpp @@ -509,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 9c93057c1..0bda4f2b6 100644 --- a/vehicle/Gauge.h +++ b/vehicle/Gauge.h @@ -55,10 +55,10 @@ public: 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 @@ -142,10 +142,10 @@ private: 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 3c4e5f6fe..000000000 --- a/vehicle/Train.cpp +++ /dev/null @@ -1,13344 +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/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 -#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::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}, -}; - -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, unless the cruise control has its own - if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1 && false == Train->mvControlled->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->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); - } - // visual feedback - Train->ggAutoRelayButton.UpdateValue(Train->mvOccupied->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->mvControlled->IsSpeedCtrlEngaged()) - { - // turn on if it's not active - Train->mvControlled->SpeedCtrlSwitch(true); - // visual feedback - Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // otherwise turn off - Train->mvControlled->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->mvControlled->IsSpeedCtrlEngaged()) - { - // turn on - Train->mvControlled->SpeedCtrlSwitch(true); - // visual feedback - Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // turn off - Train->mvControlled->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->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, unless the cruise control has its own - if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1 && false == Train->mvControlled->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->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 == 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 (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 == linebreaker::state::open) - { - return; - } // already in the desired state - - if (true == Train->mvControlled->MainSwitch(false, Train->mvControlled->MainSwitchRange())) - { - Train->m_linebreakerstate = linebreaker::state::open; - 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 == 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->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()) ? 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 - -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); -} - -// 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->mvControlled->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->mvControlled->TractionModeSwitch(TMoverParameters::traction_mode::catenary, range_t::consist); - if (false == Train->mvControlled->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->mvControlled->TractionModeSwitch(TMoverParameters::traction_mode::genset, range_t::consist); - if (Train->mvControlled->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->mvControlled->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->mvControlled->GensetSwitch(true, range_t::consist); - if (Train->mvControlled->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->mvControlled->GensetSwitch(false, range_t::consist); - if (false == Train->mvControlled->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->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) - { - if (false == restartcycle) - { - Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->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->mvOccupied->LightsPos - 1), true, Train->mvOccupied->LightsPosNo, Train->dsbSwitch); - } - } - } -} - -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) - { - if (false == restartcycle) - { - Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->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->mvOccupied->LightsPos - 1), false, Train->mvOccupied->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->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; - } - - 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->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); - // 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->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); - // 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->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, 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->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 == linebreaker::state::open && true == mvControlled->Mains) - { - // crude way to sync state of the linebreaker with ai-issued commands - m_linebreakerstate = linebreaker::state::closed; - } - if (m_linebreakerstate == linebreaker::state::closed && 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 = linebreaker::state::open; - } - 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 == 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 (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 == linebreaker::state::open && 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 = 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 || 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()) ? linebreaker::state::closed : linebreaker::state::open; - } - // 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 == linebreaker::state::closing || mvControlled->Mains); - btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); - btLampkaMainBreakerReady.Turn(mvControlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != linebreaker::state::closing && !mvControlled->Mains); - btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || 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->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 (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(); - ggAutoRelayButton.UpdateValue(mvOccupied->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(); - - //--------- - // 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(); - //------------ - // 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 && mvOccupied->ConvSwitchType != "impulse" && mvOccupied->ConverterStart == start_t::manual) - { - ggConverterButton.UpdateValue(mvOccupied->ConverterAllow ? 1.f : 0.f, dsbSwitch); - } - ggConverterButton.Update(); - if (ggConverterLocalButton.SubModel != nullptr) - { - ggConverterLocalButton.UpdateValue(mvOccupied->ConverterAllowLocal ? 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->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(); - ggTractionModeSwitch.Update(); - ggGensetButton.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 (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)); -} - -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(); - 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 : 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 != 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) - { - 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(mvOccupied->ConverterAllow ? 1.f : 0.f); - } - ggConverterLocalButton.PutValue(mvOccupied->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); - // automatic relays (AutoRelay) - ggAutoRelayButton.PutValue(mvOccupied->AutoRelayFlag ? 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 selector and genset of a dual-mode vehicle - ggTractionModeSwitch.PutValue(mvControlled->GensetSelected() ? 1.f : 0.f); - if (ggGensetButton.type() != TGaugeType::push) - { - ggGensetButton.PutValue(mvControlled->Genset.is_enabled ? 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->IsSpeedCtrlEngaged() ? 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}, - {"i-compartmentlights:", &mvOccupied->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, &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 8e51447ce..e77e8ffc4 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -180,6 +180,36 @@ class TTrain { 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; @@ -218,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 ); @@ -233,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 @@ -243,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(); @@ -562,11 +592,11 @@ 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 linebreaker::state m_linebreakerstate { linebreaker::state::open }; static const commandhandler_map m_commandhandlers; @@ -940,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 @@ -961,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 @@ -985,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 }; @@ -1012,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/brakesetting.cpp b/vehicle/brakesetting.cpp index 918da3d02..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,12 +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(int const Orders, bool const Coupled) { - return (Orders & (Shunt | Loose_shunt | Obey_train | Bank)) != 0 || ((Orders & Connect) != 0 && false == Coupled); +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) { @@ -248,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)) { @@ -284,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 e3e5b4974..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,7 @@ 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 @@ -72,7 +74,7 @@ bool runs_as_train(int Orders); // (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(int Orders, bool Coupled); +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 @@ -87,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, @@ -103,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 1cd1397aa..f28439ed0 100644 --- a/vehicle/brakingcurve.cpp +++ b/vehicle/brakingcurve.cpp @@ -87,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 3b49597e5..ab8371827 100644 --- a/vehicle/brakingcurve.h +++ b/vehicle/brakingcurve.h @@ -57,4 +57,11 @@ bool brake_acting(double Trainbrakeposition, double Localbrakeposition); // 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/crew.cpp b/vehicle/crew.cpp index d32bcc82c..0efda42fb 100644 --- a/vehicle/crew.cpp +++ b/vehicle/crew.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/crew.h" -#include "McZapkie/MOVER.h" +#include "physics/vehicle.h" #include "vehicle/handover.h" namespace crew { @@ -23,17 +23,17 @@ char lower_ascii(char const Character) { } // the controllers of the vehicle to the positions giving no power, and the vehicles it controls told so -void cut_power(TMoverParameters &Vehicle) { - Vehicle.MainCtrlPos = Vehicle.MainCtrlNoPowerPos(); - Vehicle.ScndCtrlPos = 0; +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.eimic_real = 0.0; + Vehicle.SetEimicReal(0.0); Vehicle.SpeedCtrlValue = 0.0; Vehicle.SpeedCtrlUnit.IsActive = false; - Vehicle.SendCtrlToNext("MainCtrl", Vehicle.MainCtrlPosForCoupled(), Vehicle.CabActive); - Vehicle.SendCtrlToNext("ScndCtrl", Vehicle.ScndCtrlPos, Vehicle.CabActive); - Vehicle.SendCtrlToNext("EIMIC", 0.0, Vehicle.CabActive); + 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 @@ -110,17 +110,17 @@ std::string_view describe(action const Action) { } } -void secure(TMoverParameters &Occupied, TMoverParameters &Controlling) { +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.Handle->GetPos(bh_EB)); + 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.BrakeSystem == TBrakeSystem::Individual) { - if (Occupied.LocalBrake == TLocalBrake::ManualBrake) { + if (Occupied.brakes.config.kind == TBrakeSystem::Individual) { + if (Occupied.brakes.config.localKind == TLocalBrake::ManualBrake) { Occupied.IncManualBrakeLevel(ManualBrakePosNo); } else { @@ -128,7 +128,7 @@ void secure(TMoverParameters &Occupied, TMoverParameters &Controlling) { } } Occupied.CabDeactivisation(); - Occupied.CabOccupied = 0; + Occupied.SetCabOccupied(0); } } // namespace crew diff --git a/vehicle/crew.h b/vehicle/crew.h index f2ab938f1..d7c7fb325 100644 --- a/vehicle/crew.h +++ b/vehicle/crew.h @@ -12,7 +12,7 @@ http://mozilla.org/MPL/2.0/. #include #include -class TMoverParameters; +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 @@ -76,7 +76,7 @@ std::string_view describe(action Action); // 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 mvOccupied and mvControlling; the same one in a locomotive) -void secure(TMoverParameters &Occupied, TMoverParameters &Controlling); +// 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 index e7bf4abe8..9202934f5 100644 --- a/vehicle/crewchange.cpp +++ b/vehicle/crewchange.cpp @@ -16,12 +16,13 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "vehicle/Train.h" #include "vehicle/handover.h" +#include "physics/vehicle.h" namespace crew { namespace { -// TMoverParameters::CategoryFlag of the rail vehicles +// 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}; @@ -30,7 +31,7 @@ constexpr int consist_walk_limit{300}; // 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(end::front)}; + auto side{static_cast(VehicleEnd::front)}; auto *vehicle{Vehicle.FirstFind(side)}; side = 1 - side; auto count{0}; @@ -56,9 +57,9 @@ 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.MoverParameters->HasDriverCab() || Vehicle.MoverParameters->CategoryFlag != rail_category; + 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; + 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; @@ -69,7 +70,7 @@ vehicle_state state_of(TDynamicObject &Vehicle) { // 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.MoverParameters->CabOccupied = Cab; + Vehicle.physics->SetCabOccupied(Cab); Vehicle.Controller = AIdriver; Vehicle.create_controller(Cab > 0 ? "1" : "2", false); } @@ -77,12 +78,12 @@ void add_driver(TDynamicObject &Vehicle, int const Cab) { // 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 (TMoverParameters::damage_coupler()) parts the train and leaves +// 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.MoverParameters}; - auto &controlling{*Vehicle.FindPowered()->MoverParameters}; + 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); @@ -90,7 +91,7 @@ void remove_driver(TDynamicObject &Vehicle) { else { // somebody else drives the train, so only what this one held is let go handover::release_ai_controls(occupied, controlling); - occupied.CabOccupied = 0; + occupied.SetCabOccupied(0); } Vehicle.Mechanik = nullptr; auto released{0}; diff --git a/vehicle/derailmotion.cpp b/vehicle/derailmotion.cpp index 89b9a1831..252ba7f4d 100644 --- a/vehicle/derailmotion.cpp +++ b/vehicle/derailmotion.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/derailmotion.h" -#include "McZapkie/derailment.h" +#include "physics/derailment.h" #include #include diff --git a/vehicle/derailmotion.h b/vehicle/derailmotion.h index 8513e7e13..20c89747f 100644 --- a/vehicle/derailmotion.h +++ b/vehicle/derailmotion.h @@ -19,10 +19,10 @@ http://mozilla.org/MPL/2.0/. #include -// a rail vehicle off the rails (physics.derailment new, see McZapkie/derailment.h for when it derails): from then on +// 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 (TMoverParameters), which brakes it with the +// 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 @@ -39,7 +39,7 @@ http://mozilla.org/MPL/2.0/. // 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 McZapkie/derailment.h reaches 1 at. what tips it: the +// 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 @@ -67,7 +67,7 @@ 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 (McZapkie/derailment.h) as it tips over +// 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 @@ -299,7 +299,7 @@ struct vehicle_shape { 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 McZapkie/derailment.h takes it: flexibility and roll centre + // 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 @@ -382,7 +382,7 @@ public: 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 - // TMoverParameters, of its couplers at its ends) goes with the body; the speed changes its sign with each + // 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 diff --git a/vehicle/doorwings.h b/vehicle/doorwings.h index db05b03fc..259c85575 100644 --- a/vehicle/doorwings.h +++ b/vehicle/doorwings.h @@ -20,11 +20,11 @@ http://mozilla.org/MPL/2.0/. #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 (TMoverParameters::door_data::type) +// 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}; 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 index df8fc37a7..7105edfda 100644 --- a/vehicle/drivingaid.cpp +++ b/vehicle/drivingaid.cpp @@ -10,8 +10,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/drivingaid.h" -#include "McZapkie/MOVER.h" -#include "McZapkie/hamulce.h" +#include "physics/vehicle.h" +#include "physics/brakes.h" #include #include @@ -59,19 +59,19 @@ readout compute(input const &Input) { return result; } -input from_movers(TMoverParameters const &Vehicle, TMoverParameters const &Controlling, cab_controls const &Cab) { +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.SplitEDPneumaticBrake; + result.splited = Controlling.brakes.electrodynamic.splitFromPneumatic; result.integratedbrake = Vehicle.UniCtrlIntegratedBrakeCtrl; - result.eimic_real = Vehicle.eimic_real; - result.dynamicbrakepos = Controlling.DynamicBrakeCtrlPos; - result.dynamicbrakeposno = Controlling.DynamicBrakeCtrlPosNo; - result.mainctrlpos = Controlling.MainCtrlPos; - result.scndctrlpos = Controlling.ScndCtrlPos; - result.brakectrlpos = Vehicle.fBrakeCtrlPos; - result.localbrakepos = Vehicle.LocalBrakePosA; + 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; } diff --git a/vehicle/drivingaid.h b/vehicle/drivingaid.h index 8cec257da..71b44f773 100644 --- a/vehicle/drivingaid.h +++ b/vehicle/drivingaid.h @@ -11,7 +11,7 @@ http://mozilla.org/MPL/2.0/. #include -class TMoverParameters; +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) @@ -63,6 +63,6 @@ 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_movers(TMoverParameters const &Vehicle, TMoverParameters const &Controlling, cab_controls const &Cab); +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..38e2097e0 --- /dev/null +++ b/vehicle/dynamic/lights.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/. +*/ +/* + 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; +} + +int TDynamicObject::OccupiedCab() const { + return physics->CabOccupied(); +} + +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..5b2e32e9c --- /dev/null +++ b/vehicle/dynamic/update.cpp @@ -0,0 +1,1130 @@ +/* +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 ) +{ + // held by the editor, the pantograph goes where it was put, whatever the air and the switches + if( ( i < static_cast( m_heldpantographs.size() ) ) + && ( m_heldpantographs[ i ] != pantograph_hold::none ) ) { + move_pantograph( *p, m_heldpantographs[ i ] == pantograph_hold::up, dt1 ); + return; + } + 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..0ac5a45be --- /dev/null +++ b/vehicle/dynamic/visual.cpp @@ -0,0 +1,923 @@ +/* +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(); + } + // the parts the editor holds, over what the vehicle has set + if( apply_held_parts() ) { + btnOn = true; + } + // 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 ) }; +} + +std::array const &TDynamicObject::held_part_table() { + static std::array const table { { + { "coupler1", &TDynamicObject::btCoupler1 }, + { "coupler2", &TDynamicObject::btCoupler2 }, + { "cpneumatic1", &TDynamicObject::btCPneumatic1 }, + { "cpneumatic1r", &TDynamicObject::btCPneumatic1r }, + { "cpneumatic2", &TDynamicObject::btCPneumatic2 }, + { "cpneumatic2r", &TDynamicObject::btCPneumatic2r }, + { "pneumatic1", &TDynamicObject::btPneumatic1 }, + { "pneumatic1r", &TDynamicObject::btPneumatic1r }, + { "pneumatic2", &TDynamicObject::btPneumatic2 }, + { "pneumatic2r", &TDynamicObject::btPneumatic2r }, + { "headlamp11", &TDynamicObject::m_headlamp11 }, + { "headlamp12", &TDynamicObject::m_headlamp12 }, + { "headlamp13", &TDynamicObject::m_headlamp13 }, + { "highbeam12", &TDynamicObject::m_highbeam12 }, + { "highbeam13", &TDynamicObject::m_highbeam13 }, + { "headsignal12", &TDynamicObject::m_headsignal12 }, + { "headsignal13", &TDynamicObject::m_headsignal13 }, + { "headlamp21", &TDynamicObject::m_headlamp21 }, + { "headlamp22", &TDynamicObject::m_headlamp22 }, + { "headlamp23", &TDynamicObject::m_headlamp23 }, + { "highbeam22", &TDynamicObject::m_highbeam22 }, + { "highbeam23", &TDynamicObject::m_highbeam23 }, + { "headsignal22", &TDynamicObject::m_headsignal22 }, + { "headsignal23", &TDynamicObject::m_headsignal23 } } }; + return table; +} + +char const *TDynamicObject::held_part_name( std::size_t const Part ) { + return held_part_table()[ Part ].name; +} + +bool TDynamicObject::held_part_present( std::size_t const Part ) const { + return ( this->*( held_part_table()[ Part ].part ) ).Active(); +} + +std::size_t TDynamicObject::part_of( TSubModel const *Submodel ) const { + auto const &table { held_part_table() }; + for( auto const *submodel { Submodel }; submodel != nullptr; submodel = submodel->Parent ) { + auto const found { std::ranges::find_if( table, [ this, submodel ]( held_part_entry const &Entry ) { return ( this->*( Entry.part ) ).is_part( submodel ); } ) }; + if( found != table.end() ) { + return static_cast( std::distance( table.begin(), found ) ); + } + } + return held_part_total; +} + +bool TDynamicObject::apply_held_parts() { + auto held { false }; + auto const &table { held_part_table() }; + for( std::size_t idx = 0; idx < table.size(); ++idx ) { + auto &part { this->*( table[ idx ].part ) }; + switch( m_heldparts[ idx ] ) { + case part_hold::off: { part.TurnOff(); break; } + case part_hold::on: { part.TurnOn(); break; } + case part_hold::xon: { part.TurnxOn(); break; } + default: { continue; } + } + held = true; + } + return held; +} + +int TDynamicObject::pantograph_count() const { + return std::min( iAnimType[ ANIM_PANTS ], static_cast( m_heldpantographs.size() ) ); +} + +void TDynamicObject::hold_pantograph( int const Pantograph, pantograph_hold const Hold ) { + if( ( Pantograph < 0 ) || ( Pantograph >= pantograph_count() ) ) { + return; + } + m_heldpantographs[ Pantograph ] = Hold; +} + +void TDynamicObject::step_held_pantographs( double const Timedelta ) { + if( pants == nullptr ) { + return; + } + for( int idx = 0; idx < pantograph_count(); ++idx ) { + if( ( m_heldpantographs[ idx ] != pantograph_hold::none ) && ( pants[ idx ].fParamPants != nullptr ) ) { + move_pantograph( *pants[ idx ].fParamPants, m_heldpantographs[ idx ] == pantograph_hold::up, Timedelta ); + } + } +} + +int TDynamicObject::pantograph_of( TSubModel const *Submodel ) const { + if( pants == nullptr ) { + return -1; + } + for( auto const *submodel { Submodel }; submodel != nullptr; submodel = submodel->Parent ) { + for( int idx = 0; idx < pantograph_count(); ++idx ) { + auto const *arms { pants[ idx ].smElement }; + if( ( arms != nullptr ) && std::ranges::find( arms, arms + 5, submodel ) != arms + 5 ) { + return idx; + } + } + } + return -1; +} + +void TDynamicObject::move_pantograph( TAnimPant &Pantograph, bool const Up, double const Timedelta ) { + // the upper arm follows the lower one, and the height follows both, as the pantograph moves in Update() + auto const upper = [ &Pantograph ]( double const Lower ) { + return std::acos( std::clamp( ( Pantograph.fLenL1 * std::cos( Lower ) + Pantograph.fHoriz ) / Pantograph.fLenU1, -1.0, 1.0 ) ); }; + auto const height = [ &Pantograph, &upper ]( double const Lower ) { + return Pantograph.fLenL1 * std::sin( Lower ) + Pantograph.fLenU1 * std::sin( upper( Lower ) ) + Pantograph.fHeight; }; + // the angle of the lower arm it goes to: down at rest, up at the wire it has, or without one 1.6 m over its rest, and no + // further than the arms reach + auto target { Pantograph.fAngleL0 }; + if( Up ) { + auto const top { Pantograph.hvPowerWire != nullptr ? Pantograph.PantTraction : height( target ) + 1.6 }; + constexpr double step { 0.002 }; + while( ( height( target ) < top ) && ( target + step + upper( target + step ) < std::numbers::pi ) ) { + target += step; + } + } + // a few seconds from the rest to the wire, a little slower down, as the air moves it + auto const pace { ( Up ? 0.3 : 0.2 ) * std::max( 0.0, Timedelta ) }; + auto lower { Pantograph.fAngleL }; + lower = lower < target ? std::min( lower + pace, target ) : std::max( lower - pace, target ); + Pantograph.fAngleL = lower; + Pantograph.fAngleU = upper( lower ); + Pantograph.PantWys = height( lower ); +} + +void TDynamicObject::release_holds() { + m_heldparts.fill( part_hold::none ); + m_heldpantographs.fill( pantograph_hold::none ); +} 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/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.h b/vehicle/linebreaker.h index e87312dd1..cfcf76003 100644 --- a/vehicle/linebreaker.h +++ b/vehicle/linebreaker.h @@ -12,7 +12,7 @@ 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 (TMoverParameters::Mains) +// the state the cab keeps of the line breaker, besides the vehicle's own (physics::Vehicle::Mains) enum class state : int { open, closed, 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.h b/vehicle/odometer.h index 958a15f60..4fe369764 100644 --- a/vehicle/odometer.h +++ b/vehicle/odometer.h @@ -105,7 +105,7 @@ private: // 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 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 index f01ed5768..e1b7a73ed 100644 --- a/vehicle/pulleemode.h +++ b/vehicle/pulleemode.h @@ -13,7 +13,7 @@ http://mozilla.org/MPL/2.0/. #include // the pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): a vehicle prepared for being hauled dead in a train, -// TMoverParameters::PulleeModeSwitch(). a scenery asks for it with the parameter H among the ones written after the +// 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 { 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 index 913e9d2d4..eac25815b 100644 --- a/vehicle/timetableservice.cpp +++ b/vehicle/timetableservice.cpp @@ -10,11 +10,11 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/timetableservice.h" -#include "McZapkie/MOVER.h" +#include "physics/vehicle.h" namespace timetable { -bool opens_doors(TMoverParameters const &Vehicle, service_flags const &Flags) { +bool opens_doors(physics::Vehicle const &Vehicle, service_flags const &Flags) { switch (Vehicle.Doors.open_control) { case control_t::conductor: case control_t::driver: diff --git a/vehicle/timetableservice.h b/vehicle/timetableservice.h index b5c72adf7..b1c32576f 100644 --- a/vehicle/timetableservice.h +++ b/vehicle/timetableservice.h @@ -13,7 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "world/timetableflags.h" -class TMoverParameters; +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 @@ -22,7 +22,7 @@ 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(TMoverParameters const &Vehicle, service_flags const &Flags); +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); diff --git a/vehicle/uphillstart.h b/vehicle/uphillstart.h index 687934990..e50876588 100644 --- a/vehicle/uphillstart.h +++ b/vehicle/uphillstart.h @@ -62,6 +62,46 @@ struct top_up { 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/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 4d3dc50e9..53be0fb3a 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -34,6 +34,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/Logs.h" #include "widgets/map_objects.h" +#include "physics/vehicle.h" #include @@ -729,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, @@ -1041,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 ? @@ -1049,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 @@ -1080,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 { diff --git a/world/Road.cpp b/world/Road.cpp index bbfb9d8cc..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 { @@ -3160,8 +3161,8 @@ void junction_node::update(double const Deltatime) if (first != nullptr) { gate.distance = nearest; - gate.speed = std::abs(first->MoverParameters->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; } diff --git a/world/RoadPoint.cpp b/world/RoadPoint.cpp index 776d747e4..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 { @@ -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,9 +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->repair_damage(); - 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 @@ -1078,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; } @@ -1087,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/Sweep.h b/world/Sweep.h index b83b7fa12..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 { diff --git a/world/Track.cpp b/world/Track.cpp index 990ff4b0b..06aa6ce00 100644 --- a/world/Track.cpp +++ b/world/Track.cpp @@ -31,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 @@ -2343,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 ); } } diff --git a/world/TrackBuckle.cpp b/world/TrackBuckle.cpp index c8c20fe08..a3d056db8 100644 --- a/world/TrackBuckle.cpp +++ b/world/TrackBuckle.cpp @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/Logs.h" #include "vehicle/DynObj.h" +#include "physics/vehicle.h" #include @@ -213,8 +214,8 @@ void TTrack::buckle_pass_enter( TDynamicObject const &Dynamic ) { return; } ++m_buckle_passes; - auto const *mover { Dynamic.MoverParameters }; - auto const train { mover != nullptr && track_buckle::stirs( std::abs( mover->Vel ), mover->BrakePress > 0.5 ) }; + 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 ); diff --git a/world/TrackCheck.h b/world/TrackCheck.h index e6e99fb2b..c7b40feba 100644 --- a/world/TrackCheck.h +++ b/world/TrackCheck.h @@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include "McZapkie/derailment.h" +#include "physics/derailment.h" #include "world/TrackUneven.h" #include @@ -20,7 +20,7 @@ http://mozilla.org/MPL/2.0/. #include // the check of the geometry of the rail tracks of a scenery (physics.trackcheck yes in eu07.ini): what the criteria of -// derailment (McZapkie/derailment.h) and the plain rules of the track find suspicious, to the log once the scenery +// 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 diff --git a/world/TrkFoll.cpp b/world/TrkFoll.cpp index bc8027f43..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 ); 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/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;