diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6e4a74ba7..758b4c8d5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -14,6 +14,14 @@ on: permissions: {} +# A newer push to a pull request makes the run for its older commit pointless, so that run is +# cancelled (sonar.yml then marks the analysis of the older commit as skipped). A push to master +# gets a group of its own, its commit, so the runs on master are neither cancelled nor held back +# by one another. +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.sha }} + cancel-in-progress: true + jobs: build: name: Build under Build Wrapper @@ -23,18 +31,26 @@ jobs: env: BUILD_WRAPPER_OUT_DIR: bw-output steps: - - uses: actions/checkout@v5 + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 with: fetch-depth: 0 submodules: recursive - name: Set up Python 3.14 - uses: actions/setup-python@v6 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version: '3.14' + # A mirror that stops answering used to hold this step for over an hour. + # Time out each download, retry it, and give up on the whole step early. - name: Install build dependencies + timeout-minutes: 15 run: | + printf '%s\n' \ + 'Acquire::Retries "3";' \ + 'Acquire::http::Timeout "60";' \ + 'Acquire::https::Timeout "60";' \ + | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null sudo apt-get update -y sudo apt-get install -y \ build-essential \ @@ -103,10 +119,11 @@ jobs: --exclude='*.o' \ --exclude='*.a' \ --exclude='*.so' \ + --exclude='*.so.*' \ -C "$GITHUB_WORKSPACE" . - name: Upload analysis input - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: sonar-input path: /tmp/workspace.tar.gz diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index 8c900b8f5..d3c33f032 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -27,9 +27,17 @@ jobs: # Windows / MSVC # ============================================================ + # A newer push to the same branch or pull request cancels the build of the older commit. The + # groups are set on the build jobs rather than on the workflow, so a publish job that is already + # running is left to finish; with a build cancelled the publish job of that run is skipped. A push + # to master gets a group of its own, its commit, so the builds of master are never cancelled. + windows: name: Windows x64 / MSVC / ${{ matrix.variant.name }} runs-on: windows-2022 + concurrency: + group: ${{ github.workflow }}-windows-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} + cancel-in-progress: true strategy: fail-fast: false @@ -44,18 +52,27 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 submodules: recursive - name: Setup Python 3.14 id: python - uses: actions/setup-python@v6 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version: "3.14" architecture: "x64" + # the cab screens are drawn with Pillow; CMake copies this Python's Lib, site-packages included, next to the + # executable as python64\Lib, so Pillow has to be installed here to come with the build (as on Linux) + - name: Install Pillow for the screens + shell: pwsh + run: | + $pythonExe = "${{ steps.python.outputs.python-path }}" + & $pythonExe -m pip install --no-cache-dir Pillow + & $pythonExe -c "from PIL import Image; print('Pillow:', Image.__version__)" + - name: Show environment shell: pwsh run: | @@ -78,6 +95,27 @@ jobs: run: | call setup.bat + # 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 + 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" + call "%VSDIR%\VC\Auxiliary\Build\vcvars64.bat" || exit /b 1 + git init -q "%RUNNER_TEMP%\LuaJIT" || exit /b 1 + cd /d "%RUNNER_TEMP%\LuaJIT" + rem the v2.0 branch of LuaJIT, pinned + git fetch -q --depth 1 https://github.com/LuaJIT/LuaJIT.git b83bcba6ea300d4eb16e8257ddf80bcdef1f938b || exit /b 1 + git checkout -q FETCH_HEAD || exit /b 1 + cd src + rem msvcbuild.bat runs the tools it builds (minilua, buildvm) from the current folder + set NoDefaultCurrentDirectoryInExePath= + call .\msvcbuild.bat || exit /b 1 + if not exist lua51.dll exit /b 1 + mkdir "%RUNNER_TEMP%\lua51" + copy /y lua51.dll "%RUNNER_TEMP%\lua51\" || exit /b 1 + echo %RUNNER_TEMP%\lua51>> "%GITHUB_PATH%" + - name: Configure shell: pwsh run: | @@ -100,7 +138,7 @@ jobs: --config $env:CONFIG_WIN ` --parallel - - name: Copy shaders + - name: Copy shaders and translations shell: pwsh run: | $output = "build/bin/$env:CONFIG_WIN" @@ -116,8 +154,31 @@ jobs: -Recurse ` -Force + New-Item ` + -ItemType Directory ` + -Force ` + -Path "$output/lang" | Out-Null + + Copy-Item ` + -Path "lang/*" ` + -Destination "$output/lang" ` + -Recurse ` + -Force + + # the Python 3 version of the module every cab screen builds on; the game data still has the Python 2 one + New-Item ` + -ItemType Directory ` + -Force ` + -Path "$output/python/local" | Out-Null + + Copy-Item ` + -Path "staticFiles/python/local/*" ` + -Destination "$output/python/local" ` + -Recurse ` + -Force + - name: Upload Windows build - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: maszyna-windows-x64-${{ matrix.variant.suffix }}-${{ env.CONFIG_WIN }} path: | @@ -126,7 +187,7 @@ jobs: retention-days: 14 - name: Upload Windows debug symbols - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: maszyna-windows-x64-symbols-${{ matrix.variant.suffix }}-${{ env.CONFIG_WIN }} path: | @@ -143,26 +204,43 @@ jobs: linux: name: Linux x64 / GCC runs-on: ubuntu-24.04 + # see the note above the windows job + concurrency: + group: ${{ github.workflow }}-linux-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} + cancel-in-progress: true steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 submodules: recursive - name: Setup Python 3.14 id: python - uses: actions/setup-python@v6 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 with: python-version: "3.14" + # A mirror that stops answering used to hold this step for over an hour. + # Time out each download, retry it, and give up on the whole step early. - name: Install Linux dependencies + timeout-minutes: 15 run: | + printf '%s\n' \ + 'Acquire::Retries "3";' \ + 'Acquire::http::Timeout "60";' \ + 'Acquire::https::Timeout "60";' \ + | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null sudo apt-get update + # libasound2-dev, libpulse-dev and libpipewire-0.3-dev: the headers of OpenAL Soft's audio backends (built below). + # Without them it builds with OSS only, which modern distributions and the Steam Linux Runtime don't have: no sound. sudo apt-get install -y \ build-essential \ + libasound2-dev \ + libpulse-dev \ + libpipewire-0.3-dev \ libgl1-mesa-dev \ libglew-dev \ libglfw3-dev \ @@ -171,6 +249,7 @@ jobs: libluajit-5.1-dev \ libserialport-dev \ libsndfile1-dev \ + libcurl4-openssl-dev \ xorg-dev \ libxkbcommon-dev \ libwayland-dev \ @@ -188,12 +267,17 @@ jobs: https://github.com/kcat/openal-soft.git \ /tmp/openal-soft + # the backends are loaded with dlopen at run time (ALSOFT_DLOPEN), so the bundled library needs none of them; + # REQUIRE makes a missing header fail the build instead of shipping a library without sound cmake \ -S /tmp/openal-soft \ -B /tmp/openal-soft/build \ -DCMAKE_BUILD_TYPE=Release \ -DALSOFT_EXAMPLES=OFF \ - -DALSOFT_UTILS=OFF + -DALSOFT_UTILS=OFF \ + -DALSOFT_REQUIRE_PIPEWIRE=ON \ + -DALSOFT_REQUIRE_PULSEAUDIO=ON \ + -DALSOFT_REQUIRE_ALSA=ON cmake \ --build /tmp/openal-soft/build \ @@ -229,7 +313,31 @@ jobs: cmake \ --build build \ --parallel "$(nproc)" - + + # 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 + - name: Check the bundled libraries + run: | + GAME="$(find build/bin -maxdepth 1 -type f -name 'eu07*' -perm -u+x | head -n 1)" + test -n "$GAME" + echo "Game: $GAME" + readelf -d "$GAME" | grep -E 'R(UN)?PATH' + readelf -d "$GAME" | grep -q 'Library rpath: \[\$ORIGIN\]' + cat build/bin/bundled_libs.txt + ldd "$GAME" + if ldd "$GAME" | grep -q 'not found'; then + echo "::error::the game needs a library that is neither bundled nor in the system" + exit 1 + fi + while read -r name; do + [ -n "$name" ] || continue + loaded="$(ldd "$GAME" | awk -v n="$name" '$1 == n { print $3 }')" + if [ -z "$loaded" ] || [ "$(realpath "$loaded")" != "$(realpath "build/bin/$name")" ]; then + echo "::error::$name is bundled, but the game loads it from '$loaded'" + exit 1 + fi + done < build/bin/bundled_libs.txt + - name: Prepare Linux Python environment run: | PYTHON_ROOT="$(python -c 'import sys; print(sys.base_prefix)')" @@ -251,16 +359,96 @@ jobs: "$PYTHON_HOME/bin/python" -c "from PIL import Image; print('Pillow:', Image.__version__)" - - name: Copy shaders + - name: Copy shaders and translations run: | - mkdir -p build/bin/shaders + mkdir -p build/bin/shaders build/bin/lang build/bin/python/local cp -R shaders/. build/bin/shaders/ + cp -R lang/. build/bin/lang/ + # the Python 3 version of the module every cab screen builds on; the game data still has the Python 2 one + cp -R staticFiles/python/local/. build/bin/python/local/ - name: Upload Linux build - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: maszyna-linux-x64-${{ env.CONFIG_LINUX }} path: | build/bin/ if-no-files-found: error retention-days: 14 + + + # ============================================================ + # Public download: release assets need no GitHub account + # ============================================================ + + publish: + name: Publish public download + needs: [windows, linux] + if: github.event_name != 'pull_request' + runs-on: ubuntu-24.04 + permissions: + contents: write + concurrency: + group: publish-${{ github.ref }} + cancel-in-progress: false + + steps: + - name: Download Windows build + uses: actions/download-artifact@v4 + with: + name: maszyna-windows-x64-${{ env.CONFIG_WIN }} + path: dist/maszyna-windows-x64 + + - name: Download Linux build + uses: actions/download-artifact@v4 + with: + name: maszyna-linux-x64-${{ env.CONFIG_LINUX }} + path: dist/maszyna-linux-x64 + + - name: Pack + run: | + cd dist + + find maszyna-linux-x64 -type f -exec sh -c 'file -b "$1" | grep -q "^ELF" && chmod +x "$1"' _ {} \; + if [ -d maszyna-linux-x64/linuxpython64/bin ]; then + chmod +x maszyna-linux-x64/linuxpython64/bin/* + fi + + (cd maszyna-windows-x64 && zip -qr9 ../maszyna-windows-x64.zip .) + tar -czf maszyna-linux-x64.tar.gz -C maszyna-linux-x64 . + ls -la + + - name: Publish rolling release of the branch + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + BRANCH: ${{ github.ref_name }} + SHA: ${{ github.sha }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + slug="$(printf '%s' "$BRANCH" | tr '/ ' '--' | tr -cd '[:alnum:]._-')" + tag="build-$slug" + base="${{ github.server_url }}/${{ github.repository }}/releases/download/$tag" + + 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" \ + "- Linux: $base/maszyna-linux-x64.tar.gz" \ + "" \ + "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-linux-x64.tar.gz \ + --target "$SHA" \ + --prerelease \ + --latest=false \ + --title "Build: $BRANCH" \ + --notes "$notes" + + echo "### Public download" >> "$GITHUB_STEP_SUMMARY" + echo "- Windows: $base/maszyna-windows-x64.zip" >> "$GITHUB_STEP_SUMMARY" + echo "- Linux: $base/maszyna-linux-x64.tar.gz" >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/build_cleanup.yml b/.github/workflows/build_cleanup.yml new file mode 100644 index 000000000..8b20be0da --- /dev/null +++ b/.github/workflows/build_cleanup.yml @@ -0,0 +1,21 @@ +name: Remove public build of a deleted branch + +on: + delete: + +permissions: + contents: write + +jobs: + cleanup: + if: github.event.ref_type == 'branch' + runs-on: ubuntu-24.04 + steps: + - name: Delete the rolling release of the branch + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + BRANCH: ${{ github.event.ref }} + run: | + slug="$(printf '%s' "$BRANCH" | tr '/ ' '--' | tr -cd '[:alnum:]._-')" + gh release delete "build-$slug" --yes --cleanup-tag || true diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml new file mode 100644 index 000000000..d2f00bccd --- /dev/null +++ b/.github/workflows/coverage.yml @@ -0,0 +1,135 @@ +# .github/workflows/coverage.yml +# UNTRUSTED CONTEXT. This workflow runs fork-authored code. +# It must never reference `secrets.*`. It only builds, runs the unit tests and +# uploads a report; nothing here feeds the SonarQube Cloud analysis. +# +# Coverage of the game's core library (eu07_core) by the unit tests, measured with +# gcov on a GCC build: the report goes to the summary of the run and to an artifact. +# It is not sent to SonarQube Cloud on purpose: the project's quality gate ("Sonar +# way") fails a pull request whose new code is covered in less than 80%, a condition +# that isn't evaluated as long as sonar-project.properties excludes every file from +# coverage. Wiring this report in would turn that condition on. + +name: Coverage + +on: + push: + branches: + - master + pull_request: + types: [ opened, reopened, synchronize ] + +permissions: {} + +# A newer push to a pull request cancels the run for its older commit; a push to master +# gets a group of its own (its commit), so the runs on master are never cancelled. +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.sha }} + cancel-in-progress: true + +jobs: + coverage: + name: Unit test coverage (GCC) + runs-on: ubuntu-24.04 + timeout-minutes: 60 + permissions: + contents: read + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + submodules: recursive + + - name: Set up Python 3.14 + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6.3.0 + with: + python-version: '3.14' + + # the same packages as the Build workflow: the game is configured as a whole, + # though only the unit tests and the core library they link are built + - name: Install build dependencies + run: | + sudo apt-get update -y + sudo apt-get install -y \ + build-essential \ + libgl1-mesa-dev libglew-dev libglfw3-dev \ + libpng-dev libopenal-dev libluajit-5.1-dev \ + libserialport-dev libsndfile1-dev \ + xorg-dev libxkbcommon-dev libwayland-dev wayland-protocols + python3 -m pip install --no-cache-dir --only-binary :all: gcovr==8.3 + + - name: Build current OpenAL Soft + run: | + git clone --depth 1 --branch 1.24.2 https://github.com/kcat/openal-soft.git /tmp/openal-soft + cmake -S /tmp/openal-soft -B /tmp/openal-soft/build \ + -DCMAKE_BUILD_TYPE=Release -DALSOFT_EXAMPLES=OFF -DALSOFT_UTILS=OFF + cmake --build /tmp/openal-soft/build -j"$(nproc)" + sudo cmake --install /tmp/openal-soft/build + sudo ldconfig + + # see the Build workflow + - name: Patch GLM for GCC + run: | + sed -i 's/GLM_FUNC_QUALIFIER std::string format(const char\* message, \.\.\.)/inline std::string format(const char* message, ...)/' \ + ref/glm/glm/gtx/string_cast.inl + grep -n "std::string format(const char\* message" ref/glm/glm/gtx/string_cast.inl + + # unoptimised, so every line keeps its own code and the counts are those of the source + - name: Configure (CMake) + run: | + cmake -S . -B build \ + -DCMAKE_BUILD_TYPE=Debug \ + -DWITH_BETTER_RENDERER=OFF \ + -DWITH_ZMQ=OFF -DWITH_OPENVR=OFF -DUSE_LTO=OFF \ + -DCMAKE_CXX_FLAGS="--coverage -O0 -Wno-attributes -fno-inline-functions-called-once" \ + -DPython3_EXECUTABLE="$(which python3)" + + # the tests alone: the game itself isn't linked, so they aren't run by its build + - name: Build the unit tests + run: cmake --build build --target eu07_unit_tests -j"$(nproc)" + + - name: Run the unit tests + run: ./build/tests/unit/eu07_unit_tests + + # the game's own sources only: no submodules, no vendored code, not the tests themselves. + # betterRenderer/ is left out for its thirdparty/yaml-cpp, which every target of the game links and so builds here + - name: Coverage report + run: | + # a failure of gcovr fails the step, though its output goes through tee + set -o pipefail + mkdir -p coverage-report/html + gcovr --root . build \ + --exclude 'ref/' --exclude 'imgui/' --exclude 'stb/' --exclude 'betterRenderer/' \ + --exclude 'tests/' --exclude 'build/' \ + --gcov-ignore-parse-errors=negative_hits.warn_once_per_file \ + --gcov-ignore-errors=no_working_dir_found \ + --print-summary \ + --txt coverage-report/coverage.txt \ + --html-details coverage-report/html/index.html \ + --sonarqube coverage-report/coverage-sonarqube.xml \ + --json-summary-pretty --json-summary coverage-report/coverage-summary.json \ + | tee coverage-report/summary.txt + { + echo '## Unit test coverage of the core library' + echo + echo 'GCC, unoptimised build, `eu07_unit_tests`. Lines run by the tests, per source file of the game the tests compile.' + echo + echo '```' + grep -E '^(lines|functions|branches):' coverage-report/summary.txt + echo '```' + echo + echo '
Per file' + echo + echo '```' + cat coverage-report/coverage.txt + echo '```' + echo + echo '
' + } >> "$GITHUB_STEP_SUMMARY" + + - name: Upload the coverage report + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: unit-test-coverage + path: coverage-report + retention-days: 14 + if-no-files-found: error diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 8140317ea..b29511894 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -64,7 +64,7 @@ jobs: if: github.event.action == 'completed' && github.event.workflow_run.conclusion == 'success' runs-on: ubuntu-24.04 permissions: - contents: read # checkout trusted config + contents: read # fetch trusted config actions: read # download artifact from the Build run statuses: write # post the commit status pull-requests: read # verify PR head sha via the API @@ -83,16 +83,23 @@ jobs: -f description="Analysis in progress" \ -f target_url="$RUN_URL" - # Trusted copy of the repo config, used to overwrite anything the PR - # might have tampered with (sonar-project.properties etc). - - name: Checkout trusted config from master - uses: actions/checkout@v5 - with: - ref: master - path: .trusted + # Trusted copy of the scanner config, used to overwrite anything the PR + # might have tampered with. Fetched as a single file through the API rather + # than with actions/checkout: nothing gets checked out in this privileged + # context. Kept outside the workspace, so the archive can't overwrite it. + - name: Fetch trusted config from master + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + set -euo pipefail + url="repos/${{ github.repository }}/contents/sonar-project.properties?ref=master" + if ! gh api -H "Accept: application/vnd.github.raw" "$url" > /tmp/trusted-sonar-project.properties; then + echo "::warning::no sonar-project.properties on master" + rm -f /tmp/trusted-sonar-project.properties + fi - name: Download analysis input - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: sonar-input path: /tmp/sonar-input @@ -102,12 +109,20 @@ jobs: - name: Unpack analysis input run: | set -euo pipefail + # The archive holds the whole PR workspace and is unpacked over this one. + # Nothing may be written outside the workspace: reject absolute members and + # any member reaching through a parent directory before unpacking anything. + tar -tzf /tmp/sonar-input/workspace.tar.gz > /tmp/archive-members.txt + if grep -qE '^/|(^|/)[.][.](/|$)' /tmp/archive-members.txt; then + echo "::error::archive contains paths outside the workspace" + exit 1 + fi tar -xzf /tmp/sonar-input/workspace.tar.gz -C "$GITHUB_WORKSPACE" # Strip PR-controlled scanner configuration, restore the trusted one. rm -f "$GITHUB_WORKSPACE/sonar-project.properties" \ "$GITHUB_WORKSPACE/.sonarcloud.properties" - if [ -f "$GITHUB_WORKSPACE/.trusted/sonar-project.properties" ]; then - cp "$GITHUB_WORKSPACE/.trusted/sonar-project.properties" "$GITHUB_WORKSPACE/" + if [ -f /tmp/trusted-sonar-project.properties ]; then + cp /tmp/trusted-sonar-project.properties "$GITHUB_WORKSPACE/sonar-project.properties" fi - name: Resolve and verify PR metadata diff --git a/.gitignore b/.gitignore index 5186ceaee..70a6d1c68 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,5 @@ vcpkg.json # Local Python (setup.bat / CMake) for embedding tools/python314/ +__pycache__/ +*.pyc diff --git a/.gitmodules b/.gitmodules index df7f5ddaa..55d108a70 100644 --- a/.gitmodules +++ b/.gitmodules @@ -32,3 +32,7 @@ [submodule "betterRenderer/thirdparty/bvh"] path = betterRenderer/thirdparty/bvh url = https://github.com/madmann91/bvh.git +[submodule "ref/wamr"] + path = ref/wamr + url = https://github.com/bytecodealliance/wasm-micro-runtime + shallow = true diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..3b52f36ee --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,172 @@ +# MaSzyna: notes for coding agents + +These are the instructions for every coding agent that works in this repository: Claude Code, OpenAI Codex, Gemini CLI and any +other tool that reads `AGENTS.md`. `CLAUDE.md` and `GEMINI.md` only point to this file, so a rule is added or changed here, never +there. + +## The code builds and works with GCC, not only MSVC + +The Linux CI (`.github/workflows/build.yml`) builds with GCC 13 on ubuntu-24.04, through the Sonar build-wrapper, and `sonar.yml` +analyses that build once it has passed. A change that compiles with MSVC only fails there, and a failed GCC build also leaves Sonar +without an analysis of the PR. So every change has to compile with GCC, and behave the same with it, as well as with MSVC. The CI +builds with `-DWITH_BETTER_RENDERER=OFF` and Sonar excludes `betterRenderer/`, so that part is neither built on CI nor analysed. + +Where no GCC is at hand, read the new code for what MSVC lets through and GCC doesn't: + +- `constexpr` initialised from a floating or class-type constant declared only `const`: make the source `constexpr` too. +- Standard headers MSVC pulls in through others: include them yourself. For example, `` for `std::views`, ``, + ``, ``, ``, `` and ``. +- `typename` and `this->` where a template needs them. +- A temporary bound to a non-const reference. +- Explicit specialisations inside a class. +- A name a class uses and then declares again in its own body (GCC: "changes meaning"). +- A nested type with default member initialisers used as a default argument inside the class that encloses it. +- A declaration changed in a header (`const`, parameters) without its definition, or a new member function defined but not declared. +- `std::ifstream` / `std::ofstream` opened with a `std::wstring`. +- MSVC-only functions: `_stricmp`, `sprintf_s`, `fopen_s`, `localtime_s` and the like. +- Designated initialisers out of declaration order. +- `emplace_back(a, b, c)` with parenthesised aggregate initialisation is fine on GCC 13, but not for `std::array`. There is no brace + elision in parentheses, so build a named local instead. + +The same behaviour needs portable code. Don't rely on the order arguments are evaluated in, on the signedness of `char`, on the size of +`wchar_t`, or on `long` being 32 bits. + +## SonarCloud: the PR passes the quality gate + +SonarCloud (`sonar.yml`, `sonar-project.properties`) analyses each PR. A PR has to pass Sonar's quality gate. The gate rates the new +code: reliability, security and maintainability have to be A, duplication is at most 3% and the security hotspots are reviewed. +Any bug or vulnerability on the new code lowers its rating below A, so each one gets fixed (or gets a NOSONAR when it is a false +positive). Code smells count only together, through the maintainability rating, so a single one rarely fails the gate, but many in a +large PR can. A hotspot is reviewed by marking it in SonarCloud as safe or fixed, which is the user's step there, not a reason to +rewrite the code. A remark that doesn't fail the gate doesn't have to be fixed. Leave large restructurings that only answer such a +remark (splitting a class or a file, rewriting a working algorithm) out of the PR. The analysis runs on the GCC build, so a PR that +fails to build with GCC gets no analysis at all, and so it doesn't pass the gate. + +Fixing a remark must not change what the code does: + +- Keep the order of side effects, the conditions and the floating-point results as they were. +- Text in `STR(...)`, `STR_C(...)` and `_(...)` is looked up in the translations (`lang/*.po`), so it stays byte for byte the same. + The same goes for what is written to the log. +- `// NOSONAR: ` is only for a real false positive, or where a fix would change behaviour. Use it rarely, always with the + reason. + +To keep the gate passing, write new code so that it doesn't raise the rules that keep coming up: + +- **S134** (nesting deeper than 3 `if` / `for` / `while` / `switch` / `try`) and **S3776** (cognitive complexity over 25): + - use early `continue` / `return`; + - move loop bodies and branches into named helpers, preferably free functions in the anonymous namespace; + - group the state of a long algorithm in a small struct with methods. + + Every `else if`, every `&&` / `||` sequence and every nested lambda adds to the complexity. +- **S1188**: a lambda over 20 lines becomes a named function. +- **S107**: a function with more than 7 parameters takes a struct. +- **S3608**: lambdas capture explicitly (`[this, &points]`, not `[&]` or `[=]`). The only exception is `[&]` on a lambda passed + straight to a standard algorithm; `[=]` is flagged even there, and so is `[&]` passed to one of our own functions. +- **S6197** / **S5566**: use the `std::ranges::` algorithm that takes the container rather than a begin/end pair or a hand-written + loop. +- **S6165**: use `std::erase_if` rather than erase-remove. +- **S6004**: a variable used only by the condition is declared in the `if (init; condition)`. +- **S3358**: no nested `?:`; use an `if` or a small function. +- **S1121**: no assignment inside an expression, chained ones included (`a = b = c`). +- **S1117**: no declaration shadowing a local, a member or an enumerator. +- **S6003**: `v.emplace_back(a, b, c)` rather than `v.push_back({a, b, c})`. For a `std::array` element, push a named local instead + (see the GCC notes above). +- **S6012**: let class template argument deduction work: `std::vector values{1.0, 2.0}`. +- **S5945**: `std::array` / `std::vector` / `std::string`, not C arrays. +- **S1659**: one declaration per statement. +- **S6009**: `std::string_view` rather than `std::string const &` for a string parameter that is only read. +- **S6185** / **S6494**: `std::format` rather than concatenation or `snprintf`. +- **S924**: at most one `break` per loop. +- **S886**: a `for` whose counter changes in its body becomes a `while`. +- **S5997**: `std::scoped_lock` rather than `std::lock_guard`. +- **S6168**: `std::jthread` rather than `std::thread`. A `std::jthread` joins in its destructor where a `std::thread` would + terminate, so in existing code switch only where the thread is always joined or detached before it is destroyed. +- **S6177**: `using enum` where a function names many enumerators. +- **S5350** / **S995**: `const` on references and pointers that aren't written through. +- **S5817**: `const` on member functions that change nothing. +- **S2193**: no `float` loop counters. +- **S5421**: no non-const globals. +- **S6179**: `std::lerp` rather than a hand-written interpolation, in new code. In existing code only where it gives the very same + result. +- **S6164**: `std::numbers::pi` rather than a literal, in new code. In existing code only where it gives the very same result. + +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`. + +## 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 +26.11 release) replaces the OpenGL 3.3 renderer with an OpenGL 4.6 core one and adds a Vulkan 1.4 renderer beside it. It also +removes the legacy OpenGL 2.1, the OpenGL ES / ANGLE and the NVRHI (`betterRenderer/`) paths. + +- `betterRenderer/` will be removed. Don't put work into it. +- On that branch, of the `rendering/opengl*` files only `openglcamera.*` and `openglmatrixstack.*` stay. The whole + `rendering/opengl33*` family and the rest of the legacy `rendering/opengl*` go, and the new renderers are in + `rendering/opengl46/`, `rendering/vulkan14/` and `rendering/common/`. The shared `rendering/renderer.*`, `geometrybank.*`, + `particles.*` and the like stay. The shaders move from `shaders/` to `shaders/ogl46/` and `shaders/vk14/`. +- So a change on `master` to the code that goes away, or to the shaders, may be pointless. Keep it to fixes and to what a feature + on `master` needs in order to be drawn at all. For such a change, say in the PR where `feat/gl46-migration` has the counterpart, + or that the branch already carries the change. + +## Building, testing and running + +- The unit tests (`tests/unit`) run at the end of the build, which prints `Unit tests: N/N passed` and fails on any failed case. + `-DWITH_TESTS=OFF` builds the game without them. +- A new feature goes on its own branch from `master`, not on whatever branch is checked out. Say which branch the work lands on + before the first edit. A fresh worktree has empty submodules, so it doesn't build until they are filled. +- The editor runs a script when `EU07_EDITOR_SELFTEST=` is set: one command per line, `#` for comments. The commands are in + `application/editormodeselftest*.cpp` (`camera`, `wait`, `select`, `lay`, `screenshot`, `save`, `quit` and many more). + - Run it on a copy of the scenery, never on the original, and delete the copy afterwards. + - Give every run a timeout and keep an eye on its memory. A loop gone wrong can fill the RAM of the whole machine. + - `screenshot` only queues the grab and waits 3 frames; the image is written later on another thread. A click right after it + has been seen to lose the selection, so leave a `wait` of about 15 frames after a `screenshot` before clicking. +- At run time the editor's texts load from `lang/editor_.po` in the game folder (`utilities/translation.cpp`), not from + the build. New strings of a branch show in English until that file has them. Without the `fonts` folder Polish letters show as `?`. +- When a build runs on a copy of the game data made of links to the real folders, turn off whatever writes into the data + (`convertmodels 0` in `eu07.ini`), or the run changes the real game folder through the links. +- A test of code that moves, migrates or deletes files in the user's profile (`%APPDATA%`, `%LOCALAPPDATA%`, caches) gets its own + test folder. Never point it at the real profile. +- A GPU hang (Windows TDR) can freeze the whole machine, not just the game. Don't test a hang hypothesis by running it. Guard the + code against what causes it (degenerate geometry, NaN in the camera or in transforms) and read the `LiveKernelEvent` / watchdog + dumps instead. +- PowerShell variable names are case-insensitive: `$Track` and `$track` are the same variable. + +## Game data and backward compatibility + +The code and the game data live apart. The assets (sceneries, vehicles with their `.fiz` and `.mmd`, models, textures, sounds, +timetables, most of `lang` and the shipped `eu07.ini`) are in a separate SVN repository, `https://svn.eu07.pl/pctga`. It needs an +account; there is no anonymous checkout. Of `lang/`, only `editor_pl.po` is in this repository. Players install and +launch the game through Steam, GOG and the like, and run new builds on the data they already have. + +The official starter is StarterNG (`https://github.com/MaSzyna-EU07/StarterNG`), a separate repository; the older +`MaSzyna-EU07/Starter` is not the one in use. `launcher/` in this repository is the simulator's built-in scenario and vehicle +picker (`launcher_mode`), not StarterNG. + +- Every existing file must still be read the way it was. Don't rename or drop a keyword, change the meaning or the unit of a value, + or make an optional entry required. This holds for every format the game reads: for example `.scn` and its includes, `.fiz`, + `.mmd`, `.e3d` / `.t3d`, `.mat`, the `.txt` timetables and track profiles, `eu07.ini` and the Python screens. +- A bug fix may change what an existing file leads to, such as how a vehicle from its `.fiz` behaves, as long as the PR says so. +- Something new in a format is optional, and without it the code does exactly what it did before. A file that loaded correctly + before doesn't get new warnings or errors in the log. A real fault that is newly detected may be logged. +- A code change must not need a change in the SVN to work. Where it uses new or changed assets, it falls back to the old behaviour + without them, and the PR says what is to be added to the SVN and in what order the two go in. +- A change that uses new or changed assets (and falls back without them, see above) says so plainly in its commit message: which + files, and what is to change in them. It is never left implied. Before such a commit, either make the asset change right away in + the user's SVN working copy, or get the user's agreement to leave it for later. Ask the user where their SVN working copy is; the + installed game folder is not one. Pushing to git and committing to the SVN both need the user's consent. +- A scenery saved by the editor without using a new feature holds nothing the current release can't read. The entries of a new + feature (such as a new kind of node) appear only where that feature was used, and the PR says that the release doesn't read + them. +- Saving patches the scenery files by byte spans: unchanged definitions stay byte for byte, and an edited node is written anew by + its `export_as_text`. A change to saving must not widen what gets rewritten, nor make `export_as_text` drop more of an edited + node (comments, unknown tokens) than it did before. +- A new feature that changes what the simulator does or shows with existing sceneries and vehicles can be turned off in + `eu07.ini`, and turned off, the simulator behaves as it did before the feature. Editor tools and new optional entries of a + format are covered by the points above. The key is parsed in `utilities/Globals.cpp` (`global_settings::ConfigParse*`) and + written by `global_settings::export_as_text`, which puts the settings in the log at start. `eu07.ini` is read from the user's + profile (`user_config_path`), and from the game folder only when the profile has none; test the switch in the file that is + actually read. +- A feature doesn't make existing sceneries and vehicles look suddenly different after an update. A change to how things look is + something the player turns on, or comes in gradually. +- When a format really has to change, read both the old and the new form, and say in the PR what changes for the data and for + the people who make it. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 000000000..bbbaa3835 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,5 @@ +# MaSzyna: notes for Claude Code + +The instructions for every coding agent in this repository are in `AGENTS.md`. Add or change rules there, not here. + +@AGENTS.md diff --git a/CMakeLists.txt b/CMakeLists.txt index 56cf1bce2..e97e41d03 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -72,12 +72,15 @@ option(WITH_OPENGL_LEGACY "Compile with OpenGL legacy renderer" ON) option(WITH_PYTHON "Python 3.14 embedded scripting" ON) option(WITH_UART "Compile with libserialport" ON) option(WITH_LUA "Compile with lua scripting support" ON) +option(WITH_WASM "WebAssembly script screens (wasmscreen:, wasmdestinationsign:), run by the WAMR interpreter in ref/wamr" ON) option(WITH_OPENVR "Compile with OpenVR" OFF) option(WITH_ZMQ "Compile with cppzmq" OFF) option(WITH_CRASHPAD "Compile with crashpad" OFF) option(WITH_DISCORD_RPC "Compile with DISCORD RICH PRESENCE" ON) option(USE_LTO "Use link-time optimization" OFF) -option(WITH_BETTER_RENDERER "Experimental multi-backend renderer based on NVRHI" ON) +option(WITH_TESTS "Build and run the unit tests with the game, a failing test fails the build" ON) +option(WITH_EDITOR_SELFTESTS "Run the scripts of the editor and launcher self-tests named by the EU07_EDITOR_SELFTEST and EU07_LAUNCHER_SELFTEST variables" OFF) +option(WITH_BETTER_RENDERER "Experimental multi-backend renderer based on NVRHI" OFF) option(GENERATE_PDB "Generate executable with program debugging symbols" ON) option(ENABLE_MCC "Enable multicore compilation" ON) option(WITHDUMPGEN "Enable generating DMP files on crash" ON) @@ -95,6 +98,24 @@ set(SOURCES "model/Texture.cpp" "utilities/Timer.cpp" "world/Track.cpp" +"world/TrackSleepers.cpp" +"world/SleeperPaths.cpp" +"world/SleeperFeatures.cpp" +"world/SleeperLines.cpp" +"world/SleeperLayout.cpp" +"world/SleeperModels.cpp" +"world/SleeperWorker.cpp" +"world/GaugeLine.cpp" +"world/RailCrossings.cpp" +"world/RailMaterials.cpp" +"world/RailProfile.cpp" +"world/RailPlan.cpp" +"world/RailCarve.cpp" +"world/RailLayer.cpp" +"world/TrackUneven.cpp" +"world/Road.cpp" +"world/Sweep.cpp" +"world/RoadPoint.cpp" "world/Traction.cpp" "world/TractionPower.cpp" "vehicle/Train.cpp" @@ -108,21 +129,18 @@ set(SOURCES "vehicle/DynObj.cpp" "EU07.cpp" "export_e3d_standalone.cpp" +"export_btf_standalone.cpp" +"nodebank_previews_standalone.cpp" "world/Event.cpp" "world/EvLaunch.cpp" "utilities/Float3d.cpp" "vehicle/Gauge.cpp" "utilities/Globals.cpp" "utilities/Logs.cpp" -"McZapkie/friction.cpp" -"McZapkie/hamulce.cpp" -"McZapkie/Mover.cpp" -"McZapkie/Oerlikon_ESt.cpp" "model/MdlMngr.cpp" "world/MemCell.cpp" "model/Model3d.cpp" "world/mtable.cpp" -"utilities/parser.cpp" "rendering/nullrenderer.cpp" "rendering/renderer.cpp" "model/ResourceManager.cpp" @@ -150,15 +168,16 @@ set(SOURCES "scene/scene.cpp" "scene/scenenode.cpp" "simulation/simulation.cpp" +"simulation/blackboxrecorder.cpp" "model/vertex.cpp" "audio/audio.cpp" "audio/audiorenderer.cpp" "utilities/motiontelemetry.cpp" -"utilities/utilities.cpp" "application/uitranscripts.cpp" "world/station.cpp" "application/application.cpp" "simulation/simulationtime.cpp" +"simulation/simulationtest.cpp" "scene/sceneeditor.cpp" "rendering/screenshot.cpp" "input/driverkeyboardinput.cpp" @@ -167,15 +186,99 @@ set(SOURCES "application/driveruipanels.cpp" "input/editorkeyboardinput.cpp" "editor/editorSettings.cpp" +"editor/editorModelSets.cpp" +"editor/editorTrackPresets.cpp" +"editor/editorIncludeInfo.cpp" "editor/editorTerrain.cpp" +"editor/editorTrack.cpp" +"editor/editorTrackTrace.cpp" +"editor/editorFouling.cpp" +"editor/editorRoad.cpp" +"editor/editorAlignment.cpp" +"editor/editorTrackShape.cpp" +"editor/editorGroundFollow.cpp" +"editor/editorAlignmentStore.cpp" +"editor/editorSwitchStore.cpp" +"editor/editorSwitchCurve.cpp" +"editor/editorKilometrage.cpp" +"editor/editorStation.cpp" +"editor/editorSwitchDesign.cpp" +"editor/editorConnections.cpp" +"application/editormodeconnection.cpp" +"application/editormodeconnectioncurve.cpp" +"application/editormodedigitize.cpp" +"editor/editorSpeed.cpp" +"editor/editorProfile.cpp" +"editor/editorGauge.cpp" +"editor/editorInfra.cpp" "editor/editorTerrainStreamer.cpp" +"editor/editorOrthophoto.cpp" +"editor/editorHttp.cpp" +"editor/editorNmt.cpp" +"editor/editorGeoMap.cpp" +"editor/editorPreviews.cpp" +"editor/editorIcons.cpp" +"editor/editorClips.cpp" "application/editormode.cpp" +"application/editormodetrack.cpp" +"application/editormoderoute.cpp" +"application/editormodestraights.cpp" +"application/editormodelay.cpp" +"application/editormodeswitchplace.cpp" +"application/editormodetrackgizmo.cpp" +"application/editormoderecords.cpp" +"application/editormodeswitchdrive.cpp" +"application/editormodeswitchtool.cpp" +"application/editormodeswitchtemplate.cpp" +"application/editormodenmt.cpp" +"application/editormodegradeline.cpp" +"application/editormodeswitchslide.cpp" +"application/editormodeswitchdesign.cpp" +"application/editormodetrackbed.cpp" +"application/editormodetrackux.cpp" +"application/editormodetrackprops.cpp" +"application/editormoderoad.cpp" +"application/editormodeprofile.cpp" +"application/editormodetextures.cpp" +"application/editormodegauge.cpp" +"application/editormoderide.cpp" +"application/editormodeminimap.cpp" +"application/editormodeinfra.cpp" +"application/editormodespeed.cpp" +"application/editormodesrk.cpp" +"application/editormodekm.cpp" +"application/editormodejoints.cpp" +"application/editormodeparallel.cpp" +"application/editormodelineside.cpp" +"application/editormodevehicle.cpp" +"application/editormodeselection.cpp" +"application/editormodeviewport.cpp" +"application/editormodesignal.cpp" +"application/editormodesweep.cpp" +"application/editormodeturntable.cpp" +"application/editormodeselftest.cpp" +"application/editormodeselftestscene.cpp" +"application/editormodeselftestsleepers.cpp" +"application/editormodeselftestsweep.cpp" +"application/editormodeselftesttrack.cpp" +"application/editormodeselftestswitch.cpp" +"application/editormodeselftestjoin.cpp" +"application/editormodeselftestsignal.cpp" +"application/editormodeselftestterrain.cpp" +"application/editormodeselftestrails.cpp" +"application/editormodeselftestmonkey.cpp" +"application/scriptedinput.cpp" "input/editormouseinput.cpp" "application/editoruilayer.cpp" "application/editoruipanels.cpp" "application/scenarioloadermode.cpp" "application/scenarioloaderuilayer.cpp" "scene/scenenodegroups.cpp" +"scene/scenelayers.cpp" +"scene/scenelayerssave.cpp" +"scene/sceneterrain.cpp" +"scene/heightmapterrain.cpp" +"scene/scenemodelentries.cpp" "simulation/simulationenvironment.cpp" "simulation/simulationstateserializer.cpp" "rendering/precipitation.cpp" @@ -183,7 +286,6 @@ set(SOURCES "utilities/dictionary.cpp" "rendering/particles.cpp" "utilities/headtrack.cpp" -"scripting/ladderlogic.cpp" "rendering/geometrybank.cpp" "rendering/openglcolor.cpp" "simulation/simulationsounds.cpp" @@ -205,6 +307,7 @@ set(SOURCES "${DEPS_DIR}/glad/src/glad.c" "${DEPS_DIR}/dds-ktx/src/dds-ktx.c" +"${DEPS_DIR}/zstd/zstd.c" "gl/shader.cpp" "gl/vao.cpp" @@ -223,6 +326,7 @@ set(SOURCES "imgui/imgui_demo.cpp" "imgui/imgui_draw.cpp" "imgui/imgui_widgets.cpp" +"imgui/imgui_tables.cpp" "imgui/imgui_impl_glfw.cpp" "imgui/ImGuizmo.cpp" @@ -235,6 +339,7 @@ set(SOURCES "launcher/keymapper.cpp" "launcher/textures_scanner.cpp" "launcher/scenery_scanner.cpp" +"launcher/scenery_wizard.cpp" "vr/vr_interface.cpp" ) @@ -282,6 +387,16 @@ if (WITH_LUA) set(SOURCES ${SOURCES} "scripting/lua.cpp") endif() +# the script screens (scripting/scriptscreens.cpp), with the Lua and the WebAssembly runtime when they're built +set(SOURCES ${SOURCES} "scripting/scriptscreens.cpp") +if (WITH_LUA) + set(SOURCES ${SOURCES} "scripting/luaprogram.cpp") +endif() +if (WITH_WASM) + set(DEFINITIONS ${DEFINITIONS} "WITH_WASM") + set(SOURCES ${SOURCES} "scripting/wasmprogram.cpp") +endif() + if (WITHDUMPGEN) set(DEFINITIONS ${DEFINITIONS} "WITHDUMPGEN") endif() @@ -293,6 +408,8 @@ if (WITH_OPENGL_MODERN) "rendering/opengl33skydome.cpp" "rendering/opengl33precipitation.cpp" "rendering/opengl33particles.cpp" + "rendering/opengl33terrain.cpp" + "rendering/opengl33screenpost.cpp" "rendering/opengl33renderer.cpp") set(DEFINITIONS ${DEFINITIONS} "WITH_OPENGL_MODERN") endif() @@ -343,6 +460,14 @@ endif() configure_file("${CMAKE_SOURCE_DIR}/version_info.h.in" "${CMAKE_BINARY_DIR}/geninc/version_info.h") +# the icons of the editor are built into the executable: the png is written out as the bytes of an array, see editor/editorIcons.cpp +set(EDITOR_ICONS "${CMAKE_SOURCE_DIR}/editor/icons/editor_icons.png") +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${EDITOR_ICONS}") +file(READ "${EDITOR_ICONS}" EDITOR_ICONS_HEX HEX) +string(REGEX REPLACE "(................................)" "\\1\n" EDITOR_ICONS_HEX "${EDITOR_ICONS_HEX}") +string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," EDITOR_ICONS_HEX "${EDITOR_ICONS_HEX}") +file(CONFIGURE OUTPUT "${CMAKE_BINARY_DIR}/geninc/editor_icons_png.inc" CONTENT "${EDITOR_ICONS_HEX}\n") + set (PREFIX "") set (SUFFIX "") @@ -401,17 +526,53 @@ if (${CMAKE_CXX_COMPILER_ID} STREQUAL MSVC) add_compile_options("/utf-8") endif() +# the build settings of the game: include dirs, definitions, compile options and libraries. the game, +# its core library and the unit tests all build with the same ones +add_library(eu07_settings INTERFACE) + +# the parts of the simulation the game shares with the unit tests: the vehicle physics, the vehicle +# definition parser, the helpers they use and the rules of the test mode. built once, and tested as the game uses them +set(CORE_SOURCES +"McZapkie/friction.cpp" +"McZapkie/hamulce.cpp" +"McZapkie/Mover.cpp" +"McZapkie/couplerphysics.cpp" +"McZapkie/Oerlikon_ESt.cpp" +"utilities/parser.cpp" +"utilities/utilities.cpp" +"scripting/ladderlogic.cpp" +"scripting/scriptscreenrules.cpp" +"scripting/scriptscreenkernels.cpp" +"scripting/scriptscreendrawing.cpp" +"simulation/simulationtestrules.cpp" +"vehicle/blackbox.cpp" +"vehicle/enginestart.cpp" +"vehicle/brakesetting.cpp" +"vehicle/handover.cpp" +"vehicle/horn.cpp" +"vehicle/linebreaker.cpp" +"vehicle/smoke.cpp" +"vehicle/odometer.cpp" +) +add_library(eu07_core STATIC ${CORE_SOURCES}) +target_link_libraries(eu07_core PUBLIC eu07_settings) +set_target_properties(eu07_core PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" + FOLDER "libraries") + add_executable(${PROJECT_NAME} ${SOURCES} ${HEADERS}) +target_link_libraries(${PROJECT_NAME} eu07_core) -target_compile_definitions(${PROJECT_NAME} PRIVATE ${DEFINITIONS}) +target_compile_definitions(eu07_settings INTERFACE ${DEFINITIONS}) -target_include_directories(${PROJECT_NAME} PRIVATE +target_include_directories(eu07_settings INTERFACE "." "Console" "McZapkie" "gl" "${DEPS_DIR}/glad/include" "${DEPS_DIR}/dds-ktx/include" + "${DEPS_DIR}/zstd" "${CMAKE_BINARY_DIR}/geninc" "${GLOBAL_INCLUDE_DIR}") @@ -425,7 +586,7 @@ if (${CMAKE_CXX_COMPILER_ID} STREQUAL MSVC) # /wd4996: disable "deprecation" warnings # /wd4244: disable warnings for conversion with possible loss of data # /wd5033: disable because it is all over Python headers - set_target_properties(${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "/wd4996 /wd4244 /wd5033") + target_compile_options(eu07_settings INTERFACE /wd4996 /wd4244 /wd5033) set_target_properties(${PROJECT_NAME} PROPERTIES LINK_FLAGS "/LARGEADDRESSAWARE") endif() @@ -441,7 +602,7 @@ set_target_properties( ${PROJECT_NAME} check_cxx_symbol_exists(__GNUC__ "" COMPILER_HAVE_GNUC) if (COMPILER_HAVE_GNUC) - set_target_properties(${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "-fvisibility=hidden") + target_compile_options(eu07_settings INTERFACE -fvisibility=hidden) endif() if(NOT ${CMAKE_VERSION} VERSION_LESS "3.16.0") @@ -449,19 +610,20 @@ if(NOT ${CMAKE_VERSION} VERSION_LESS "3.16.0") if (USE_PCH) target_precompile_headers(${PROJECT_NAME} PRIVATE "$<$:${CMAKE_CURRENT_SOURCE_DIR}/stdafx.h>") - set_source_files_properties("/glad/src/glad.c" "ref/dds-ktx/src/dds-ktx.c" "stb/stb_image.c" - "imgui/imgui.cpp" "imgui/imgui_demo.cpp" "imgui/imgui_draw.cpp" "imgui/imgui_widgets.cpp" "imgui/imgui_impl_glfw.cpp" "imgui/ImGuizmo.cpp" + target_precompile_headers(eu07_core PRIVATE "$<$:${CMAKE_CURRENT_SOURCE_DIR}/stdafx.h>") + set_source_files_properties("/glad/src/glad.c" "ref/dds-ktx/src/dds-ktx.c" "ref/zstd/zstd.c" "stb/stb_image.c" + "imgui/imgui.cpp" "imgui/imgui_demo.cpp" "imgui/imgui_draw.cpp" "imgui/imgui_widgets.cpp" "imgui/imgui_tables.cpp" "imgui/imgui_impl_glfw.cpp" "imgui/ImGuizmo.cpp" PROPERTIES SKIP_PRECOMPILE_HEADERS TRUE) endif() endif() if (USE_LTO) - set_property(TARGET ${PROJECT_NAME} PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE) + set_property(TARGET ${PROJECT_NAME} eu07_core PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE) endif() if (WITH_OPENVR) - target_include_directories(${PROJECT_NAME} PRIVATE ${OPENVR_INCLUDE_DIR}) - target_link_libraries(${PROJECT_NAME} ${OPENVR_LIBRARY}) + target_include_directories(eu07_settings INTERFACE ${OPENVR_INCLUDE_DIR}) + target_link_libraries(eu07_settings INTERFACE ${OPENVR_LIBRARY}) endif() if (WITH_CRASHPAD) @@ -476,12 +638,12 @@ if (WITH_CRASHPAD) endif() endif() -target_link_libraries(${PROJECT_NAME} glfw) +target_link_libraries(eu07_settings INTERFACE glfw) if(WITH_PYTHON) find_package(Python3 3.14 REQUIRED COMPONENTS Development) - target_include_directories(${PROJECT_NAME} PRIVATE ${Python3_INCLUDE_DIRS}) - target_link_libraries(${PROJECT_NAME} ${Python3_LIBRARIES}) + target_include_directories(eu07_settings INTERFACE ${Python3_INCLUDE_DIRS}) + target_link_libraries(eu07_settings INTERFACE ${Python3_LIBRARIES}) if(WIN32) # Python3_ROOT_DIR is only an input hint and is not populated by @@ -499,74 +661,94 @@ endif() if (NOT WIN32) find_package(PNG 1.6 REQUIRED) - target_link_libraries(${PROJECT_NAME} PNG::PNG) + target_link_libraries(eu07_settings INTERFACE PNG::PNG) else() include_directories(${PNG_INCLUDE_DIRS}) - target_link_libraries(${PROJECT_NAME} ${PNG_LIBRARIES}) + target_link_libraries(eu07_settings INTERFACE ${PNG_LIBRARIES}) endif() find_package(Threads REQUIRED) -target_link_libraries(${PROJECT_NAME} Threads::Threads) +target_link_libraries(eu07_settings INTERFACE Threads::Threads) find_package(GLM REQUIRED) -target_include_directories(${PROJECT_NAME} PRIVATE ${GLM_INCLUDE_DIR}) +target_include_directories(eu07_settings INTERFACE ${GLM_INCLUDE_DIR}) # JSON lib add_subdirectory(ref/json) -target_link_libraries(${PROJECT_NAME} nlohmann_json::nlohmann_json) -target_include_directories(${PROJECT_NAME} PRIVATE ${NLOHMANN_JSON_INCLUDE_INSTALL_DIR}) +target_link_libraries(eu07_settings INTERFACE nlohmann_json::nlohmann_json) +target_include_directories(eu07_settings INTERFACE ${NLOHMANN_JSON_INCLUDE_INSTALL_DIR}) if (WITH_DISCORD_RPC) add_subdirectory(ref/discord-rpc) set_target_properties(discord-rpc PROPERTIES FOLDER "libraries") - target_link_libraries(${PROJECT_NAME} discord-rpc) + target_link_libraries(eu07_settings INTERFACE discord-rpc) # Add the include directory so the compiler can find discord_rpc.h - target_include_directories(${PROJECT_NAME} PUBLIC + target_include_directories(eu07_settings INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/ref/discord-rpc/include" ) - target_compile_definitions(${PROJECT_NAME} PUBLIC WITH_DISCORD_RPC=1) + target_compile_definitions(eu07_settings INTERFACE WITH_DISCORD_RPC=1) else() - target_compile_definitions(${PROJECT_NAME} PUBLIC WITH_DISCORD_RPC=0) + target_compile_definitions(eu07_settings INTERFACE WITH_DISCORD_RPC=0) +endif() + +if(WITH_EDITOR_SELFTESTS) + target_compile_definitions(eu07_settings INTERFACE WITH_EDITOR_SELFTESTS=1) +else() + target_compile_definitions(eu07_settings INTERFACE WITH_EDITOR_SELFTESTS=0) endif() find_package(OpenAL REQUIRED) if (TARGET OpenAL::OpenAL) - target_link_libraries(${PROJECT_NAME} OpenAL::OpenAL) + target_link_libraries(eu07_settings INTERFACE OpenAL::OpenAL) else() - target_include_directories(${PROJECT_NAME} PRIVATE ${OPENAL_INCLUDE_DIR}) - target_link_libraries(${PROJECT_NAME} ${OPENAL_LIBRARY}) + target_include_directories(eu07_settings INTERFACE ${OPENAL_INCLUDE_DIR}) + target_link_libraries(eu07_settings INTERFACE ${OPENAL_LIBRARY}) endif() find_package(SndFile REQUIRED) -target_link_libraries(${PROJECT_NAME} SndFile::sndfile) +target_link_libraries(eu07_settings INTERFACE SndFile::sndfile) if (WITH_LUA) find_package(LuaJIT REQUIRED) - target_include_directories(${PROJECT_NAME} PRIVATE ${LUAJIT_INCLUDE_DIR}) - target_link_libraries(${PROJECT_NAME} ${LUAJIT_LIBRARIES}) + target_include_directories(eu07_settings INTERFACE ${LUAJIT_INCLUDE_DIR}) + target_link_libraries(eu07_settings INTERFACE ${LUAJIT_LIBRARIES}) endif() if (WITH_UART) find_package(libserialport REQUIRED) - target_include_directories(${PROJECT_NAME} PRIVATE ${libserialport_INCLUDE_DIR}) - target_link_libraries(${PROJECT_NAME} ${libserialport_LIBRARY}) + target_include_directories(eu07_settings INTERFACE ${libserialport_INCLUDE_DIR}) + target_link_libraries(eu07_settings INTERFACE ${libserialport_LIBRARY}) endif() find_package(ASIO REQUIRED) -target_link_libraries(${PROJECT_NAME} asio::asio) +target_link_libraries(eu07_settings INTERFACE asio::asio) if (WIN32) - target_link_libraries(${PROJECT_NAME} ws2_32) + target_link_libraries(eu07_settings INTERFACE ws2_32) +endif() + +# http client of the editor, for the orthophoto, the terrain model and the topo map of geoportal.gov.pl: WinHTTP on Windows, +# libcurl elsewhere when available +if (WIN32) + target_link_libraries(eu07_settings INTERFACE winhttp) +else() + find_package(CURL QUIET) + if (CURL_FOUND) + target_link_libraries(eu07_settings INTERFACE CURL::libcurl) + target_compile_definitions(eu07_settings INTERFACE EU07_WITH_CURL) + else() + message(STATUS "libcurl not found: the editor's orthophoto and terrain model will only show what's cached, its topo map nothing") + endif() endif() if (WITH_ZMQ) find_package(cppzmq REQUIRED) - target_include_directories(${PROJECT_NAME} PRIVATE ${cppzmq_INCLUDE_DIR}) - target_link_libraries(${PROJECT_NAME} ${cppzmq_LIBRARY}) + target_include_directories(eu07_settings INTERFACE ${cppzmq_INCLUDE_DIR}) + target_link_libraries(eu07_settings INTERFACE ${cppzmq_LIBRARY}) endif() if (WIN32) @@ -576,15 +758,71 @@ if (WIN32) ) endif () -if(WIN32 AND WITH_PYTHON) - add_custom_command( - TARGET ${PROJECT_NAME} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_DLL}" "$" - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_ZLIB}" "$" - COMMAND ${CMAKE_COMMAND} -E copy_directory "${EU07_PY_LIBDIR}" "$/python64/Lib" - COMMAND ${CMAKE_COMMAND} -E copy_directory "${EU07_PY_DLLSDIR}" "$/python64/DLLs" - ) +# Linux: the game loads its shared libraries from its own folder first ($ORIGIN), and the build copies them there, +# so the folder runs on a system that doesn't have them, or has other versions. the RPATH is a DT_RPATH rather +# than a DT_RUNPATH, because only that one is also used for the libraries the copied ones load (libsndfile's codecs) +if (UNIX AND NOT APPLE) + option(BUNDLE_RUNTIME_LIBS "Linux: copy the shared libraries the game needs next to it and load them from there" ON) endif() +if (UNIX AND NOT APPLE AND BUNDLE_RUNTIME_LIBS) + set_target_properties(${PROJECT_NAME} PROPERTIES + BUILD_WITH_INSTALL_RPATH TRUE + INSTALL_RPATH "$ORIGIN") + target_link_options(${PROJECT_NAME} PRIVATE "LINKER:--disable-new-dtags") + + # the RPATH no longer leads to libraries outside the system folders (Python from setup-python, an OpenAL Soft + # in /usr/local), so their folders are given to the script as well + set(EU07_BUNDLE_SEARCH_DIRS "") + foreach(library IN LISTS Python3_LIBRARIES OPENAL_LIBRARY LUAJIT_LIBRARIES libserialport_LIBRARY) + if (IS_ABSOLUTE "${library}") + get_filename_component(library_dir "${library}" DIRECTORY) + list(APPEND EU07_BUNDLE_SEARCH_DIRS "${library_dir}") + endif() + endforeach() + list(APPEND EU07_BUNDLE_SEARCH_DIRS ${Python3_LIBRARY_DIRS}) + list(REMOVE_DUPLICATES EU07_BUNDLE_SEARCH_DIRS) + string(REPLACE ";" "|" EU07_BUNDLE_SEARCH_DIRS "${EU07_BUNDLE_SEARCH_DIRS}") + + add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} + -DGAME=$ + -DSEARCH_DIRS=${EU07_BUNDLE_SEARCH_DIRS} + -DCMAKE_OBJDUMP=${CMAKE_OBJDUMP} + -P "${CMAKE_CURRENT_SOURCE_DIR}/CMake_modules/bundle_runtime_libs.cmake" + COMMENT "Copying the shared libraries next to the game" + VERBATIM) +endif() + +if(WIN32 AND WITH_PYTHON) + # the Python runtime next to the game, copied when it isn't there yet or the Python install changed, rather + # than after every link of the game: the library alone is thousands of files. the folder is the game's + # RUNTIME_OUTPUT_DIRECTORY, spelled out: $ here would make this target depend on the game + get_property(EU07_MULTI_CONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) + if (EU07_MULTI_CONFIG) + set(EU07_PY_TARGET_DIR "${CMAKE_BINARY_DIR}/bin/$") + else() + set(EU07_PY_TARGET_DIR "${CMAKE_BINARY_DIR}/bin") + endif() + set(EU07_PY_STAMP "${EU07_PY_TARGET_DIR}/python64/python_runtime.stamp") + add_custom_command( + OUTPUT "${EU07_PY_STAMP}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_DLL}" "${EU07_PY_TARGET_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_ZLIB}" "${EU07_PY_TARGET_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_directory_if_different "${EU07_PY_LIBDIR}" "${EU07_PY_TARGET_DIR}/python64/Lib" + COMMAND ${CMAKE_COMMAND} -E copy_directory_if_different "${EU07_PY_DLLSDIR}" "${EU07_PY_TARGET_DIR}/python64/DLLs" + COMMAND ${CMAKE_COMMAND} -E touch "${EU07_PY_STAMP}" + DEPENDS "${EU07_PY_DLL}" "${EU07_PY_ZLIB}" + COMMENT "Copying the Python runtime next to the game" + VERBATIM) + add_custom_target(eu07_python_runtime DEPENDS "${EU07_PY_STAMP}") + set_target_properties(eu07_python_runtime PROPERTIES FOLDER "libraries") + add_dependencies(${PROJECT_NAME} eu07_python_runtime) +endif() + +if (WITH_WASM) + add_subdirectory("CMake_modules/wamr" "${CMAKE_CURRENT_BINARY_DIR}/wamr") + target_link_libraries(${PROJECT_NAME} eu07_wamr) +endif () if (WITH_BETTER_RENDERER) add_subdirectory("betterRenderer") @@ -592,6 +830,13 @@ if (WITH_BETTER_RENDERER) target_link_libraries(${PROJECT_NAME} "betterRenderer") endif () +# yaml-cpp, for the descriptions of scenery templates edited in the scenery editor. +# the experimental renderer brings in the same copy on its own, when enabled +if (NOT TARGET yaml-cpp) + add_subdirectory("betterRenderer/thirdparty/yaml-cpp" "${CMAKE_CURRENT_BINARY_DIR}/yaml-cpp" EXCLUDE_FROM_ALL) +endif () +target_link_libraries(eu07_settings INTERFACE yaml-cpp) + # Enable compiling with debug symbols if(GENERATE_PDB) @@ -605,7 +850,7 @@ if(GENERATE_PDB) add_link_options(/DEBUG /MAP) # Ensure that the PCH is built with the correct runtime library for each configuration - set_target_properties(${PROJECT_NAME} PROPERTIES + set_target_properties(${PROJECT_NAME} eu07_core PROPERTIES COMPILE_OPTIONS "$<$:/MDd>$<$:/MD>") else() # GCC/Clang (ensure -g is set for all configurations) @@ -621,8 +866,27 @@ endif() if(ENABLE_AVX2) message(STATUS "Enabling AVX2 instruction set.") if (MSVC) - target_compile_options(${PROJECT_NAME} PRIVATE /arch:AVX2) + target_compile_options(eu07_settings INTERFACE /arch:AVX2) else() - target_compile_options(${PROJECT_NAME} PRIVATE -mavx2) + target_compile_options(eu07_settings INTERFACE -mavx2) endif() -endif() \ No newline at end of file +endif() + +if(WITH_TESTS) + enable_testing() + add_subdirectory(tests/unit) + # the unit tests run at the end of building the game, once it's linked: a failing one fails the build + # (and removes the game binary, so the next build links it again and reruns them) + add_dependencies(${PROJECT_NAME} eu07_unit_tests) + add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD + COMMAND ${CMAKE_COMMAND} + -DTESTS=$ + -DGAME=$ + -P "${CMAKE_CURRENT_SOURCE_DIR}/tests/unit/run_tests.cmake" + COMMENT "Running the unit tests" + VERBATIM) + # a change of the tests alone links the game again, so they run (Ninja and Makefile generators; + # Visual Studio builds rerun them with the next change of the game) + set_property(TARGET ${PROJECT_NAME} APPEND PROPERTY LINK_DEPENDS + $ ${UNIT_TEST_DATA} "${CMAKE_CURRENT_SOURCE_DIR}/tests/unit/run_tests.cmake") +endif() diff --git a/CMake_modules/bundle_runtime_libs.cmake b/CMake_modules/bundle_runtime_libs.cmake new file mode 100644 index 000000000..a0f71543e --- /dev/null +++ b/CMake_modules/bundle_runtime_libs.cmake @@ -0,0 +1,75 @@ +# copies the shared libraries the game needs next to it, where its RPATH ($ORIGIN) finds them first. Linux only: +# cmake -DGAME= -DSEARCH_DIRS= [-DCMAKE_OBJDUMP=] -P bundle_runtime_libs.cmake +# +# the libraries of the system itself stay out: the C library and the loader, the GPU driver stack (libGL and its +# kin come with the driver), X11 / Wayland, the sound servers, libstdc++ (the GPU drivers bring their own need of a +# newer one) and a few more every distribution has. what a library left out depends on isn't bundled either + +get_filename_component(game_folder "${GAME}" DIRECTORY) +set(manifest "${game_folder}/bundled_libs.txt") + +# the libraries copied by the previous build go first: the game's RPATH would find them in its folder, and then +# a library updated in the system would never be copied again +if(EXISTS "${manifest}") + file(STRINGS "${manifest}" previous) + foreach(name IN LISTS previous) + if(NOT name STREQUAL "") + file(REMOVE "${game_folder}/${name}") + endif() + endforeach() + file(REMOVE "${manifest}") +endif() + +string(REPLACE "|" ";" search_dirs "${SEARCH_DIRS}") +if(DEFINED ENV{LD_LIBRARY_PATH}) + string(REPLACE ":" ";" ld_library_path "$ENV{LD_LIBRARY_PATH}") + list(APPEND search_dirs ${ld_library_path}) +endif() +list(REMOVE_ITEM search_dirs "") +list(REMOVE_DUPLICATES search_dirs) + +set(system_libraries + "^ld-linux" + "^linux-vdso" + "^lib(c|m|dl|rt|pthread|resolv|util|mvec|anl|nsl|crypt|BrokenLocale|thread_db)\\.so" + "^libstdc\\+\\+\\.so" + "^libgcc_s\\.so" + "^lib(GL|GLX|EGL|OpenGL|GLdispatch|GLESv1_CM|GLESv2|GLU|gbm|drm|vulkan)\\.so" + "^libX[A-Za-z0-9_-]*\\.so" + "^libxcb" + "^libxkbcommon" + "^libwayland-" + "^libdecor" + "^lib(asound|pulse|pulse-simple|jack|pipewire-[0-9.]+)\\.so" + "^lib(udev|systemd|dbus-1)\\.so" + "^libz\\.so" + "^lib(fontconfig|freetype|harfbuzz|expat|uuid)\\.so") + +file(GET_RUNTIME_DEPENDENCIES + EXECUTABLES "${GAME}" + RESOLVED_DEPENDENCIES_VAR resolved + UNRESOLVED_DEPENDENCIES_VAR unresolved + DIRECTORIES ${search_dirs} + PRE_EXCLUDE_REGEXES ${system_libraries}) + +if(unresolved) + list(JOIN unresolved ", " unresolved_text) + message(WARNING "Bundled libraries: not found, so not copied next to the game: ${unresolved_text}") +endif() + +# each library is copied under the name the game asks for (libpng16.so.16), as a file rather than the chain of +# symlinks it is in the system: the build artifacts don't keep symlinks +set(names "") +foreach(library IN LISTS resolved) + get_filename_component(name "${library}" NAME) + file(REAL_PATH "${library}" source) + file(COPY_FILE "${source}" "${game_folder}/${name}") + list(APPEND names "${name}") +endforeach() + +list(SORT names) +list(JOIN names "\n" manifest_text) +file(WRITE "${manifest}" "${manifest_text}\n") +list(LENGTH names count) +list(JOIN names " " names_text) +message("Bundled libraries (${count}): ${names_text}") diff --git a/CMake_modules/wamr/CMakeLists.txt b/CMake_modules/wamr/CMakeLists.txt new file mode 100644 index 000000000..d12d48cd4 --- /dev/null +++ b/CMake_modules/wamr/CMakeLists.txt @@ -0,0 +1,67 @@ +# The WebAssembly Micro Runtime (ref/wamr) for the WebAssembly script screens (scripting/wasmprogram.cpp). +# +# Built here, in a directory of its own, because the WAMR build scripts set their configuration with +# add_definitions() and include_directories(): kept in this directory, none of it reaches the game's sources. +# Only the interpreter is built (see WAMR_BUILD_FAST_INTERP), with instruction metering so that a screen stuck in a loop +# can't hang the worker thread, and without the signal-based bounds checks, which would compete with the +# game's own crash handling. + +if (WIN32) + set(WAMR_BUILD_PLATFORM "windows") +elseif (APPLE) + set(WAMR_BUILD_PLATFORM "darwin") +else () + set(WAMR_BUILD_PLATFORM "linux") +endif () + +set(WAMR_ROOT_DIR "${CMAKE_SOURCE_DIR}/ref/wamr") + +set(WAMR_BUILD_INTERP 1) +# the fast interpreter counts the instructions only where it dispatches with computed gotos (GCC, Clang): built with +# MSVC it would let a screen stuck in a loop hang the worker. the classic interpreter counts them everywhere +if (MSVC) + set(WAMR_BUILD_FAST_INTERP 0) +else () + set(WAMR_BUILD_FAST_INTERP 1) +endif () +set(WAMR_BUILD_AOT 0) +set(WAMR_BUILD_JIT 0) +set(WAMR_BUILD_FAST_JIT 0) +set(WAMR_BUILD_LIBC_BUILTIN 0) +set(WAMR_BUILD_LIBC_WASI 0) +set(WAMR_BUILD_MULTI_MODULE 0) +set(WAMR_BUILD_LIB_PTHREAD 0) +set(WAMR_BUILD_LIB_WASI_THREADS 0) +set(WAMR_BUILD_THREAD_MGR 0) +set(WAMR_BUILD_SIMD 0) +set(WAMR_BUILD_BULK_MEMORY 1) +set(WAMR_BUILD_REF_TYPES 1) +set(WAMR_BUILD_MINI_LOADER 0) +set(WAMR_BUILD_INSTRUCTION_METERING 1) +# NOTE: the calls into the natives use WAMR's assembler invokeNative (MASM with MSVC). its C version +# (WAMR_BUILD_INVOKE_NATIVE_GENERAL) crashes on Windows x64 as soon as a module runs +set(WAMR_DISABLE_HW_BOUND_CHECK 1) +set(WAMR_DISABLE_STACK_HW_BOUND_CHECK 1) + +find_package(Threads REQUIRED) +include("${WAMR_ROOT_DIR}/build-scripts/runtime_lib.cmake") + +add_library(eu07_wamr STATIC ${WAMR_RUNTIME_LIB_SOURCE}) +target_include_directories(eu07_wamr INTERFACE "${WAMR_ROOT_DIR}/core/iwasm/include") +# with MSVC the WAMR headers declare the API dllimport unless told otherwise; the library is linked statically +target_compile_definitions(eu07_wamr INTERFACE "WASM_RUNTIME_API_EXTERN=") +target_link_libraries(eu07_wamr PRIVATE Threads::Threads) +if (WIN32) + target_link_libraries(eu07_wamr PRIVATE ws2_32 ntdll) +else () + target_link_libraries(eu07_wamr PRIVATE m ${CMAKE_DL_LIBS}) +endif () +if (MSVC) + # third-party code: its warnings are not ours to fix + target_compile_options(eu07_wamr PRIVATE /W0) +else () + target_compile_options(eu07_wamr PRIVATE -w) +endif () +set_target_properties(eu07_wamr PROPERTIES + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib" + FOLDER "libraries") diff --git a/Console.h b/Console.h index e99beb4b9..1f7f9e2b1 100644 --- a/Console.h +++ b/Console.h @@ -20,7 +20,8 @@ class TLPT; class TKeyTrans { // przekodowanie kodu naciśnięcia i zwolnienia klawisza public: - short int iDown, iUp; + short int iDown; + short int iUp; }; class Console diff --git a/EU07.cpp b/EU07.cpp index e1be85847..20f24aa5a 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -19,8 +19,14 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #include "stdafx.h" #include "application/application.h" +#include "simulation/simulationtest.h" +#include "utilities/Globals.h" #include "utilities/Logs.h" #include +#include +#include +#include +#include #ifdef WITHDUMPGEN #ifdef _WIN32 #include @@ -33,6 +39,8 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #endif void export_e3d_standalone(std::string in, std::string out, int flags, bool dynamic); +int export_btf_standalone(std::string in, std::string out); +int generate_nodebank_previews(int Argc, char *Argv[]); #include #include @@ -68,7 +76,9 @@ LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo) MINIDUMP_TYPE dumpType = MINIDUMP_TYPE(MiniDumpWithFullMemory | MiniDumpWithHandleData | MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules | MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithFullMemoryInfo | MiniDumpWithTokenInformation); - MessageBoxA(nullptr, "Simulator crash occured :(\n", "Simulator crashed :(", MB_ICONERROR); + // in test mode nobody is there to close the box, and the run would wait for it until killed + if (false == Global.test.enabled) + MessageBoxA(nullptr, "Simulator crash occured :(\n", "Simulator crashed :(", MB_ICONERROR); MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, dumpType, &dumpInfo, nullptr, nullptr); CloseHandle(hFile); @@ -79,6 +89,55 @@ LONG WINAPI CrashHandler(EXCEPTION_POINTERS *ExceptionInfo) #endif +namespace +{ + +// the log is written by a thread of its own, which the closing of the application stops and waits for. on the ways +// out that skip the closing (a failed start, an exception) what was logged last would be lost with the process +void finish_log() +{ + StopLogService(); + if (auto const logservice{Global.threads.find("LogService")}; + logservice != Global.threads.end() && logservice->second.joinable() && logservice->second.get_id() != std::this_thread::get_id()) + logservice->second.join(); +} + +// ends a test run with its verdict on the standard output and in the exit code. a test the simulator didn't end +// (a failed start, an exception) ends with the error and Reason +[[noreturn]] void end_test_run(std::string_view const Reason) +{ + simulation::test().conclude(simulation::test_result::error, Reason); + finish_log(); + fflush(stdout); + fflush(stderr); + // skip destructors, there are ordering errors which causes segfaults + std::_Exit(simulation::test().exit_code()); +} + +// a test run (--test): whatever stops it, it ends with its verdict. any other run never gets here and ends as +// it always has +[[noreturn]] void run_test(int argc, char *argv[]) +{ + // for what doesn't reach the catch below: an exception leaving a noexcept function, or on Linux one leaving + // a thread (on Windows the handler is the main thread's only) + std::set_terminate([] { end_test_run(simulation::describe_exception(std::current_exception())); }); + try + { + if (Application.init(argc, argv) == 0) + { + Application.run(); + Application.exit(); + } + } + catch (...) + { + end_test_run(simulation::describe_exception(std::current_exception())); + } + end_test_run("the simulator stopped before the test ended"); +} + +} // namespace + int main(int argc, char *argv[]) { #ifdef WITHDUMPGEN @@ -98,6 +157,41 @@ int main(int argc, char *argv[]) int dynamic = std::stoi(std::string(argv[5])); export_e3d_standalone(in, out, flags, dynamic); } + // standalone generation of preview images of the node bank models: -generate-nodebank-previews [options] + else if (argc >= 2 && std::string(argv[1]) == "-generate-nodebank-previews") + { + auto const result{generate_nodebank_previews(argc, argv)}; + fflush(stdout); + fflush(stderr); + std::_Exit(result); + } + // standalone conversion of text terrain file to binary format: -btf -s [-o ] + else if (argc >= 4 && std::string(argv[1]) == "-btf") + { + std::string in; + std::string out; + for (int i = 2; i + 1 < argc; i += 2) + { + std::string const option(argv[i]); + if (option == "-s") + { + in = argv[i + 1]; + } + else if (option == "-o") + { + out = argv[i + 1]; + } + } + auto const result{export_btf_standalone(in, out)}; + fflush(stdout); + fflush(stderr); + std::_Exit(result); + } + // unattended test run of a scenery, which says its result in the exit code (eu07/maszyna#541) + else if (simulation::parse_test_command_line(std::vector(argv, argv + argc)).enabled) + { + run_test(argc, argv); + } else { try diff --git a/GEMINI.md b/GEMINI.md new file mode 100644 index 000000000..bf28f3062 --- /dev/null +++ b/GEMINI.md @@ -0,0 +1,5 @@ +# MaSzyna: notes for Gemini CLI + +The instructions for every coding agent in this repository are in `AGENTS.md`. Add or change rules there, not here. + +@./AGENTS.md diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h index a66584941..b619ba7de 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -10,9 +10,15 @@ http://mozilla.org/MPL/2.0/. #pragma once //--------------------------------------------------------------------------- // Q: 20160805 - odlaczenie pliku fizyki .pas od kompilacji +#include #include +#include #include "hamulce.h" +#include "couplerphysics.h" #include "scripting/ladderlogic.h" +#include "vehicle/odometerreading.h" + +class cParser; /* MaSzyna EU07 locomotive simulator Copyright (C) 2001-2004 Maciej Czapkiewicz and others @@ -167,6 +173,8 @@ enum DerailReason WRONG_TRACK_TYPE = 4, // Ra: powód wykolejenia: nieodpowiednia trajektoria /// Collision with another vehicle. COLLISION = 5, // powód wykolejenia: zderzenie z innym pojazdem + /// Trailing through a switch with a movable nose set the other way. + TRAILED_SWITCH = 6, // powód wykolejenia: rozprucie rozjazdu z ruchomym dziobem }; /*wagi prawdopodobienstwa dla funkcji FuzzyLogic*/ @@ -259,6 +267,22 @@ enum class range_t /// 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 { @@ -277,6 +301,16 @@ enum class operation_t /// 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 { @@ -322,6 +356,21 @@ enum light 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 { @@ -674,6 +723,13 @@ struct TTractionParam }; /*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 { @@ -764,7 +820,7 @@ enum class TLocalBrake HydraulicBrake }; /// Brake delay parameter table (apply/release for passenger and freight). -typedef double TBrakeDelayTable[4]; +using TBrakeDelayTable = double[4]; /// One row of the brake pressure / pipe pressure / flow-speed table for a brake handle position. struct TBrakePressure @@ -780,7 +836,7 @@ struct TBrakePressure }; /// Brake pressure table indexed by handle position. -typedef std::map TBrakePressureTable; +using TBrakePressureTable = std::map; /// Engine / drive type. enum class TEngineType @@ -989,11 +1045,11 @@ struct TTransducer struct TPowerParameters { /// Maximum source voltage [V]. - double MaxVoltage; + double MaxVoltage{0.0}; /// Maximum source current [A]. - double MaxCurrent; + double MaxCurrent{0.0}; /// Internal resistance [Ω]. - double IntR; + double IntR{0.001}; /// Type of source (selects which union member is meaningful). TPowerSource SourceType; union @@ -1029,9 +1085,6 @@ struct TPowerParameters }; inline TPowerParameters() { - MaxVoltage = 0.0; - MaxCurrent = 0.0; - IntR = 0.001; SourceType = TPowerSource::NotDefined; PowerType = TPowerType::NoPower; RPowerCable.PowerTrans = TPowerType::NoPower; @@ -1048,7 +1101,7 @@ struct TScheme 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*/ }; -typedef TScheme TSchemeTable[ResArraySize + 1]; /*tablica rezystorow rozr.*/ +using TSchemeTable = TScheme[ResArraySize + 1]; /*tablica rezystorow rozr.*/ struct TDEScheme { double RPM = 0.0; /*obroty diesla*/ @@ -1056,13 +1109,13 @@ struct TDEScheme double Umax = 0.0; /*napiecie maksymalne*/ double Imax = 0.0; /*prad maksymalny*/ }; -typedef TDEScheme TDESchemeTable[33]; /*tablica WWList dla silnikow spalinowych*/ +using TDESchemeTable = TDEScheme[33]; /*tablica WWList dla silnikow spalinowych*/ struct TFFScheme { double v = 0.0; // parametr wejsciowy double freq = 0.0; // wyjscie: czestotliwosc falownika }; -typedef TFFScheme TFFSchemeTable[33]; +using TFFSchemeTable = TFFScheme[33]; struct TWiperScheme { @@ -1071,7 +1124,7 @@ struct TWiperScheme double interval = 0.0; // interwal pracy wycieraczki double outBackDelay = 0.0; // czas po jakim wycieraczka zacznie wracac z konca do poczatku }; -typedef TWiperScheme TWiperSchemeTable[16]; +using TWiperSchemeTable = TWiperScheme[16]; struct TShuntScheme { @@ -1080,33 +1133,23 @@ struct TShuntScheme double Pmin = 0.0; double Pmax = 0.0; }; -typedef TShuntScheme TShuntSchemeTable[33]; +using TShuntSchemeTable = TShuntScheme[33]; struct TMPTRelay { /*lista przekaznikow bocznikowania*/ double Iup = 0.0; double Idown = 0.0; }; -typedef TMPTRelay TMPTRelayTable[8]; +using TMPTRelayTable = TMPTRelay[MotorParametersArraySize + 1]; // indexed like MotorParam struct TMotorParameters { - double mfi; - double mIsat; - double mfi0; // aproksymacja M(I) silnika} {dla dizla mIsat=przekladnia biegu - double fi; - double Isat; - double fi0; // aproksymacja E(n)=fi*n} {dla dizla fi, mfi: predkosci przelozenia biegu <-> - bool AutoSwitch; - TMotorParameters() - { - mfi = 0.0; - mIsat = 0.0; - mfi0 = 0.0; - fi = 0.0; - Isat = 0.0; - fi0 = 0.0; - AutoSwitch = false; - } + 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 @@ -1135,6 +1178,7 @@ class TSecuritySystem 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; @@ -1150,6 +1194,7 @@ class TSecuritySystem 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); @@ -1159,6 +1204,7 @@ class TSecuritySystem 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; @@ -1223,6 +1269,7 @@ struct TCoupling 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 @@ -1232,6 +1279,11 @@ struct TCoupling power_coupling power_110v; power_coupling power_24v; + // the physical model of the coupling (couplerphysics in eu07.ini), see couplerphysics.h: the parameters of this end, + // and the state of the coupling with the vehicle at this end, which that vehicle keeps alike on its own end + coupler_physics::end_parameters physics; + coupler_physics::pair_state physics_state; + int sounds{0}; // sounds emitted by the coupling devices bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/ std::string control_type; // abstraction of control coupling interface and communication standard @@ -1240,7 +1292,7 @@ struct TCoupling { return adapter_type != TCouplerType::NoCoupler; } - inline TCouplerType const type() const + inline TCouplerType type() const { return adapter_type == TCouplerType::NoCoupler ? CouplerType : adapter_type; } @@ -1443,6 +1495,7 @@ class TMoverParameters 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 @@ -1465,7 +1518,8 @@ class TMoverParameters { float temp_min{-1}; // lowest accepted temperature float temp_max{-1}; // highest accepted temperature - } config; + }; + heater_config_t config; // ld inputs bool breaker{false}; // device is allowed to operate bool is_enabled{false}; // device is requested to operate @@ -1500,12 +1554,17 @@ class TMoverParameters 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 - } config; + }; + 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 - } water, water_aux, oil, engine; + }; + 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 @@ -1588,6 +1647,9 @@ class TMoverParameters 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.*/ @@ -1701,6 +1763,13 @@ class TMoverParameters 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 @@ -1715,12 +1784,20 @@ class TMoverParameters 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*/ @@ -1729,6 +1806,15 @@ class TMoverParameters 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; @@ -1880,9 +1966,9 @@ class TMoverParameters 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 = 0; // czy korekcja sily hamowania EP, gdy nie ma dostepnego ED + 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 = 0; // czy korekcja sily hamowania z uwzglednieniem nacisku + 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) @@ -1928,6 +2014,7 @@ class TMoverParameters 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*/ @@ -1940,6 +2027,9 @@ class TMoverParameters 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 @@ -1948,6 +2038,7 @@ class TMoverParameters int SoundFlag = 0; /*!o patrz stale sound_ */ int AIFlag{0}; // HACK: events of interest for consist owner double DistCounter = 0.0; /*! licznik kilometrow */ + odometer::reading Odometer; // total distance run, kept between the sessions (eu07/maszyna#72) std::pair EnergyMeter; // energy from grid [kWh] double V = 0.0; // predkosc w [m/s] względem sprzęgów (dodania gdy jedzie w stronę 0) double Vel = 0.0; // moduł prędkości w [km/h], używany przez AI @@ -1997,6 +2088,8 @@ class TMoverParameters 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}; @@ -2043,6 +2136,9 @@ class TMoverParameters 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*/ @@ -2076,6 +2172,14 @@ class TMoverParameters 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}; @@ -2090,7 +2194,7 @@ class TMoverParameters int CabActive = 0; // numer kabiny, z której jest sterowanie: 1 lub -1; w przeciwnym razie brak sterowania - rozrzad int CabOccupied = 0; // numer kabiny, w ktorej jest obsada (zwykle jedna na skład) // TODO: move to TController bool CabMaster = false; // czy pojazd jest nadrzędny w składzie - inline bool IsCabMaster() + inline bool IsCabMaster() const { return CabActive == CabOccupied && CabMaster; } // czy aktualna kabina jest na pewno tą, z której można sterować @@ -2135,13 +2239,17 @@ class TMoverParameters 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 - bool NoVoltRelay{true}; // switches off if the power level drops below threshold + // 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 @@ -2154,6 +2262,10 @@ class TMoverParameters 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*/ @@ -2182,12 +2294,14 @@ class TMoverParameters 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; @@ -2224,6 +2338,7 @@ class TMoverParameters // 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 @@ -2268,6 +2383,14 @@ class TMoverParameters // 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 @@ -2282,11 +2405,13 @@ class TMoverParameters 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 - public: - TMoverParameters(double VelInitial, std::string TypeNameInit, std::string NameInit, int Cab); + 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); @@ -2294,11 +2419,15 @@ class TMoverParameters int DettachStatus(int ConnectNo); bool Dettach(int ConnectNo); void damage_coupler(int const End); + // repairs the broken coupler of the end, and the one of the vehicle it was coupled with, so they can be coupled + // again; the vehicles clear their coupler damage once neither of their couplers is broken. returns: whether there + // was a broken coupler to repair + bool repair_coupler(int const End); void Derail(DerailReason Reason); bool DirectionForward(); bool DirectionBackward(void); /*! kierunek ruchu*/ bool EIMDirectionChangeAllow(void) const; - inline double IsVehicleEIMBrakingFactor() + inline double IsVehicleEIMBrakingFactor() const { return DynamicBrakeFlag && ResistorsFlag ? 0.0 : eimv[eimv_Ipoj] < 0 ? -1.0 : 1.0; } @@ -2310,32 +2439,32 @@ class TMoverParameters bool CurrentSwitch(bool const State); bool IsMotorOverloadRelayHighThresholdOn() const; void UpdateBatteryVoltage(double dt); - double ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam &Track, TTractionParam &ElectricTraction, TLocation const &NewLoc, + 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); + double ShowEngineRotation(int VehN) const; // Q ******************************************************************************************* double GetTrainsetVoltage(int const Coupling = coupling::heating | coupling::highvoltage) const; double GetTrainsetHighVoltage() const; bool switch_physics(bool const State); - double LocalBrakeRatio(void); - double ManualBrakeRatio(void); - double PipeRatio(void); /*ile napelniac*/ - double RealPipeRatio(void); /*jak szybko*/ + 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 NewCommand, double NewValue1, double NewValue2, int const Couplertype = coupling::control); - double GetExternalCommand(std::string &Command); - bool RunCommand(std::string Command, double CValue1, double CValue2, int const Couplertype = coupling::control); + bool SendCtrlToNext(std::string const &CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype = coupling::control); + bool SetInternalCommand(std::string const &NewCommand, double NewValue1, double NewValue2, int const Couplertype = coupling::control); + double GetExternalCommand(std::string &Command) const; + bool RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype = coupling::control); bool RunInternalCommand(); - void PutCommand(std::string NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation); + 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); @@ -2351,10 +2480,24 @@ class TMoverParameters 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(); + int GetVirtualScndPos() const; + // whether ScndCtrlResistiveLock keeps the shunt controller from being moved at the current master controller position + bool IsScndCtrlLockedByMainCtrl() const; + // ScndCtrlResistiveLock: the shunt controller drops to 0 once the master controller is at zero or on a resistive position, so it + // can't stay engaged there, locked in place (eu07/maszyna#402) + void ScndCtrlResistiveLockCheck(); bool IsScndCtrlNoPowerPos() const; bool IsScndCtrlMaxPowerPos() const; @@ -2396,6 +2539,8 @@ class TMoverParameters 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*/ @@ -2420,11 +2565,105 @@ class TMoverParameters double Adhesive(double staticfriction) const; double TractionForce(double dt); double FrictionForce() const; - double BrakeForceR(double ratio, double velocity); - double BrakeForceP(double press, double velocity); + double BrakeForceR(double ratio, double velocity) const; + double BrakeForceP(double press, double velocity) const; double BrakeForce(const TTrackParam &Track); double CouplerForce(int const End, double dt); + // whether the coupling at the end is computed by the physical model: couplerphysics set in eu07.ini, and this + // vehicle or the one at the end covered by it (CouplerPhysics), or every vehicle with couplerphysics all + bool coupler_physics_at(int const End) const; + // the force of the coupling at the end by the physical model (couplerphysics in eu07.ini), see couplerphysics.h + double coupler_force_physical(int const End, double const dt); + // with the physical model: whether the vehicles at the end hit the stop of their springs at the last update and + // still close in on it, so that they collide; a hit hard enough breaks the coupling or crushes the buffers + bool coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd); + // couples the automatic couplers of the end and of the other vehicle pressed against each other, unless the hit + // is too fast for them to catch + void automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd); void CollisionDetect(int const End, double const dt); + // closing speed of a collision [km/h] above which the vehicles involved may derail, adjusted for their mass ratio + static constexpr double SafeCollisionVelocity{15.0}; + // closing speed [km/h] of the End of this vehicle and the OtherEnd of the other vehicle it touches, along the coupler + // axis: the sum of the speeds in a head-on collision, the difference in a rear-end one, negative when they part + double CollisionVelocity(int const End, TMoverParameters const &Other, int const OtherEnd) const; + // velocity [m/s] of this vehicle relative to the other vehicle it touches with its End and the OtherEnd of the + // other one, along this vehicle's axis + double CouplerVelocityDifference(int const End, TMoverParameters const &Other, int const OtherEnd) const; + // whether the automatic couplers at the End of this vehicle and the OtherEnd of the other one can catch each other on + // contact, rather than the vehicles colliding (with crash damage enabled, only at a closing speed which doesn't derail them) + bool AutomaticCouplingSafe(int const End, TMoverParameters const &Other, int const OtherEnd) const; + // whether the control coupling (multiple-unit control) can join the End of this vehicle and the OtherEnd of the other + // one: not between an electric and a diesel traction vehicle, unless both couplers name the same control system + // (ControlType). Vehicles without own traction (cars, control trailers) take any. Global.control_coupling_engine_check + // off allows it always (eu07/maszyna#520) + bool ControlCouplingAllowed(int const End, TMoverParameters const &Other, int const OtherEnd) const; + // the CouplingType to join the End of this vehicle and the OtherEnd of the other one with, without the control coupling + // when ControlCouplingAllowed() rules it out. a permanent coupling (of the vehicles of one unit) is kept whole + int CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, int const CouplingType) const; + // the horns of the Signal (WarningSignal bits) which have the air or the voltage they need to sound + int SoundingHorns(int const Signal) const; + // whether the signal lamps of the main circuit (line contactors, ground relay, motor overload relays) can light: + // the pressure switch, when fitted, cuts the start off and puts them out, otherwise they go out once the brakes are applied + bool MainCircuitLampsEnabled() const + { + return false == ControlPressureSwitch && (HasControlPressureSwitch || BrakePress < 1.0); + } + // whether the lamp of the open line contactors is lit. on the electric locomotives it tells the start can be made, so + // it goes out with the start cut off; on the diesel-electric ones (the SU45 and SU46 family) it just tells the + // contactors are open, whatever opened them: the master controller at 0, or the pressure switch (eu07/maszyna#263) + bool LineContactorsLampLit() const + { + if (EngineType == TEngineType::DieselElectric) + { + return false == StLinFlag; + } + return false == StLinFlag && MainCircuitLampsEnabled(); + } + // the vehicles the line breaker / engine start switch of this vehicle works, and its engine stopping on its own + // stops: the whole consist, or with JointEngineStart=No this vehicle alone (eu07/maszyna#80) + range_t MainSwitchRange() const + { + return JointEngineStart ? range_t::consist : range_t::local; + } + // whether the pneumatic louvres of the motor fans are still closed, the main reservoir short of the pressure that opens them + bool LouvresClosed() const + { + return Compressor < LouvresOpenPressure; + } + // whether the devices the line contactors are interlocked with (LineContactorsInterlock) let them close + bool LineContactorsInterlockReleased() const; + // whether the line contactors wait for the converter of the vehicle, switched off with its local switch (converterlocal_sw). + // the AI driver doesn't leave it so: the converters of the other vehicles running, it would wait for the contactors forever + bool LineContactorsHeldByLocalConverterSwitch() const + { + return LineContactorsInterlock == line_contactors_interlock::converter && false == ConverterAllowLocal; + } + // whether the vehicle has a driver's cab: it has the driver's brake valve (BrakeHandle in the Cntrl. section of the + // .fiz), which the wagons and most cars of the units without a cab don't (a few copy the Cntrl. section of the cab + // car, as the EN57 s car does). it's the vehicle type's, unlike the cab the scenario puts a driver in + bool HasDriverCab() const + { + return BrakeHandle != TBrakeHandle::NoHandle; + } + // whether the cab command opening the main circuit opens it where the only cab switch of the circuit is the button + // closing it: on a diesel that's the starter button, and the command is the one way to stop an engine whose fuel pump + // starts on its own (eu07/maszyna#427). the other vehicles with such a button keep ignoring the command + bool MainCircuitOpensWithStarterOnly() const + { + return EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric; + } + // whether the pumps a joint oil and fuel pump switch works, those not started automatically, are all switched on + bool OilFuelPumpsEnabled() const + { + auto const fuelmanual{FuelPump.start_type != start_t::automatic}; + auto const oilmanual{OilPump.start_type != start_t::automatic}; + return (fuelmanual || oilmanual) && (false == fuelmanual || FuelPump.is_enabled) && (false == oilmanual || OilPump.is_enabled); + } + // whether the radio is switched on, its power supply isn't cut off and it has the low voltage to work + bool RadioPowered() const + { + return Radio && RadioFuse && (Power24vIsAvailable || Power110vIsAvailable); + } /*obrot kol uwzgledniajacy poslizg*/ double ComputeRotatingWheel(double WForce, double dt, double n) const; @@ -2452,6 +2691,11 @@ class TMoverParameters bool HeatingSwitch(bool const State, range_t const Notify = range_t::consist); void HeatingSwitch_(bool const State); double EnginePowerSourceVoltage() const; // returns voltage of defined main engine power source + // whether the main circuit feeds what runs on it (the converter, a compressor, the heating, the motor and resistor + // blowers, the traction motors): the line breaker closed, and where it closes ahead of the pantographs and holds + // without traction voltage (PantographsRequireMains) also the voltage there, at least the one the undervoltage + // trip takes. everywhere else it's the same as Mains + bool MainCircuitPowered() const; /*-funkcje typowe dla lokomotywy elektrycznej*/ void LowVoltagePowerCheck(double const Deltatime); @@ -2464,6 +2708,8 @@ class TMoverParameters void FuelPumpCheck(double const Timestep); void OilPumpCheck(double const Timestep); void MotorBlowersCheck(double const Timestep); + // whether the circuit a traction motor blower runs off has power: the battery, the converter or the main circuit, by its start type + bool MotorBlowerPowerIsAvailable(cooling_fan const &Blower) const; void PantographsCheck(double const Timestep); void LightsCheck(double const Timestep); bool FuseOn(range_t const Notify = range_t::consist); // bezpiecznik nadamiary @@ -2479,8 +2725,8 @@ class TMoverParameters /*funkcje uzalezniajace sile pociagowa od predkosci: v2n, n2r, current, momentum*/ double v2n(void); double Current(double n, double U); - double Momentum(double I); - double MomentumF(double I, double Iw, int SCP); + 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*/ @@ -2517,7 +2763,7 @@ class TMoverParameters /* funckje dla wagonow*/ bool AssignLoad(std::string const &Name, float const Amount = 0.f); - bool LoadingDone(double LSpeed, std::string const &Loadname); + 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); @@ -2527,16 +2773,24 @@ class TMoverParameters bool LockDoors(bool const State, range_t const Notify = range_t::consist); bool signal_departure(bool const State, range_t const Notify = range_t::consist); // toggles departure warning void update_doors(double const Deltatime); // door controller update + door_closure_t door_closure() const; // state of the door closure signalling of this vehicle + // whether the door closure lamp in the cab of this vehicle is lit: with DoorClosureSignal, for the given state of the + // consist; without it, for the lock of the vehicle's own doors, as the lamp always worked + bool door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const; /* funkcje dla samochodow*/ bool ChangeOffsetH(double DeltaOffset); /*funkcje ladujace pliki opisujace pojazd*/ - bool LoadFIZ(std::string chkpath); // Q 20160717 bool LoadChkFile(std::string chkpath); + bool LoadFIZ(std::string const &chkpath); // Q 20160717 bool LoadChkFile(std::string chkpath); + bool LoadFIZ_Text(std::string const &Text); // the same, from text in the .fiz format bool CheckLocomotiveParameters(bool ReadyFlag, int Dir); std::string EngineDescription(int what) const; + // the cab interior light the light preset at given position (1-based, as LightsPos) sets, if it sets one + std::optional LightsPresetCabLight(int Position) const; private: + bool LoadFIZ_Parse(cParser &Parser); // reads the definition from either of the above void LoadFIZ_Param(std::string const &line); void LoadFIZ_Load(std::string const &line); void LoadFIZ_Dimensions(std::string const &line); @@ -2568,10 +2822,10 @@ class TMoverParameters 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); - TPowerSource LoadFIZ_SourceDecode(std::string const &Source); - TEngineType LoadFIZ_EngineDecode(std::string const &Engine); + 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); diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 83c918e24..825137675 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -16,6 +16,10 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/parser.h" #include "simulation/simulation.h" + +#include +#include +#include //--------------------------------------------------------------------------- // Ra: tu należy przenosić funcje z mover.pas, które nie są z niego wywoływane. @@ -49,8 +53,13 @@ double ComputeCollision(double &v1, double &v2, double m1, double m2, double bet double sum = m1 + m2; double w1 = (m2 * v2 * 2.0 + v1 * (m1 - m2)) / sum; double w2 = (m1 * v1 * 2.0 + v2 * (m2 - m1)) / sum; - v1 = w1 * std::sqrt(1.0 - beta); // niejawna zmiana predkosci wskutek zderzenia - v2 = w2 * std::sqrt(1.0 - beta); + // 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); } } @@ -144,11 +153,23 @@ void TSecuritySystem::update(double dt, double vel, bool pwr, int cab) velocity = vel; cabactive = cab; - if (vigilance_enabled && velocity > AwareMinSpeed) - vigilance_timer += dt; + 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 (pressed && (!is_sifa || velocity > AwareMinSpeed)) + press_timer += dt; + } if (vigilance_timer > AwareDelay || press_timer > MaxHoldTime || cabsignal_active) alert_timer += dt; @@ -223,6 +244,11 @@ 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) @@ -252,11 +278,12 @@ void TSecuritySystem::load(std::string const &line, double Vmax) 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.size() == 0) + if (Map.empty()) return 0.0; if (Map.size() == 1) return Map.begin()->second; @@ -289,8 +316,11 @@ double TMoverParameters::Current(double n, double U) // a takze wywala bezpiecznik nadmiarowy gdy za duzy prad lub za male napiecie // jest takze mozliwosc uszkodzenia silnika wskutek nietypowych parametrow - double R, MotorCurrent; - double Rz, Delta, Isf; + double R; + double MotorCurrent; + double Rz; + double Delta; + double Isf; double Mn; // przujmuje int, ale dla poprawnosci obliczeń double Bn; int SP = 0; @@ -347,7 +377,6 @@ double TMoverParameters::Current(double n, double U) Mn = RList[MainCtrlActualPos].Mn * RList[MainCtrlActualPos].Bn; if (RList[MainCtrlActualPos].Bn > 1) { - Bn = 1; R = CircuitRes; } } @@ -355,7 +384,7 @@ double TMoverParameters::Current(double n, double U) if (DynamicBrakeFlag && !FuseFlag && DynamicBrakeType == dbrake_automatic && Power110vIsAvailable && Mains) // hamowanie EP09 //TUHEX { // TODO: zrobic bardziej uniwersalne nie tylko dla EP09 - MotorCurrent = -std::max(MotorParam[0].fi * (Vadd / (Vadd + MotorParam[0].Isat) - MotorParam[0].fi0), 0.) * n * 2.0 / DynamicBrakeRes; + 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) { @@ -390,7 +419,7 @@ double TMoverParameters::Current(double n, double U) if (DynamicBrakeType == dbrake_switch && TrainType == dt_ET42) { // z Megapacka Rz = WindingRes + R; - MotorCurrent = -MotorParam[SP].fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} + MotorCurrent = -motor_param(SP).fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} } } else @@ -398,23 +427,23 @@ double TMoverParameters::Current(double n, double U) } else { - U1 = U + Mn * n * MotorParam[SP].fi0 * MotorParam[SP].fi; + 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) * MotorParam[SP].Isat; + Isf = Sign(U1) * motor_param(SP).Isat; // writepaslog("Isf ", FloatToStr(Isf)); - Delta = square(Isf * Rz + Mn * MotorParam[SP].fi * n - U1) + 4.0 * U1 * Isf * Rz; // 105 * 1.67 + Mn * 140.9 * 20.532 - U1 + 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 (Mains) + if (MainCircuitPowered()) { if (U > 0) - MotorCurrent = (U1 - Isf * Rz - Mn * MotorParam[SP].fi * n + std::sqrt(Delta)) / (2.0 * Rz); + MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n + std::sqrt(Delta)) / (2.0 * Rz); else - MotorCurrent = (U1 - Isf * Rz - Mn * MotorParam[SP].fi * n - std::sqrt(Delta)) / (2.0 * Rz); + MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n - std::sqrt(Delta)) / (2.0 * Rz); } else MotorCurrent = 0; @@ -429,7 +458,6 @@ double TMoverParameters::Current(double n, double U) if (DynamicBrakeType == dbrake_switch && (BrakePress > 2.0 || PipePress < 3.6)) { Im = 0; - MotorCurrent = 0; // Im:=0; Itot = 0; } @@ -443,17 +471,13 @@ double TMoverParameters::Current(double n, double U) if (MotorCurrent > 0) { - if (FuzzyLogic(abs(n), nmax * 1.1, p_elengproblem)) - if (MainSwitch(false)) - EventFlag = true; /*zbyt duze obroty - wywalanie wskutek ognia okreznego*/ - if (TestFlag(DamageFlag, dtrain_engine)) - if (FuzzyLogic(MotorCurrent, (double)ImaxLo / 10.0, p_elengproblem)) - if (MainSwitch(false)) - EventFlag = true; /*uszkodzony silnik (uplywy)*/ - if (FuzzyLogic(abs(Im), Imax * 2, p_elengproblem) || FuzzyLogic(abs(n), nmax * 1.11, p_elengproblem)) - /* or FuzzyLogic(Abs(U/Mn),2*NominalVoltage,1)) then */ /*poprawic potem*/ - if (SetFlag(DamageFlag, dtrain_engine)) - EventFlag = true; + 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*/ } @@ -463,36 +487,37 @@ double TMoverParameters::Current(double n, double U) // ************************************************************************************************* // główny konstruktor // ************************************************************************************************* -TMoverParameters::TMoverParameters(double VelInitial, std::string TypeNameInit, std::string NameInit, int Cab) : TypeName(TypeNameInit), Name(NameInit), CabOccupied(Cab) +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 + "]"); - Dim = TDimension(); // 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 (int b = 0; b < ResArraySize + 1; ++b) + for (auto &scheme : RList) { - RList[b] = TScheme(); + scheme = TScheme(); } RlistSize = 0; - for (int b = 0; b < MotorParametersArraySize + 1; ++b) + for (auto &motorparam : MotorParam) { - MotorParam[b] = TMotorParameters(); + motorparam = TMotorParameters(); } - for (int b = 0; b < 2; ++b) + for (auto &cablights : Lights) for (int k = 0; k < 17; ++k) - Lights[b][k] = 0; + cablights[k] = 0; - for (int b = 0; b < 4; ++b) + for (auto &compressorrow : CompressorList) for (int k = 1; k < 9; ++k) - CompressorList[b][k] = 0; + compressorrow[k] = 0; CompressorList[0][0] = 0.0; - CompressorList[1][0] = CompressorList[2][0] = CompressorList[3][0] = 1.0; + CompressorList[1][0] = 1.0; + CompressorList[2][0] = 1.0; + CompressorList[3][0] = 1.0; for (int b = -1; b <= MainBrakeMaxPos; ++b) { @@ -506,9 +531,9 @@ TMoverParameters::TMoverParameters(double VelInitial, std::string TypeNameInit, BrakePressureTable[-2].BrakePressureVal = -1.0; BrakePressureTable[-2].FlowSpeedVal = 0.0; } - for (int b = 0; b < 4; ++b) + for (auto &delay : BrakeDelay) { - BrakeDelay[b] = 0.0; + delay = 0.0; } for (int b = 0; b < 2; ++b) // Ra: kto tu zrobił "for b:=1 to 2 do" ??? @@ -521,40 +546,40 @@ TMoverParameters::TMoverParameters(double VelInitial, std::string TypeNameInit, Couplers[b].DmaxC = 0.1; Couplers[b].FmaxC = 1000.0; } - for (int b = 0; b < 3; ++b) + for (auto &cylindermult : BrakeCylMult) { - BrakeCylMult[b] = 0.0; + cylindermult = 0.0; } - for (int b = 0; b < 26; ++b) + for (auto &eimcvalue : eimc) { - eimc[b] = 0.0; + eimcvalue = 0.0; } eimc[eimc_p_eped] = 1.5; - for (int b = 0; b < 2; ++b) + for (auto &couplerentry : Couplers) { - Couplers[b].AllowedFlag = 3; // domyślnie hak i hamulec, inne trzeba włączyć jawnie w FIZ - Couplers[b].CouplingFlag = 0; - Couplers[b].Connected = nullptr; - Couplers[b].ConnectedNr = 0; // Ra: to nie ma znaczenia jak nie podłączony - Couplers[b].Render = false; - Couplers[b].CForce = 0.0; - Couplers[b].Dist = 0.0; - Couplers[b].CheckCollision = false; + 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 (int b = 0; b < 5; ++b) + for (auto &brakepress : MaxBrakePress) { - MaxBrakePress[b] = 0.0; + brakepress = 0.0; } Vel = abs(VelInitial); V = VelInitial / 3.6; - for (int b = 0; b < 21; b++) + for (auto &eimvvalue : eimv) { - eimv[b] = 0.0; + eimvvalue = 0.0; } RunningShape.Len = 1.0; @@ -592,30 +617,45 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters * return false; } - auto &coupler{Couplers[ConnectNo]}; - auto &othercoupler = ConnectTo->Couplers[(ConnectToNr != 2 ? ConnectToNr : coupler.ConnectedNr)]; - auto const distance{CouplerDist(this, ConnectTo) - (coupler.adapter_length + othercoupler.adapter_length)}; + 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)}; - auto const couplercheck{Enforce || (distance <= dEpsilon && coupler.type() != TCouplerType::NoCoupler && coupler.type() == othercoupler.type())}; - if (false == couplercheck) + if (auto const couplercheck{Enforce || (distance <= dEpsilon && thiscoupler.type() != TCouplerType::NoCoupler && thiscoupler.type() == othercoupler.type())}; false == couplercheck) { return false; } - // stykaja sie zderzaki i kompatybilne typy sprzegow, chyba że łączenie na starcie - if (coupler.CouplingFlag == coupling::faux) + // 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 - coupler.Render = true; // tego rysować + thiscoupler.Render = true; // tego rysować othercoupler.Render = false; // a tego nie - }; - auto const couplingchange{CouplingType ^ coupler.CouplingFlag}; - coupler.Connected = ConnectTo; - coupler.CouplingFlag = CouplingType; // ustawienie typu sprzęgu + } + auto const couplingchange{CouplingType ^ thiscoupler.CouplingFlag}; + thiscoupler.Connected = ConnectTo; + thiscoupler.CouplingFlag = CouplingType; // ustawienie typu sprzęgu if (ConnectToNr != 2) { - coupler.ConnectedNr = ConnectToNr; // 2=nic nie podłączone + thiscoupler.ConnectedNr = ConnectToNr; // 2=nic nie podłączone } othercoupler.Connected = this; othercoupler.CouplingFlag = CouplingType; @@ -628,14 +668,14 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters * 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 &soundmapping : soundmappings) + for (auto const &[mappingcoupling, mappingsound] : soundmappings) { - if ((couplingchange & soundmapping.first) != 0) + if ((couplingchange & mappingcoupling) != 0) { - soundflag |= soundmapping.second; + soundflag |= mappingsound; } } - SetFlag(coupler.sounds, soundflag); + SetFlag(thiscoupler.sounds, soundflag); } return true; @@ -659,44 +699,44 @@ int TMoverParameters::DettachStatus(int ConnectNo) bool TMoverParameters::Dettach(int ConnectNo) { // rozlaczanie - auto &coupler{Couplers[ConnectNo]}; - auto &othervehicle{coupler.Connected}; - auto &othercoupler{othervehicle->Couplers[coupler.ConnectedNr]}; + 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{coupler.CouplingFlag}; // presume we'll uncouple all active flags + 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(coupler.Connected, coupler.ConnectedNr, coupler.CouplingFlag) = std::tie(othercoupler.Connected, othercoupler.ConnectedNr, othercoupler.CouplingFlag) = - std::make_tuple(nullptr, -1, coupling::faux); + 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) - coupler.CouplingFlag &= coupling::coupler; + thiscoupler.CouplingFlag &= coupling::coupler; othercoupler.CouplingFlag &= coupling::coupler; } // set sound event flag - couplingchange ^= coupler.CouplingFlag; // remaining bits were removed from coupling + 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 &soundmapping : soundmappings) + for (auto const &[mappingcoupling, mappingsound] : soundmappings) { - if ((couplingchange & soundmapping.first) != 0) + if ((couplingchange & mappingcoupling) != 0) { - soundflag |= soundmapping.second; + soundflag |= mappingsound; } } - SetFlag(coupler.sounds, soundflag); + SetFlag(thiscoupler.sounds, soundflag); } return couplingstate < 0; @@ -735,7 +775,7 @@ void TMoverParameters::BrakeLevelSet(double b) fBrakeCtrlPos = Handle->GetPos(bh_MAX); // TODO: verify whether BrakeCtrlPosR and fBrakeCtrlPos can be rolled into single variable BrakeCtrlPosR = fBrakeCtrlPos; - int x = static_cast(std::floor(fBrakeCtrlPos)); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być + 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:: @@ -804,6 +844,19 @@ bool TMoverParameters::ChangeCab(int direction) // 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)) { @@ -813,20 +866,6 @@ bool TMoverParameters::CurrentSwitch(bool const State) } return true; } - // TBD, TODO: split off shunt mode toggle into a separate command? It doesn't make much sense to have these two together like that - // dla 2Ls150 - if (EngineType == TEngineType::DieselEngine && true == ShuntModeAllow && DirActive == 0) - { - // przed ustawieniem kierunku - ShuntMode = State; - return true; - } - // for SM42/SP42 - if (EngineType == TEngineType::DieselElectric && true == ShuntModeAllow && IsMainCtrlNoPowerPos()) - { - ShuntMode = State; - return true; - } return false; }; @@ -936,8 +975,11 @@ void TMoverParameters::UpdatePantVolume(double dt) void TMoverParameters::UpdateBatteryVoltage(double dt) { // przeliczenie obciążenia baterii - double sn1 = 0.0, sn2 = 0.0, sn3 = 0.0, sn4 = 0.0, - sn5 = 0.0; // Ra: zrobić z tego amperomierz NN + double sn1 = 0.0; + double sn2 = 0.0; + double sn3 = 0.0; + double sn4 = 0.0; + double sn5 = 0.0; // Ra: zrobić z tego amperomierz NN if (BatteryVoltage > 0 && EngineType != TEngineType::DieselEngine && EngineType != TEngineType::WheelsDriven && NominalBatteryVoltage > 0) { @@ -968,7 +1010,7 @@ void TMoverParameters::UpdateBatteryVoltage(double dt) sn5 = dt * 0.001; else sn5 = 0; - }; + } if (NominalBatteryVoltage / BatteryVoltage >= 1.22 && Battery) { // 90V if (PantCompFlag) @@ -991,7 +1033,7 @@ void TMoverParameters::UpdateBatteryVoltage(double dt) sn5 = dt * 0.0010; else sn5 = 0; - }; + } if (!Battery) { if (NominalBatteryVoltage / BatteryVoltage < 1.22) @@ -1002,11 +1044,10 @@ void TMoverParameters::UpdateBatteryVoltage(double dt) sn3 = dt * 0.000001; sn4 = dt * 0.000001; sn5 = dt * 0.000001; // bardzo powolny spadek przy wyłączonych bateriach - }; + } BatteryVoltage -= sn1 + sn2 + sn3 + sn4 + sn5; - if (NominalBatteryVoltage / BatteryVoltage > 1.57) - if (MainSwitch(false) && EngineType != TEngineType::DieselEngine && EngineType != TEngineType::WheelsDriven) - EventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia + if (NominalBatteryVoltage / BatteryVoltage > 1.57 && MainSwitch(false) && EngineType != TEngineType::DieselEngine && EngineType != TEngineType::WheelsDriven) + EventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia if (BatteryVoltage > NominalBatteryVoltage) BatteryVoltage = NominalBatteryVoltage; // wstrzymanie ładowania pow. 110V if (BatteryVoltage < 0.01) @@ -1062,7 +1103,7 @@ ZN //masa // Q: 20160714 // Oblicza iloraz aktualnej pozycji do maksymalnej hamulca pomocnicznego // ***************************************************************************** -double TMoverParameters::LocalBrakeRatio(void) +double TMoverParameters::LocalBrakeRatio(void) const { double LBR; if (BrakeHandle == TBrakeHandle::MHZ_EN57) @@ -1086,7 +1127,7 @@ double TMoverParameters::LocalBrakeRatio(void) // Q: 20160714 // Oblicza iloraz aktualnej pozycji do maksymalnej hamulca ręcznego // ***************************************************************************** -double TMoverParameters::ManualBrakeRatio(void) +double TMoverParameters::ManualBrakeRatio(void) const { double MBR; @@ -1113,7 +1154,7 @@ double TMoverParameters::BrakeVP(void) const // Q: 20160713 // Zwraca iloraz różnicy między przewodem kontrolnym i głównym oraz DeltaPipePress // ***************************************************************************** -double TMoverParameters::RealPipeRatio(void) +double TMoverParameters::RealPipeRatio(void) const { double rpp; @@ -1128,7 +1169,7 @@ double TMoverParameters::RealPipeRatio(void) // Q: 20160713 // Zwraca iloraz ciśnienia w przewodzie do DeltaPipePress // ***************************************************************************** -double TMoverParameters::PipeRatio(void) +double TMoverParameters::PipeRatio(void) const { double pr; @@ -1177,6 +1218,109 @@ double TMoverParameters::EngineMaxRPM() const 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 @@ -1188,27 +1332,39 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) return; } // shouldn't normally happen but, eh - auto &coupler{Couplers[End]}; + auto const &thiscoupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; auto const otherend{Neighbours[End].vehicle_end}; - auto &othercoupler{othervehicle->Couplers[otherend]}; + auto const &othercoupler{othervehicle->Couplers[otherend]}; + auto const physical{coupler_physics_at(End)}; + if (physical && false == coupler_stop_hit(End, *othervehicle, otherend)) + { + return; + } + // the share of the energy of the relative motion the hit takes: in the physical model the springs gone solid give + // for good, rather than spring back as the legacy model has it + auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0}; + + // the velocities along this vehicle's axis: the other vehicle's one is turned around when the vehicles face each + // other (touch with the same ends), as in CouplerForce() + auto const otherdirection{DirPatch(End, otherend)}; auto velocity{V}; - auto othervehiclevelocity{othervehicle->V}; + auto othervehiclevelocity{othervehicle->V * otherdirection}; // calculate collision force and new velocities for involved vehicles - auto const VirtualCoupling{(coupler.CouplingFlag == coupling::faux)}; + auto const VirtualCoupling{(thiscoupler.CouplingFlag == coupling::faux)}; auto CCF{0.0}; switch (End) { case 0: { - CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, (coupler.beta + othercoupler.beta) / 2.0, VirtualCoupling) / dt; + 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, (coupler.beta + othercoupler.beta) / 2.0, VirtualCoupling) / dt; + CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, loss, VirtualCoupling) / dt; break; } default: @@ -1219,66 +1375,61 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) if (Global.crash_damage) { - if (-coupler.Dist >= coupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (coupler.FmaxC + 1.0), p_coupldmg)) + // 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); } - if (coupler.CouplingFlag == coupling::faux || true == TestFlag(othervehicle->DamageFlag, dtrain_out)) - { // HACK: limit excessive speed derailment checks to vehicles which aren't part of the same consist - auto const safevelocitylimit{15.0}; - auto const velocitydifference{glm::length(glm::angleAxis(Rot.Rz, glm::dvec3{0, 1, 0}) * V - glm::angleAxis(othervehicle->Rot.Rz, glm::dvec3{0, 1, 0}) * othervehicle->V) * - 3.6}; // m/s -> km/h + // 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 > safevelocitylimit) + 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)) { - // 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"); - } + WriteLog("Bad driving: " + Name + " and " + othervehicle->Name + " collided with velocity " + to_string(velocitydifference, 0) + " km/h"); + } - if (velocitydifference > safevelocitylimit * (TotalMass / othervehicle->TotalMass)) - { - Derail(COLLISION); - } - if (velocitydifference > safevelocitylimit * (othervehicle->TotalMass / TotalMass)) - { - othervehicle->Derail(COLLISION); - } + if (velocitydifference > SafeCollisionVelocity * (TotalMass / othervehicle->TotalMass)) + { + Derail(COLLISION); + } + if (velocitydifference > SafeCollisionVelocity * (othervehicle->TotalMass / TotalMass)) + { + othervehicle->Derail(COLLISION); } } } - // adjust velocity and acceleration of affected vehicles + // adjust velocity and acceleration of affected vehicles. the physical model changes the velocities alone: the + // integration of the next step (ComputeMovement()) would carry a quarter of an acceleration spike over into the + // velocity once more, and the vehicles would bounce off the stop faster than they hit it + auto const accelerationspike{physical ? 0.0 : 1.0}; if (false == TestFlag(DamageFlag, dtrain_out)) { auto const accelerationchange{(velocity - V) / dt}; - // if( accelerationchange / AccS < 1.0 ) { - // HACK: prevent excessive vehicle pinball cases - AccS += accelerationchange; - // AccS = std::clamp( AccS, -2.0, 2.0 ); + AccS += accelerationchange * accelerationspike; V = velocity; - // } } if (false == TestFlag(othervehicle->DamageFlag, dtrain_out)) { - auto const othervehicleaccelerationchange{(othervehiclevelocity - othervehicle->V) / dt}; - // if( othervehicleaccelerationchange / othervehicle->AccS < 1.0 ) { - // HACK: prevent excessive vehicle pinball cases - othervehicle->AccS += othervehicleaccelerationchange; - othervehicle->V = othervehiclevelocity; - // } + 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 &coupler{Couplers[End]}; + auto &thiscoupler{Couplers[End]}; - if (coupler.type() == TCouplerType::Articulated) + if (thiscoupler.type() == TCouplerType::Articulated) { return; } // HACK: don't break articulated couplings no matter what @@ -1286,39 +1437,72 @@ void TMoverParameters::damage_coupler(int const End) if (SetFlag(DamageFlag, dtrain_coupling)) EventFlag = true; - if ((coupler.CouplingFlag & coupling::brakehose) == coupling::brakehose) + auto const hosetorn{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; + if (hosetorn) { // hamowanie nagle - zerwanie przewodow hamulcowych AlarmChainFlag = true; } - coupler.CouplingFlag = 0; + thiscoupler.CouplingFlag = 0; + thiscoupler.broken = true; - if (coupler.Connected != nullptr) + if (thiscoupler.Connected != nullptr) { - switch (End) + // 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)) { - // break connection with other vehicle, if there's any - case 0: - { - coupler.Connected->Couplers[end::rear].CouplingFlag = coupling::faux; - break; - } - case 1: - { - coupler.Connected->Couplers[end::front].CouplingFlag = coupling::faux; - break; - } - default: - { - break; - } + // the brake pipe of the other part of the train vents through the torn hose as well + thiscoupler.Connected->AlarmChainFlag = true; } } WriteLog("Bad driving: " + Name + " broke a coupler"); } +namespace +{ + +// the coupler as good as new, the vehicle without the coupler damage (and the emergency braking of the torn brake +// hose) once neither of its couplers is broken +void repair(TMoverParameters &Vehicle, TCoupling &Coupler) +{ + Coupler.broken = false; + Coupler.stretch_duration = 0.f; + Coupler.physics_state.couple(); + if (Vehicle.Couplers[end::front].broken || Vehicle.Couplers[end::rear].broken) + { + return; + } + ClearFlag(Vehicle.DamageFlag, dtrain_coupling); + // either vehicle of the pair may have been braking through the torn hose + Vehicle.AlarmChainFlag = false; +} + +} // namespace + +bool TMoverParameters::repair_coupler(int const End) +{ + auto &thiscoupler{Couplers[End]}; + if (false == thiscoupler.broken) + { + return false; + } + repair(*this, thiscoupler); + // the other half of the coupling, which may be the vehicle flagged with the damage + if (auto *other{thiscoupler.Connected}; other != nullptr && other->Couplers[thiscoupler.ConnectedNr].broken) + { + repair(*other, other->Couplers[thiscoupler.ConnectedNr]); + } + WriteLog(std::format("Coupler of {} repaired, at its {} end", Name, End == end::front ? "front" : "rear")); + return true; +} + void TMoverParameters::Derail(DerailReason const Reason) { if (SetFlag(DamageFlag, dtrain_out)) @@ -1347,16 +1531,16 @@ void TMoverParameters::Derail(DerailReason const Reason) ErrorLog("Bad dynamic: " + Name + " derailed due to wrong track type"); // błąd w scenerii else if (Reason == COLLISION) WriteLog("Bad driving: " + Name + " derailed"); // This reason also generates its own message in `TMoverParameters::CollisionDetect()` + else if (Reason == TRAILED_SWITCH) + ErrorLog("Bad driving: " + Name + " derailed trailing through a switch with a movable nose set the other way"); } } // ************************************************************************************************* // Oblicza przemieszczenie taboru // ************************************************************************************************* -double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam &Track, TTractionParam &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot) +double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot) { - const double Vepsilon = 1e-5; - const double Aepsilon = 1e-3; // ASBSpeed=0.8; if (!TestFlag(DamageFlag, dtrain_out)) { // Ra: to przepisywanie tu jest bez sensu @@ -1377,12 +1561,11 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap if (CategoryFlag == 4) OffsetTrackV = TotalMass / (Dim.L * Dim.W * 1000.0); - else if (TestFlag(CategoryFlag, 1) && TestFlag(RunningTrack.CategoryFlag, 1)) - if (TestFlag(DamageFlag, dtrain_out)) - { - OffsetTrackV = -0.2; - OffsetTrackH = Sign(RunningShape.R) * 0.2; - } + 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; @@ -1462,6 +1645,7 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap dL)}; DistCounter += fabs(dL) / 1000.0; + Odometer.run(dL); dL = 0; // koniec procedury, tu nastepuja dodatkowe procedury pomocnicze @@ -1477,9 +1661,8 @@ double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShap // Oblicza przemieszczenie taboru - uproszczona wersja // ************************************************************************************************* -double TMoverParameters::FastComputeMovement(double dt, const TTrackShape &Shape, TTrackParam &Track, TLocation const &NewLoc, TRotation const &NewRot) +double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Shape*/, TTrackParam & /*Track*/, TLocation const &NewLoc, TRotation const &NewRot) { - int b; // T_MoverParameters::FastComputeMovement(dt, Shape, Track, NewLoc, NewRot); Loc = NewLoc; @@ -1520,7 +1703,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape &Shape dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha // ale jesli jest kolizja (zas. zach. pedu) to... - for (b = 0; b < 2; b++) + for (int b = 0; b < 2; b++) if (Couplers[b].CheckCollision) CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! } // liczone dL, predkosc i przyspieszenie @@ -1529,6 +1712,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape &Shape dL)}; DistCounter += fabs(dL) / 1000.0; + Odometer.run(dL); dL = 0; // koniec procedury, tu nastepuja dodatkowe procedury pomocnicze @@ -1548,24 +1732,21 @@ void TMoverParameters::compute_movement_(double const Deltatime) RunInternalCommand(); // relay settings - if (EngineType == TEngineType::ElectricSeriesMotor) + // adjust motor overload relay threshold + if (EngineType == TEngineType::ElectricSeriesMotor && ImaxHi > ImaxLo) { - // adjust motor overload relay threshold - if (ImaxHi > ImaxLo) - { - if (MotorOverloadRelayHighThreshold) - { // set high threshold - if (TrainType != dt_ET42 ? RList[MainCtrlPos].Bn < 2 : MainCtrlPos == 0) - { - Imax = ImaxHi; - } + 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; - } + } + else + { // set low threshold + if (TrainType != dt_ET42 || MainCtrlPos == 0) + { + Imax = ImaxLo; } } } @@ -1573,10 +1754,9 @@ void TMoverParameters::compute_movement_(double const Deltatime) // Uproszczona symulacja wentylatorow rezystora hamowania // Prad oddawany na rezystor - double Irh = abs(eimv[eimv_Pe]) - abs(eimv[eimv_Ipoj]); // Wlacz wentylator jesli prad rekuperacji przekroczy maksymalny dla pasywnego chlodzenia rezystora - if (Irh > Imaxrpc && eimv[eimv_Ipoj] < 0) + if (double Irh = abs(eimv[eimv_Pe]) - abs(eimv[eimv_Ipoj]); Irh > Imaxrpc && eimv[eimv_Ipoj] < 0) { BRVtimer = 0; BRVentilators = true; @@ -1588,21 +1768,17 @@ void TMoverParameters::compute_movement_(double const Deltatime) 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) + if (EngineType == TEngineType::ElectricSeriesMotor && AutoRelayCheck()) { - if (AutoRelayCheck()) - { - SetFlag(SoundFlag, sound::relay); - } + SetFlag(SoundFlag, sound::relay); } - if (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) + if ((EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) && dizel_Update(Deltatime)) { - if (dizel_Update(Deltatime)) - { - SetFlag(SoundFlag, sound::relay); - } + SetFlag(SoundFlag, sound::relay); } // TODO: gather and move current calculations to dedicated method @@ -1624,7 +1800,7 @@ void TMoverParameters::compute_movement_(double const Deltatime) { Compressor = 0; CompressorFlag = false; - }; + } if (VeselVolume > 0.0) { // sprężarka musi mieć jakąś niezerową wydajność żeby rozważać jej załączenie i pracę @@ -1698,7 +1874,8 @@ void TMoverParameters::MainsCheck(double const Deltatime) break; } } - auto const maincircuitpowersupply{std::abs(localvoltage) > 0.1 || GetTrainsetHighVoltage() > 0.1}; + // 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) { @@ -1725,14 +1902,12 @@ void TMoverParameters::MainsCheck(double const Deltatime) } } -void TMoverParameters::LowVoltagePowerCheck(double const Deltatime) +void TMoverParameters::LowVoltagePowerCheck(double const /*Deltatime*/) { auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; - switch (EngineType) - { - case TEngineType::ElectricSeriesMotor: + if (EngineType == TEngineType::ElectricSeriesMotor) { GroundRelay &= lowvoltagepower; if (GroundRelayStart != start_t::manual) @@ -1741,17 +1916,16 @@ void TMoverParameters::LowVoltagePowerCheck(double const Deltatime) // TODO: generic check method which takes these into account GroundRelay |= lowvoltagepower; } - break; - } - default: - { - break; - } } } -void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const Coupling) +void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling const Coupling) { + if (Coupling != coupling::highvoltage && Coupling != coupling::power110v && Coupling != coupling::power24v) + { + // only power couplings carry voltage + return; + } auto localvoltage{0.0}; @@ -1780,7 +1954,7 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const case TPowerSource::Main: { // HACK: main circuit can be fed through couplers, so we explicitly check pantograph supply here - localvoltage = true == Mains ? PantographVoltage : 0.0; + localvoltage = MainCircuitPowered() ? PantographVoltage : 0.0; break; } default: @@ -1790,17 +1964,9 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const } } // high voltage power sources - switch (EnginePowerSource.SourceType) - { - case TPowerSource::CurrentCollector: + if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { localvoltage = std::max(localvoltage, PantographVoltage); - break; - } - default: - { - break; - } } break; } @@ -1840,9 +2006,9 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const for (auto side = 0; side < 2; ++side) { - auto &coupler{Couplers[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)]}; + auto &oppositecoupler{Couplers[side == end::front ? end::rear : end::front]}; bool oppositecouplingispresent; bool localpowerexportisenabled; @@ -1880,9 +2046,9 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const } } - auto const *coupling = Coupling == coupling::highvoltage ? &coupler.power_high : - Coupling == coupling::power110v ? &coupler.power_110v : - Coupling == coupling::power24v ? &coupler.power_24v : + auto const *coupling = Coupling == coupling::highvoltage ? &thiscoupler.power_high : + Coupling == coupling::power110v ? &thiscoupler.power_110v : + Coupling == coupling::power24v ? &thiscoupler.power_24v : nullptr; auto *oppositecoupling = Coupling == coupling::highvoltage ? &oppositecoupler.power_high : Coupling == coupling::power110v ? &oppositecoupler.power_110v : @@ -1894,9 +2060,9 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const oppositecoupling->is_live = false; oppositecoupling->is_local = localpowersource; // indicate power source // draw from external source - if (coupler.Connected != nullptr) + if (thiscoupler.Connected != nullptr) { - auto const &connectedcoupler{coupler.Connected->Couplers[coupler.ConnectedNr]}; + auto const &connectedcoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]}; auto const *connectedcoupling = Coupling == coupling::highvoltage ? &connectedcoupler.power_high : Coupling == coupling::power110v ? &connectedcoupler.power_110v : Coupling == coupling::power24v ? &connectedcoupler.power_24v : @@ -1919,17 +2085,17 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const { case coupling::highvoltage: { - couplervoltage = Couplers[end::front].power_high.voltage + Couplers[end::rear].power_high.voltage; + couplervoltage = static_cast(Couplers[end::front].power_high.voltage + Couplers[end::rear].power_high.voltage); break; } case coupling::power110v: { - couplervoltage = Couplers[end::front].power_110v.voltage + Couplers[end::rear].power_110v.voltage; + couplervoltage = static_cast(Couplers[end::front].power_110v.voltage + Couplers[end::rear].power_110v.voltage); break; } case coupling::power24v: { - couplervoltage = Couplers[end::front].power_24v.voltage + Couplers[end::rear].power_24v.voltage; + couplervoltage = static_cast(Couplers[end::front].power_24v.voltage + Couplers[end::rear].power_24v.voltage); break; } default: @@ -1943,23 +2109,21 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const Coupling == coupling::power24v ? &PowerCircuits[0].second : nullptr; - for (auto side = 0; side < 2; ++side) + for (auto &thiscoupler : Couplers) { - - auto &coupler{Couplers[side]}; - auto *coupling = Coupling == coupling::highvoltage ? &coupler.power_high : - Coupling == coupling::power110v ? &coupler.power_110v : - Coupling == coupling::power24v ? &coupler.power_24v : + auto *coupling = Coupling == coupling::highvoltage ? &thiscoupler.power_high : + Coupling == coupling::power110v ? &thiscoupler.power_110v : + Coupling == coupling::power24v ? &thiscoupler.power_24v : nullptr; coupling->current = 0.0; - if (coupler.Connected == nullptr) + if (thiscoupler.Connected == nullptr) { continue; } - auto const &connectedothercoupler{coupler.Connected->Couplers[(coupler.ConnectedNr == end::front ? end::rear : end::front)]}; + auto const &connectedothercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr == end::front ? end::rear : end::front]}; auto const *connectedothercoupling = Coupling == coupling::highvoltage ? &connectedothercoupler.power_high : Coupling == coupling::power110v ? &connectedothercoupler.power_110v : Coupling == coupling::power24v ? &connectedothercoupler.power_24v : @@ -1989,7 +2153,7 @@ void TMoverParameters::PowerCouplersCheck(double const Deltatime, coupling const } } -double TMoverParameters::ShowEngineRotation(int VehN) +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) @@ -1998,19 +2162,17 @@ double TMoverParameters::ShowEngineRotation(int VehN) return std::abs(enrot); case 2: for (b = 0; b <= 1; ++b) - if (TestFlag(Couplers[b].CouplingFlag, coupling::control)) - if (Couplers[b].Connected->Power > 0.01) - return fabs(Couplers[b].Connected->enrot); + 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)) - if (Couplers[b].Connected->Power > 0.01) - if (TestFlag(Couplers[b].Connected->Couplers[b].CouplingFlag, coupling::control)) - if (Couplers[b].Connected->Couplers[b].Connected->Power > 0.01) - return fabs(Couplers[b].Connected->Couplers[b].Connected->enrot); + 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; }; @@ -2049,7 +2211,7 @@ void TMoverParameters::ConverterCheck(double const Timestep) if (ConverterAllow && ConverterAllowLocal && false == ConvOvldFlag && false == PantPressLockActive // HACK: allow carriages to operate converter without (missing) fuse prerequisite - && (Power > 1.0 ? Mains : GetTrainsetHighVoltage() > 0.0)) + && (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) @@ -2075,14 +2237,12 @@ void TMoverParameters::ConverterCheck(double const Timestep) }; // heating system status check -void TMoverParameters::HeatingCheck(double const Timestep) +void TMoverParameters::HeatingCheck(double const /*Timestep*/) { // update heating devices // TBD, TODO: move this to a separate method? - switch (HeatingPowerSource.SourceType) - { - case TPowerSource::Generator: + if (HeatingPowerSource.SourceType == TPowerSource::Generator) { if (HeatingPowerSource.EngineGenerator.engine_revolutions != nullptr && HeatingPowerSource.EngineGenerator.revolutions_max > 0) { @@ -2101,12 +2261,6 @@ void TMoverParameters::HeatingCheck(double const Timestep) std::clamp((absrevolutions - generator.revolutions_min) / (generator.revolutions_max - generator.revolutions_min), 0.0, 1.0))) * sign(generator.revolutions); } - break; - } - default: - { - break; - } } // quick check first to avoid unnecessary calls... @@ -2143,7 +2297,7 @@ void TMoverParameters::HeatingCheck(double const Timestep) } case TPowerSource::Main: { - voltage = true == Mains ? std::max(GetTrainsetHighVoltage(), PantographVoltage) : 0.0; + voltage = MainCircuitPowered() ? std::max(GetTrainsetHighVoltage(), PantographVoltage) : 0.0; break; } default: @@ -2161,7 +2315,7 @@ void TMoverParameters::HeatingCheck(double const Timestep) } // water pump status check -void TMoverParameters::WaterPumpCheck(double const Timestep) +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 && @@ -2169,7 +2323,7 @@ void TMoverParameters::WaterPumpCheck(double const Timestep) } // water heater status check -void TMoverParameters::WaterHeaterCheck(double const Timestep) +void TMoverParameters::WaterHeaterCheck(double const /*Timestep*/) { WaterHeater.is_active = false == WaterHeater.is_damaged && true == (Power24vIsAvailable || Power110vIsAvailable) && true == WaterHeater.is_enabled && true == WaterHeater.breaker && @@ -2184,13 +2338,14 @@ void TMoverParameters::WaterHeaterCheck(double const Timestep) } // fuel pump status update -void TMoverParameters::FuelPumpCheck(double const Timestep) +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 == start_t::manual ? FuelPump.is_enabled : - FuelPump.start_type == start_t::automatic ? dizel_startup || Mains : - FuelPump.start_type == start_t::manualwithautofallback ? FuelPump.is_enabled || dizel_startup || Mains : + (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 } @@ -2213,11 +2368,11 @@ void TMoverParameters::OilPumpCheck(double const Timestep) 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, OilPump.pressure + (enrot > 5.0 ? 0.05 : 0.035) * Timestep); + 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, OilPump.pressure - (enrot > 5.0 ? 0.05 : 0.035) * 0.5 * Timestep); + 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); } @@ -2234,7 +2389,7 @@ void TMoverParameters::MotorBlowersCheck(double const Timestep) { if (stop) { - blower.stop_timer += Timestep; + blower.stop_timer += static_cast(Timestep); if (blower.stop_timer > blower.sustain_time) { disable = true; @@ -2251,9 +2406,7 @@ void TMoverParameters::MotorBlowersCheck(double const Timestep) } blower.is_active = // TODO: bind properly power source when ld is in place - (blower.start_type == start_t::battery ? Power24vIsAvailable : - blower.start_type == start_t::converter ? Power110vIsAvailable : - Mains) // power source + MotorBlowerPowerIsAvailable(blower) // power source // breaker condition disabled until it's implemented in the class data // && ( true == blower.breaker ) && false == disable && @@ -2274,23 +2427,37 @@ void TMoverParameters::MotorBlowersCheck(double const Timestep) 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 += std::clamp(revolutionstarget - fan.revolutions, speedincreasecap * -2, speedincreasecap) * Timestep; + fan.revolutions += static_cast(std::clamp(revolutionstarget - fan.revolutions, speedincreasecap * -2, speedincreasecap) * Timestep); } else { - fan.revolutions *= std::max(0.0, 1.0 - Timestep); + fan.revolutions *= static_cast(std::max(0.0, 1.0 - Timestep)); } } } -void TMoverParameters::PantographsCheck(double const 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 &valve{PantsValve}; + auto const &valve{PantsValve}; auto const lowvoltagepower{valve.solenoid ? Power24vIsAvailable || Power110vIsAvailable : true}; - auto const autostart{valve.start_type == start_t::automatic || valve.start_type == start_t::manualwithautofallback}; - auto const manualcontrol{valve.start_type == start_t::manual || valve.start_type == start_t::manualwithautofallback}; + 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 @@ -2305,13 +2472,14 @@ void TMoverParameters::PantographsCheck(double const Timestep) auto &valve{pantograph.valve}; auto const lowvoltagepower{valve.solenoid ? Power24vIsAvailable || Power110vIsAvailable : true}; - auto const autostart{valve.start_type == start_t::automatic || valve.start_type == start_t::manualwithautofallback}; - auto const manualcontrol{valve.start_type == start_t::manual || valve.start_type == start_t::manualwithautofallback}; + 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) && - (valve.is_active || (manualcontrol && lowvoltagepower && valve.is_enabled) || (autostart && lowvoltagepower)); // shouldn't ever get this far but, eh + (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}; @@ -2321,7 +2489,7 @@ void TMoverParameters::PantographsCheck(double const Timestep) } } -void TMoverParameters::LightsCheck(double const Timestep) +void TMoverParameters::LightsCheck(double const /*Timestep*/) { auto &light{CompartmentLights}; @@ -2403,16 +2571,14 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) if (CtrlSpeed > 1) { OK = IncMainCtrl(1) && IncMainCtrl(CtrlSpeed - 1); // a fail will propagate up the recursion chain. should this be || instead? + break; } - else + ++MainCtrlPos; + OK = true; + if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos) { - ++MainCtrlPos; - OK = true; - if (EIMCtrlType == 0 && SpeedCtrlAutoTurnOffFlag & 1 == 1 && MainCtrlActualPos != MainCtrlPos) - { - DecScndCtrl(2); - SpeedCtrlUnit.IsActive = false; - } + DecScndCtrl(2); + SpeedCtrlUnit.IsActive = false; } break; } @@ -2434,7 +2600,6 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) 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 @@ -2446,21 +2611,18 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) { // CtrlSpeed == 1 ++MainCtrlPos; OK = true; - if (Imax == ImaxHi) + if (Imax == ImaxHi && RList[MainCtrlPos].Bn > 1) { - if (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) { - /* 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; - } + --MainCtrlPos; + OK = false; } } // @@ -2473,13 +2635,10 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) //} } - if (TrainType == dt_ET42 && true == DynamicBrakeFlag) + if (TrainType == dt_ET42 && true == DynamicBrakeFlag && MainCtrlPos > 20) { - if (MainCtrlPos > 20) - { - MainCtrlPos = 20; - OK = false; - } + MainCtrlPos = 20; + OK = false; } break; } @@ -2490,7 +2649,7 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) { while (MainCtrlPos < MainCtrlPosNo && IncMainCtrl(1)) { - ; + // all work is done in the loop header } } else @@ -2507,6 +2666,8 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) OK = AddPulseForce(CtrlSpeed); break; } + default: + break; } // switch EngineType of } else @@ -2528,7 +2689,8 @@ bool TMoverParameters::IncMainCtrl(int CtrlSpeed) if (true == OK) { - SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); //??? + ScndCtrlResistiveLockCheck(); // e.g. from the last series position on to the resistive parallel ones + SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); } @@ -2591,7 +2753,7 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) { MainCtrlPos--; OK = true; - if (EIMCtrlType == 0 && SpeedCtrlAutoTurnOffFlag & 1 == 1 && MainCtrlActualPos != MainCtrlPos) + if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos) { DecScndCtrl(2); SpeedCtrlUnit.IsActive = false; @@ -2641,6 +2803,8 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) } break; } + default: + break; } // switch EngineType } } @@ -2651,7 +2815,8 @@ bool TMoverParameters::DecMainCtrl(int CtrlSpeed) if (OK) { - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); // hmmmm...???!!! + ScndCtrlResistiveLockCheck(); // the shunt drops when the master controller leaves a resistance-free position + /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); // hmmmm...???!!! /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); } } @@ -2699,7 +2864,7 @@ int TMoverParameters::MainCtrlNoPowerPos() const } case 2: { - return 3; + return 3 + EIMCtrlEmergencyPositions(); } case 3: { @@ -2724,6 +2889,27 @@ 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 @@ -2740,7 +2926,7 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed) { // if (RList[MainCtrlPos].R=0) and (MainCtrlPos>0) and (ScndCtrlPos CtrlDelay) - LastRelayTime = 0; + if (OK && LastRelayTime > CtrlDelay) + LastRelayTime = 0; if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1 && MainCtrlPos > 0) { SpeedCtrlValue = Vel; - if (EIMCtrlType == 0 && SpeedCtrlAutoTurnOffFlag & 1 == 1) + if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1) { MainCtrlActualPos = MainCtrlPos; } @@ -2790,7 +2975,7 @@ bool TMoverParameters::IncScndCtrl(int CtrlSpeed) if (OK && SpeedCtrl && ScndCtrlPos == 1 && EngineType == TEngineType::DieselEngine) { // NOTE: round() already adds 0.5, are the ones added here as well correct? - SpeedCtrlValue = Round(Vel); + SpeedCtrlValue = static_cast(Round(Vel)); SpeedCtrlUnit.IsActive = true; } @@ -2812,7 +2997,7 @@ bool TMoverParameters::DecScndCtrl(int CtrlSpeed) } else if (ScndCtrlPosNo > 0 && CabActive != 0) { - if (ScndCtrlPos > 0 && !CoupledCtrl && (EngineType != TEngineType::DieselElectric || !AutoRelayFlag)) + if (ScndCtrlPos > 0 && !CoupledCtrl && (EngineType != TEngineType::DieselElectric || !AutoRelayFlag) && !IsScndCtrlLockedByMainCtrl()) { if (CtrlSpeed == 1) { @@ -2828,7 +3013,7 @@ bool TMoverParameters::DecScndCtrl(int CtrlSpeed) OK = false; if (OK) { - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPos, CabActive); //??? + /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); } } @@ -2836,9 +3021,8 @@ bool TMoverParameters::DecScndCtrl(int CtrlSpeed) OK = false; // if OK then LastRelayTime:=0; // hunter-101012: poprawka - if (OK) - if (LastRelayTime > CtrlDownDelay) - LastRelayTime = 0; + if (OK && LastRelayTime > CtrlDownDelay) + LastRelayTime = 0; if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1) { @@ -2863,13 +3047,26 @@ bool TMoverParameters::DecScndCtrl(int CtrlSpeed) return OK; } -int TMoverParameters::GetVirtualScndPos() +bool TMoverParameters::IsScndCtrlLockedByMainCtrl() const { - if (TrainType == dt_ET42) + // 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()) { - if (DynamicBrakeFlag && !ScndCtrlPos) - return -1; + ScndCtrlPos = 0; } +} + +int TMoverParameters::GetVirtualScndPos() const +{ + if (TrainType == dt_ET42 && DynamicBrakeFlag && !ScndCtrlPos) + return -1; return ScndCtrlPos; } @@ -2901,7 +3098,7 @@ bool TMoverParameters::CabActivisation(bool const Enforce) CabMaster = true; SecuritySystem.set_enabled(true); // activate the alerter TODO: make it part of control based cab selection SendCtrlToNext("CabActivisation", 1, CabActive); - SendCtrlToNext("Direction", DirAbsolute, CabActive); + SendCtrlToNext("Direction", DirActive, CabActive); if (InactiveCabFlag & activation::springbrakeoff) { SpringBrakeActivate(false); @@ -3029,8 +3226,7 @@ bool TMoverParameters::SandboxManual(bool const State, range_t const Notify) bool TMoverParameters::SandboxAuto(bool const State, range_t const Notify) { bool result{false}; - bool NewState = State && SandDoseAutoAllow; - if (SandDoseAuto != NewState) + if (bool NewState = State && SandDoseAutoAllow; SandDoseAuto != NewState) { if (SandDoseAuto == false) { @@ -3138,9 +3334,11 @@ void TMoverParameters::SecuritySystemReset(void) // zbijanie czuwaka/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) + if (!Battery || !Radio || !RadioFuse) { // wyłączenie baterii deaktywuje sprzęt RadiostopSwitch(false); } @@ -3152,6 +3350,7 @@ void TMoverParameters::SecuritySystemCheck(double dt) // ************************************************************************************************* bool TMoverParameters::BatterySwitch(bool State, range_t const Notify) { + using enum range_t; auto const initialstate{Battery}; // Ra: ukrotnienie załączania baterii jest jakąś fikcją... @@ -3161,10 +3360,10 @@ bool TMoverParameters::BatterySwitch(bool State, range_t const Notify) } // switching batteries does not require activation - if (Notify != range_t::local) + if (Notify != local) { - SendCtrlToNext("BatterySwitch", State ? 1 : 0, 1, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - SendCtrlToNext("BatterySwitch", State ? 1 : 0, -1, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); + 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; @@ -3247,11 +3446,10 @@ bool TMoverParameters::DirectionBackward(void) return false; } - if (DirActive == 1 && MainCtrlPos == 0 && TrainType == dt_EZT && EngineType != TEngineType::ElectricInductionMotor) - if (MinCurrentSwitch(false)) - { - return true; - } + 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) @@ -3659,6 +3857,7 @@ void TMoverParameters::MainSwitch_(bool const State) 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 @@ -3666,18 +3865,19 @@ bool TMoverParameters::MainSwitchCheck() const switch (EngineType) { - case TEngineType::DieselElectric: - case TEngineType::DieselEngine: - case TEngineType::Dumb: + case DieselElectric: + case DieselEngine: + case Dumb: { powerisavailable = Power24vIsAvailable; break; } - case TEngineType::ElectricSeriesMotor: - case TEngineType::ElectricInductionMotor: + case ElectricSeriesMotor: + case ElectricInductionMotor: { // TODO: check whether we can simplify this check and skip the outer EngineType switch - powerisavailable = EnginePowerSourceVoltage() > 0.5 * EnginePowerSource.MaxVoltage; + // 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: @@ -3686,8 +3886,9 @@ bool TMoverParameters::MainSwitchCheck() const } } - return powerisavailable && (ScndCtrlPos == 0 || EngineType == TEngineType::ElectricInductionMotor) && MainsInitTimeCountdown <= 0.0 && - (ConvOvldFlag == false || ConverterOverloadRelayOffWhenMainIsOff) && true == GroundRelay && true == NoVoltRelay && true == OvervoltageRelay && LastSwitchingTime > CtrlDelay && + 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) && @@ -3792,6 +3993,25 @@ double TMoverParameters::EnginePowerSourceVoltage() const 0.0; } +// whether the main circuit feeds what runs on it: the converter, a compressor, the heating, the motor and resistor +// blowers, the traction motors +bool TMoverParameters::MainCircuitPowered() const +{ + if (false == Mains) + { + return false; + } + if (false == PantographsRequireMains || EnginePowerSource.SourceType != TPowerSource::CurrentCollector) + { + // the closed line breaker says it all: the undervoltage trip opens it without traction voltage, and an engine + // which runs is its own supply + return true; + } + // closed ahead of the pantographs the line breaker holds without the voltage, which the undervoltage trip isn't + // there to vouch for + return EnginePowerSourceVoltage() >= EnginePowerSource.CollectorParameters.MinV; +} + // ************************************************************************************************* // Q: 20160711 // zwiększenie nastawy hamulca @@ -3944,8 +4164,7 @@ double TMoverParameters::DynamicBrakeRatio(void) const bool TMoverParameters::DynamicBrakeAvailable(void) const { double const vh0{eimc[eimc_p_Vh0]}; - double const vh1{eimc[eimc_p_Vh1]}; - if (vh1 <= 0.001) + if (double const vh1{eimc[eimc_p_Vh1]}; vh1 <= 0.001) { // brak zdefiniowanej strefy - ED dziala zawsze return true; @@ -4009,10 +4228,10 @@ bool TMoverParameters::DynamicBrakeSwitch(bool Switch) { DynamicBrakeFlag = Switch; DBS = true; - for (int b = 0; b < 2; b++) + for (auto &thiscoupler : Couplers) // with Couplers[b] do - if (TestFlag(Couplers[b].CouplingFlag, coupling::control)) - Couplers[b].Connected->DynamicBrakeFlag = Switch; + if (TestFlag(thiscoupler.CouplingFlag, coupling::control)) + thiscoupler.Connected->DynamicBrakeFlag = Switch; // end; // if (DynamicBrakeType=dbrake_passive) and (TrainType=dt_ET42) then // begin @@ -4156,7 +4375,8 @@ bool TMoverParameters::SwitchEPBrake(int state) OK = false; if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0) { - if (state > 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; @@ -4168,6 +4388,11 @@ bool TMoverParameters::SwitchEPBrake(int state) return OK; } +bool TMoverParameters::EPBrakeControlPowered() const +{ + return Power24vIsAvailable && DirActive != 0 && EpFuse; +} + // ************************************************************************************************* // Q: 20160711 // zwiększenie ciśnienia hamowania @@ -4342,7 +4567,7 @@ void TMoverParameters::CompressorCheck(double dt) EmergencyValveOpen = Compressor > (EmergencyValveOpen ? EmergencyValveOff : EmergencyValveOn); if (EmergencyValveOpen) { - float dV = PF(0, Compressor, EmergencyValveArea) * dt; + auto dV = static_cast(PF(0, Compressor, EmergencyValveArea) * dt); CompressedVolume -= dV; } @@ -4354,9 +4579,8 @@ void TMoverParameters::CompressorCheck(double dt) 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}; - auto const AllowFactor{CompressorList[TCompressorList::cl_Allow][CompressorListPos]}; // checking the impact on the compressor allowance - if (AllowFactor > 0.5) + if (auto const AllowFactor{CompressorList[TCompressorList::cl_Allow][CompressorListPos]}; AllowFactor > 0.5) { CompressorAllow = AllowFactor > 1.5; } @@ -4380,7 +4604,10 @@ void TMoverParameters::CompressorCheck(double dt) } } - auto const compressorpower{(CompressorPower == 0 ? Mains : CompressorPower == 3 ? Mains : Power110vIsAvailable)}; + // 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}; @@ -4402,7 +4629,7 @@ void TMoverParameters::CompressorCheck(double dt) auto const compressorflag{CompressorFlag}; CompressorFlag = - compressorpower && false == compressordisable && (false == governorlock || CompressorPower == 3) && (CompressorFlag || (compressorenable && LastSwitchingTime > CtrlDelay)); + compressorready && false == compressordisable && (false == governorlock || CompressorPower == 3) && (CompressorFlag || (compressorenable && LastSwitchingTime > CtrlDelay)); if (CompressorFlag && CompressorFlag != compressorflag) { @@ -4416,56 +4643,39 @@ void TMoverParameters::CompressorCheck(double dt) } // working compressor adds air to the air reservoir - switch (CompressorPower) - { - case 3: + 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 - break; } - default: + else { // the compressor is a stand-alone device, working at steady pace CompressedVolume += CompressorSpeedF * (2.0 * MaxCompressorF - Compressor) / MaxCompressorF * dt; - break; - } } 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); - CompressedVolume *= false == governorlockispresent ? 0.80 : // arbitrary amount - CompressorTankValve ? MinCompressorF / MaxCompressorF : // drop to mincompressor level - 0.999; // HACK: drop a tiny bit so the sound doesn't trigger repeatedly + 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; } } - // tymczasowo tylko obciążenie sprężarki, tak z 5A na sprężarkę - // TODO: draw power from proper high- or low voltage circuit - switch (CompressorPower) - { - case 3: - { - // diesel-powered compressor doesn't draw power - break; - } - default: - { - // TODO: drain power from 110v circuit - /* - if( compressorowner != nullptr ) { - compressorowner->TotalCurrent += 0.0015 * compressorowner->PantographVoltage; - } - */ - break; - } - } + // a compressor not driven by the engine doesn't draw power (some 5 A) from the high- or low voltage circuit yet } // ************************************************************************************************* @@ -4480,8 +4690,6 @@ void TMoverParameters::UpdatePipePressure(double dt) Pipe->Act(); } - const double LBDelay = 100; - const double kL = 0.5; // double dV; // TMoverParameters *c; // T_MoverParameters double temp; @@ -4572,6 +4780,7 @@ void TMoverParameters::UpdatePipePressure(double dt) } if (dpMainValve < 0) // && (PipePressureVal > 0.01) //50 + { if (Compressor > ScndPipePress) { CompressedVolume = CompressedVolume + dpMainValve / 1500.0; @@ -4579,21 +4788,19 @@ void TMoverParameters::UpdatePipePressure(double dt) } else Pipe2->Flow(dpMainValve); + } } // ulepszony hamulec bezp. EmergencyValveFlow = 0.0; - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; - if (true == RadioStopFlag || true == AlarmChainFlag || (true == EIMCtrlEmergency && LocalBrakePosA >= 1.0) || SecuritySystem.is_braking() || - (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) - /* - // NOTE: disabled because 32 is 'load destroyed' flag, what does this have to do with emergency brake? - // (if it's supposed to be broken coupler, such event sets alarmchainflag instead when appropriate) - || ( true == TestFlag( EngDmgFlag, 32 ) ) - */ - || (0 == CabActive && InactiveCabFlag & activation::emergencybrake) || (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive)) + // EngDmgFlag 32 (load destroyed) used to trigger this too; dropped, it has nothing to do with + // the emergency brake (a broken coupler sets AlarmChainFlag instead). the Elf's emergency brake position + // vents the pipe only from the vehicle driven from, whatever the controllers of the others show + if (RadioStopFlag || AlarmChainFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || + (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) || + (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)) { EmergencyValveFlow = PF(0, PipePress, 0.15) * dt; } @@ -4640,11 +4847,11 @@ void TMoverParameters::UpdatePipePressure(double dt) { LocBrakePress = LocHandle->GetCP(); - for (int b = 0; b < 2; b++) - if ((TrainType & (dt_ET41 | dt_ET42)) != 0 && Couplers[b].Connected != nullptr) // nie podoba mi się to rozwiązanie, chyba trzeba - // dodać jakiś wpis do fizyki na to - if ((Couplers[b].Connected->TrainType & (dt_ET41 | dt_ET42)) != 0 && (Couplers[b].CouplingFlag & 36) == 36) - LocBrakePress = std::max(Couplers[b].Connected->LocHandle->GetCP(), LocBrakePress); + 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)) //{ @@ -4657,10 +4864,12 @@ void TMoverParameters::UpdatePipePressure(double dt) //(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; } @@ -4718,7 +4927,7 @@ void TMoverParameters::UpdatePipePressure(double dt) if ((BrakeHandle == TBrakeHandle::FVel6 || BrakeHandle == TBrakeHandle::FVE408) && CabOccupied != 0) { - if (Power24vIsAvailable && DirActive != 0 && EpFuse) // tu powinien byc jeszcze bezpiecznik EP i baterie - + if (EPBrakeControlPowered()) // tu powinien byc jeszcze bezpiecznik EP i baterie - // temp = (Handle as TFVel6).GetCP EpForce = Handle->GetEP(); else @@ -4732,11 +4941,16 @@ void TMoverParameters::UpdatePipePressure(double dt) if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) temp1 = 0; Hamulec->SetEPS(temp1); - TUHEX_StageActual = EpForce; + TUHEX_StageActual = static_cast(EpForce); TUHEX_Active = TUHEX_StageActual > 0; // Ra 2014-11: na tym się wysypuje, ale nie wiem, w jakich warunkach SendCtrlToNext("Brake", EpForce, CabActive); } + else if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0 && std::abs(EpForce) > 0.001 && !EPBrakeControlPowered()) + { + // the EP brake switched on with the button drops out with the control's supply + SwitchEPBrake(0); + } Pipe->Act(); PipePress = Pipe->P(); @@ -4782,7 +4996,9 @@ void TMoverParameters::UpdateScndPipePressure(double dt) const double Spz = 0.5067; TMoverParameters *c; - double dv1, dv2, dV; + double dv1; + double dv2; + double dV; UpdateSpringBrake(dt); @@ -4790,32 +5006,29 @@ void TMoverParameters::UpdateScndPipePressure(double dt) dv2 = 0; // sprzeg 1 - if (Couplers[0].Connected != nullptr) - if (TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) - { - c = Couplers[0].Connected; // skrot - dv1 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); - if (dv1 * dv1 > 0.00000000000001) - c->switch_physics(true); - c->Pipe2->Flow(-dv1); - } + if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) + { + c = Couplers[0].Connected; // skrot + dv1 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); + if (dv1 * dv1 > 0.00000000000001) + c->switch_physics(true); + c->Pipe2->Flow(-dv1); + } // sprzeg 2 - if (Couplers[1].Connected != nullptr) - if (TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); - if (dv2 * dv2 > 0.00000000000001) - c->switch_physics(true); - c->Pipe2->Flow(-dv2); - } - if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr) - if (TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic) && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); - Couplers[0].Connected->Pipe2->Flow(+dV); - Couplers[1].Connected->Pipe2->Flow(-dV); - } + if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + { + c = Couplers[1].Connected; // skrot + dv2 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); + if (dv2 * dv2 > 0.00000000000001) + c->switch_physics(true); + c->Pipe2->Flow(-dv2); + } + if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic) && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) + { + dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); + Couplers[0].Connected->Pipe2->Flow(+dV); + Couplers[1].Connected->Pipe2->Flow(-dV); + } Pipe2->Flow(Hamulec->GetHPFlow(ScndPipePress, dt)); // NOTE: condition disabled to allow the air flow from the main hose to the main tank as well @@ -4841,7 +5054,7 @@ void TMoverParameters::UpdateScndPipePressure(double dt) // yB: 20190906 // Aktualizacja ciśnienia w hamulcu sprezynowym // ************************************************************************************************* -void TMoverParameters::UpdateSpringBrake(double dt) +void TMoverParameters::UpdateSpringBrake(double /*dt*/) { double BP = SpringBrake.PNBrakeConnection ? BrakePress : 0; double MSP = SpringBrake.ShuttOff ? 0 : SpringBrake.MaxSetPressure; @@ -4875,30 +5088,29 @@ double TMoverParameters::GetDVc(double dt) { // T_MoverParameters *c; TMoverParameters *c; - double dv1, dv2; // , dV; + double dv1; + double dv2; // , dV; dv1 = 0; dv2 = 0; // sprzeg 1 - if (Couplers[0].Connected != nullptr) - if (TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) - { //*0.85 - c = Couplers[0].Connected; // skrot //0.08 //e/D * L/D = e/D^2 * L - dv1 = 0.5 * dt * PF(PipePress, c->PipePress, Spg / (1.0 + 0.015 / Spg * Dim.L)); - if (dv1 * dv1 > 0.00000000000001) - c->switch_physics(true); - c->Pipe->Flow(-dv1); - } + if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) + { //*0.85 + c = Couplers[0].Connected; // skrot //0.08 //e/D * L/D = e/D^2 * L + dv1 = 0.5 * dt * PF(PipePress, c->PipePress, Spg / (1.0 + 0.015 / Spg * Dim.L)); + if (dv1 * dv1 > 0.00000000000001) + c->switch_physics(true); + c->Pipe->Flow(-dv1); + } // sprzeg 2 - if (Couplers[1].Connected != nullptr) - if (TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic)) - { - c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(PipePress, c->PipePress, Spg / (1.0 + 0.015 / Spg * Dim.L)); - if (dv2 * dv2 > 0.00000000000001) - c->switch_physics(true); - c->Pipe->Flow(-dv2); - } + if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic)) + { + c = Couplers[1].Connected; // skrot + dv2 = 0.5 * dt * PF(PipePress, c->PipePress, Spg / (1.0 + 0.015 / Spg * Dim.L)); + if (dv2 * dv2 > 0.00000000000001) + c->switch_physics(true); + c->Pipe->Flow(-dv2); + } // if ((Couplers[1].Connected != NULL) && (Couplers[0].Connected != NULL)) // if ((TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) && // (TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic))) @@ -4919,11 +5131,13 @@ double TMoverParameters::GetDVc(double dt) // ************************************************************************************************* void TMoverParameters::ComputeConstans(void) { - double BearingF, RollF, HideModifier; + 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; + BearingF = (DamageFlag & dtrain_bearing) != 0 ? 2.0 : 0; HideModifier = 0; // int(Couplers[0].CouplingFlag>0)+int(Couplers[1].CouplingFlag>0); @@ -4948,7 +5162,7 @@ void TMoverParameters::ComputeConstans(void) // 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 const *previousvehicle{Couplers[V >= 0.0 ? end::front : end::rear].Connected}; auto dragarea{Dim.W * Dim.H}; if (previousvehicle) { @@ -5068,7 +5282,7 @@ void TMoverParameters::ComputeTotalForce(double dt) } else { - EngineVoltage *= DirAbsolute; // DirActive*CabActive; + EngineVoltage *= DirAbsolute; // the reverser of the active cab, relative to the couplers } } // bo nie dzialalo else @@ -5092,6 +5306,14 @@ void TMoverParameters::ComputeTotalForce(double dt) { 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) { @@ -5148,9 +5370,10 @@ void TMoverParameters::ComputeTotalForce(double dt) FTotal = FTrain - Sign(V) * FStand; } -double TMoverParameters::BrakeForceR(double ratio, double velocity) +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)); @@ -5166,8 +5389,8 @@ double TMoverParameters::BrakeForceR(double ratio, double velocity) 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 && velocity < 40) - ratio = ratio / 2; + 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; @@ -5177,7 +5400,7 @@ double TMoverParameters::BrakeForceR(double ratio, double velocity) return BrakeForceP(press * ratio, velocity); } -double TMoverParameters::BrakeForceP(double press, double velocity) +double TMoverParameters::BrakeForceP(double press, double velocity) const { double BFP = 0; double K = ((press * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj) * BrakeRigEff; @@ -5190,10 +5413,11 @@ double TMoverParameters::BrakeForceP(double press, double velocity) // Q: 20160713 // oblicza siłę na styku koła i szyny // ************************************************************************************************* -double TMoverParameters::BrakeForce(TTrackParam const &Track) +double TMoverParameters::BrakeForce(TTrackParam const & /*Track*/) { - double K{0}, Fb{0}, sm{0}; + double K{0}; + double brakeforce{0}; switch (LocalBrake) { @@ -5250,11 +5474,11 @@ double TMoverParameters::BrakeForce(TTrackParam const &Track) // 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 - Fb = UnitBrakeForce * NBrakeAxles * std::max(1, NBpA); + brakeforce = UnitBrakeForce * NBrakeAxles * std::max(1, NBpA); // u:=((BrakePress*P2FTrans)-BrakeCylSpring*BrakeCylMult[BCMFlag]/BrakeCylNo-0.83*BrakeSlckAdj/(BrakeCylNo))*BrakeCylNo; // { end; } - return Fb; + return brakeforce; } // ************************************************************************************************* @@ -5333,8 +5557,12 @@ double TMoverParameters::Adhesive(double staticfriction) const // ************************************************************************************************* double TMoverParameters::CouplerForce(int const End, double dt) { + if (coupler_physics_at(End)) + { + return coupler_force_physical(End, dt); + } - auto &coupler{Couplers[End]}; + auto &thiscoupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; auto const otherend{Neighbours[End].vehicle_end}; auto &othercoupler{othervehicle->Couplers[otherend]}; @@ -5345,85 +5573,85 @@ double TMoverParameters::CouplerForce(int const End, double dt) auto const newdistance{initialdistance + 10.0 * distancedelta}; - auto const dV{V - othervehicle->V * DirPatch(End, otherend)}; + auto const dV{CouplerVelocityDifference(End, *othervehicle, otherend)}; auto const absdV{std::abs(dV)}; // potentially generate sounds on clash or stretch - if (newdistance < 0.0 && coupler.Dist > newdistance && dV < -0.1 && false == coupler.has_adapter()) + 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(coupler.sounds, absdV > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash); + SetFlag(thiscoupler.sounds, absdV > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash); } - else if (coupler.CouplingFlag != coupling::faux && newdistance > 0.001 && coupler.Dist <= 0.001 && absdV > 0.005 && Vel > 1.0) + else if (thiscoupler.CouplingFlag != coupling::faux && newdistance > 0.001 && thiscoupler.Dist <= 0.001 && absdV > 0.005 && Vel > 1.0) { // 090503: dzwieki pracy sprzegu - SetFlag(coupler.sounds, absdV > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch); + SetFlag(thiscoupler.sounds, absdV > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch); } - coupler.CheckCollision = false; - coupler.Dist = 0.0; + thiscoupler.CheckCollision = false; + thiscoupler.Dist = 0.0; double CF{0.0}; - if (coupler.CouplingFlag == coupling::faux && initialdistance > 0.05) + if (thiscoupler.CouplingFlag == coupling::faux && initialdistance > 0.05) { // arbitrary distance // potentially reset auto coupling lock - coupler.AutomaticCouplingAllowed = true; + thiscoupler.AutomaticCouplingAllowed = true; } - if (coupler.CouplingFlag != coupling::faux || initialdistance < 0) + if (thiscoupler.CouplingFlag != coupling::faux || initialdistance < 0) { - coupler.Dist = std::clamp(newdistance, coupler.has_adapter() ? 0 : -coupler.DmaxB, coupler.DmaxC); + thiscoupler.Dist = std::clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); double BetaAvg = 0; double Fmax = 0; - if (coupler.CouplingFlag == coupling::faux) + if (thiscoupler.CouplingFlag == coupling::faux) { - BetaAvg = coupler.beta; - Fmax = (coupler.FmaxC + coupler.FmaxB) * CouplerTune; + BetaAvg = thiscoupler.beta; + Fmax = (thiscoupler.FmaxC + thiscoupler.FmaxB) * CouplerTune; } else { // usrednij bo wspolny sprzeg - BetaAvg = 0.5 * (coupler.beta + othercoupler.beta); - Fmax = 0.5 * (coupler.FmaxC + coupler.FmaxB + othercoupler.FmaxC + othercoupler.FmaxB) * CouplerTune; + 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(coupler.Dist)}; // McZapkie-191103: poprawka na histereze + auto const distDelta{std::abs(newdistance) - std::abs(thiscoupler.Dist)}; // McZapkie-191103: poprawka na histereze if (newdistance > 0) { if (distDelta > 0) { - CF = -(coupler.SpringKC + othercoupler.SpringKC) * coupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; + CF = -(thiscoupler.SpringKC + othercoupler.SpringKC) * thiscoupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; } else { - CF = -(coupler.SpringKC + othercoupler.SpringKC) * coupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; + CF = -(thiscoupler.SpringKC + othercoupler.SpringKC) * thiscoupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; } // liczenie sily ze sprezystosci sprzegu - if (newdistance > coupler.DmaxC + othercoupler.DmaxC) + if (newdistance > thiscoupler.DmaxC + othercoupler.DmaxC) { // zderzenie - coupler.CheckCollision = true; + thiscoupler.CheckCollision = true; } - if (std::abs(CF) > coupler.FmaxC) + if (std::abs(CF) > thiscoupler.FmaxC) { // coupler is stretched with excessive force, may break - coupler.stretch_duration += dt; + 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 && coupler.stretch_duration > 1.f && Random() < coupler.stretch_duration * 0.1f * dt) + if (Global.crash_damage && thiscoupler.stretch_duration > 1.f && Random() < thiscoupler.stretch_duration * 0.1f * dt) { damage_coupler(End); } } else { - coupler.stretch_duration = 0.f; + thiscoupler.stretch_duration = 0.f; } } if (newdistance < 0) @@ -5431,67 +5659,214 @@ double TMoverParameters::CouplerForce(int const End, double dt) if (distDelta > 0) { - CF = -(coupler.SpringKB + othercoupler.SpringKB) * coupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; + CF = -(thiscoupler.SpringKB + othercoupler.SpringKB) * thiscoupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; } else { - CF = -(coupler.SpringKB + othercoupler.SpringKB) * coupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; + CF = -(thiscoupler.SpringKB + othercoupler.SpringKB) * thiscoupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; } // liczenie sily ze sprezystosci zderzaka - auto const collisiondistance{(coupler.has_adapter() || othercoupler.has_adapter() ? - std::min(coupler.DmaxB, othercoupler.DmaxB) : // HACK: only take into account buffering ability of automatic coupler - coupler.DmaxB + othercoupler.DmaxB)}; + 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 - coupler.CheckCollision = true; + thiscoupler.CheckCollision = true; } if (-newdistance >= std::min(collisiondistance, dEpsilon)) { - if (coupler.type() == TCouplerType::Automatic && coupler.type() == othercoupler.type() && coupler.CouplingFlag == coupling::faux && - coupler.AutomaticCouplingAllowed && - othercoupler.AutomaticCouplingAllowed) - { - // sprzeganie wagonow z samoczynnymi sprzegami - auto couplingtype{coupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; - // potentially exclude incompatible control coupling - if (coupler.control_type != othercoupler.control_type) - { - couplingtype &= ~coupling::control; - } - - if (Attach(End, otherend, othervehicle, couplingtype)) - { - // HACK: we're reusing sound enum to mark whether vehicle was connected to another - SetFlag(AIFlag, sound::attachcoupler); - coupler.AutomaticCouplingAllowed = false; - othercoupler.AutomaticCouplingAllowed = false; - } - /* - coupler.CouplingFlag = ( coupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag ); - SetFlag( coupler.sounds, sound::attachcoupler ); - */ - } + automatic_coupling(End, *othervehicle, otherend); } } } - if (coupler.CouplingFlag != coupling::faux) + if (thiscoupler.CouplingFlag != coupling::faux) { - // uzgadnianie prawa Newtona - othervehicle->Couplers[1 - End].CForce = -CF; + // uzgadnianie prawa Newtona, on the coupler of the other vehicle this one is coupled with, along that vehicle's + // axis: turned around once more when the vehicles face each other + othervehicle->Couplers[otherend].CForce = -CF * DirPatch(End, otherend); } return CF; } +bool TMoverParameters::coupler_physics_at(int const End) const +{ + if (false == Global.coupler_physics) + { + return false; + } + if (Global.coupler_physics_all || CouplerPhysics) + { + return true; + } + // either vehicle of the pair covered takes the pair in, so both of them compute it the same way + auto const *other{Neighbours[End].vehicle}; + return other != nullptr && other->MoverParameters->CouplerPhysics; +} + +void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd) +{ + auto &thiscoupler{Couplers[End]}; + auto &othercoupler{Other.Couplers[OtherEnd]}; + + if (thiscoupler.type() != TCouplerType::Automatic || thiscoupler.type() != othercoupler.type() || thiscoupler.CouplingFlag != coupling::faux || false == thiscoupler.AutomaticCouplingAllowed || + false == othercoupler.AutomaticCouplingAllowed) + { + return; + } + // sprzeganie wagonow z samoczynnymi sprzegami + auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; + // potentially exclude incompatible control coupling + if (thiscoupler.control_type != othercoupler.control_type) + { + couplingtype &= ~coupling::control; + } + couplingtype = CompatibleCoupling(End, Other, OtherEnd, couplingtype); + + // too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect()) + auto const safe{AutomaticCouplingSafe(End, Other, OtherEnd)}; + auto const caught{safe && Attach(End, OtherEnd, &Other, couplingtype)}; + // HACK: we're reusing sound enum to mark whether vehicle was connected to another + AIFlag |= (caught ? sound::attachcoupler : 0); + // coupled, or locked until the vehicles part, so they don't couple as soon as the collision slows them down + thiscoupler.AutomaticCouplingAllowed = safe && false == caught; + othercoupler.AutomaticCouplingAllowed = safe && false == caught; +} + +namespace +{ + +// the gap between the ends of a coupled pair, taking up the play of the coupling, opens up enough to jerk the train +constexpr double coupler_stretch_threshold{0.001}; + +// the sounds of the buffers hitting each other, and of the coupling taking up its play +struct coupler_sound_input +{ + double gap{0.0}; // between the ends [m] + double previous_gap{0.0}; + double gap_rate{0.0}; // [m/s] + double draw_gear{0.0}; // deflection [m] + double previous_draw_gear{0.0}; + bool coupled{false}; + bool adapter{false}; + bool moving{false}; +}; + +int coupler_sounds(coupler_sound_input const &Input) +{ + if (Input.gap < 0.0 && Input.gap < Input.previous_gap && Input.gap_rate < -0.1 && false == Input.adapter) + { + // 090503: dzwieki pracy zderzakow + return std::abs(Input.gap_rate) > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash; + } + if (Input.coupled && Input.moving && Input.draw_gear > coupler_stretch_threshold && Input.previous_draw_gear <= coupler_stretch_threshold && std::abs(Input.gap_rate) > 0.005) + { + // 090503: dzwieki pracy sprzegu + return std::abs(Input.gap_rate) > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch; + } + return sound::none; +} + +} // namespace + +double TMoverParameters::coupler_force_physical(int const End, double const dt) +{ + auto &thiscoupler{Couplers[End]}; + auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; + auto const otherend{Neighbours[End].vehicle_end}; + auto &othercoupler{othervehicle->Couplers[otherend]}; + auto &state{thiscoupler.physics_state}; + + // the gap as it is now: the distance found at the start of the frame, and the movement of both vehicles since + auto const othervehiclemove{othervehicle->dMoveLen * DirPatch(End, otherend)}; + auto const gap{Neighbours[End].distance + (End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; + // the gap opens up when the front end falls behind the vehicle ahead of it, or the rear end runs ahead of the one behind + auto const gaprate{CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; + auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; + auto const adapter{thiscoupler.has_adapter() || othercoupler.has_adapter()}; + + if (false == coupled && Neighbours[End].distance > 0.05) + { // arbitrary distance + // potentially reset auto coupling lock + thiscoupler.AutomaticCouplingAllowed = true; + } + + auto const previousgap{state.gap}; + auto const previousdrawgear{state.draw_gear.deflection}; + auto const result{coupler_physics::update_pair(thiscoupler.physics, othercoupler.physics, state, {gap, gaprate, coupled, adapter, Global.crash_damage})}; + + SetFlag(thiscoupler.sounds, coupler_sounds({gap, previousgap, gaprate, state.draw_gear.deflection, previousdrawgear, coupled, adapter, Vel > 1.0})); + + thiscoupler.CheckCollision = state.stop != 0; + // for the buffers drawn pressed in, see TDynamicObject: twice the deflection of the buffers of this end + thiscoupler.Dist = result.compression > 0.0 ? -2.0 * result.buffers_deflection : std::max(gap, 0.0); + // the link pulled past its yield force, which the AI drivers ease off on + thiscoupler.stretch_duration = result.overloaded ? thiscoupler.stretch_duration + static_cast(dt) : 0.f; + + if (result.broken) + { + damage_coupler(End); + } + if (false == coupled && gap < 0.0) + { + auto const collisiondistance{adapter ? std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : thiscoupler.DmaxB + othercoupler.DmaxB}; + if (-gap >= std::min(collisiondistance, dEpsilon)) + { + automatic_coupling(End, *othervehicle, otherend); + } + } + + // tension pulls this vehicle towards the other one + auto const force{result.force * -DirF(End)}; + if (thiscoupler.CouplingFlag != coupling::faux) + { + // uzgadnianie prawa Newtona, as in CouplerForce() + othercoupler.CForce = -force * DirPatch(End, otherend); + } + return force; +} + +bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd) +{ + auto &thiscoupler{Couplers[End]}; + auto &othercoupler{Other.Couplers[OtherEnd]}; + auto &state{thiscoupler.physics_state}; + + // the draw gear went solid with the gap opening up, the buffers with it closing + auto const gaprate{CouplerVelocityDifference(End, Other, OtherEnd) * DirF(End)}; + auto const closing{state.stop > 0 ? gaprate : -gaprate}; + if (state.stop == 0 || closing <= 0.0) + { + // parting from the stop already, after the hit on the other vehicle's end + return false; + } + if (false == Global.crash_damage) + { + return true; + } + auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, TotalMass, Other.TotalMass)}; + // the other vehicle keeps the state of the pair alike + othercoupler.physics_state.elongation = state.elongation; + if (hit.broken || hit.crushed) + { + damage_coupler(End); + } + // a broken coupling lets the vehicles part + return false == hit.broken; +} + // ************************************************************************************************* // Q: 20160714 // oblicza sile trakcyjna lokomotywy (dla elektrowozu tez calkowity prad) // ************************************************************************************************* double TMoverParameters::TractionForce(double dt) { - double PosRatio, dmoment, dtrans, tmp; + double PosRatio; + double dmoment; + double dtrans; + double tmp; Ft = 0; dtrans = 0; @@ -5507,7 +5882,7 @@ double TMoverParameters::TractionForce(double dt) 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; + tmp = DElist[ControlPressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; if (true == HeatingAllow && HeatingPower > 0 && EngineHeatingRPM > 0) { @@ -5537,9 +5912,9 @@ double TMoverParameters::TractionForce(double dt) case TEngineType::DieselEngine: { if (ShuntMode) // dodatkowa przekładnia np. dla 2Ls150 - dtrans = AnPos * Transmision.Ratio * MotorParam[ScndCtrlActualPos].mIsat; + dtrans = AnPos * Transmision.Ratio * motor_param(ScndCtrlActualPos).mIsat; else - dtrans = Transmision.Ratio * MotorParam[ScndCtrlActualPos].mIsat; + dtrans = Transmision.Ratio * motor_param(ScndCtrlActualPos).mIsat; dmoment = dizel_Momentum(dizel_fill, dtrans * nrot * DirActive, dt); // oblicza tez enrot break; @@ -5567,7 +5942,7 @@ double TMoverParameters::TractionForce(double dt) case TEngineType::ElectricSeriesMotor: { - if (true == Mains) + if (MainCircuitPowered()) { switch (RVentType) { @@ -5628,14 +6003,14 @@ double TMoverParameters::TractionForce(double dt) { // TBD, TODO: currently ignores RVentType, fix this? RventRot += std::clamp(enrot - RventRot, -100.0, 50.0) * dt; - dizel_heat.rpmw += std::clamp(dizel_heat.rpmwz - dizel_heat.rpmw, -100.f, 50.f) * dt; - dizel_heat.rpmw2 += std::clamp(dizel_heat.rpmwz2 - dizel_heat.rpmw2, -100.f, 50.f) * 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 *= std::max(0.0, 1.0 - dizel_heat.rpmw * dt); - dizel_heat.rpmw2 *= std::max(0.0, 1.0 - dizel_heat.rpmw2 * 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; } @@ -5645,13 +6020,13 @@ double TMoverParameters::TractionForce(double dt) // NOTE: we update only radiator fans, as vehicles with diesel engine don't have other ventilators if (true == Mains) { - dizel_heat.rpmw += std::clamp(dizel_heat.rpmwz - dizel_heat.rpmw, -100.f, 50.f) * dt; - dizel_heat.rpmw2 += std::clamp(dizel_heat.rpmwz2 - dizel_heat.rpmw2, -100.f, 50.f) * 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 { - dizel_heat.rpmw *= std::max(0.0, 1.0 - dizel_heat.rpmw * dt); - dizel_heat.rpmw2 *= std::max(0.0, 1.0 - dizel_heat.rpmw2 * 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; } @@ -5699,11 +6074,18 @@ double TMoverParameters::TractionForce(double dt) { // update the state of voltage relays auto const voltage{std::max(GetTrainsetHighVoltage(), PantographVoltage)}; - NoVoltRelay = EnginePowerSource.SourceType != TPowerSource::CurrentCollector || voltage >= EnginePowerSource.CollectorParameters.MinV; + // 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 - EventFlag |= true == Mains && (false == NoVoltRelay || false == OvervoltageRelay) && + // (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; } @@ -5711,14 +6093,12 @@ double TMoverParameters::TractionForce(double dt) case TEngineType::ElectricInductionMotor: { // TODO: check if we can use instead the code for electricseriesmotor - if (Mains) + // nie wchodzić w funkcję bez potrzeby + // (a line breaker closed ahead of the pantographs holds without voltage) + if (Mains && ((std::max(GetTrainsetHighVoltage(), PantographVoltage) < EnginePowerSource.CollectorParameters.MinV && false == PantographsRequireMains) || + std::max(GetTrainsetHighVoltage(), PantographVoltage) > EnginePowerSource.CollectorParameters.MaxV + 200)) { - // nie wchodzić w funkcję bez potrzeby - if (std::max(GetTrainsetHighVoltage(), PantographVoltage) < EnginePowerSource.CollectorParameters.MinV || - std::max(GetTrainsetHighVoltage(), PantographVoltage) > EnginePowerSource.CollectorParameters.MaxV + 200) - { - MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide - } + MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide } break; } @@ -5765,9 +6145,8 @@ double TMoverParameters::TractionForce(double dt) case TEngineType::WheelsDriven: { - if (EnginePowerSource.SourceType == TPowerSource::InternalSource) - if (EnginePowerSource.PowerType == TPowerType::BioPower) - Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; + if (EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) + Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; PulseForceTimer = PulseForceTimer + dt; if (PulseForceTimer > CtrlDelay) { @@ -5936,7 +6315,6 @@ double TMoverParameters::TractionForce(double dt) auto power = Power; tempImax = DElist[MainCtrlPos].Imax; tempUmax = DElist[MainCtrlPos].Umax; - tempPmax = DElist[MainCtrlPos].GenPower; if (true == Heating) { power -= HeatingPower; @@ -5984,10 +6362,10 @@ double TMoverParameters::TractionForce(double dt) Mm = Mw / Transmision.Ratio; // moment silnika trakcyjnego // with MotorParam[ScndCtrlPos] do - if (abs(Mm) > MotorParam[ScndCtrlPos].fi) - Im = NPoweredAxles * abs(abs(Mm) / MotorParam[ScndCtrlPos].mfi + MotorParam[ScndCtrlPos].mIsat); + if (abs(Mm) > motor_param(ScndCtrlPos).fi) + Im = NPoweredAxles * abs(abs(Mm) / motor_param(ScndCtrlPos).mfi + motor_param(ScndCtrlPos).mIsat); else - Im = NPoweredAxles * sqrt(abs(Mm * MotorParam[ScndCtrlPos].Isat)); + Im = NPoweredAxles * sqrt(abs(Mm * motor_param(ScndCtrlPos).Isat)); if (ShuntMode) { @@ -6193,24 +6571,21 @@ double TMoverParameters::TractionForce(double dt) } } // malenie - if (MainCtrlPos < 12 && ScndCtrlPos > 0) + if (MainCtrlPos < 12 && ScndCtrlPos > 0 && Vel < 50.0) { - if (Vel < 50.0) + // above 50 km/h already active shunt field can be maintained until lower controller setting + if (ScndCtrlPos % 2 == 0) { - // above 50 km/h already active shunt field can be maintained until lower controller setting - if (ScndCtrlPos % 2 == 0) + if (MPTRelay[ScndCtrlPos].Idown < Im) { - if (MPTRelay[ScndCtrlPos].Idown < Im) - { - --ScndCtrlPos; - } + --ScndCtrlPos; } - else + } + else + { + if (MPTRelay[ScndCtrlPos + 1].Idown < Im && MPTRelay[ScndCtrlPos].Idown > Vel) { - if (MPTRelay[ScndCtrlPos + 1].Idown < Im && MPTRelay[ScndCtrlPos].Idown > Vel) - { - --ScndCtrlPos; - } + --ScndCtrlPos; } } } @@ -6241,10 +6616,10 @@ double TMoverParameters::TractionForce(double dt) case TEngineType::ElectricInductionMotor: { - if (true == Mains && !SecuritySystem.is_engine_blocked()) + if (MainCircuitPowered() && !SecuritySystem.is_engine_blocked()) { double ActiveInverters = 0.0; - for (auto &inv : Inverters) + for (auto const &inv : Inverters) { if (inv.IsActive) ActiveInverters += 1.0; @@ -6296,6 +6671,8 @@ double TMoverParameters::TractionForce(double dt) SpeedCtrlValue = Vmax; SpeedCtrlTimer = 10; break; + default: + break; } } else if (ScndCtrlPosNo > 1) @@ -6311,7 +6688,7 @@ double TMoverParameters::TractionForce(double dt) SpeedCtrlTimer += dt; if (SpeedCtrlTimer > SpeedCtrlDelay) { - int NewSCAP = (float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax; + auto NewSCAP = static_cast((float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax); if (NewSCAP != SpeedCtrlValue) { SpeedCtrlValue = NewSCAP; @@ -6350,7 +6727,7 @@ double TMoverParameters::TractionForce(double dt) { PosRatio = 0; } - PosRatio = Round(20.0 * PosRatio) / 20.0; // stopniowanie PN/ED + 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 @@ -6395,12 +6772,8 @@ double TMoverParameters::TractionForce(double dt) // PosRatio = 1.0 * (PosRatio * 0 + 1) * PosRatio; // 1 * 1 * PosRatio = PosRatio Hamulec->SetED(0); // (Hamulec as TLSt).SetLBP(LocBrakePress); - if (PosRatio > eimv_pr) - tmp = 4; - else - tmp = 4; // szybkie malenie, powolne wzrastanie + tmp = 4; // szybkie malenie, powolne wzrastanie } - dmoment = eimv[eimv_Fful]; // 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) @@ -6504,9 +6877,8 @@ double TMoverParameters::TractionForce(double dt) auto const tmpV{std::abs(eimv[eimv_fp])}; auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; auto const list = useFFEDList ? FFEDlist : FFlist; - auto const listSize = useFFEDList ? FFEDListSize : FFListSize; - if (listSize > 0 && std::abs(eimv[eimv_If]) > 1.0 && tmpV > 0.0001) + if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(eimv[eimv_If]) > 1.0 && tmpV > 0.0001) { int i = 0; @@ -6543,8 +6915,8 @@ double TMoverParameters::TractionForce(double dt) eimv_pr = 0.0; EnginePower = 0.0; { - for (int i = 0; i < 21; ++i) - eimv[i] = 0.0; + for (auto &eimvvalue : eimv) + eimvvalue = 0.0; } Hamulec->SetED(0.0); InverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); @@ -6559,18 +6931,10 @@ double TMoverParameters::TractionForce(double dt) } } // case EngineType - switch (EngineType) - { - case TEngineType::DieselElectric: + if (EngineType == TEngineType::DieselElectric) { // rough approximation of extra effort to overcome friction etc EnginePower += EngineRPMRatio() * 0.15 * DElist[MainCtrlPosNo].GenPower; - break; - } - default: - { - break; - } } return Ft; @@ -6582,7 +6946,8 @@ double TMoverParameters::TractionForce(double dt) // ************************************************************************************************* double TMoverParameters::ComputeRotatingWheel(double WForce, double dt, double n) const { - double newn = 0, eps = 0; + double newn = 0; + double eps = 0; if (n == 0 && WForce * Sign(V) < 0) newn = 0; else @@ -6607,10 +6972,9 @@ bool TMoverParameters::FuseFlagCheck(void) const if (Power > 0.01) FFC = FuseFlag; else // pobor pradu jezeli niema mocy - for (int b = 0; b < 2; b++) - if (TestFlag(Couplers[b].CouplingFlag, coupling::control)) - if (Couplers[b].Connected->Power > 0.01) - FFC = Couplers[b].Connected->FuseFlagCheck(); + for (auto &thiscoupler : Couplers) + if (TestFlag(thiscoupler.CouplingFlag, coupling::control) && thiscoupler.Connected->Power > 0.01) + FFC = thiscoupler.Connected->FuseFlagCheck(); return FFC; } @@ -6644,8 +7008,7 @@ void TMoverParameters::FuseOff(void) bool TMoverParameters::UniversalResetButton(int const Button, range_t const Notify) { - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; - if (false == lowvoltagepower) + if (auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; false == lowvoltagepower) { return false; } @@ -6668,43 +7031,34 @@ bool TMoverParameters::RelayReset(int const Relays, range_t const Notify) auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; bool reset{false}; - if (TestFlag(Relays, relay_t::maincircuitground)) - { - if ((EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && + 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; - } + { + // NOTE: true means the relay is operational + reset |= !GroundRelay && lowvoltagepower; + GroundRelay |= lowvoltagepower; } - if (TestFlag(Relays, relay_t::tractionnmotoroverload)) - { - if ((EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && + 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; - } + { + // 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)) - { - if (ConverterOverloadRelayStart == start_t::manual + 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; - } + { + // 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) @@ -6728,7 +7082,8 @@ double TMoverParameters::v2n(void) { // przelicza predkosc liniowa na obrotowa const double dmgn = 0.5; - double n, deltan = 0; + 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 @@ -6737,14 +7092,10 @@ double TMoverParameters::v2n(void) 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) - if (FuzzyLogic(deltan, dmgn, p_slippdmg)) - if (SetFlag(DamageFlag, dtrain_wheelwear)) // podkucie - EventFlag = true; - if (deltan < -dmgn) - if (FuzzyLogic(-deltan, dmgn, p_slippdmg)) - if (SetFlag(DamageFlag, dtrain_thinwheel)) // wycieranie sie obreczy - EventFlag = true; + 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; @@ -6754,29 +7105,28 @@ double TMoverParameters::v2n(void) // Q: 20160714 // Oblicza moment siły wytwarzany przez silnik // ************************************************************************************************* -double TMoverParameters::Momentum(double I) +double TMoverParameters::Momentum(double I) const { // liczy moment sily wytwarzany przez silnik elektryczny} int SP; SP = ScndCtrlActualPos; - if (ScndInMain) - if (!(RList[MainCtrlActualPos].ScndAct == 255)) - SP = RList[MainCtrlActualPos].ScndAct; + if (ScndInMain && !(RList[MainCtrlActualPos].ScndAct == 255)) + SP = RList[MainCtrlActualPos].ScndAct; // Momentum:=mfi*I*(1-1.0/(Abs(I)/mIsat+1)); - return MotorParam[SP].mfi * I * (abs(I) / (abs(I) + MotorParam[SP].mIsat) - MotorParam[SP].mfi0); + 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) +double TMoverParameters::MomentumF(double I, double Iw, int SCP) const { // umozliwia dokladne sterowanie wzbudzeniem - return MotorParam[SCP].mfi * I * std::max(abs(Iw) / (abs(Iw) + MotorParam[SCP].mIsat) - MotorParam[SCP].mfi0, 0.); + return motor_param(SCP).mfi * I * std::max(abs(Iw) / (abs(Iw) + motor_param(SCP).mIsat) - motor_param(SCP).mfi0, 0.); } // ************************************************************************************************* @@ -6786,13 +7136,10 @@ double TMoverParameters::MomentumF(double I, double Iw, int SCP) bool TMoverParameters::CutOffEngine(void) { bool COE = false; // Ra: wartość domyślna, sprawdzić to trzeba - if (NPoweredAxles > 0 && CabActive == 0 && EngineType == TEngineType::ElectricSeriesMotor) + if (NPoweredAxles > 0 && CabActive == 0 && EngineType == TEngineType::ElectricSeriesMotor && SetFlag(DamageFlag, -dtrain_engine)) { - if (SetFlag(DamageFlag, -dtrain_engine)) - { - NPoweredAxles = NPoweredAxles / 2; // bylo div czyli mod? - COE = true; - } + NPoweredAxles = NPoweredAxles / 2; // bylo div czyli mod? + COE = true; } return COE; } @@ -6855,10 +7202,9 @@ bool TMoverParameters::ResistorsFlagCheck(void) const RFC = ResistorsFlag; else // pobor pradu jezeli niema mocy { - for (int b = 0; b < 2; b++) - if (TestFlag(Couplers[b].CouplingFlag, coupling::control)) - if (Couplers[b].Connected->Power > 0.01) - RFC = Couplers[b].Connected->ResistorsFlagCheck(); + for (auto &thiscoupler : Couplers) + if (TestFlag(thiscoupler.CouplingFlag, coupling::control) && thiscoupler.Connected->Power > 0.01) + RFC = thiscoupler.Connected->ResistorsFlagCheck(); } return RFC; } @@ -6890,7 +7236,6 @@ bool TMoverParameters::AutoRelaySwitch(bool State) bool TMoverParameters::AutoRelayCheck(void) { bool OK = false; // b:int; - bool ARC = false; auto const motorconnectorsoff{false == MotorConnectorsCheck()}; @@ -6909,7 +7254,7 @@ bool TMoverParameters::AutoRelayCheck(void) } // sprawdzenie wszystkich warunkow (AutoRelayFlag, AutoSwitch, Im BackwardsBranchesAllowed) - { - return false; // nie poprawiamy przy konwersji - // return ARC;// bbylo exit; //Ra: to powoduje, że EN57 nie wyłącza się przy IminLo - } - } + // 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 (MainCtrlActualPos < sizeof(RList) / sizeof(TScheme) - 1 // crude guard against running out of current fixed table + 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))) { @@ -7051,12 +7392,12 @@ bool TMoverParameters::AutoRelayCheck(void) --MainCtrlActualPos; OK = true; } - if (MainCtrlActualPos > 0) // hunter-111211: poprawki - if (RList[MainCtrlActualPos].R == 0) - { - // dzwieki schodzenia z bezoporowej} - SetFlag(SoundFlag, sound::parallel); - } + // hunter-111211: poprawki + if (MainCtrlActualPos > 0 && RList[MainCtrlActualPos].R == 0) + { + // dzwieki schodzenia z bezoporowej} + SetFlag(SoundFlag, sound::parallel); + } } } else if (RList[MainCtrlActualPos].R > 0 && ScndCtrlActualPos > 0) @@ -7193,9 +7534,36 @@ bool TMoverParameters::MotorConnectorsCheck() return false; } - auto const connectorsoff{false == Mains || true == FuseFlag || true == StLinSwitchOff || DirActive == 0}; + // 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}; - return false == connectorsoff; + 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) @@ -7208,40 +7576,41 @@ bool TMoverParameters::OperatePantographsValve(operation_t const State, range_t switch (State) { - case operation_t::none: + using enum operation_t; + case none: { valve.is_enabled = false; valve.is_disabled = false; break; } - case operation_t::enable: + case enable: { valve.is_enabled = true; valve.is_disabled = false; break; } - case operation_t::disable: + case disable: { valve.is_enabled = false; valve.is_disabled = true; break; } - case operation_t::enable_on: + case enable_on: { valve.is_enabled = true; break; } - case operation_t::enable_off: + case enable_off: { valve.is_enabled = false; break; } - case operation_t::disable_on: + case disable_on: { valve.is_disabled = true; break; } - case operation_t::disable_off: + case disable_off: { valve.is_disabled = false; break; @@ -7267,40 +7636,41 @@ bool TMoverParameters::OperatePantographValve(end const End, operation_t const S switch (State) { - case operation_t::none: + using enum operation_t; + case none: { valve.is_enabled = false; valve.is_disabled = false; break; } - case operation_t::enable: + case enable: { valve.is_enabled = true; valve.is_disabled = false; break; } - case operation_t::disable: + case disable: { valve.is_enabled = false; valve.is_disabled = true; break; } - case operation_t::enable_on: + case enable_on: { valve.is_enabled = true; break; } - case operation_t::enable_off: + case enable_off: { valve.is_enabled = false; break; } - case operation_t::disable_on: + case disable_on: { valve.is_disabled = true; break; } - case operation_t::disable_off: + case disable_off: { valve.is_disabled = false; break; @@ -7335,6 +7705,60 @@ bool TMoverParameters::DropAllPantographs(bool const State, range_t const Notify 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; + } + return safe_clamp(value, Position.MinCtrlVal, Position.MaxCtrlVal); +} +} // namespace + void TMoverParameters::CheckEIMIC(double dt) { double offset = EIMCtrlAdditionalZeros ? 1.0 : 0.0; @@ -7393,6 +7817,8 @@ void TMoverParameters::CheckEIMIC(double dt) 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; @@ -7400,10 +7826,16 @@ void TMoverParameters::CheckEIMIC(double dt) eimic = 0; break; case 2: - if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) + 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; - switch (MainCtrlPos) + // the positions below are those of the controller without the emergency brake position + switch (MainCtrlPos - EIMCtrlEmergencyPositions()) { case 0: case 1: @@ -7422,6 +7854,8 @@ void TMoverParameters::CheckEIMIC(double dt) if (eimic < 0) eimic = 0; break; + default: + break; } } if (MainCtrlActualPos == MainCtrlPos) @@ -7455,11 +7889,14 @@ void TMoverParameters::CheckEIMIC(double dt) if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) { - eimic -= safe_clamp(-UniCtrlList[MainCtrlPos].SetCtrlVal + eimic, 0.0, - MainCtrlActualPos == MainCtrlPos ? dt * UniCtrlList[MainCtrlPos].SpeedDown : sign(UniCtrlList[MainCtrlPos].SpeedDown) * 0.01); // odejmuj do X - eimic += safe_clamp(UniCtrlList[MainCtrlPos].SetCtrlVal - eimic, 0.0, - MainCtrlActualPos == MainCtrlPos ? dt * UniCtrlList[MainCtrlPos].SpeedUp : sign(UniCtrlList[MainCtrlPos].SpeedUp) * 0.01); // dodawaj do X - eimic = safe_clamp(eimic, UniCtrlList[MainCtrlPos].MinCtrlVal, UniCtrlList[MainCtrlPos].MaxCtrlVal); + 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; @@ -7499,7 +7936,7 @@ void TMoverParameters::CheckEIMIC(double dt) eimic = 0; } - auto const eimicpowerenabled{(true == Mains || Power == 0.0) && (!SpringBrake.IsActive || !SpringBrakeCutsOffDrive) && !LockPipe && DirAbsolute != 0}; + auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!SpringBrake.IsActive || !SpringBrakeCutsOffDrive) && !LockPipe && DirAbsolute != 0}; auto const eimicdoorenabled{(SpringBrake.IsActive && ReleaseParkingBySpringBrakeWhenDoorIsOpen)}; double eimic_max = 0.0; if (Doors.instances[side::left].open_permit == false && Doors.instances[side::right].open_permit == false) @@ -7540,11 +7977,8 @@ void TMoverParameters::CheckSpeedCtrl(double dt) { SpeedCtrlUnit.Standby = false; } - if (!SpeedCtrlUnit.BrakeIntervention) - { - if (Hamulec->GetEDBCP() > 0.4 || PipePress < HighPipePress - 0.2) - SpeedCtrlUnit.Standby = true; - } + if (!SpeedCtrlUnit.BrakeIntervention && (Hamulec->GetEDBCP() > 0.4 || PipePress < HighPipePress - 0.2)) + SpeedCtrlUnit.Standby = true; if (EIMCtrlType >= 3 && UniCtrlList[MainCtrlPos].SpeedUp <= 0) { accfactor = 0.0; @@ -7557,11 +7991,8 @@ void TMoverParameters::CheckSpeedCtrl(double dt) { if (!SpeedCtrlUnit.Standby) { - if (SpeedCtrlUnit.ManualStateOverride) - { - if (eimic > 0.0009) - eimic = 1.0; - } + 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 @@ -7732,13 +8163,13 @@ bool TMoverParameters::dizel_AutoGearCheck(void) { auto OK{false}; - auto const VelUp{(MotorParam[ScndCtrlActualPos].mfi0 != 0.0 ? - MotorParam[ScndCtrlActualPos].mfi0 + (MotorParam[ScndCtrlActualPos].mfi - MotorParam[ScndCtrlActualPos].mfi0) * std::max(0.0, eimic_real) : - MotorParam[ScndCtrlActualPos].mfi)}; + 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{(MotorParam[ScndCtrlActualPos].fi0 != 0.0 && eimic_real <= 0.0 ? MotorParam[ScndCtrlActualPos].fi0 : MotorParam[ScndCtrlActualPos].fi)}; + auto const VelDown{(motor_param(ScndCtrlActualPos).fi0 != 0.0 && eimic_real <= 0.0 ? motor_param(ScndCtrlActualPos).fi0 : motor_param(ScndCtrlActualPos).fi)}; - if (MotorParam[ScndCtrlActualPos].AutoSwitch && Mains) + if (motor_param(ScndCtrlActualPos).AutoSwitch && Mains) { if (RList[MainCtrlPos].Mn == 0 && !hydro_TC) { @@ -7749,7 +8180,7 @@ bool TMoverParameters::dizel_AutoGearCheck(void) } else { - if (MotorParam[ScndCtrlActualPos].AutoSwitch && dizel_automaticgearstatus == 0) // sprawdz czy zmienic biegi + if (motor_param(ScndCtrlActualPos).AutoSwitch && dizel_automaticgearstatus == 0) // sprawdz czy zmienic biegi { if (Vel > VelUp) { @@ -7834,7 +8265,7 @@ bool TMoverParameters::dizel_AutoGearCheck(void) } else dizel_EngageSwitch(0.0); - if (!(MotorParam[ScndCtrlActualPos].mIsat > 0)) + if (!(motor_param(ScndCtrlActualPos).mIsat > 0)) dizel_EngageSwitch(0.0); // wylacz sprzeglo na pozycjach neutralnych if (!AutoRelayFlag) ScndCtrlActualPos = ScndCtrlPos; @@ -7890,6 +8321,9 @@ bool TMoverParameters::dizel_Update(double 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; @@ -7904,6 +8338,7 @@ bool TMoverParameters::dizel_Update(double dt) LastSwitchingTime = 0; 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)); @@ -7915,7 +8350,8 @@ bool TMoverParameters::dizel_Update(double dt) { // 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 - MainSwitch(false); + // an engine started on its own stops on its own + MainSwitch(false, MainSwitchRange()); } bool DU{false}; @@ -7956,7 +8392,7 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) // napelnienie zalezne od MainCtrlPos if (EIMCtrlType > 0) { - realfill = std::max(0.0, std::min(eimic_real, 1 - MotorParam[ScndCtrlActualPos].Isat)); + 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); @@ -7968,7 +8404,7 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) else dizel_nreg_min = dizel_nmin; } - if (dizel_vel2nmax_Table.size() > 0 && !hydro_TC_Lockup) + 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)); } @@ -8025,8 +8461,6 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) } if (enrot > nreg) // nad predkoscia regulatora zeruj dawke realfill = 0; - if (enrot < nreg) // pod predkoscia regulatora dawka zadana - realfill = realfill; if (enrot < dizel_nreg_min && RList[mcp].R > 0.001) // jesli ponizej biegu jalowego i niezerowa dawka, to dawaj pelna realfill = 1; } @@ -8039,30 +8473,36 @@ double TMoverParameters::dizel_fillcheck(int mcp, double dt) // Q: 20160715 // Oblicza moment siły wytwarzany przez silnik spalinowy // ************************************************************************************************* -double TMoverParameters::dizel_Momentum(double dizel_fill, double n, double dt) +double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) { // liczy moment sily wytwarzany przez silnik spalinowy} - double Moment = 0, enMoment = 0, gearMoment = 0, eps = 0, newn = 0, friction = 0, neps = 0; - double TorqueH = 0, TorqueL = 0, TorqueC = 0; + 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 (MotorParam[ScndCtrlActualPos].mIsat < 0.001 || DirActive == 0) + 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 - neps = (n - dizel_n_old) / dt; // przyspieszenie katowe walu wejsciowego skrzyni biegow if (enrot > 0) { if (dizel_Momentum_Table.size() > 1) { - Moment = TableInterpolation(dizel_Momentum_Table, enrot) * dizel_fill - dizel_Mstand; + 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))) * dizel_fill - dizel_Mstand; + 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 * dizel_fill; + 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); @@ -8193,7 +8633,6 @@ double TMoverParameters::dizel_Momentum(double dizel_fill, double n, double dt) { dizel_engagedeltaomega = 0; gearMoment = Moment; - enMoment = 0; 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); @@ -8203,7 +8642,13 @@ double TMoverParameters::dizel_Momentum(double dizel_fill, double n, double dt) if (enrot <= 0 && false == dizel_spinup) { - MainSwitch(false); + // 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; } @@ -8249,8 +8694,7 @@ double TMoverParameters::dizel_MomentumRetarder(double n, double dt) } double Moment = hydro_R_MaxTorque; - double pwr = Moment * std::abs(n) * M_PI * 2 * 0.001; - if (pwr > hydro_R_MaxPower) + 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); @@ -8264,8 +8708,16 @@ double TMoverParameters::dizel_MomentumRetarder(double n, double dt) void TMoverParameters::dizel_HeatSet(float const Value) { - dizel_heat.Te = // TODO: don't include ambient temperature, pull it from environment data instead - dizel_heat.Ts = dizel_heat.To = dizel_heat.Tsr = dizel_heat.Twy = dizel_heat.Tsr2 = dizel_heat.Twy2 = dizel_heat.temperatura1 = dizel_heat.temperatura2 = 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 @@ -8319,13 +8771,13 @@ void TMoverParameters::dizel_Heat(double const dt) // 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 += dTss * dt; + 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 += dTo * dt; + dizel_heat.To += static_cast(dTo * dt); // heater /* @@ -8344,7 +8796,7 @@ void TMoverParameters::dizel_Heat(double const dt) (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 = PTC2 * (dizel_heat.fan_speed >= 0 ? rpm * dizel_heat.fan_speed : dizel_heat.fan_speed * -1); + 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 @@ -8356,8 +8808,8 @@ void TMoverParameters::dizel_Heat(double const dt) // 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 = Twe2 + dTs2 * dt; - dizel_heat.Tsr2 = 0.5 * (dizel_heat.Twy2 + Twe2); + 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 @@ -8367,7 +8819,7 @@ void TMoverParameters::dizel_Heat(double const dt) 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 = PTC1 * (dizel_heat.fan_speed >= 0 ? rpm * dizel_heat.fan_speed : dizel_heat.fan_speed * -1); + 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 @@ -8378,8 +8830,8 @@ void TMoverParameters::dizel_Heat(double const dt) auto const dTch{Qch / (gw * Cw)}; // primary water circuit heat transfers finalization auto const Twe{dizel_heat.Twy + dTch * dt}; - dizel_heat.Twy = Twe + dTs * dt; - dizel_heat.Tsr = 0.5 * (dizel_heat.Twy + Twe); + 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 ); @@ -8427,10 +8879,10 @@ void TMoverParameters::dizel_Heat(double const dt) */ } -bool TMoverParameters::AssignLoad(std::string const &Name, float const Amount) +bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amount) { - if (Name == "pantstate") + if (Loadname == "pantstate") { if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { @@ -8470,40 +8922,38 @@ bool TMoverParameters::AssignLoad(std::string const &Name, float const Amount) } } - if (Name.empty()) + if (Loadname.empty()) { // empty the vehicle if requested - LoadTypeChange = LoadType.name != Name; + 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 != Name) + if (LoadAmount > 0 && LoadType.name != Loadname) { return false; } - for (auto const &loadattributes : LoadAttributes) + auto const loadattributes = std::ranges::find_if(LoadAttributes, [&](auto const &attributes) { return attributes.name == Loadname; }); + if (loadattributes == std::end(LoadAttributes)) { - if (Name == loadattributes.name) - { - LoadTypeChange = LoadType.name != Name; - LoadType = loadattributes; - LoadAmount = std::clamp(Amount, 0.f, MaxLoad); - ComputeMass(); - return true; - } + // didn't find matching load configuration, this type is unsupported + return false; } - // didn't find matching load configuration, this type is unsupported - return false; + LoadTypeChange = LoadType.name != Loadname; + LoadType = *loadattributes; + LoadAmount = std::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 const &Loadname) +bool TMoverParameters::LoadingDone(double const LSpeed, std::string_view Loadname) { if (LSpeed == 0.0) @@ -8560,7 +9010,7 @@ bool TMoverParameters::LoadingDone(double const LSpeed, std::string const &Loadn if (LoadAmount >= MaxLoad * (1.0 + OverLoadFactor) || CommandIn.Value1 <= 0) { LoadStatus = 4; // skończony załadunek - LoadAmount = std::min(MaxLoad * (1.0 + OverLoadFactor), LoadAmount); + LoadAmount = std::min(static_cast(MaxLoad * (1.0 + OverLoadFactor)), LoadAmount); } ComputeMass(); } @@ -8737,6 +9187,48 @@ bool TMoverParameters::signal_departure(bool const State, range_t const Notify) 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) { @@ -8799,10 +9291,10 @@ void TMoverParameters::update_doors(double const Deltatime) if (false == door.step_unfolding // no wait if no doorstep || Doors.step_type == 2) { // no wait for rotating doorstep - door.open_delay += Deltatime; + door.open_delay += static_cast(Deltatime); if (door.open_delay > Doors.open_delay) { - door.position = std::min(Doors.range, door.position + Doors.open_rate * Deltatime); + door.position = std::min(Doors.range, static_cast(door.position + Doors.open_rate * Deltatime)); } } door.close_delay = 0.f; @@ -8810,10 +9302,10 @@ void TMoverParameters::update_doors(double const Deltatime) if (true == door.is_closing) { // close door - door.close_delay += Deltatime; + door.close_delay += static_cast(Deltatime); if (door.close_delay > Doors.close_delay) { - door.position = std::max(0.f, door.position - Doors.close_rate * Deltatime); + door.position = std::max(0.f, static_cast(door.position - Doors.close_rate * Deltatime)); } door.open_delay = 0.f; } @@ -8821,7 +9313,7 @@ void TMoverParameters::update_doors(double const Deltatime) if (door.step_unfolding) { // unfold left doorstep - door.step_position = std::min(1.f, door.step_position + Doors.step_rate * Deltatime); + door.step_position = std::min(1.f, static_cast(door.step_position + Doors.step_rate * Deltatime)); } if (door.step_folding) { @@ -8831,12 +9323,12 @@ void TMoverParameters::update_doors(double const Deltatime) // multi-unit vehicles typically fold the doorstep only after closing the door if (door.position <= 0.f) { - door.step_position = std::max(0.f, door.step_position - Doors.step_rate * Deltatime); + door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); } } else { - door.step_position = std::max(0.f, door.step_position - Doors.step_rate * Deltatime); + door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); } } } @@ -8859,7 +9351,7 @@ void TMoverParameters::update_doors(double const Deltatime) if (door.auto_timer > 0.f) { - door.auto_timer -= Deltatime; + 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) @@ -8913,9 +9405,7 @@ bool TMoverParameters::ChangeOffsetH(double DeltaOffset) std::string TMoverParameters::EngineDescription(int what) const { std::string outstr{"OK"}; - switch (what) - { - case 0: + if (what == 0) { if (DamageFlag == 255) { @@ -8965,13 +9455,10 @@ std::string TMoverParameters::EngineDescription(int what) const outstr = "DERAILED"; } } - break; } - default: + else { outstr = "Invalid qualifier"; - break; - } } return outstr; } @@ -8983,22 +9470,21 @@ std::string TMoverParameters::EngineDescription(int what) const 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? - double voltages[] = {0.0, 0.0}; + std::array voltages{0.0, 0.0}; for (int end = end::front; end <= end::rear; ++end) { if (Couplers[end].Connected == nullptr) { continue; } - auto const &coupler{Couplers[end]}; - auto const fullcoupling{coupler.CouplingFlag | (TestFlag(coupler.CouplingFlag, coupler.PowerCoupling) ? coupler.PowerFlag : 0)}; - if ((fullcoupling & Coupling) == 0) + auto const &thiscoupler{Couplers[end]}; + if (auto const fullcoupling{thiscoupler.CouplingFlag | (TestFlag(thiscoupler.CouplingFlag, thiscoupler.PowerCoupling) ? thiscoupler.PowerFlag : 0)}; (fullcoupling & Coupling) == 0) { continue; } - auto *connectedpowercoupling = (Coupling & (coupling::highvoltage | coupling::heating)) != 0 ? &coupler.Connected->Couplers[coupler.ConnectedNr].power_high : - (Coupling & coupling::power110v) != 0 ? &coupler.Connected->Couplers[coupler.ConnectedNr].power_110v : - (Coupling & coupling::power24v) != 0 ? &coupler.Connected->Couplers[coupler.ConnectedNr].power_24v : + 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) { @@ -9037,15 +9523,25 @@ bool TMoverParameters::switch_physics(bool const State) // DO PRZETLUMACZENIA NA // FUNKCJE PARSERA WCZYTYWANIA PLIKU FIZYKI POJAZDU // ************************************************************************************************* bool startBPT; -bool startMPT, startMPT0; -bool startRLIST, startUCLIST; -bool startDIZELMOMENTUMLIST, startDIZELV2NMAXLIST, startHYDROTCLIST, startPMAXLIST; -bool startDLIST, startFFLIST, startWWLIST, startWiperList, startDimmerList, startFFEDLIST; +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 const &Name, std::string const &Input) +bool issection(std::string_view Name, std::string_view Input) { return Input.compare(0, Name.size(), Name) == 0; @@ -9055,10 +9551,10 @@ int s2NPW(std::string s) { // wylicza ilosc osi napednych z opisu ukladu osi const char A = 64; int NPW = 0; - for (std::size_t k = 0; k < s.size(); ++k) + for (char const chentry : s) { - if (s[k] >= (char)65 && s[k] <= (char)90) - NPW += s[k] - A; + if (chentry >= (char)65 && chentry <= (char)90) + NPW += chentry - A; } return NPW; } @@ -9067,10 +9563,10 @@ int s2NNW(std::string s) { // wylicza ilosc osi nienapedzanych z opisu ukladu osi const char Zero = 48; int NNW = 0; - for (std::size_t k = 0; k < s.size(); ++k) + for (char const ch : s) { - if (s[k] >= (char)49 && s[k] <= (char)57) - NNW += s[k] - Zero; + if (ch >= (char)49 && ch <= (char)57) + NNW += ch - Zero; } return NNW; } @@ -9079,6 +9575,17 @@ int s2NNW(std::string s) // 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) { @@ -9091,22 +9598,21 @@ bool TMoverParameters::readMPT0(std::string const &line) } int idx = 0; // numer pozycji parser >> idx; - switch (EngineType) + if (false == is_valid_mpt_index(idx)) { - case TEngineType::DieselEngine: + 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; - break; } - default: + else { parser >> MotorParam[idx].mfi >> MotorParam[idx].mIsat >> MotorParam[idx].mfi0 >> MotorParam[idx].fi >> MotorParam[idx].Isat >> MotorParam[idx].fi0; - break; - } } if (true == parser.getTokens(1, false)) { - int autoswitch; + int autoswitch{0}; parser >> autoswitch; MotorParam[idx].AutoSwitch = autoswitch == 1; } @@ -9155,10 +9661,14 @@ bool TMoverParameters::readMPTElectricSeries(std::string const &line) } 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; + int autoswitch{0}; parser >> autoswitch; MotorParam[idx].AutoSwitch = autoswitch == 1; } @@ -9180,6 +9690,10 @@ bool TMoverParameters::readMPTDieselElectric(std::string const &line) } 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; @@ -9196,10 +9710,14 @@ bool TMoverParameters::readMPTDieselEngine(std::string const &line) } 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; + int autoswitch{0}; parser >> autoswitch; MotorParam[idx].AutoSwitch = autoswitch == 1; } @@ -9252,7 +9770,7 @@ bool TMoverParameters::readRList(std::string const &Input) return false; } auto idx = LISTLINE++; - if (idx >= sizeof(RList) / sizeof(TScheme)) + if (idx >= std::size(RList)) { WriteLog("Read RList: number of entries exceeded capacity of the data table"); return false; @@ -9277,7 +9795,7 @@ bool TMoverParameters::readUCList(std::string const &line) cParser parser(line); parser.getTokens(10, false); auto idx = LISTLINE++; - if (idx >= sizeof(UniCtrlList) / sizeof(TUniversalCtrl)) + if (idx >= std::size(UniCtrlList)) { WriteLog("Read UCList: number of entries exceeded capacity of the data table"); return false; @@ -9295,7 +9813,7 @@ bool TMoverParameters::readDList(std::string const &line) cParser parser(line); parser.getTokens(3, false); auto idx = LISTLINE++; - if (idx >= sizeof(RList) / sizeof(TScheme)) + if (idx >= std::size(RList)) { WriteLog("Read DList: number of entries exceeded capacity of the data table"); return false; @@ -9315,7 +9833,7 @@ bool TMoverParameters::readDMList(std::string const &line) WriteLog("Read DMList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - auto idx = LISTLINE++; + ++LISTLINE; double x = 0.0; double y = 0.0; parser >> x >> y; @@ -9335,7 +9853,7 @@ bool TMoverParameters::readV2NMAXList(std::string const &line) WriteLog("Read V2nmaxList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - auto idx = LISTLINE++; + ++LISTLINE; double x = 0.0; double y = 0.0; parser >> x >> y; @@ -9355,7 +9873,7 @@ bool TMoverParameters::readHTCList(std::string const &line) WriteLog("Read HTCList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - auto idx = LISTLINE++; + ++LISTLINE; double x = 0.0; double y = 0.0; parser >> x >> y; @@ -9375,7 +9893,7 @@ bool TMoverParameters::readPmaxList(std::string const &line) WriteLog("Read PmaxList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - auto idx = LISTLINE++; + ++LISTLINE; double x = 0.0; double y = 0.0; parser >> x >> y; @@ -9395,7 +9913,7 @@ bool TMoverParameters::readFFList(std::string const &line) return false; } int idx = LISTLINE++; - if (idx >= sizeof(FFlist) / sizeof(TFFScheme)) + if (idx >= std::size(FFlist)) { WriteLog("Read FList: number of entries exceeded capacity of the data table"); return false; @@ -9415,7 +9933,7 @@ bool TMoverParameters::readFFEDList(std::string const &line) return false; } int idx = LISTLINE++; - if (idx >= sizeof(FFEDlist) / sizeof(TFFScheme)) + if (idx >= std::size(FFEDlist)) { WriteLog("Read FList: number of entries exceeded capacity of the data table"); return false; @@ -9435,7 +9953,7 @@ bool TMoverParameters::readWiperList(std::string const &line) return false; } int idx = LISTLINE++; - if (idx >= sizeof(WiperList) / sizeof(TWiperScheme)) + if (idx >= std::size(WiperList)) { WriteLog("Read WiperList: number of entries exceeded capacity of the data table"); return false; @@ -9452,7 +9970,7 @@ bool TMoverParameters::readDimmerList(std::string const &line) WriteLog("Read DimmerList: arguments missing in line " + std::to_string(LISTLINE + 1)); return false; } - int idx = LISTLINE++; + ++LISTLINE; dimPosition dps; parser >> dps.isHighBeam >> dps.isDimmed >> dps.isOff; @@ -9460,6 +9978,52 @@ bool TMoverParameters::readDimmerList(std::string const &line) 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) { @@ -9471,7 +10035,7 @@ bool TMoverParameters::readWWList(std::string const &line) return false; } int idx = LISTLINE++; - if (idx >= sizeof(DElist) / sizeof(TDEScheme)) + if (idx >= std::size(DElist)) { WriteLog("Read WWList: number of entries exceeded capacity of the data table"); return false; @@ -9505,10 +10069,38 @@ bool TMoverParameters::readLightsList(std::string const &Input) 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) { @@ -9535,42 +10127,43 @@ bool TMoverParameters::readCompressorList(std::string const &Input) // ************************************************************************************************* void TMoverParameters::BrakeValveDecode(std::string const &Valve) { + using enum TBrakeValve; - std::map valvetypes{{"W", TBrakeValve::W}, - {"W_Lu_L", TBrakeValve::W_Lu_L}, - {"W_Lu_XR", TBrakeValve::W_Lu_XR}, - {"W_Lu_VI", TBrakeValve::W_Lu_VI}, - {"K", TBrakeValve::K}, - {"Kg", TBrakeValve::Kg}, - {"Kp", TBrakeValve::Kp}, - {"Kss", TBrakeValve::Kss}, - {"Kkg", TBrakeValve::Kkg}, - {"Kkp", TBrakeValve::Kkp}, - {"Kks", TBrakeValve::Kks}, - {"Hikp1", TBrakeValve::Hikp1}, - {"Hikss", TBrakeValve::Hikss}, - {"Hikg1", TBrakeValve::Hikg1}, - {"KE", TBrakeValve::KE}, - {"SW", TBrakeValve::SW}, - {"EStED", TBrakeValve::EStED}, - {"NESt3", TBrakeValve::NESt3}, - {"ESt3", TBrakeValve::ESt3}, - {"LSt", TBrakeValve::LSt}, - {"ESt4", TBrakeValve::ESt4}, - {"ESt3AL2", TBrakeValve::ESt3AL2}, - {"EP1", TBrakeValve::EP1}, - {"EP2", TBrakeValve::EP2}, - {"M483", TBrakeValve::M483}, - {"CV1_L_TR", TBrakeValve::CV1_L_TR}, - {"CV1", TBrakeValve::CV1}, - {"CV1_R", TBrakeValve::CV1_R}}; + 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 : TBrakeValve::Other; + BrakeValve = lookup != valvetypes.end() ? lookup->second : Other; - if (BrakeValve == TBrakeValve::Other && contains(Valve, "ESt")) + if (BrakeValve == Other && contains(Valve, "ESt")) { - BrakeValve = TBrakeValve::ESt3; + BrakeValve = ESt3; } } @@ -9579,32 +10172,36 @@ void TMoverParameters::BrakeValveDecode(std::string const &Valve) // ************************************************************************************************* void TMoverParameters::BrakeSubsystemDecode() { - BrakeSubsystem = TBrakeSubSystem::ss_None; + using enum TBrakeSubSystem; + BrakeSubsystem = ss_None; switch (BrakeValve) { - case TBrakeValve::W: - case TBrakeValve::W_Lu_L: - case TBrakeValve::W_Lu_VI: - case TBrakeValve::W_Lu_XR: - BrakeSubsystem = TBrakeSubSystem::ss_W; + using enum TBrakeValve; + case W: + case W_Lu_L: + case W_Lu_VI: + case W_Lu_XR: + BrakeSubsystem = ss_W; break; - case TBrakeValve::ESt3: - case TBrakeValve::ESt3AL2: - case TBrakeValve::ESt4: - case TBrakeValve::EP2: - case TBrakeValve::EP1: - BrakeSubsystem = TBrakeSubSystem::ss_ESt; + case ESt3: + case ESt3AL2: + case ESt4: + case EP2: + case EP1: + BrakeSubsystem = ss_ESt; break; - case TBrakeValve::KE: - BrakeSubsystem = TBrakeSubSystem::ss_KE; + case KE: + BrakeSubsystem = ss_KE; break; - case TBrakeValve::CV1: - case TBrakeValve::CV1_L_TR: - BrakeSubsystem = TBrakeSubSystem::ss_Dako; + case CV1: + case CV1_L_TR: + BrakeSubsystem = ss_Dako; break; - case TBrakeValve::LSt: - case TBrakeValve::EStED: - BrakeSubsystem = TBrakeSubSystem::ss_LSt; + case LSt: + case EStED: + BrakeSubsystem = ss_LSt; + break; + default: break; } } @@ -9615,14 +10212,42 @@ void TMoverParameters::BrakeSubsystemDecode() // TDynamicObject::Init() // Po niej wykonywana jest CreateBrakeSys(), ktora jest odpowiednikiem CheckLocomotiveParameters() // ************************************************************************************************* -bool TMoverParameters::LoadFIZ(std::string chkpath) +bool TMoverParameters::LoadFIZ(std::string const &chkpath) { chkPath = chkpath; // assign class path for reloading - const int param_ok = 1; - const int wheels_ok = 2; - const int dimensions_ok = 4; ConversionError = 666; + std::string file = TypeName + ".fiz"; + + WriteLog("LOAD FIZ FROM " + file); + /* + std::ifstream in(file); + if (!in.is_open()) + { + WriteLog("E8 - FIZ FILE NOT EXIST."); + return false; + } + */ + cParser fizparser(file, cParser::buffer_FILE, chkpath); + if (false == fizparser.ok()) + { + WriteLog("E8 - FIZ FILE NOT EXIST."); + return false; + } + + return LoadFIZ_Parse(fizparser); +} + +// reads the vehicle definition from text in the .fiz format, e.g. one made up by a unit test +bool TMoverParameters::LoadFIZ_Text(std::string const &Text) +{ + ConversionError = 666; + cParser fizparser(Text, cParser::buffer_TEXT); + return LoadFIZ_Parse(fizparser); +} + +bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former body of LoadFIZ(), moved as it was; splitting it up is a change of its own +{ LISTLINE = 0; startBPT = false; startMPT = false; @@ -9641,23 +10266,6 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) startDimmerList = false; startLIGHTSLIST = false; startCOMPRESSORLIST = false; - 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; - } ConversionError = 0; @@ -9788,7 +10396,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Param.", inputline)) { startBPT = false; - fizlines.emplace("Param", inputline); + fizlines.try_emplace("Param", inputline); LoadFIZ_Param(inputline); continue; } @@ -9796,7 +10404,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Load:", inputline)) { startBPT = false; - fizlines.emplace("Load", inputline); + fizlines.try_emplace("Load", inputline); LoadFIZ_Load(inputline); continue; } @@ -9804,7 +10412,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Dimensions:", inputline)) { startBPT = false; - fizlines.emplace("Dimensions", inputline); + fizlines.try_emplace("Dimensions", inputline); LoadFIZ_Dimensions(inputline); continue; } @@ -9812,7 +10420,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Wheels:", inputline)) { startBPT = false; - fizlines.emplace("Wheels", inputline); + fizlines.try_emplace("Wheels", inputline); LoadFIZ_Wheels(inputline); continue; } @@ -9820,7 +10428,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Brake:", inputline)) { startBPT = false; - fizlines.emplace("Brake", inputline); + fizlines.try_emplace("Brake", inputline); LoadFIZ_Brake(inputline); continue; } @@ -9829,7 +10437,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) { startBPT = false; - fizlines.emplace("Doors", inputline); + fizlines.try_emplace("Doors", inputline); LoadFIZ_Doors(inputline); continue; } @@ -9838,7 +10446,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) { startBPT = false; - fizlines.emplace("BuffCoupl", inputline); + fizlines.try_emplace("BuffCoupl", inputline); LoadFIZ_BuffCoupl(inputline, 0); continue; } @@ -9847,7 +10455,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) { startBPT = false; - fizlines.emplace("BuffCoupl1", inputline); + fizlines.try_emplace("BuffCoupl1", inputline); LoadFIZ_BuffCoupl(inputline, 1); continue; } @@ -9856,7 +10464,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) { startBPT = false; - fizlines.emplace("BuffCoupl2", inputline); + fizlines.try_emplace("BuffCoupl2", inputline); LoadFIZ_BuffCoupl(inputline, 2); continue; } @@ -9865,7 +10473,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) { startBPT = false; - fizlines.emplace("TurboPos", inputline); + fizlines.try_emplace("TurboPos", inputline); LoadFIZ_TurboPos(inputline); continue; } @@ -9875,7 +10483,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) startBPT = true; LISTLINE = 0; - fizlines.emplace("Cntrl", inputline); + fizlines.try_emplace("Cntrl", inputline); LoadFIZ_Cntrl(inputline); continue; } @@ -9883,7 +10491,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Headlights:", inputline)) { startBPT = false; - fizlines.emplace("Headlights", inputline); + fizlines.try_emplace("Headlights", inputline); LoadFIZ_Headlights(inputline); continue; } @@ -9893,7 +10501,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) startBPT = false; LISTLINE = 0; - fizlines.emplace("Blending", inputline); + fizlines.try_emplace("Blending", inputline); LoadFIZ_Blending(inputline); continue; } @@ -9903,7 +10511,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) startBPT = false; LISTLINE = 0; - fizlines.emplace("DCEMUED", inputline); + fizlines.try_emplace("DCEMUED", inputline); LoadFIZ_DCEMUED(inputline); continue; } @@ -9913,7 +10521,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) startBPT = false; LISTLINE = 0; - fizlines.emplace("SpringBrake", inputline); + fizlines.try_emplace("SpringBrake", inputline); LoadFIZ_SpringBrake(inputline); continue; } @@ -9922,7 +10530,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) { startBPT = false; - fizlines.emplace("Light", inputline); + fizlines.try_emplace("Light", inputline); LoadFIZ_Light(inputline); continue; } @@ -9930,7 +10538,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Security:", inputline)) { startBPT = false; - fizlines.emplace("Security", inputline); + fizlines.try_emplace("Security", inputline); SecuritySystem.load(inputline, Vmax); extract_value(EmergencyBrakeWarningSignal, "EmergencyBrakeWarningSignal", inputline, ""); continue; @@ -9940,7 +10548,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) { startBPT = false; - fizlines.emplace("Clima", inputline); + fizlines.try_emplace("Clima", inputline); LoadFIZ_Clima(inputline); continue; } @@ -9948,7 +10556,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Power:", inputline)) { startBPT = false; - fizlines.emplace("Power", inputline); + fizlines.try_emplace("Power", inputline); LoadFIZ_Power(inputline); continue; } @@ -9956,7 +10564,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("SpeedControl:", inputline)) { startBPT = false; - fizlines.emplace("SpeedControl", inputline); + fizlines.try_emplace("SpeedControl", inputline); LoadFIZ_SpeedControl(inputline); continue; } @@ -9964,7 +10572,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Engine:", inputline)) { startBPT = false; - fizlines.emplace("Engine", inputline); + fizlines.try_emplace("Engine", inputline); LoadFIZ_Engine(inputline); continue; } @@ -9972,7 +10580,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Switches:", inputline)) { startBPT = false; - fizlines.emplace("Switches", inputline); + fizlines.try_emplace("Switches", inputline); LoadFIZ_Switches(inputline); continue; } @@ -9982,7 +10590,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) startBPT = false; startMPT = true; LISTLINE = 0; - fizlines.emplace("MotorParamTable", inputline); + fizlines.try_emplace("MotorParamTable", inputline); LoadFIZ_MotorParamTable(inputline); continue; } @@ -9998,7 +10606,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("Circuit:", inputline)) { startBPT = false; - fizlines.emplace("Circuit", inputline); + fizlines.try_emplace("Circuit", inputline); LoadFIZ_Circuit(inputline); continue; } @@ -10006,7 +10614,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("AI:", inputline)) { startBPT = false; - fizlines.emplace("AI", inputline); + fizlines.try_emplace("AI", inputline); LoadFIZ_AI(inputline); continue; } @@ -10014,7 +10622,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("RList:", inputline)) { startBPT = false; - fizlines.emplace("RList", inputline); + fizlines.try_emplace("RList", inputline); startRLIST = true; LISTLINE = 0; LoadFIZ_RList(inputline); @@ -10024,7 +10632,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("UCList:", inputline)) { startBPT = false; - fizlines.emplace("UCList", inputline); + fizlines.try_emplace("UCList", inputline); startUCLIST = true; LISTLINE = 0; LoadFIZ_UCList(inputline); @@ -10034,7 +10642,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("DList:", inputline)) { startBPT = false; - fizlines.emplace("DList", inputline); + fizlines.try_emplace("DList", inputline); startDLIST = true; LISTLINE = 0; LoadFIZ_DList(inputline); @@ -10044,7 +10652,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("DMList:", inputline)) { startBPT = false; - fizlines.emplace("DMList", inputline); + fizlines.try_emplace("DMList", inputline); startDIZELMOMENTUMLIST = true; LISTLINE = 0; continue; @@ -10053,7 +10661,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("HTCList:", inputline)) { startBPT = false; - fizlines.emplace("HTCList", inputline); + fizlines.try_emplace("HTCList", inputline); startHYDROTCLIST = true; LISTLINE = 0; continue; @@ -10062,7 +10670,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("PmaxList:", inputline)) { startBPT = false; - fizlines.emplace("PmaxList", inputline); + fizlines.try_emplace("PmaxList", inputline); startPMAXLIST = true; LISTLINE = 0; continue; @@ -10071,7 +10679,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("V2NList:", inputline)) { startBPT = false; - fizlines.emplace("V2NList", inputline); + fizlines.try_emplace("V2NList", inputline); startDIZELV2NMAXLIST = true; LISTLINE = 0; continue; @@ -10107,7 +10715,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("WiperList:", inputline)) { startBPT = false; - fizlines.emplace("WiperList", inputline); + fizlines.try_emplace("WiperList", inputline); startWiperList = true; LISTLINE = 0; LoadFIZ_WiperList(inputline); @@ -10120,7 +10728,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) dimPositions.clear(); // uzywamy customowej listy startBPT = false; startDimmerList = true; - fizlines.emplace("DimmerList", inputline); + fizlines.try_emplace("DimmerList", inputline); LoadFIZ_DimmerList(inputline); continue; } @@ -10128,7 +10736,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("LightsList:", inputline)) { startBPT = false; - fizlines.emplace("LightsList", inputline); + fizlines.try_emplace("LightsList", inputline); startLIGHTSLIST = true; LISTLINE = 0; LoadFIZ_LightsList(inputline); @@ -10138,7 +10746,7 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) if (issection("CompressorList:", inputline)) { startBPT = false; - fizlines.emplace("CompressorList", inputline); + fizlines.try_emplace("CompressorList", inputline); startCOMPRESSORLIST = true; LISTLINE = 0; LoadFIZ_CompressorList(inputline); @@ -10245,6 +10853,9 @@ bool TMoverParameters::LoadFIZ(std::string chkpath) 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; @@ -10266,7 +10877,7 @@ void TMoverParameters::LoadFIZ_Param(std::string const &line) extract_value(LightPower, "LightP", line, "0"); { - std::map categories{{"train", 1}, {"road", 2}, {"unimog", 3}, {"ship", 4}, {"airplane,", 8}}; + 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); @@ -10278,7 +10889,7 @@ void TMoverParameters::LoadFIZ_Param(std::string const &line) } { - std::map types{ + std::map> types{ {"pseudodiesel", dt_PseudoDiesel}, {"ezt", dt_EZT}, {"dmu", dt_DMU}, @@ -10361,7 +10972,7 @@ void TMoverParameters::LoadFIZ_Dimensions(std::string const &line) if (Dim.H <= 2.0) { // gdyby nie było parametru, lepsze to niż zero - Floor = Dim.H; + Floor = static_cast(Dim.H); } else { @@ -10463,7 +11074,7 @@ void TMoverParameters::LoadFIZ_Brake(std::string const &line) 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}, + 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; @@ -10479,7 +11090,10 @@ void TMoverParameters::LoadFIZ_Brake(std::string const &line) P2FTrans = 0; } - CntrlPipePress = 5 + 0.001 * (Random(10) - Random(10)); // Ra 2014-07: trochę niedokładności + // 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); @@ -10507,7 +11121,7 @@ void TMoverParameters::LoadFIZ_Brake(std::string const &line) extract_value(HandleUnlock, "HandlePipeUnlockPos", line, "-3"); extract_value(EmergencyCutsOffHandle, "EmergencyCutsOffHandle", line, ""); { - std::map compressorpowers{ + std::map> compressorpowers{ {"Main", 0}, // 1: default, powered by converter, with manual state control {"Converter", 2}, @@ -10518,6 +11132,7 @@ void TMoverParameters::LoadFIZ_Brake(std::string const &line) 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, "")) { @@ -10550,7 +11165,7 @@ void TMoverParameters::LoadFIZ_Brake(std::string const &line) void TMoverParameters::LoadFIZ_Doors(std::string const &line) { - std::map doorcontrols{ + 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 { @@ -10568,6 +11183,8 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &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) @@ -10578,7 +11195,7 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &line) { // 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(Doors.permit_presets.size(), Doors.permit_preset) - 1; + Doors.permit_preset = std::min(static_cast(Doors.permit_presets.size()), Doors.permit_preset) - 1; } } @@ -10590,7 +11207,7 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &line) extract_value(Doors.range, "DoorMaxShiftR", line, ""); extract_value(Doors.range_out, "DoorMaxShiftPlug", line, ""); - std::map doortypes{ + std::map> doortypes{ {"Shift", 1}, {"Rotate", 2}, {"Fold", 3}, @@ -10629,62 +11246,138 @@ void TMoverParameters::LoadFIZ_Doors(std::string const &line) extract_value(DoorsPermitLightBlinking, "DoorsPermitLightBlinking", line, ""); } +namespace +{ + +// the value of an optional key of the line, or the default without it +double optional_value(std::string const &Line, std::string const &Key, double const Default) +{ + auto value{Default}; + extract_value(value, Key, Line, ""); + return value; +} + +// the value of an optional key of the line given in kilo-units, in units; or the default (in units) without it +double optional_kilo_value(std::string const &Line, std::string const &Key, double const Default) +{ + auto value{0.0}; + return extract_value(value, Key, Line, "") && value > 0.0 ? value * 1000.0 : Default; +} + +// the play of a coupling as made, for each kind: a screw coupling is tightened so that the buffers touch, the knuckles of +// an automatic coupler have about a centimetre between them, a chain hangs loose +double default_slack(TCouplerType const Type) +{ + switch (Type) + { + case TCouplerType::Automatic: + return 0.005; + case TCouplerType::Chain: + return 0.05; + default: + return 0.0; + } +} + +// the parameters of the physical model of the coupling (couplerphysics in eu07.ini, see couplerphysics.h), taken from +// those of the legacy model, and the optional keys of the .fiz for what the legacy model doesn't have: +// Slack [m] the play of the coupling of this end, negative for a screw coupling tightened to press the buffers in +// ProgB, ProgC [-] progression of the buffers and of the draw gear, 0 linear, up to 0.9 +// UnloadB, UnloadC [-] force of the unloading curve of the buffers and of the draw gear to that of the loading one +// FyieldC [kN] the force past which the link stretches for good; DbreakC [m] the elongation at which it breaks +// kL [kN/m] stiffness of the steel parts past the travel of the springs; FcrushB [kN] the buffers give under it +// RestitutionSolid [-] coefficient of restitution of a hit on the springs gone solid +coupler_physics::end_parameters coupler_physics_parameters(TCoupling const &Coupler, std::string const &Line) +{ + coupler_physics::end_parameters parameters; + parameters.buffers = {Coupler.SpringKB, Coupler.DmaxB, std::clamp(optional_value(Line, "ProgB", 0.5), 0.0, 0.9)}; + parameters.draw_gear = {Coupler.SpringKC, Coupler.DmaxC, std::clamp(optional_value(Line, "ProgC", 0.3), 0.0, 0.9)}; + // only a screw coupling can be tightened to press the buffers in, and not past their travel + auto const tightest{Coupler.CouplerType == TCouplerType::Screw ? -Coupler.DmaxB : 0.0}; + parameters.slack = std::max(optional_value(Line, "Slack", default_slack(Coupler.CouplerType)), tightest); + // the legacy model sprang back at beta of the force it was loaded with + auto const unloading{Coupler.beta > 0.0 && Coupler.beta < 1.0 ? Coupler.beta : 0.5}; + parameters.buffers_unloading = std::clamp(optional_value(Line, "UnloadB", unloading), 0.05, 1.0); + parameters.draw_gear_unloading = std::clamp(optional_value(Line, "UnloadC", unloading), 0.05, 1.0); + // as much as the legacy model had + parameters.damping = CouplerTune * (Coupler.FmaxC + Coupler.FmaxB) * std::max(Coupler.beta, 0.0); + + // FmaxC is the rated breaking force of the coupling + auto const ultimate{std::max(Coupler.FmaxC, 1.0)}; + auto const yield{std::min(optional_kilo_value(Line, "FyieldC", 0.8 * ultimate), ultimate)}; + auto const elongation{std::max(optional_value(Line, "DbreakC", 0.02), 0.001)}; + parameters.link = {yield, ultimate, std::max((ultimate - yield) / elongation, 1.0), Coupler.CouplerType != TCouplerType::Articulated}; + // the steel parts give a few millimetres under the rated force + parameters.link_stiffness = optional_kilo_value(Line, "kL", ultimate / 0.003); + parameters.crush_force = optional_kilo_value(Line, "FcrushB", 2.5 * std::max(Coupler.FmaxB, Coupler.FmaxC)); + parameters.solid_restitution = std::clamp(optional_value(Line, "RestitutionSolid", parameters.solid_restitution), 0.05, 0.95); + return parameters; +} + +void scale_strength(coupler_physics::link_strength &Link, double const Factor) +{ + Link.yield *= Factor; + Link.ultimate *= Factor; +} + +} // namespace + void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Index) { - TCoupling *coupler; + TCoupling *thiscoupler; if (Index == 2) { - coupler = &Couplers[1]; + thiscoupler = &Couplers[1]; } else { - coupler = &Couplers[0]; + thiscoupler = &Couplers[0]; } - std::map couplertypes{ + 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)); - coupler->CouplerType = lookup != couplertypes.end() ? lookup->second : TCouplerType::NoCoupler; + thiscoupler->CouplerType = lookup != couplertypes.end() ? lookup->second : TCouplerType::NoCoupler; - extract_value(coupler->SpringKC, "kC", line, ""); - extract_value(coupler->DmaxC, "DmaxC", line, ""); - extract_value(coupler->FmaxC, "FmaxC", line, ""); - extract_value(coupler->SpringKB, "kB", line, ""); - extract_value(coupler->DmaxB, "DmaxB", line, ""); - extract_value(coupler->FmaxB, "FmaxB", line, ""); - extract_value(coupler->beta, "beta", line, ""); - extract_value(coupler->AutomaticCouplingFlag, "AutomaticFlag", line, ""); - extract_value(coupler->AllowedFlag, "AllowedFlag", line, ""); - if (coupler->AllowedFlag < 0) + 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) { - coupler->AllowedFlag = -coupler->AllowedFlag | coupling::permanent; + thiscoupler->AllowedFlag = -thiscoupler->AllowedFlag | coupling::permanent; } - extract_value(coupler->PowerCoupling, "PowerCoupling", line, ""); - extract_value(coupler->PowerFlag, "PowerFlag", line, ""); - extract_value(coupler->control_type, "ControlType", line, ""); + extract_value(thiscoupler->PowerCoupling, "PowerCoupling", line, ""); + extract_value(thiscoupler->PowerFlag, "PowerFlag", line, ""); + extract_value(thiscoupler->control_type, "ControlType", line, ""); - if (coupler->CouplerType != TCouplerType::NoCoupler && coupler->CouplerType != TCouplerType::Bare && coupler->CouplerType != TCouplerType::Articulated) + if (thiscoupler->CouplerType != TCouplerType::NoCoupler && thiscoupler->CouplerType != TCouplerType::Bare && thiscoupler->CouplerType != TCouplerType::Articulated) { - coupler->SpringKC *= 1000; - coupler->FmaxC *= 1000; - coupler->SpringKB *= 1000; - coupler->FmaxB *= 1000; + thiscoupler->SpringKC *= 1000; + thiscoupler->FmaxC *= 1000; + thiscoupler->SpringKB *= 1000; + thiscoupler->FmaxB *= 1000; } - else if (coupler->CouplerType == TCouplerType::Bare) + else if (thiscoupler->CouplerType == TCouplerType::Bare) { - coupler->SpringKC = 50.0 * Mass + Ftmax / 0.05; - coupler->DmaxC = 0.05; - coupler->FmaxC = 100.0 * Mass + 2 * Ftmax; - coupler->SpringKB = 60.0 * Mass + Ftmax / 0.05; - coupler->DmaxB = 0.05; - coupler->FmaxB = 50.0 * Mass + 2.0 * Ftmax; - coupler->beta = 0.3; + 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 (coupler->CouplerType == TCouplerType::Articulated) + else if (thiscoupler->CouplerType == TCouplerType::Articulated) { /* coupler->SpringKC = 60.0 * Mass + 1000; @@ -10695,20 +11388,33 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde coupler->FmaxB = 4000000.0 + 2.0 * Ftmax; coupler->beta = 0.55; */ - coupler->SpringKC = 4500 * 1000; - coupler->DmaxC = 0.05; - coupler->FmaxC = 850 * 1000; - coupler->SpringKB = 9200 * 1000; - coupler->DmaxB = 0.05; - coupler->FmaxB = 320 * 1000; - coupler->beta = 0.55; + thiscoupler->SpringKC = 4500 * 1000; + thiscoupler->FmaxC = 850 * 1000; + thiscoupler->SpringKB = 9200 * 1000; + thiscoupler->FmaxB = 320 * 1000; + thiscoupler->beta = 0.55; + // the spring force is taken up to Dmax only, past it the vehicles collide (CollisionDetect()); so the joint + // carries the full FmaxC either way before it gives. with 0.05 m it carried 225 kN, short of what a loaded + // articulated wagon in a freight train takes, which then collided at every step (eu07/maszyna#553) + thiscoupler->DmaxC = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKC); + thiscoupler->DmaxB = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKB); } + thiscoupler->physics = coupler_physics_parameters(*thiscoupler, line); + if (Index == 0) { // 0 indicates single entry for both couplers Couplers[1] = Couplers[0]; } + // each coupling as made is a little stronger than its rated force, a different one at each end + for (int end = end::front; end <= end::rear; ++end) + { + if (Index == 0 || end == (Index == 2 ? end::rear : end::front)) + { + scale_strength(Couplers[end].physics.link, coupler_physics::strength_scatter(Name, end)); + } + } } void TMoverParameters::LoadFIZ_TurboPos(std::string const &Input) @@ -10721,22 +11427,24 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) { { - std::map brakesystems{{"Pneumatic", TBrakeSystem::Pneumatic}, {"ElectroPneumatic", TBrakeSystem::ElectroPneumatic}}; + using enum TBrakeSystem; + std::map> brakesystems{{"Pneumatic", Pneumatic}, {"ElectroPneumatic", ElectroPneumatic}}; auto lookup = brakesystems.find(extract_value("BrakeSystem", line)); - BrakeSystem = lookup != brakesystems.end() ? lookup->second : TBrakeSystem::Individual; + BrakeSystem = lookup != brakesystems.end() ? lookup->second : Individual; } if (BrakeSystem != TBrakeSystem::Individual) { + using enum TBrakeHandle; extract_value(BrakeCtrlPosNo, "BCPN", line, ""); for (int idx = 0; idx < 4; ++idx) { - extract_value(BrakeDelay[idx], "BDelay" + std::to_string(idx + 1), line, ""); + extract_value(BrakeDelay[idx], std::format("BDelay{}", idx + 1), line, ""); } // brakedelays, brakedelayflag { - std::map brakedelays{{"GPR", bdelay_G + bdelay_P + bdelay_R}, + std::map> brakedelays{{"GPR", bdelay_G + bdelay_P + bdelay_R}, {"PR", bdelay_P + bdelay_R}, {"GP", bdelay_G + bdelay_P}, {"R", bdelay_R}, @@ -10744,7 +11452,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) {"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::map> brakedelayflags{{"R", bdelay_R}, {"P", bdelay_P}, {"G", bdelay_G}}; std::string brakedelay; extract_value(brakedelay, "BrakeDelays", line, ""); auto lookup = brakedelays.find(brakedelay); @@ -10754,18 +11462,18 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) } // 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}}; + 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", TBrakeHandle::FV4a}, {"test", TBrakeHandle::testH}, {"D2", TBrakeHandle::D2}, {"MHZ_EN57", TBrakeHandle::MHZ_EN57}, {"MHZ_K5P", TBrakeHandle::MHZ_K5P}, - {"MHZ_K8P", TBrakeHandle::MHZ_K8P}, {"MHZ_6P", TBrakeHandle::MHZ_6P}, {"M394", TBrakeHandle::M394}, {"Knorr", TBrakeHandle::Knorr}, {"Westinghouse", TBrakeHandle::West}, - {"FVel6", TBrakeHandle::FVel6}, {"FVE408", TBrakeHandle::FVE408}, {"St113", TBrakeHandle::St113}}; + 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 : TBrakeHandle::NoHandle; + BrakeHandle = lookup != brakehandles.end() ? lookup->second : NoHandle; } extract_value(Handle_AutomaticOverload, "HAO", line, ""); extract_value(Handle_ManualOverload, "HMO", line, ""); @@ -10775,9 +11483,9 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) extract_value(Handle_OverloadPressureDecrease, "OPD", line, ""); // brakelochandle { - std::map locbrakehandles{{"FD1", TBrakeHandle::FD1}, {"Knorr", TBrakeHandle::Knorr}, {"Westinghouse", TBrakeHandle::West}}; + std::map> locbrakehandles{{"FD1", FD1}, {"Knorr", Knorr}, {"Westinghouse", West}}; auto lookup = locbrakehandles.find(extract_value("LocBrakeHandle", line)); - BrakeLocHandle = lookup != locbrakehandles.end() ? lookup->second : TBrakeHandle::NoHandle; + BrakeLocHandle = lookup != locbrakehandles.end() ? lookup->second : NoHandle; } // mbpm @@ -10817,9 +11525,10 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // localbrake { - std::map localbrakes{{"ManualBrake", TLocalBrake::ManualBrake}, {"PneumaticBrake", TLocalBrake::PneumaticBrake}, {"HydraulicBrake", TLocalBrake::HydraulicBrake}}; + 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 : TLocalBrake::NoBrake; + LocalBrake = lookup != localbrakes.end() ? lookup->second : NoBrake; } // mbrake extract_value(MBrake, "ManualBrake", line, ""); @@ -10827,9 +11536,19 @@ void TMoverParameters::LoadFIZ_Cntrl(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}}; + 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, ""); @@ -10852,8 +11571,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) extract_value(ScndInMain, "SCIM", line, ""); extract_value(MainCtrlMaxDirChangePos, "DirChangeMaxPos", line, ""); - auto const autorelay{ToLower(extract_value("AutoRelay", line))}; - if (autorelay == "optional") + if (auto const autorelay{ToLower(extract_value("AutoRelay", line))}; autorelay == "optional") { AutoRelayType = 2; } @@ -10873,8 +11591,19 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) 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, ""); @@ -10903,7 +11632,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) extract_value(shouldHoldBatteryButton, "SBBBH", line, ""); extract_value(BatteryButtonHoldTime, "BBHT", line, ""); - std::map starts{{"Disabled", start_t::disabled}, {"Manual", start_t::manual}, {"Automatic", start_t::automatic}, {"Mixed", start_t::manualwithautofallback}, + std::map> starts{{"Disabled", start_t::disabled}, {"Manual", start_t::manual}, {"Automatic", start_t::automatic}, {"Mixed", start_t::manualwithautofallback}, {"Battery", start_t::battery}, {"Converter", start_t::converter}, {"Direction", start_t::direction}}; // main circuit @@ -10912,6 +11641,7 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) auto lookup = starts.find(extract_value("MainStart", line)); MainsStart = lookup != starts.end() ? lookup->second : start_t::manual; } + extract_value(PantographsRequireMains, "PantRequiresMain", line, ""); // battery { auto lookup = starts.find(extract_value("BatteryStart", line)); @@ -10976,8 +11706,17 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // traction motor fans { auto lookup = starts.find(extract_value("MotorBlowersStart", line)); - MotorBlowers[end::front].start_type = MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : start_t::manual; + MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : start_t::manual; + MotorBlowers[end::front].start_type = MotorBlowers[end::rear].start_type; } + // what else the line contactors need to close + { + std::map> const interlocks{{"Converter", line_contactors_interlock::converter}, + {"MotorBlowers", line_contactors_interlock::motor_blowers}}; + auto lookup = interlocks.find(extract_value("LineContactorsInterlock", line)); + LineContactorsInterlock = lookup != interlocks.end() ? lookup->second : line_contactors_interlock::none; + } + extract_value(LouvresOpenPressure, "LouvresOpenPressure", line, ""); // compartment lights { auto lookup = starts.find(extract_value("CompartmentLightsStart", line)); @@ -10986,14 +11725,15 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) // ground relay { auto lookup = starts.find(extract_value("GroundRelayStart", line)); - GroundRelayStart = lookup != starts.end() ? lookup->second : TrainType == dt_EZT ? start_t::automatic : start_t::manual; + auto const defaultstart{TrainType == dt_EZT ? start_t::automatic : start_t::manual}; + GroundRelayStart = lookup != starts.end() ? lookup->second : defaultstart; } // converter overload relay { auto lookup = starts.find(extract_value("ConverterOverloadRelayStart", line)); - ConverterOverloadRelayStart = lookup != starts.end() ? lookup->second : - TrainType == dt_EZT ? start_t::converter : // relay activates when converter is switched off - start_t::manual; + // the relay of a multiple unit activates when the converter is switched off + auto const defaultstart{TrainType == dt_EZT ? start_t::converter : start_t::manual}; + ConverterOverloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart; } } @@ -11024,7 +11764,7 @@ void TMoverParameters::LoadFIZ_DCEMUED(std::string const &line) void TMoverParameters::LoadFIZ_SpringBrake(std::string const &line) { - double vol; + double vol{1.0}; extract_value(vol, "Volume", line, "1"); if (!SpringBrake.Cylinder) SpringBrake.Cylinder = std::make_shared(); @@ -11056,7 +11796,7 @@ void TMoverParameters::LoadFIZ_Light(std::string const &line) extract_value(NominalVoltage, "Volt", line, ""); extract_value(BatteryVoltage, "LMaxVoltage", line, ""); - NominalBatteryVoltage = BatteryVoltage; + NominalBatteryVoltage = static_cast(BatteryVoltage); } void TMoverParameters::LoadFIZ_Clima(std::string const &line) @@ -11133,9 +11873,9 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) { EngineType = LoadFIZ_EngineDecode(extract_value("EngineType", Input)); + extract_value(JointEngineStart, "JointEngineStart", Input, ""); - std::string transmission = extract_value("Trans", Input); - if (false == transmission.empty()) + 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 @@ -11342,6 +12082,9 @@ void TMoverParameters::LoadFIZ_Engine(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, ""); @@ -11367,7 +12110,7 @@ void TMoverParameters::LoadFIZ_Engine(std::string const &Input) // water heater extract_value(WaterHeater.config.temp_min, "HeaterMinTemperature", Input, ""); extract_value(WaterHeater.config.temp_max, "HeaterMaxTemperature", Input, ""); - float pf; + float pf{ 1235.f }; extract_value(pf, "NominalCoolingPower", Input, "1235"); dizel_heat.powerfactor = 1235 / pf; } @@ -11387,6 +12130,7 @@ 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); @@ -11400,7 +12144,7 @@ void TMoverParameters::LoadFIZ_Switches(std::string const &Input) { auto &presets{PantsPreset.first}; extract_value(presets, "PantographPresets", Input, "0|1|3|2"); - presets.erase(std::remove(std::begin(presets), std::end(presets), '|'), std::end(presets)); + std::erase(presets, '|'); } } @@ -11450,6 +12194,7 @@ 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, ""); } @@ -11459,8 +12204,7 @@ void TMoverParameters::LoadFIZ_RList(std::string const &Input) extract_value(RlistSize, "Size", Input, ""); - auto const venttype{ToLower(extract_value("RVent", Input))}; - if (venttype == "automatic") + if (auto const venttype{ToLower(extract_value("RVent", Input))}; venttype == "automatic") { RVentType = 2; @@ -11492,6 +12236,8 @@ void TMoverParameters::LoadFIZ_UCList(std::string const &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) @@ -11557,7 +12303,7 @@ void TMoverParameters::LoadFIZ_CompressorList(std::string const &Input) extract_value(CompressorListDefPos, "Default", Input, ""); } -void TMoverParameters::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const Prefix, std::string const &Line) +void TMoverParameters::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const &Prefix, std::string const &Line) { switch (Powerparameters.SourceType) @@ -11581,8 +12327,7 @@ void TMoverParameters::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparamete // prime mover for the generator auto &generatorparameters{Powerparameters.EngineGenerator}; - auto const enginetype{LoadFIZ_EngineDecode(extract_value(Prefix + "GeneratorEngine", Line))}; - if (enginetype == TEngineType::Main) + if (auto const enginetype{LoadFIZ_EngineDecode(extract_value(Prefix + "GeneratorEngine", Line))}; enginetype == TEngineType::Main) { generatorparameters.engine_revolutions = &enrot; } @@ -11678,51 +12423,53 @@ void TMoverParameters::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparamete } } -TPowerType TMoverParameters::LoadFIZ_PowerDecode(std::string const &Power) +TPowerType TMoverParameters::LoadFIZ_PowerDecode(std::string const &Powertype) const { + using enum TPowerType; - std::map powertypes{ - {"BioPower", TPowerType::BioPower}, {"MechPower", TPowerType::MechPower}, {"ElectricPower", TPowerType::ElectricPower}, {"SteamPower", TPowerType::SteamPower}}; - auto lookup = powertypes.find(Power); - return lookup != powertypes.end() ? lookup->second : TPowerType::NoPower; + 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) +TPowerSource TMoverParameters::LoadFIZ_SourceDecode(std::string const &Source) const { + using enum TPowerSource; - std::map powersources{{"Transducer", TPowerSource::Transducer}, {"Generator", TPowerSource::Generator}, - {"Accu", TPowerSource::Accumulator}, // legacy compatibility leftover. TODO: check if we can get rid of it - {"Accumulator", TPowerSource::Accumulator}, {"CurrentCollector", TPowerSource::CurrentCollector}, - {"PowerCable", TPowerSource::PowerCable}, {"Heater", TPowerSource::Heater}, - {"Internal", TPowerSource::InternalSource}, {"Main", TPowerSource::Main}}; + 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 : TPowerSource::NotDefined; + return lookup != powersources.end() ? lookup->second : NotDefined; } -TEngineType TMoverParameters::LoadFIZ_EngineDecode(std::string const &Engine) +TEngineType TMoverParameters::LoadFIZ_EngineDecode(std::string const &Engine) const { + using enum TEngineType; - std::map enginetypes{{"ElectricSeriesMotor", TEngineType::ElectricSeriesMotor}, - {"DieselEngine", TEngineType::DieselEngine}, - {"SteamEngine", TEngineType::SteamEngine}, - {"WheelsDriven", TEngineType::WheelsDriven}, - {"Dumb", TEngineType::Dumb}, - {"DieselElectric", TEngineType::DieselElectric}, - {"DumbDE", TEngineType::DieselElectric}, - {"ElectricInductionMotor", TEngineType::ElectricInductionMotor}, - {"Main", TEngineType::Main}}; + 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 : TEngineType::None; + return lookup != enginetypes.end() ? lookup->second : None; } // ************************************************************************************************* // Q: 20160717 // ************************************************************************************************* -bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int Dir) +bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) { WriteLog("check locomotive parameters..."); - int b; bool OK = true; AutoRelayFlag = AutoRelayType == 1; @@ -11740,6 +12487,14 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int Dir) 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) @@ -11749,9 +12504,8 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int Dir) // WriteLogSS("aa ok", BoolToYN(OK)); } - if (BrakeSystem == TBrakeSystem::Individual) - if (BrakeSubsystem != TBrakeSubSystem::ss_None) - OK = false; //! + if (BrakeSystem == TBrakeSystem::Individual && BrakeSubsystem != TBrakeSubSystem::ss_None) + OK = false; //! if (BrakeVVolume == 0 && MaxBrakePress[3] > 0 && BrakeSystem != TBrakeSystem::Individual) { @@ -11860,35 +12614,36 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int Dir) switch (BrakeHandle) { - case TBrakeHandle::FV4a: + using enum TBrakeHandle; + case FV4a: Handle = std::make_shared(); break; - case TBrakeHandle::MHZ_EN57: - case TBrakeHandle::MHZ_K8P: + case MHZ_EN57: + case MHZ_K8P: Handle = std::make_shared(); break; - case TBrakeHandle::FVel6: + case FVel6: Handle = std::make_shared(); break; - case TBrakeHandle::FVE408: + case FVE408: Handle = std::make_shared(); break; - case TBrakeHandle::testH: + case testH: Handle = std::make_shared(); break; - case TBrakeHandle::M394: + case M394: Handle = std::make_shared(); break; - case TBrakeHandle::Knorr: + case Knorr: Handle = std::make_shared(); break; - case TBrakeHandle::St113: + case St113: Handle = std::make_shared(); break; - case TBrakeHandle::MHZ_K5P: + case MHZ_K5P: Handle = std::make_shared(); break; - case TBrakeHandle::MHZ_6P: + case MHZ_6P: Handle = std::make_shared(); break; default: @@ -12064,9 +12819,9 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int Dir) BrakeOpModeFlag = bom_PN; // yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)% - int DefBrakeTable[8] = {15, 4, 25, 25, 13, 3, 12, 2}; + std::array const DefBrakeTable{15, 4, 25, 25, 13, 3, 12, 2}; - for (b = 1; b < 4; b++) + for (int b = 1; b < 4; b++) { if (BrakeDelay[b] == 0) BrakeDelay[b] = DefBrakeTable[b]; @@ -12107,7 +12862,7 @@ bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int Dir) // Q: 20160714 // Wstawia komendę z parametrem, od sprzęgu i w lokalizacji do pojazdu // ************************************************************************************************* -void TMoverParameters::PutCommand(std::string NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation) +void TMoverParameters::PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation) { CommandLast = NewCommand; // zapamiętanie komendy @@ -12122,7 +12877,7 @@ void TMoverParameters::PutCommand(std::string NewCommand, double NewValue1, doub // Q: 20160714 // Pobiera komendę z parametru funkcji oraz wartość zmiennej jako return // ************************************************************************************************* -double TMoverParameters::GetExternalCommand(std::string &Command) +double TMoverParameters::GetExternalCommand(std::string &Command) const { Command = CommandOut; return ValueOut; @@ -12132,7 +12887,7 @@ double TMoverParameters::GetExternalCommand(std::string &Command) // Q: 20160714 // Ustawienie komendy wraz z parametrami // ************************************************************************************************* -bool TMoverParameters::SetInternalCommand(std::string NewCommand, double NewValue1, double NewValue2, int const Couplertype) +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) @@ -12154,7 +12909,7 @@ bool TMoverParameters::SetInternalCommand(std::string NewCommand, double NewValu // 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 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 @@ -12163,24 +12918,21 @@ bool TMoverParameters::SendCtrlToNext(std::string const CtrlCommand, double cons // 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ł - if (OK) + // musi być wybrana niezerowa kabina + if (OK && Couplers[d].Connected != nullptr && TestFlag(Couplers[d].CouplingFlag, Couplertype)) { - // musi być wybrana niezerowa kabina - if (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 - } + 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; @@ -12197,15 +12949,16 @@ bool TMoverParameters::SendCtrlToNext(std::string const CtrlCommand, double cons // 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 Command, double CValue1, double CValue2, int const Couplertype) +bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype) { bool OK{false}; if (Command == "MainCtrl") { - if (MainCtrlPosNo >= floor(CValue1)) + // sent as MainCtrlPosForCoupled(), passed on unchanged + if (auto const position{MainCtrlPosFromCoupled(static_cast(floor(CValue1)))}; MainCtrlPosNo >= position) { - MainCtrlPos = static_cast(floor(CValue1)); + MainCtrlPos = position; if (DelayCtrlFlag) { if (LastRelayTime >= InitialCtrlDelay && MainCtrlPos == 1) @@ -12249,7 +13002,7 @@ bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CV if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) temp1 = 0; Hamulec->SetEPS(temp1); - TUHEX_StageActual = CValue1; + TUHEX_StageActual = static_cast(CValue1); TUHEX_Active = TUHEX_StageActual > 0; if (CValue1 < 0.001) DynamicBrakeEMUStatus = true; @@ -12259,7 +13012,7 @@ bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CV } // youby - odluzniacz hamulcow, przyda sie else if (Command == "BrakeReleaser") { - OK = BrakeReleaser(Round(CValue1)); // samo się przesyła dalej + OK = BrakeReleaser(static_cast(Round(CValue1))); // samo się przesyła dalej // OK:=SendCtrlToNext(command,CValue1,CValue2); //to robiło kaskadę 2^n } else if (Command == "WaterPumpBreakerSwitch") @@ -12470,7 +13223,7 @@ bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CV } else if (Command == "RelayReset") { - RelayReset(CValue1, range_t::local); + RelayReset(static_cast(CValue1), range_t::local); OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else if (Command == "ConverterSwitch") /*NBMX*/ @@ -12508,14 +13261,13 @@ bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CV else if (Command == "DoorPermit") { - auto const left{CValue2 > 0 ? 1 : 2}; - auto const right{3 - left}; + auto const leftside{CValue2 > 0 ? 1 : 2}; - if (std::abs(static_cast(CValue1)) & right) + if (auto const rightside{3 - leftside}; std::abs(static_cast(CValue1)) & rightside) { PermitDoors_(side::right, CValue1 > 0); } - if (std::abs(static_cast(CValue1)) & left) + if (std::abs(static_cast(CValue1)) & leftside) { PermitDoors_(side::left, CValue1 > 0); } @@ -12524,50 +13276,42 @@ bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CV } else if (Command == "DoorOpen") /*NBMX*/ { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - if (Doors.open_control == control_t::conductor || Doors.open_control == control_t::driver || Doors.open_control == control_t::mixed) + // ignore remote command if the door is only operated locally + if ((Doors.open_control == control_t::conductor || Doors.open_control == control_t::driver || Doors.open_control == control_t::mixed) && (Power24vIsAvailable || Power110vIsAvailable)) { - // ignore remote command if the door is only operated locally - if (Power24vIsAvailable || Power110vIsAvailable) + + auto const leftside{CValue2 > 0 ? 1 : 2}; + + if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) { - - auto const left{CValue2 > 0 ? 1 : 2}; - auto const right{3 - left}; - - if (static_cast(CValue1) & right) - { - Doors.instances[side::right].remote_open = true; - Doors.instances[side::right].remote_close = false; - } - if (static_cast(CValue1) & left) - { - Doors.instances[side::left].remote_open = true; - Doors.instances[side::left].remote_close = false; - } + Doors.instances[side::right].remote_open = true; + Doors.instances[side::right].remote_close = false; + } + if (static_cast(CValue1) & leftside) + { + Doors.instances[side::left].remote_open = true; + Doors.instances[side::left].remote_close = false; } } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); } else if (Command == "DoorClose") /*NBMX*/ { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - if (Doors.close_control == control_t::conductor || Doors.close_control == control_t::driver || Doors.close_control == control_t::mixed) + // ignore remote command if the door is only operated locally + if ((Doors.close_control == control_t::conductor || Doors.close_control == control_t::driver || Doors.close_control == control_t::mixed) && (Power24vIsAvailable || Power110vIsAvailable)) { - // ignore remote command if the door is only operated locally - if (Power24vIsAvailable || Power110vIsAvailable) + + auto const leftside{CValue2 > 0 ? 1 : 2}; + + if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) { - - auto const left{CValue2 > 0 ? 1 : 2}; - auto const right{3 - left}; - - if (static_cast(CValue1) & right) - { - Doors.instances[side::right].remote_close = true; - Doors.instances[side::right].remote_open = false; - } - if (static_cast(CValue1) & left) - { - Doors.instances[side::left].remote_close = true; - Doors.instances[side::left].remote_open = false; - } + Doors.instances[side::right].remote_close = true; + Doors.instances[side::right].remote_open = false; + } + if (static_cast(CValue1) & leftside) + { + Doors.instances[side::left].remote_close = true; + Doors.instances[side::left].remote_open = false; } } OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); @@ -12598,9 +13342,8 @@ bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CV 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)}; - auto const reversed{inputcab != (CabActive != -1 ? 1 : 0)}; - if (reversed) + 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 @@ -12643,8 +13386,7 @@ bool TMoverParameters::RunCommand(std::string Command, double CValue1, double CV } else if (Command == "BrakeDelay") { - auto const brakesetting = static_cast(std::floor(CValue1)); - if (true == Hamulec->SetBDF(brakesetting)) + if (auto const brakesetting = static_cast(std::floor(CValue1)); true == Hamulec->SetBDF(brakesetting)) { BrakeDelayFlag = brakesetting; OK = true; @@ -12765,7 +13507,7 @@ bool TMoverParameters::RunInternalCommand() // ************************************************************************************************* double TMoverParameters::ShowCurrentP(int AmpN) const { - int b, Bn; + int Bn; bool Grupowy; // ClearPendingExceptions; @@ -12789,11 +13531,10 @@ double TMoverParameters::ShowCurrentP(int AmpN) const else // pobor pradu jezeli niema mocy { int current = 0; - for (b = 0; b < 2; b++) + for (int b = 0; b < 2; b++) // with Couplers[b] do - if (TestFlag(Couplers[b].CouplingFlag, coupling::control)) - if (Couplers[b].Connected->Power > 0.01) - current = static_cast(Couplers[b].Connected->ShowCurrent(AmpN)); + if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01) + current = static_cast(Couplers[b].Connected->ShowCurrent(AmpN)); return current; } } @@ -12803,8 +13544,7 @@ bool TMoverParameters::reload_FIZ() WriteLog("[DEV] Reloading FIZ for " + Name); // pause simulation Global.iPause |= 0b1000; - bool result = LoadFIZ(chkPath); - if (result == true) + if (bool result = LoadFIZ(chkPath); result == true) { // jesli sie udalo przeladowac FIZ Global.iPause &= 0b0111; diff --git a/McZapkie/Oerlikon_ESt.cpp b/McZapkie/Oerlikon_ESt.cpp index 9559d3052..0717eff5d 100644 --- a/McZapkie/Oerlikon_ESt.cpp +++ b/McZapkie/Oerlikon_ESt.cpp @@ -16,6 +16,11 @@ Copyright (C) 2007-2014 Maciej Cierniak #include "Oerlikon_ESt.h" #include "utilities/utilities.h" +// wstepny nacisk sprezyn na glowny przyrzad rozrzadczy, wyrazony jako roznica cisnien ZS - PG [bar] +static double const dPSprezyny = 0.21; +// najmniejszy stopien hamowania w cylindrze [bar] (tablica 3-9, proby 12 i 22: 0,25-0,30) +static double const pStopnia = 0.28; + double d2A( double const d ) { return d * d * 0.7854 / 1000.0; @@ -211,17 +216,18 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr double dV{ 0.0 }; double dV1{ 0.0 }; - double const nastG = static_cast(BrakeDelayFlag & bdelay_G); + auto const nastG = static_cast(BrakeDelayFlag & bdelay_G); // sprawdzanie stanu CheckState(BCP, dV1); CheckReleaser(dt); // luzowanie + double const cel{ CelBCP( CVP, VVP ) }; if ((BrakeStatus & b_hld) == b_off) dV = PF(0.0, BCP, Nozzles[dTO] * nastG + (1.0 - nastG) * Nozzles[dOO]) - * dt * (0.1 + 4.9 * std::min(0.2, BCP - ((CVP - 0.05 - VVP) * BVM + 0.1))); + * dt * (0.1 + 4.9 * std::min(0.2, BCP - (cel > 0.0 ? cel + 0.1 : 0.0))); // bez stopnia luzuje do zera else dV = 0.0; // BrakeCyl.Flow(-dV); @@ -229,7 +235,7 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr if ( (BrakeStatus & b_on) == b_on && Przekladniki[1]->P() * HBG300 < MaxBP ) dV = PF( BVP, BCP, Nozzles[dTN] * (nastG + 2.0 * (BCP < Podskok ? 1.0 : 0.0)) + Nozzles[dON] * (1.0 - nastG) ) - * dt * (0.1 + 4.9 * std::min( 0.2, (CVP - 0.05 - VVP) * BVM - BCP ) ); + * dt * (0.1 + 4.9 * std::min( 0.2, cel - BCP ) ); else dV = 0; // BrakeCyl.Flow(-dV); @@ -294,8 +300,9 @@ double TNESt3::GetPF( double const PP, double const dt, double const Vel ) // pr return dV - dV1; } -void TNESt3::EStParams( double const i_crc ) // parametry charakterystyczne dla ESt +void TNESt3::EStParams( double const /*i_crc*/ ) const // parametry charakterystyczne dla ESt { + // no effect for this device type } void TNESt3::Init( double const PP, double const HPP, double const LPP, double const BP, int const BDF ) @@ -312,18 +319,31 @@ void TNESt3::Init( double const PP, double const HPP, double const LPP, double c Miedzypoj->CreateCap(5.0); Miedzypoj->CreatePress(PP); - BVM = 1.0 / (HPP - 0.05 - LPP) * MaxBP; + BVM = 1.0 / (HPP - dPSprezyny - LPP) * MaxBP; BrakeDelayFlag = BDF; Zamykajacy = false; - if ( typeid(*FM) == typeid(TDisk1) || typeid(*FM) == typeid(TDisk2) ) // jesli zeliwo to schodz + auto const &frictionmaterial { *FM }; + auto const &frictionmaterialtype { typeid( frictionmaterial ) }; + if ( frictionmaterialtype == typeid(TDisk1) || frictionmaterialtype == typeid(TDisk2) ) // jesli zeliwo to schodz RapidStaly = true; else RapidStaly = false; } +double TNESt3::GetRapidRatio(double const Vel) const +{ + // ESt3 has no rapid relay, and with disc brakes the rapid step stays engaged at all speeds + if( ( PrzekRapid == nullptr ) || RapidStaly ) { + return 1.0; + } + // a braking vehicle comes from above, so the step is still engaged down to the speed + // at which GetPF() drops it, not the one at which it engages + return ( Vel < 50.0 ? 1.0 / PrzekRapid->GetRapidMult() : 1.0 ); +} + double TNESt3::GetCRP() { return CntrlRes->P(); @@ -331,9 +351,26 @@ double TNESt3::GetCRP() // return Miedzypoj.P; } -void TNESt3::CheckState(double const BCP, double &dV1) // glowny przyrzad rozrzadczy +double TNESt3::GetBrakeRatio( double const Ratio ) const // udzial cisnienia w cylindrze dla udzialu spadku w PG +{ + if( MaxBP <= 0.0 || BVM <= 0.0 ) { + return Ratio; + } + // pelny spadek sluzbowy w PG (HPP - LPP), odtworzony z przelozenia + double const spadek{ MaxBP / BVM + dPSprezyny }; + double const cel{ ( Ratio * spadek - dPSprezyny ) * BVM }; + return ( cel > 0.0 ? std::max( cel, pStopnia ) / MaxBP : 0.0 ); +} + +double TNESt3::CelBCP( double const CVP, double const VVP ) const // docelowe cisnienie w cylindrze +{ + double const cel{ ( CVP - dPSprezyny - VVP ) * BVM }; + // gdy zawor hamuje, nie daje mniej niz najmniejszy stopien + return ( cel > 0.0 ? std::max( cel, pStopnia ) : cel ); +} + +void TNESt3::CheckState(double const BCP, double & /*dV1*/) // glowny przyrzad rozrzadczy { - double const BVP{ BrakeRes->P() }; //-> tu ma byc komora rozprezna double const VVP{ ValveRes->P() }; double const CVP{ CntrlRes->P() }; double const MPP{ Miedzypoj->P() }; @@ -342,27 +379,26 @@ void TNESt3::CheckState(double const BCP, double &dV1) // glowny przyrzad rozrza Przys_blok = false; // sprawdzanie stanu - // if ((BrakeStatus and 1)=1)and(BCP>0.25)then - if (VVP + 0.01 + BCP / BVM < CVP - 0.05 && Przys_blok) + if (double const cel{ CelBCP( CVP, VVP ) }; BCP < cel - 0.01 * BVM && Przys_blok) BrakeStatus |= b_on | b_hld; // hamowanie stopniowe; - else if (VVP - 0.01 + (BCP - 0.1) / BVM > CVP - 0.05) + else if (BCP - 0.1 > cel + 0.01 * BVM) BrakeStatus &= ~( b_on | b_hld ); // luzowanie; - else if (VVP + BCP / BVM > CVP - 0.05) + else if (BCP > cel) BrakeStatus &= ~b_on; // zatrzymanie napelaniania; - else if (VVP + (BCP - 0.1) / BVM < CVP - 0.05 && BCP > 0.25) // zatrzymanie luzowania + else if (BCP - 0.1 < cel && BCP > 0.25) // zatrzymanie luzowania BrakeStatus |= b_hld; if( ( BrakeStatus & b_hld ) == 0 ) SoundFlag |= sf_CylU; - if (VVP + 0.10 < CVP && BCP < 0.25) // poczatek hamowania - if (false == Przys_blok) - { - ValveRes->CreatePress(0.1 * VVP); - SoundFlag |= sf_Acc; - ValveRes->Act(); - Przys_blok = true; - } + // poczatek hamowania + if (VVP + 0.10 < CVP && BCP < 0.25 && false == Przys_blok) + { + ValveRes->CreatePress(0.1 * VVP); + SoundFlag |= sf_Acc; + ValveRes->Act(); + Przys_blok = true; + } if (BCP > 0.5) Zamykajacy = true; @@ -378,13 +414,13 @@ void TNESt3::CheckReleaser(double const dt) // odluzniacz // odluzniacz automatyczny if ((BrakeStatus & b_rls) == b_rls) { - CntrlRes->Flow(PF(CVP, 0, 0.02) * dt); + CntrlRes->Flow(PF(CVP, 0, 0.0049) * dt); // ZS 15 l z 5,0 do 0,4 bar w 23 s (proba odbioru nr 27) if (CVP < VVP + 0.3 || false == autom) BrakeStatus &= ~b_rls; } } -double TNESt3::CVs(double const BP) // napelniacz sterujacego +double TNESt3::CVs(double const /*BP*/) const // napelniacz sterujacego { double const CVP{ CntrlRes->P() }; double const MPP{ Miedzypoj->P() }; @@ -398,7 +434,7 @@ double TNESt3::CVs(double const BP) // napelniacz sterujacego return Nozzles[dSm]; } -double TNESt3::BVs(double const BCP) // napelniacz pomocniczego +double TNESt3::BVs(double const BCP) const // napelniacz pomocniczego { double const CVP{ CntrlRes->P() }; double const MPP{ Miedzypoj->P() }; @@ -449,6 +485,18 @@ void TNESt3::SetLBP(double const P) LBP = P; } +void TNESt3::ScaleNozzlesForAL2() // dysze cylindra przy przekladniku AL2 +{ + if( PrzekCiagly == nullptr ) { + return; + } + // dysze cylindra skalibrowane na komore impulsowa przekladnika AL2 (1 l) wg czasow z tablicy 3-9 + Nozzles[dON] *= 0.914; + Nozzles[dTN] *= 0.885; + Nozzles[dOO] *= 0.82; + Nozzles[dTO] *= 0.8; +} + void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie dysz (rozmiaru ZR) { static double const dNO1l = 1.250; @@ -547,7 +595,7 @@ void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie { // dON,dOO,dTN,dTO,dP,dS Nozzles[dON] = 3.7; Nozzles[dOO] = 2.50; - Nozzles[dTN] = 1.65; + Nozzles[dTN] = 1.62; Nozzles[dTO] = 1.39; Nozzles[dP] = 2.65; Nozzles[dPd] = 1.80; @@ -636,15 +684,18 @@ void TNESt3::SetSize( int const size, std::string const ¶ms ) // ustawianie Nozzles[dSd] = 1.1; Nozzles[dSm] = 0.9; + ScaleNozzlesForAL2(); + // przeliczanie z mm^2 na l/m - for (int i = 0; i < dMAX; ++i) + for (auto &nozzle : Nozzles) { - Nozzles[i] = d2A(Nozzles[i]); //(/1000^2*pi/4*1000) + nozzle = d2A(nozzle); //(/1000^2*pi/4*1000) } for (int i = 1; i < 4; ++i) { Przekladniki[i]->BrakeRes = BrakeRes; - Przekladniki[i]->CreateCap(i); + // komora impulsowa przekladnika AL2 ma 1 l + Przekladniki[i]->CreateCap( ( Przekladniki[i] == PrzekCiagly ) ? 1.0 : i ); Przekladniki[i]->CreatePress(BrakeCyl->P()); if (i < 3) Przekladniki[i]->Next = Przekladniki[i + 1]; diff --git a/McZapkie/Oerlikon_ESt.h b/McZapkie/Oerlikon_ESt.h index c12691851..eaae2c032 100644 --- a/McZapkie/Oerlikon_ESt.h +++ b/McZapkie/Oerlikon_ESt.h @@ -70,38 +70,32 @@ static int const P_ed = 5; class TPrzekladnik : public TReservoir // przekladnik (powtarzacz) { - private: public: std::shared_ptr BrakeRes; std::shared_ptr Next; - TPrzekladnik() : TReservoir() {}; + using TReservoir::TReservoir; virtual void Update(double dt); }; class TRura : public TPrzekladnik // nieprzekladnik, rura laczaca { - private: public: - TRura() : TPrzekladnik() {}; - virtual double P(void) /*override*/; - virtual void Update(double dt) /*override*/; + using TPrzekladnik::TPrzekladnik; + double P(void) override; + void Update(double dt) override; }; class TPrzeciwposlizg : public TRura // przy napelnianiu - rura, przy poslizgu - upust { private: - bool Poslizg; + bool Poslizg{false}; public: void SetPoslizg(bool flag); - void Update(double dt) /*override*/; - inline TPrzeciwposlizg() : TRura() - { - Poslizg = false; - } + void Update(double dt) override; }; // przekladnik dwustopniowy @@ -117,10 +111,9 @@ class TRapid : public TPrzekladnik { public: void SetRapidParams(double mult, double size); void SetRapidStatus(bool rs); - void Update(double dt) /*override*/; - inline TRapid() : - TPrzekladnik() - {} + double GetRapidMult() const { return RapidMult; } + void Update(double dt) override; + using TPrzekladnik::TPrzekladnik; }; // AL2 @@ -131,10 +124,8 @@ class TPrzekCiagly : public TPrzekladnik { public: void SetMult(double m); - void Update(double dt) /*override*/; - inline TPrzekCiagly() : - TPrzekladnik() - {} + void Update(double dt) override; + using TPrzekladnik::TPrzekladnik; }; // podwojny zawor zwrotny @@ -145,20 +136,15 @@ class TPrzek_PZZ : public TPrzekladnik { public: void SetLBP(double P); - void Update(double dt) /*override*/; - inline TPrzek_PZZ() : - TPrzekladnik() - {} + void Update(double dt) override; + using TPrzekladnik::TPrzekladnik; }; class TPrzekZalamany : public TPrzekladnik // Knicksventil { - private: public: - TPrzekZalamany() : - TPrzekladnik() - {} + using TPrzekladnik::TPrzekladnik; }; // przy napelnianiu - rura, przy hamowaniu - upust @@ -169,10 +155,8 @@ class TPrzekED : public TRura { public: void SetP(double P); - void Update(double dt) /*override*/; - inline TPrzekED() : - TRura() - {} + void Update(double dt) override; + using TRura::TRura; }; class TNESt3 : public TBrake { @@ -206,22 +190,24 @@ class TNESt3 : public TBrake { double LBP = 0.0; // cisnienie hamulca pomocniczego public: - inline TNESt3(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : - TBrake( i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) - {} - void Init( double const PP, double const HPP, double const LPP, double const BP, int const BDF ) /*override*/; - virtual double GetPF( double const PP, double const dt, double const Vel ) /*override*/; // przeplyw miedzy komora wstepna i PG - void EStParams(double i_crc); // parametry charakterystyczne dla ESt - virtual double GetCRP() /*override*/; + using TBrake::TBrake; + void Init( double const PP, double const HPP, double const LPP, double const BP, int const BDF ) override; + double GetPF( double const PP, double const dt, double const Vel ) override; // przeplyw miedzy komora wstepna i PG + void EStParams(double i_crc) const; // parametry charakterystyczne dla ESt + double GetCRP() override; + double GetRapidRatio(double const Vel) const override; + double CelBCP(double const CVP, double const VVP) const; // docelowe cisnienie w cylindrze + double GetBrakeRatio(double const Ratio) const override; // udzial cisnienia w cylindrze dla udzialu spadku w PG void CheckState(double const BCP, double &dV1); // glowny przyrzad rozrzadczy void CheckReleaser(double const dt); // odluzniacz - double CVs(double const BP); // napelniacz sterujacego - double BVs(double const BCP); // napelniacz pomocniczego + double CVs(double const BP) const; // napelniacz sterujacego + void ScaleNozzlesForAL2(); // dysze cylindra przy przekladniku AL2 + double BVs(double const BCP) const; // napelniacz pomocniczego void SetSize( int const size, std::string const ¶ms ); // ustawianie dysz (rozmiaru ZR), przekladniki - void PLC(double const mass); // wspolczynnik cisnienia przystawki wazacej - void SetLP(double const TM, double const LM, double const TBP); // parametry przystawki wazacej - virtual void ForceEmptiness() /*override*/; // wymuszenie bycia pustym - void SetLBP(double const P); // cisnienie z hamulca pomocniczego + void PLC(double const mass) override; // wspolczynnik cisnienia przystawki wazacej + void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej + void ForceEmptiness() override; // wymuszenie bycia pustym + void SetLBP(double const P) override; // cisnienie z hamulca pomocniczego }; extern double d2A( double const d ); diff --git a/McZapkie/couplerphysics.cpp b/McZapkie/couplerphysics.cpp new file mode 100644 index 000000000..f6a226b55 --- /dev/null +++ b/McZapkie/couplerphysics.cpp @@ -0,0 +1,291 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.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 "couplerphysics.h" + +#include +#include +#include +#include + +namespace coupler_physics { + +namespace { + +// the transition between the loading and the unloading curve of a device, to the secant stiffness of the pair: the +// friction holds the device stiffer than its springs until the force changes enough to slip it +constexpr double transition_factor{3.0}; +// the force, the deflection and the energy of a curve are computed within this many iterations of the inverse +constexpr int inverse_iterations{50}; +constexpr int series_iterations{60}; + +// a device which doesn't give at all, standing in for the buffers of an end with an adapter +constexpr spring_curve rigid{1.0, 0.0, 0.0}; + +double series_stiffness(double First, double Second) { + return First * Second / (First + Second); +} + +// the buffers of the pair: those of both ends in series, or with an adapter on either end, the device with the shorter +// travel alone, the one of the automatic coupler which takes the push +struct pressed_devices { + spring_curve first; + spring_curve second; + double unloading{0.5}; + double damping{0.0}; +}; + +bool shorter(spring_curve const &First, spring_curve const &Second) { + return std::tie(First.travel, First.stiffness, First.progression) <= std::tie(Second.travel, Second.stiffness, Second.progression); +} + +pressed_devices buffers_of(end_parameters const &First, end_parameters const &Second, bool const Adapter) { + auto const unloading{0.5 * (First.buffers_unloading + Second.buffers_unloading)}; + auto const damping{0.5 * (First.damping + Second.damping)}; + if (false == Adapter) { + return {First.buffers, Second.buffers, unloading, damping}; + } + auto const &coupler{shorter(First.buffers, Second.buffers) ? First.buffers : Second.buffers}; + return {coupler, rigid, unloading, damping}; +} + +pressed_devices draw_gears_of(end_parameters const &First, end_parameters const &Second) { + return {First.draw_gear, Second.draw_gear, 0.5 * (First.draw_gear_unloading + Second.draw_gear_unloading), 0.5 * (First.damping + Second.damping)}; +} + +struct pressed_force { + double force{0.0}; // with the friction and the damping [N] + double curve_force{0.0}; // of the loading curve [N] + double first_deflection{0.0}; // of the first device [m] + bool solid{false}; // both devices at the end of their travel +}; + +// the force of the devices pressed (or pulled) by the deflection growing at the rate +pressed_force press(pressed_devices const &Devices, hysteresis &State, double const Deflection, double const Rate) { + if (Deflection <= 0.0) { + State.reset(); + return {}; + } + auto const split{series(Devices.first, Devices.second, Deflection)}; + auto const travel{Devices.first.travel + Devices.second.travel}; + auto const top{std::max(Devices.first.end_force(), Devices.second.end_force())}; + auto const transition{transition_factor * top / std::max(travel, 1e-3)}; + auto const friction{State.update(Deflection, split.force, Devices.unloading * split.force, transition)}; + // a buffer pushes, a draw gear pulls, neither the other way round however fast they spring back + return {std::max(0.0, friction + Devices.damping * Rate), split.force, split.first, Deflection >= travel}; +} + +bool weaker(link_strength const &First, link_strength const &Second) { + return std::tie(First.ultimate, First.yield, First.hardening) <= std::tie(Second.ultimate, Second.yield, Second.hardening); +} + +} // namespace + +double spring_curve::force(double const Deflection) const { + if (travel <= 0.0 || Deflection <= 0.0) { + return 0.0; + } + auto const u{std::min(Deflection / travel, 1.0)}; + return end_force() * ((1.0 - progression) * u + progression * u * u * u); +} + +double spring_curve::deflection(double const Force) const { + if (travel <= 0.0 || Force <= 0.0) { + return 0.0; + } + auto const f{Force / end_force()}; + if (f >= 1.0) { + return travel; + } + if (progression <= 0.0) { + return f * travel; + } + // the curve is rising and convex, so Newton's method from the end of the travel closes in from above + auto u{1.0}; + auto step{1.0}; + for (int iteration = 0; iteration < inverse_iterations && std::abs(step) > 1e-15; ++iteration) { + auto const value{progression * u * u * u + (1.0 - progression) * u - f}; + auto const slope{3.0 * progression * u * u + (1.0 - progression)}; + step = value / slope; + u -= step; + } + return std::clamp(u, 0.0, 1.0) * travel; +} + +double spring_curve::energy(double const Deflection) const { + if (travel <= 0.0 || Deflection <= 0.0) { + return 0.0; + } + auto const u{std::min(Deflection / travel, 1.0)}; + return end_force() * travel * ((1.0 - progression) * u * u / 2.0 + progression * u * u * u * u / 4.0); +} + +series_split series(spring_curve const &First, spring_curve const &Second, double const Deflection) { + if (Deflection <= 0.0) { + return {}; + } + if (Second.travel <= 0.0) { + return {First.force(Deflection), std::min(Deflection, First.travel), 0.0}; + } + if (First.travel <= 0.0) { + return {Second.force(Deflection), 0.0, std::min(Deflection, Second.travel)}; + } + if (std::tie(First.stiffness, First.travel, First.progression) == std::tie(Second.stiffness, Second.travel, Second.progression)) { + auto const half{std::min(Deflection / 2.0, First.travel)}; + return {First.force(half), half, half}; + } + auto const top{std::max(First.end_force(), Second.end_force())}; + if (Deflection >= First.travel + Second.travel) { + return {top, First.travel, Second.travel}; + } + // the force at which the deflections of both add up to the given one. the sum doesn't depend on the order of + // the devices, so neither does the result + auto low{0.0}; + auto high{top}; + for (int iteration = 0; iteration < series_iterations; ++iteration) { + auto const middle{0.5 * (low + high)}; + if (First.deflection(middle) + Second.deflection(middle) < Deflection) { + low = middle; + } + else { + high = middle; + } + } + auto const force{0.5 * (low + high)}; + return {force, First.deflection(force), Second.deflection(force)}; +} + +double hysteresis::update(double const Deflection, double const Loading, double const Unloading, double const Transition) { + force = std::clamp(force + Transition * (Deflection - deflection), std::min(Unloading, Loading), Loading); + deflection = Deflection; + return force; +} + +void hysteresis::reset() { + force = 0.0; + deflection = 0.0; +} + +double plastic_elongation(link_strength const &Link, double const Force, double const Elongation) { + if (false == Link.breakable || Force <= Link.yield) { + return Elongation; + } + return std::max(Elongation, (Force - Link.yield) / Link.hardening); +} + +double impact_force(double const Velocity, double const Stiffness, double const Mass1, double const Mass2) { + if (Velocity <= 0.0 || Mass1 <= 0.0 || Mass2 <= 0.0) { + return 0.0; + } + auto const mass{Mass1 * Mass2 / (Mass1 + Mass2)}; + return Velocity * std::sqrt(Stiffness * mass); +} + +double strength_scatter(std::string_view const Name, int const End) { + // FNV-1a, which std::hash isn't on every compiler + std::uint64_t hash{14695981039346656037ULL}; + auto const mix = [&hash](unsigned char const Byte) { + hash ^= Byte; + hash *= 1099511628211ULL; + }; + for (auto const character : Name) { + mix(static_cast(character)); + } + mix(static_cast(End)); + // the 53 high bits, as a fraction + auto const fraction{static_cast(hash >> 11) / 9007199254740992.0}; + return 1.0 + 0.2 * fraction; +} + +link_strength weaker_link(end_parameters const &First, end_parameters const &Second) { + auto link{weaker(First.link, Second.link) ? First.link : Second.link}; + // an articulated joint holds whatever the end of the other section is set up to + link.breakable = First.link.breakable && Second.link.breakable; + return link; +} + +double solid_hit_loss(end_parameters const &First, end_parameters const &Second) { + // the collision needs some bounce left (ComputeCollision() asserts it) + auto const restitution{std::clamp(0.5 * (First.solid_restitution + Second.solid_restitution), 0.05, 0.95)}; + return 1.0 - restitution * restitution; +} + +void pair_state::couple() { + draw_gear.reset(); + elongation = 0.0; +} + +pair_result update_pair(end_parameters const &First, end_parameters const &Second, pair_state &State, pair_input const &Input) { + pair_result result; + State.stop = 0; + State.stop_force = 0.0; + + pressed_force pulled; + if (Input.coupled) { + auto const play{First.slack + Second.slack + State.elongation}; + pulled = press(draw_gears_of(First, Second), State.draw_gear, Input.gap - play, Input.gap_rate); + } + else { + State.draw_gear.reset(); + } + auto const pushed{press(buffers_of(First, Second, Input.adapter), State.buffers, -Input.gap, -Input.gap_rate)}; + + result.tension = pulled.force; + result.compression = pushed.force; + result.buffers_deflection = Input.adapter ? 0.0 : pushed.first_deflection; + if (pulled.solid) { + State.stop = 1; + State.stop_force = pulled.curve_force; + } + else if (pushed.solid) { + State.stop = -1; + State.stop_force = pushed.curve_force; + } + + if (Input.coupled) { + auto const link{weaker_link(First, Second)}; + result.overloaded = result.tension > link.yield; + if (Input.damage && link.breakable && result.tension >= link.ultimate) { + result.broken = true; + result.tension = 0.0; + State.draw_gear.reset(); + State.stop = std::min(State.stop, 0); + } + else if (Input.damage) { + State.elongation = plastic_elongation(link, result.tension, State.elongation); + } + } + + result.force = result.tension - result.compression; + State.gap = Input.gap; + return result; +} + +impact_result impact(end_parameters const &First, end_parameters const &Second, pair_state &State, double const Velocity, double const Mass1, double const Mass2) { + impact_result result; + if (State.stop == 0 || Velocity <= 0.0) { + return result; + } + auto const stiffness{series_stiffness(First.link_stiffness, Second.link_stiffness)}; + result.force = State.stop_force + impact_force(Velocity, stiffness, Mass1, Mass2); + if (State.stop > 0) { + auto const link{weaker_link(First, Second)}; + result.broken = link.breakable && result.force >= link.ultimate; + if (false == result.broken) { + State.elongation = plastic_elongation(link, result.force, State.elongation); + } + } + else { + result.crushed = result.force >= std::min(First.crush_force, Second.crush_force); + } + return result; +} + +} // namespace coupler_physics diff --git a/McZapkie/couplerphysics.h b/McZapkie/couplerphysics.h new file mode 100644 index 000000000..47789aba2 --- /dev/null +++ b/McZapkie/couplerphysics.h @@ -0,0 +1,140 @@ +#pragma once + +#include +#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 +// 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 +namespace coupler_physics { + +// force-deflection characteristic of the spring device of one vehicle end, its buffers or its draw gear: +// F(d) = F_end * ((1 - p) * u + p * u^3), u = d / travel, F_end = stiffness * travel +// p (the progression) 0 gives a linear spring; towards 1 it's soft at first and stiffens towards the end of the +// travel, as ring springs and elastomer pads do +struct spring_curve { + double stiffness{1.0}; // secant stiffness, up to the end of the travel [N/m] + double travel{0.1}; // [m] + double progression{0.0}; // 0 to 0.9 + + double end_force() const { return stiffness * travel; } + // force at the deflection [N], the deflection held within the travel + double force(double Deflection) const; + // deflection at the force [m]: the end of the travel at the end force and past it + double deflection(double Force) const; + // energy the device takes in along the curve up to the deflection [J] + double energy(double Deflection) const; +}; + +// the devices of both ends pressed against each other: they carry the same force, their deflections add up. past +// the end of the travel of one, the other one takes the rest. the result doesn't depend on the order of the two +struct series_split { + double force{0.0}; // [N] + double first{0.0}; // deflection of the first device [m] + double second{0.0}; // of the second one [m] +}; +series_split series(spring_curve const &First, spring_curve const &Second, double Deflection); + +// friction (Coulomb) hysteresis of a spring device: the force follows the loading curve while the deflection grows, +// drops to the unloading curve when it shrinks, and in between moves along a stiff transition line, as the friction +// of ring springs or of the wedges of a draw gear holds the device until the force changes enough +struct hysteresis { + double force{0.0}; // carried at the last update [N] + double deflection{0.0}; // at the last update [m] + + // the force at the new deflection, given the force of the loading and of the unloading curve there, and the + // stiffness of the transition between them [N/m] + double update(double Deflection, double Loading, double Unloading, double Transition); + void reset(); +}; + +// steel link of the coupling (the screw coupling and the hook, the knuckle of an automatic coupler): elastic up to +// the yield force, stretched for good past it (the hardening gives the force for each metre of it), broken at the +// ultimate force +struct link_strength { + double yield{std::numeric_limits::max()}; // [N] + double ultimate{std::numeric_limits::max()}; // [N] + double hardening{1.0}; // [N/m] + bool breakable{false}; // an articulated joint, or an end without a coupler set up, holds whatever +}; + +// the permanent elongation [m] the link has after carrying the force, given the one it had +double plastic_elongation(link_strength const &Link, double Force, double Elongation); +// peak force [N] of an elastic hit of two masses [kg] at the closing velocity [m/s] on a stop of the stiffness [N/m]: +// the kinetic energy of their relative motion all goes into the stop +double impact_force(double Velocity, double Stiffness, double Mass1, double Mass2); +// spread of the strength of the couplings as made: 1.0 to 1.2 of the rated force, fixed for the vehicle end, and the +// same on every compiler +double strength_scatter(std::string_view Name, int End); + +// what the model takes of one vehicle end +struct end_parameters { + spring_curve buffers; + spring_curve draw_gear; + double slack{0.0}; // play of the coupling in tension [m], negative for the buffers pressed in by a tightened screw coupling + double buffers_unloading{0.5}; // force of the unloading curve to that of the loading one + double draw_gear_unloading{0.5}; + double damping{0.0}; // viscous damping of the devices, while pressed [N s/m] + double link_stiffness{1.0}; // of the steel parts of the end, past the travel of the springs [N/m] + double crush_force{std::numeric_limits::max()}; // a hit on the buffers past their travel with this force crushes them [N] + // coefficient of restitution of a hit on the springs gone solid: the steel of the housings and the underframe gives + // for good rather than springing back, so the vehicles share their momentum rather than pass it on + double solid_restitution{0.2}; + link_strength link; +}; + +// the share of the energy of the relative motion a hit on the solid springs of the two ends takes, as the legacy +// collision (ComputeCollision()) takes it: 1 - e^2 +double solid_hit_loss(end_parameters const &First, end_parameters const &Second); + +// the weaker of the links of the two ends, which gives first; the same whichever end asks +link_strength weaker_link(end_parameters const &First, end_parameters const &Second); + +// state of the coupling of two vehicle ends, which both vehicles keep alike: each updates its own copy with the same +// gap, so the copies stay the same +struct pair_state { + hysteresis draw_gear; + hysteresis buffers; + double elongation{0.0}; // permanent, of the link [m]; it adds to the slack until the vehicles are coupled again + double gap{0.0}; // at the last update [m] + int stop{0}; // at the last update: 1 the draw gear went solid, -1 the buffers did, 0 neither + double stop_force{0.0}; // the springs carried at the stop [N] + + // a new coupling of the ends: the link adjusted (a screw coupling tightened anew), the draw gear released + void couple(); +}; + +struct pair_input { + double gap{0.0}; // between the ends [m], negative with the buffers pressed in + double gap_rate{0.0}; // [m/s] + bool coupled{false}; + bool adapter{false}; // an adapter on either end: the buffers don't meet, the coupler takes the push alone + bool damage{false}; // the link can stretch and break (crash damage on) +}; + +struct pair_result { + double force{0.0}; // between the ends, tension positive [N] + double tension{0.0}; // carried by the link [N] + double compression{0.0}; // carried by the buffers [N] + double buffers_deflection{0.0}; // of the buffers of the first end [m] + bool overloaded{false}; // the link was pulled past its yield force + bool broken{false}; // the link broke, it carries nothing now +}; + +// the force between the first end and the second one at the gap, updating the state of the pair +pair_result update_pair(end_parameters const &First, end_parameters const &Second, pair_state &State, pair_input const &Input); + +// what a hit on the stop does to the ends +struct impact_result { + double force{0.0}; // peak force of the hit [N] + bool broken{false}; // the link broke under it + bool crushed{false}; // the buffers or the coupler of an end were crushed by it +}; + +// the hit on the stop the pair went solid against at the last update (State.stop), at the closing velocity [m/s], of +// the vehicles of the masses [kg]: stretches or breaks the link of a coupled pair, may crush the buffers +impact_result impact(end_parameters const &First, end_parameters const &Second, pair_state &State, double Velocity, double Mass1, double Mass2); + +} // namespace coupler_physics diff --git a/McZapkie/friction.h b/McZapkie/friction.h index 067a61b97..c58895a9b 100644 --- a/McZapkie/friction.h +++ b/McZapkie/friction.h @@ -41,6 +41,7 @@ class TFricMat public: virtual double GetFC(double N, double Vel); + virtual ~TFricMat() = default; }; @@ -49,7 +50,7 @@ class TP10Bg: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -59,7 +60,7 @@ class TP10Bgu: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -69,7 +70,7 @@ class TP10yBg: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -79,7 +80,7 @@ class TP10yBgu: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -89,7 +90,7 @@ class TP10: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -99,7 +100,7 @@ class TFR513: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -109,7 +110,7 @@ class TFR510: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -119,7 +120,7 @@ class TCosid: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -129,7 +130,7 @@ class TDisk1: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; @@ -139,7 +140,7 @@ class TDisk2: public TFricMat { public: - double GetFC(double N, double Vel)/*override*/; + double GetFC(double N, double Vel) override; }; diff --git a/McZapkie/hamulce.cpp b/McZapkie/hamulce.cpp index 44e8be4b2..b30372e5e 100644 --- a/McZapkie/hamulce.cpp +++ b/McZapkie/hamulce.cpp @@ -357,21 +357,14 @@ end ; */ /// Friction material id (bp_* constant, optionally OR'ed with bp_MHS). /// Number of braked axles. /// Number of blocks per axle. -TBrake::TBrake(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) +TBrake::TBrake(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : + BCN(i_bcn), BCM(1), BCA(i_bcn * i_bcr * i_bcr * M_PI), BrakeDelays(i_BD), MaxBP(i_mbp), BA(i_ba), NBpA(i_nbpa), SizeBR(i_brc * 0.0128) { // inherited:: Create; - MaxBP = i_mbp; - BCN = i_bcn; - BCM = 1; - BCA = i_bcn * i_bcr * i_bcr * M_PI; - BA = i_ba; - NBpA = i_nbpa; - BrakeDelays = i_BD; BrakeDelayFlag = bdelay_P; // 210.88 // SizeBR:=i_bcn*i_bcr*i_bcr*i_bcd*40.17*MaxBP/(5-MaxBP); //objetosc ZP w stosunku do cylindra // 14" i cisnienia 4.2 atm - SizeBR = i_brc * 0.0128; SizeBC = i_bcn * i_bcr * i_bcr * i_bcd * 210.88 * MaxBP / 4.2; // objetosc CH w stosunku do cylindra 14" i cisnienia 4.2 atm BrakeCyl = std::make_shared(); @@ -450,7 +443,7 @@ double TBrake::GetFC(double const Vel, double const N) /// Returns the gauge pressure inside the brake cylinder. // cisnienie cylindra hamulcowego -double TBrake::GetBCP() +double TBrake::GetBCP() const { return BrakeCyl->P(); } @@ -464,14 +457,14 @@ double TBrake::GetEDBCP() /// Returns the auxiliary reservoir (ZP) pressure. // cisnienie zbiornika pomocniczego -double TBrake::GetBRP() +double TBrake::GetBRP() const { return BrakeRes->P(); } /// Returns the valve pre-chamber pressure. // cisnienie komory wstepnej -double TBrake::GetVRP() +double TBrake::GetVRP() const { return ValveRes->P(); } @@ -516,7 +509,7 @@ double TBrake::GetHPFlow(double const HP, double const dt) /// /// Returns the piston force from the cylinder pressure (BCA * 100 * P). /// -double TBrake::GetBCF() +double TBrake::GetBCF() const { return BCA * 100 * BrakeCyl->P(); } @@ -558,7 +551,7 @@ bool TBrake::Releaser() const /// support the EP brake (TWest, TEStEP1/2, ...). /// /// EP intensity. -void TBrake::SetEPS(double const nEPS) {} +void TBrake::SetEPS(double const nEPS) { /* no effect for this device type */ } /// /// Sets the anti-slip brake state flags. Bit 1 of @@ -572,7 +565,7 @@ void TBrake::ASB(int const state) } /// Returns the raw BrakeStatus bitfield. -int TBrake::GetStatus() +int TBrake::GetStatus() const { return BrakeStatus; } @@ -674,14 +667,14 @@ double TWest::GetPF(double const PP, double const dt, double const Vel) BCP = BrakeCyl->P(); if ((BrakeStatus & b_hld) == b_hld) + { if (VVP + 0.03 < BVP) BrakeStatus |= b_on; else if (VVP > BVP + 0.1) BrakeStatus &= ~(b_on | b_hld); else if (VVP > BVP) BrakeStatus &= ~b_on; - else - ; + } else if (VVP + 0.25 < BVP) BrakeStatus |= b_on | b_hld; @@ -707,7 +700,6 @@ double TWest::GetPF(double const PP, double const dt, double const Vel) temp = BVP * int(EPS > 0); dv = PF(temp, LBP, 0.0015) * dt * EPS * EPS * int(LBP * EPS < MaxBP * LoadC); LBP = LBP - dv; - dv = 0; // przeplyw ZP <-> silowniki if ((BrakeStatus & b_on) == b_on && (TareBP < 0.1 || BCP < MaxBP * LoadC)) @@ -781,20 +773,15 @@ void TWest::SetLBP(double const P) /// New EP intensity. void TWest::SetEPS(double const nEPS) { - double BCP; - BCP = BrakeCyl->P(); if (nEPS > 0) DCV = true; - else if (nEPS == 0) + else if (nEPS == 0 && EPS != 0) { - if (EPS != 0) - { - if (LBP > 0.4) - LBP = BrakeCyl->P(); - if (LBP < 0.15) - LBP = 0; - } + if (LBP > 0.4) + LBP = BrakeCyl->P(); + if (LBP < 0.15) + LBP = 0; } EPS = nEPS; } @@ -838,12 +825,14 @@ void TESt::CheckReleaser(double const dt) // odluzniacz if ((BrakeStatus & b_rls) == b_rls) + { if (CVP - VVP < 0) BrakeStatus &= ~b_rls; else { CntrlRes->Flow(+PF(CVP, 0, 0.1) * dt); } + } } /// @@ -854,11 +843,10 @@ void TESt::CheckReleaser(double const dt) /// /// Brake cylinder (or impulse-chamber) pressure. /// In/out brake-pipe flow correction (unused in this base impl). -void TESt::CheckState(double const BCP, double &dV1) +void TESt::CheckState(double const BCP, double & /*dV1*/) { double const VVP{ValveRes->P()}; - double const BVP{BrakeRes->P()}; double const CVP{CntrlRes->P()}; // sprawdzanie stanu @@ -927,7 +915,7 @@ void TESt::CheckState(double const BCP, double &dV1) /// /// Brake cylinder (or impulse) pressure. /// Opening coefficient (0 closed, 1 fully open). -double TESt::CVs(double const BP) +double TESt::CVs(double const BP) const { double VVP; double BVP; @@ -958,7 +946,7 @@ double TESt::CVs(double const BP) /// /// Brake cylinder pressure. /// Opening coefficient. -double TESt::BVs(double const BCP) +double TESt::BVs(double const BCP) const { double VVP; double BVP; @@ -980,6 +968,28 @@ double TESt::BVs(double const BCP) return 0; } +/// +/// Refills the auxiliary reservoir (ZP) from the valve pre-chamber through the +/// check valve of the slide valve, opened as far as says for the +/// given cylinder (or impulse-chamber) pressure, while the pre-chamber is more +/// than 0.05 bar above the reservoir. The flows wait for the caller's Act(). +/// +/// Brake cylinder (or impulse-chamber) pressure. +/// Time step [s]. +/// Volume taken into the auxiliary reservoir, 0.96 of it drawn from the brake pipe. +double TESt::FillBrakeRes(double const BCP, double const dt) const +{ + double const BVP{BrakeRes->P()}; + double const VVP{ValveRes->P()}; + double const temp{BVs(BCP)}; + double dv{0.0}; + if (VVP - 0.05 > BVP) + dv = PF(BVP, VVP, 0.02 * SizeBR * temp / 1.87) * dt; + BrakeRes->Flow(dv); + ValveRes->Flow(-0.04 * dv); + return dv; +} + /// /// One-step Oerlikon ESt distributor advance: runs CheckState/CheckReleaser, /// integrates the ZS <-> PG, ZP <-> cylinder, ZP <-> pre-chamber and @@ -1000,11 +1010,8 @@ double TESt::GetPF(double const PP, double const dt, double const Vel) double CVP; BVP = BrakeRes->P(); - VVP = ValveRes->P(); BCP = BrakeCyl->P(); - CVP = CntrlRes->P() - 0.0; - dv = 0; dV1 = 0; // sprawdzanie stanu @@ -1036,15 +1043,7 @@ double TESt::GetPF(double const PP, double const dt, double const Vel) BrakeCyl->Flow(-dv); // przeplyw ZP <-> rozdzielacz - temp = BVs(BCP); - // if(BrakeStatus and b_hld)=b_off then - if (VVP - 0.05 > BVP) - dv = PF(BVP, VVP, 0.02 * SizeBR * temp / 1.87) * dt; - else - dv = 0; - BrakeRes->Flow(dv); - dV1 = dV1 + dv * 0.96; - ValveRes->Flow(-0.04 * dv); + dV1 = dV1 + FillBrakeRes(BCP, dt) * 0.96; // przeplyw PG <-> rozdzielacz dv = PF(PP, VVP, 0.01) * dt; ValveRes->Flow(-dv); @@ -1086,7 +1085,7 @@ void TESt::Init(double const PP, double const HPP, double const LPP, double cons /// derived variants and currently a no-op. /// /// Characteristic value. -void TESt::EStParams(double const i_crc) {} +void TESt::EStParams(double const /*i_crc*/) const { /* no effect for this device type */ } /// Returns the control reservoir (ZS) pressure. double TESt::GetCRP() @@ -1160,7 +1159,6 @@ double TEStEP2::GetPF(double const PP, double const dt, double const Vel) BCP = ImplsRes->P(); CVP = CntrlRes->P(); // 110115 - konsultacje warszawa1 - dv = 0; dV1 = 0; // odluzniacz @@ -1168,14 +1166,14 @@ double TEStEP2::GetPF(double const PP, double const dt, double const Vel) // sprawdzanie stanu if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) + { if (VVP + 0.003 + BCP / BVM < CVP - 0.12) BrakeStatus |= b_on; // hamowanie stopniowe; else if (VVP - 0.003 + BCP / BVM > CVP - 0.12) BrakeStatus &= ~(b_on | b_hld); // luzowanie; else if (VVP + BCP / BVM > CVP - 0.12) BrakeStatus &= ~b_on; // zatrzymanie napelaniania; - else - ; + } else if (VVP + 0.10 < CVP - 0.12 && BCP < 0.25) // poczatek hamowania { // if ((BrakeStatus & 1) == 0) @@ -1207,6 +1205,10 @@ double TEStEP2::GetPF(double const PP, double const dt, double const Vel) ValveRes->Flow(-0.04 * dv); dV1 = dV1 - 0.96 * dv; + // przeplyw ZP <-> rozdzielacz: as in every ESt, the auxiliary reservoir also charges from the brake pipe, + // not from the main reservoir pipe alone, so a unit hauled with the brake hose alone charges and brakes + dV1 = dV1 + FillBrakeRes(BCP, dt) * 0.96; + // hamulec EP EPCalc(dt); @@ -1343,9 +1345,9 @@ void TEStEP1::SetEPS(double const nEPS) double TESt3::GetPF(double const PP, double const dt, double const Vel) { double BVP{BrakeRes->P()}; - double VVP{ValveRes->P()}; + double VVP; double BCP{BrakeCyl->P()}; - double CVP{CntrlRes->P() - 0.0}; + double CVP; double dv{0.0}; double dV1{0.0}; @@ -1420,11 +1422,8 @@ double TESt4R::GetPF(double const PP, double const dt, double const Vel) double CVP; BVP = BrakeRes->P(); - VVP = ValveRes->P(); BCP = ImplsRes->P(); - CVP = CntrlRes->P(); - dv = 0; dV1 = 0; // sprawdzanie stanu @@ -1468,7 +1467,7 @@ double TESt4R::GetPF(double const PP, double const dt, double const Vel) result = dv - dV1; - RapidStatus = BrakeDelayFlag == bdelay_R && ((Vel > 55 && RapidStatus == true) || Vel > 70); + RapidStatus = (BrakeDelayFlag & bdelay_R) == bdelay_R && ((Vel > 55 && RapidStatus == true) || Vel > 70); RapidTemp = RapidTemp + (0.9 * int(RapidStatus) - RapidTemp) * dt / 2; temp = 1.9 - RapidTemp; @@ -1543,11 +1542,9 @@ double TESt3AL2::GetPF(double const PP, double const dt, double const Vel) double CVP; BVP = BrakeRes->P(); - VVP = ValveRes->P(); BCP = ImplsRes->P(); CVP = CntrlRes->P() - 0.0; - dv = 0; dV1 = 0; // sprawdzanie stanu @@ -1715,8 +1712,7 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) SoundFlag |= sf_CylU; } // equivalent of checkreleaser() in the base class? - bool is_releasing = BrakeStatus & b_rls || UniversalFlag & TUniversalBrake::ub_Release; - if (is_releasing) + if (bool is_releasing = BrakeStatus & b_rls || UniversalFlag & TUniversalBrake::ub_Release; is_releasing) { if (CVP < 0.0) { @@ -1774,7 +1770,7 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) // if Vel>55 then temp:=0.72 else // temp:=1;{R} // cisnienie PP - RapidTemp = RapidTemp + (RM * int(Vel > 55 && BrakeDelayFlag == bdelay_R) - RapidTemp) * dt / 2; + RapidTemp = RapidTemp + (RM * int(Vel > 55 && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; temp = 1 - RapidTemp; if (EDFlag > 0.2) temp = 10000; @@ -1934,14 +1930,14 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) else if (VVP + (BCP - 0.1) / BVM < CVP - 0.05 && BCP > 0.25) // zatrzymanie luzowania BrakeStatus |= b_hld; - if (VVP + 0.10 < CVP && BCP < 0.25) // poczatek hamowania - if (!Przys_blok) - { - ValveRes->CreatePress(0.75 * VVP); - SoundFlag |= sf_Acc; - ValveRes->Act(); - Przys_blok = true; - } + // poczatek hamowania + if (VVP + 0.10 < CVP && BCP < 0.25 && !Przys_blok) + { + ValveRes->CreatePress(0.75 * VVP); + SoundFlag |= sf_Acc; + ValveRes->Act(); + Przys_blok = true; + } if (BCP > 0.5) Zamykajacy = true; @@ -1993,7 +1989,7 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) dv = dv + PF(MPP, VVP, 0.02); Miedzypoj->Flow(dv * dt * 0.15); - RapidTemp = RapidTemp + (RM * int(Vel > RV && BrakeDelayFlag == bdelay_R) - RapidTemp) * dt / 2; + RapidTemp = RapidTemp + (RM * int(Vel > RV && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; temp = std::max(1 - RapidTemp, 0.001); // if EDFlag then temp:=1000; // temp:=temp/(1-); @@ -2069,7 +2065,6 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) void TEStED::Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) { TLSt::Init(PP, HPP, LPP, BP, BDF); - int i; ValveRes->CreatePress(PP); BrakeCyl->CreatePress(BP); @@ -2104,7 +2099,7 @@ void TEStED::Init(double const PP, double const HPP, double const LPP, double co Nozzles[6] = 0.9; { - for (i = 0; i < 11; ++i) + for (int i = 0; i < 11; ++i) { Nozzles[i] = Nozzles[i] * Nozzles[i] * 3.14159 / 4000; } @@ -2165,14 +2160,14 @@ void TCV1::CheckState(double const BCP, double &dV1) // sprawdzanie stanu if ((BrakeStatus & b_hld) == b_hld) + { if (VVP + 0.003 + BCP / BVM < CVP) BrakeStatus |= b_on; // hamowanie stopniowe; else if (VVP - 0.003 + BCP * 1.0 / BVM > CVP) BrakeStatus &= ~(b_on | b_hld); // luzowanie; else if (VVP + BCP * 1.0 / BVM > CVP) BrakeStatus &= ~b_on; // zatrzymanie napelaniania; - else - ; + } else if (VVP + 0.10 < CVP && BCP < 0.1) // poczatek hamowania { BrakeStatus |= b_on | b_hld; @@ -2188,7 +2183,7 @@ void TCV1::CheckState(double const BCP, double &dV1) /// /// Cylinder pressure. /// Opening coefficient. -double TCV1::CVs(double const BP) +double TCV1::CVs(double const BP) const { // przeplyw ZS <-> PG if (BP > 0.05) @@ -2204,7 +2199,7 @@ double TCV1::CVs(double const BP) /// /// Cylinder pressure. /// Opening coefficient. -double TCV1::BVs(double const BCP) +double TCV1::BVs(double const BCP) const { double VVP; double BVP; @@ -2243,11 +2238,9 @@ double TCV1::GetPF(double const PP, double const dt, double const Vel) double CVP; BVP = BrakeRes->P(); - VVP = std::min(ValveRes->P(), BVP + 0.05); BCP = BrakeCyl->P(); CVP = CntrlRes->P(); - dv = 0; dV1 = 0; // sprawdzanie stanu @@ -2402,11 +2395,9 @@ double TCV1L_TR::GetPF(double const PP, double const dt, double const Vel) double CVP; BVP = BrakeRes->P(); - VVP = std::min(ValveRes->P(), BVP + 0.05); BCP = ImplsRes->P(); CVP = CntrlRes->P(); - dv = 0; dV1 = 0; // sprawdzanie stanu @@ -2488,10 +2479,12 @@ void TKE::CheckReleaser(double const dt) // odluzniacz if (true == ((BrakeStatus & b_rls) == b_rls)) + { if (CVP - VVP < 0) BrakeStatus &= ~b_rls; else CntrlRes->Flow(+PF(CVP, 0, 0.1) * dt); + } } /// @@ -2502,13 +2495,11 @@ void TKE::CheckReleaser(double const dt) /// /// Cylinder (or impulse-chamber) pressure. /// In/out brake-pipe flow correction (unused here). -void TKE::CheckState(double const BCP, double &dV1) +void TKE::CheckState(double const BCP, double & /*dV1*/) { double VVP; - double BVP; double CVP; - BVP = BrakeRes->P(); VVP = ValveRes->P(); CVP = CntrlRes->P(); @@ -2578,13 +2569,11 @@ void TKE::CheckState(double const BCP, double &dV1) /// /// Cylinder (or impulse) pressure. /// Opening coefficient. -double TKE::CVs(double const BP) +double TKE::CVs(double const BP) const { double VVP; - double BVP; double CVP; - BVP = BrakeRes->P(); CVP = CntrlRes->P(); VVP = ValveRes->P(); @@ -2604,7 +2593,7 @@ double TKE::CVs(double const BP) /// /// Impulse-chamber pressure. /// Opening coefficient. -double TKE::BVs(double const BCP) +double TKE::BVs(double const /*BCP*/) const { double VVP; double BVP; @@ -2651,7 +2640,6 @@ double TKE::GetPF(double const PP, double const dt, double const Vel) IMP = ImplsRes->P(); CVP = CntrlRes->P(); - dv = 0; dV1 = 0; // sprawdzanie stanu @@ -2694,7 +2682,8 @@ double TKE::GetPF(double const PP, double const dt, double const Vel) ImplsRes->Flow(-dv); // rapid - if (!(typeid(*FM) == typeid(TDisk1) || typeid(*FM) == typeid(TDisk2))) // jesli zeliwo to schodz + auto const &frictionmaterial{*FM}; + if (auto const &frictionmaterialtype{typeid(frictionmaterial)}; !(frictionmaterialtype == typeid(TDisk1) || frictionmaterialtype == typeid(TDisk2))) // jesli zeliwo to schodz RapidStatus = (BrakeDelayFlag & bdelay_R) == bdelay_R && (RV < 0 || (Vel > RV && RapidStatus) || Vel > RV + 20); else // jesli tarczowki, to zostan RapidStatus = (BrakeDelayFlag & bdelay_R) == bdelay_R; @@ -2872,7 +2861,7 @@ void TDriverHandle::Init(double Press) /// Default reductor adjustment — no-op. /// Pressure correction. -void TDriverHandle::SetReductor(double nAdj) {} +void TDriverHandle::SetReductor(double nAdj) { /* no effect for this device type */ } /// Default cab-gauge pressure — 0. double TDriverHandle::GetCP() @@ -2969,9 +2958,8 @@ double TFV4a::GetPF(double i_bcp, double PP, double HP, double dt, double ep) if (lround(i_bcp) == -1) { CP = CP + 5 * std::min(std::abs(LimPP - CP), 0.2) * PR(CP, LimPP) * dt / 2; - if (CP < RP + 0.03) - if (TP < 5) - TP = TP + dt; + if (CP < RP + 0.03 && TP < 5) + TP = TP + dt; // if(cp+0.03<5.4)then if (RP + 0.03 < 5.4 || CP + 0.03 < 5.4) // fala dpMainValve = PF(std::min(HP, 17.1), PP, ActFlowSpeed / LBDelay) * dt; @@ -3037,11 +3025,10 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) int const LBDelay{100}; double const xpM{0.3}; // mnoznik membrany komory pod - ep = PP / 2.0 * 1.5 + ep / 2.0 * 0.5; // SPKS!! - for (int idx = 0; idx < 5; ++idx) + for (auto &soundvalue : Sounds) { - Sounds[idx] = 0; + soundvalue = 0; } // na wszelki wypadek, zeby nie wyszlo poza zakres @@ -3134,13 +3121,9 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) } } - if (EQ(i_bcp, 0)) + if (EQ(i_bcp, 0) && TP > 2) { - - if (TP > 2) - { - dpMainValve *= 1.5; - } + dpMainValve *= 1.5; } ep = dpPipe; @@ -3239,16 +3222,16 @@ double TFV4aM::GetRP() /// /// Continuous handle position. /// Interpolated target pressure [bar]. -double TFV4aM::LPP_RP(double pos) // cisnienie z zaokraglonej pozycji; +double TFV4aM::LPP_RP(double pos) const // cisnienie z zaokraglonej pozycji; { - int const i_pos = 2 + std::floor(pos); // zaokraglone w dol + auto const i_pos = static_cast(2 + std::floor(pos)); // zaokraglone w dol return BPT[i_pos][1] + (BPT[i_pos + 1][1] - BPT[i_pos][1]) * (pos + 2 - i_pos); // interpolacja liniowa } /// Returns true if pos is within ±0.5 of i_pos (detent test). /// Continuous handle position. /// Detent centre. -bool TFV4aM::EQ(double pos, double i_pos) +bool TFV4aM::EQ(double pos, double i_pos) const { return pos <= i_pos + 0.5 && pos > i_pos - 0.5; } @@ -3279,12 +3262,11 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep double DP; double pom; - for (int idx = 0; idx < 5; ++idx) + for (auto &soundvalue : Sounds) { - Sounds[idx] = 0; + soundvalue = 0; } - DP = 0; i_bcp = std::clamp(i_bcp, -0.999, 9.999); // na wszelki wypadek, zeby nie wyszlo poza zakres @@ -3425,7 +3407,7 @@ double TMHZ_EN57::GetEP(double pos) /// /// Continuous handle position. /// Target brake-pipe pressure [bar]. -double TMHZ_EN57::LPP_RP(double pos) // cisnienie z zaokraglonej pozycji; +double TMHZ_EN57::LPP_RP(double pos) const // cisnienie z zaokraglonej pozycji; { if (pos > 8.5) return 5.0 - 0.15 * pos - 0.35; @@ -3456,7 +3438,7 @@ void TMHZ_EN57::SetParams(bool AO, bool MO, double OverP, double, double OMP, do } /// Returns true if pos is within ±0.5 of i_pos (detent test). -bool TMHZ_EN57::EQ(double pos, double i_pos) +bool TMHZ_EN57::EQ(double pos, double i_pos) const { return pos <= i_pos + 0.5 && pos > i_pos - 0.5; } @@ -3484,14 +3466,12 @@ double TMHZ_K5P::GetPF(double i_bcp, double PP, double HP, double dt, double ep) double dpMainValve; double ActFlowSpeed; double DP; - double pom; - for (int idx = 0; idx < 5; ++idx) + for (auto &soundvalue : Sounds) { - Sounds[idx] = 0; + soundvalue = 0; } - DP = 0; i_bcp = std::clamp(i_bcp, -0.999, 2.999); // na wszelki wypadek, zeby nie wyszlo poza zakres @@ -3512,14 +3492,10 @@ double TMHZ_K5P::GetPF(double i_bcp, double PP, double HP, double dt, double ep) LimCP = 3.4; else // luzowanie LimCP = 5.0; - pom = CP; LimCP = std::min(LimCP, HP); // pozycja + czasowy lub zasilanie ActFlowSpeed = 4; - if (LimCP > CP) // podwyzszanie szybkie - CP = CP + 9 * std::min(abs(LimCP - CP), 0.05) * PR(CP, LimCP) * dt; // zbiornik sterujacy; - else - CP = CP + 9 * std::min(abs(LimCP - CP), 0.05) * PR(CP, LimCP) * dt; // zbiornik sterujacy + CP = CP + 9 * std::min(abs(LimCP - CP), 0.05) * PR(CP, LimCP) * dt; // zbiornik sterujacy double uop = UnbrakeOverPressure; // unbrake over pressure in actual state ManualOvrldActive = UniversalFlag & TUniversalBrake::ub_HighPressure; // button is pressed @@ -3546,10 +3522,9 @@ double TMHZ_K5P::GetPF(double i_bcp, double PP, double HP, double dt, double ep) else dpMainValve = PFVd(PP, 0, ActFlowSpeed / LBDelay, dpPipe, 0.4); - if ((EQ(i_bcp, -1) && AutoOvrld) || (i_bcp < 0.5 && UniversalFlag & TUniversalBrake::ub_Overload)) + if (((EQ(i_bcp, -1) && AutoOvrld) || (i_bcp < 0.5 && UniversalFlag & TUniversalBrake::ub_Overload)) && TP < OverloadMaxPressure) { - if (TP < OverloadMaxPressure) - TP = TP + 0.03 * dt; + TP = TP + 0.03 * dt; } if (EQ(i_bcp, 3)) @@ -3640,7 +3615,7 @@ void TMHZ_K5P::SetParams(bool AO, bool MO, double OverP, double FSF, double OMP, } /// Returns true if pos is within ±0.5 of i_pos (detent test). -bool TMHZ_K5P::EQ(double pos, double i_pos) +bool TMHZ_K5P::EQ(double pos, double i_pos) const { return pos <= i_pos + 0.5 && pos > i_pos - 0.5; } @@ -3667,14 +3642,12 @@ double TMHZ_6P::GetPF(double i_bcp, double PP, double HP, double dt, double ep) double dpMainValve; double ActFlowSpeed; double DP; - double pom; - for (int idx = 0; idx < 5; ++idx) + for (auto &soundvalue : Sounds) { - Sounds[idx] = 0; + soundvalue = 0; } - DP = 0; i_bcp = std::clamp(i_bcp, -0.999, 3.999); // na wszelki wypadek, zeby nie wyszlo poza zakres @@ -3695,14 +3668,10 @@ double TMHZ_6P::GetPF(double i_bcp, double PP, double HP, double dt, double ep) LimCP = 3.4; else // luzowanie LimCP = 5.0; - pom = CP; LimCP = std::min(LimCP, HP); // pozycja + czasowy lub zasilanie ActFlowSpeed = 4; - if (LimCP > CP) // podwyzszanie szybkie - CP = CP + 9 * std::min(abs(LimCP - CP), 0.05) * PR(CP, LimCP) * dt; // zbiornik sterujacy; - else - CP = CP + 9 * std::min(abs(LimCP - CP), 0.05) * PR(CP, LimCP) * dt; // zbiornik sterujacy + CP = CP + 9 * std::min(abs(LimCP - CP), 0.05) * PR(CP, LimCP) * dt; // zbiornik sterujacy dpPipe = std::min(HP, CP + TP + RedAdj); @@ -3729,10 +3698,9 @@ double TMHZ_6P::GetPF(double i_bcp, double PP, double HP, double dt, double ep) else dpMainValve = PFVd(PP, 0, ActFlowSpeed / LBDelay, dpPipe, 0.4); - if ((EQ(i_bcp, -1) && AutoOvrld) || (i_bcp < 0.5 && UniversalFlag & TUniversalBrake::ub_Overload)) + if (((EQ(i_bcp, -1) && AutoOvrld) || (i_bcp < 0.5 && UniversalFlag & TUniversalBrake::ub_Overload)) && TP < OverloadMaxPressure) { - if (TP < OverloadMaxPressure) - TP = TP + 0.03 * dt; + TP = TP + 0.03 * dt; } if (EQ(i_bcp, 4)) @@ -3823,7 +3791,7 @@ void TMHZ_6P::SetParams(bool AO, bool MO, double OverP, double FSF, double OMP, } /// Returns true if pos is within ±0.5 of i_pos (detent test). -bool TMHZ_6P::EQ(double pos, double i_pos) +bool TMHZ_6P::EQ(double pos, double i_pos) const { return pos <= i_pos + 0.5 && pos > i_pos - 0.5; } @@ -3852,7 +3820,7 @@ double TM394::GetPF(double i_bcp, double PP, double HP, double dt, double ep) double ActFlowSpeed; int BCP; - BCP = lround(i_bcp); + BCP = static_cast(lround(i_bcp)); if (BCP < -1) BCP = 1; @@ -3863,6 +3831,7 @@ double TM394::GetPF(double i_bcp, double PP, double HP, double dt, double ep) if (BCP == 0) LimPP = LimPP + RedAdj; if (BCP != 2) + { if (CP < LimPP) CP = CP + 4 * std::min(abs(LimPP - CP), 0.05) * PR(CP, LimPP) * dt; // zbiornik sterujacy // cp:=cp+6*(2+int(bcp<0))*std::min(abs(Limpp-cp),0.05)*PR(cp,Limpp)*dt //zbiornik @@ -3871,6 +3840,7 @@ double TM394::GetPF(double i_bcp, double PP, double HP, double dt, double ep) CP = CP - 0.2 * dt / 100; else CP = CP + 4 * (1 + int(BCP != 3) + int(BCP > 4)) * std::min(abs(LimPP - CP), 0.05) * PR(CP, LimPP) * dt; // zbiornik sterujacy + } LimPP = CP; dpPipe = std::min(HP, LimPP); @@ -3945,7 +3915,7 @@ double TH14K1::GetPF(double i_bcp, double PP, double HP, double dt, double ep) //{ (10, 0), (4, 1), (0, 1), (4, 0), (4, -1), (15, -1) }; double const NomPress = 5.0; - int BCP = std::lround(i_bcp); + auto BCP = static_cast(std::lround(i_bcp)); if (i_bcp < -1) { BCP = 1; @@ -4042,7 +4012,7 @@ double TSt113::GetPF(double i_bcp, double PP, double HP, double dt, double ep) CP = PP; - BCP = lround(i_bcp); + BCP = static_cast(lround(i_bcp)); EPS = BEP_K[BCP + 1]; diff --git a/McZapkie/hamulce.h b/McZapkie/hamulce.h index a05a36359..2fb433a85 100644 --- a/McZapkie/hamulce.h +++ b/McZapkie/hamulce.h @@ -272,10 +272,11 @@ class TReservoir /// Default constructor — creates a 1 L reservoir at zero pressure. TReservoir() = default; + virtual ~TReservoir() = default; }; /// Pointer typedef for a reservoir instance. -typedef TReservoir *PReservoir; +using PReservoir = TReservoir *; /// /// Brake cylinder reservoir — overrides pressure functions to model the @@ -290,15 +291,15 @@ class TBrakeCyl : public TReservoir /// Returns absolute pressure inside the brake cylinder (P() * 0.1). /// /// Absolute cylinder pressure. - virtual double pa() /*override*/; + double pa() override; /// /// Returns gauge pressure inside the brake cylinder, modelling the /// piston-stroke pressure curve (dead volume, linear stroke, fully extended). /// /// Cylinder pressure in bar. - virtual double P() /*override*/; + double P() override; /// Default constructor. - TBrakeCyl() : TReservoir() {}; + using TReservoir::TReservoir; }; /// @@ -399,7 +400,7 @@ class TBrake /// Returns the piston force produced by the brake cylinder pressure. /// /// Force in arbitrary engine units (BCA * 100 * P). - double GetBCF(); // sila tlokowa z tloka + double GetBCF() const; // sila tlokowa z tloka /// /// Computes the airflow drawn from the high-pressure (8 bar / main) line for one step. /// @@ -408,18 +409,22 @@ class TBrake /// Net flow from the high-pressure line. virtual double GetHPFlow(double const HP, double const dt); // przeplyw - 8 bar /// Returns brake cylinder gauge pressure [bar]. - double GetBCP(); // cisnienie cylindrow hamulcowych + double GetBCP() const; // cisnienie cylindrow hamulcowych /// /// Returns brake cylinder pressure originating only from the pneumatic /// (main) brake — used to drive the ED (electrodynamic) brake e.g. in EP09. /// virtual double GetEDBCP(); // cisnienie tylko z hamulca zasadniczego, uzywane do hamulca ED w EP09 /// Returns auxiliary reservoir (ZP) pressure [bar]. - double GetBRP(); // cisnienie zbiornika pomocniczego + double GetBRP() const; // cisnienie zbiornika pomocniczego /// Returns valve pre-chamber pressure [bar]. - double GetVRP(); // cisnienie komory wstepnej rozdzielacza + double GetVRP() const; // cisnienie komory wstepnej rozdzielacza /// Returns control reservoir (ZS) pressure [bar]; defaults to the auxiliary reservoir for valves without a dedicated ZS. virtual double GetCRP(); // cisnienie zbiornika sterujacego + /// Share of the full cylinder pressure the distributor settles at for the given share + /// of the full service pipe drop. Used only to predict the brake force; the default is proportional. + /// Share of the full service brake pipe drop. + virtual double GetBrakeRatio(double const Ratio) const { return Ratio; } /// /// Sets the brake delay (G/P/R/M) selector if requested mode is supported. /// @@ -441,7 +446,12 @@ class TBrake virtual void SetEPS(double const nEPS); // hamulec EP /// Sets the rapid step ratio. Default no-op; overridden where supported. /// Rapid ratio. - virtual void SetRM(double const RMR) {}; // ustalenie przelozenia rapida + virtual void SetRM(double const RMR) { /* no effect for this device type */ } // ustalenie przelozenia rapida + /// Share of the full cylinder pressure the distributor delivers at the given speed + /// while the vehicle is slowing down through it, for a vehicle set to R. Used only to predict + /// the brake force; the default is the approximation BrakeForceR() has always used. + /// Vehicle velocity [km/h]. + virtual double GetRapidRatio(double const Vel) const { return Vel < 40.0 ? 0.5 : 1.0; } /// Sets the velocity threshold for the rapid step. /// Velocity threshold (same unit as Vel passed to GetPF). virtual void SetRV(double const RVR) @@ -455,20 +465,20 @@ class TBrake /// Tare (empty) mass. /// Loaded mass. /// Brake cylinder pressure for the tare mass. - virtual void SetLP(double const TM, double const LM, double const TBP) {}; // parametry przystawki wazacej + virtual void SetLP(double const TM, double const LM, double const TBP) { /* no effect for this device type */ } // parametry przystawki wazacej /// Sets the auxiliary (local) brake target pressure. /// Local brake pressure [bar]. - virtual void SetLBP(double const P) {}; // cisnienie z hamulca pomocniczego + virtual void SetLBP(double const P) { /* no effect for this device type */ } // cisnienie z hamulca pomocniczego /// Updates the load-weighing pressure coefficient based on current vehicle mass. /// Current vehicle mass. - virtual void PLC(double const mass) {}; // wspolczynnik cisnienia przystawki wazacej + virtual void PLC(double const mass) { /* no effect for this device type */ } // wspolczynnik cisnienia przystawki wazacej /// /// Engages the anti-slip brake function (set hold and/or release flags). /// /// Two-bit value: bit1 = hold (b_asb), bit0 = release (b_asb_unbrake). void ASB(int state); // hamulec przeciwposlizgowy /// Returns the raw BrakeStatus flags (for sound/visual cues). - int GetStatus(); // flaga statusu, moze sie przydac do odglosow + int GetStatus() const; // flaga statusu, moze sie przydac do odglosow /// Sets the anti-slip target pressure. /// Pressure [bar]. void SetASBP(double const Press); // ustalenie cisnienia pp @@ -497,13 +507,14 @@ class TBrake /// brake when ED braking is sufficient. Default no-op; overridden where supported. /// /// ED brake intensity (0..1). - virtual void SetED(double const EDstate) {}; // stan hamulca ED do luzowania + virtual void SetED(double const EDstate) { /* no effect for this device type */ } // stan hamulca ED do luzowania /// Sets the universal-button flags (see TUniversalBrake). /// Combined ub_* flags. virtual void SetUniversalFlag(int flag) { UniversalFlag = flag; } // przycisk uniwersalny + virtual ~TBrake() = default; }; /// @@ -537,26 +548,26 @@ class TWest : public TBrake /// Low pressure. /// Initial cylinder pressure. /// Initial brake delay flag. - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// Sets the auxiliary brake target pressure and engages the DCV when above cylinder. /// Pressure [bar]. - void SetLBP(double const P); // cisnienie z hamulca pomocniczego + void SetLBP(double const P) override; // cisnienie z hamulca pomocniczego /// One-step distributor advance (Westinghouse logic). /// Net flow exchanged with the brake pipe. - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Returns the high-pressure flow drawn during the last GetPF step. - double GetHPFlow(double const HP, double const dt) /*override*/; + double GetHPFlow(double const HP, double const dt) override; /// Recomputes the load-weighing pressure coefficient for the current mass. /// Vehicle mass. - void PLC(double const mass); // wspolczynnik cisnienia przystawki wazacej + void PLC(double const mass) override; // wspolczynnik cisnienia przystawki wazacej /// Sets the EP brake state and toggles the DCV / latches LBP from cylinder pressure on release. /// New EP intensity. - void SetEPS(double const nEPS) /*override*/; // stan hamulca EP + void SetEPS(double const nEPS) override; // stan hamulca EP /// Stores the load-weighing parameters (TareM, LoadM, TareBP). - void SetLP(double const TM, double const LM, double const TBP); // parametry przystawki wazacej + void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej /// Constructs the distributor by forwarding all parameters to TBrake. - inline TWest(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TBrake(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) {} + using TBrake::TBrake; }; /// @@ -567,7 +578,6 @@ class TWest : public TBrake class TESt : public TBrake { - private: protected: /// Control reservoir (ZS) — long-term reference pressure. std::shared_ptr CntrlRes; // zbiornik sterujący @@ -576,15 +586,15 @@ class TESt : public TBrake public: /// Initialises the ESt distributor; sizes the control reservoir (15 l) and computes BVM. - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// One-step distributor advance for the ESt baseline. /// Net flow exchanged with the brake pipe. - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Sets ESt-specific characteristic parameters (placeholder; used by some variants). /// Characteristic value. - void EStParams(double i_crc); // parametry charakterystyczne dla ESt + void EStParams(double i_crc) const; // parametry charakterystyczne dla ESt /// Returns the control reservoir (ZS) pressure. - double GetCRP() /*override*/; + double GetCRP() override; /// /// Updates BrakeStatus (b_on/b_hld) according to the relations between /// pre-chamber, cylinder and control reservoir pressures (the main slide valve). @@ -602,16 +612,25 @@ class TESt : public TBrake /// /// Cylinder pressure (or impulse-chamber pressure). /// Dimensionless opening coefficient. - double CVs(double BP); // napelniacz sterujacego + double CVs(double BP) const; // napelniacz sterujacego /// /// Returns the effective opening factor of the auxiliary-reservoir filling /// slide valve (ZP <-> pre-chamber path). /// /// Brake cylinder pressure. /// Dimensionless opening coefficient. - double BVs(double BCP); // napelniacz pomocniczego + double BVs(double BCP) const; // napelniacz pomocniczego + /// + /// Refills the auxiliary reservoir (ZP) from the valve pre-chamber through the + /// check valve of the slide valve, opened as far as says, while + /// the pre-chamber is above the reservoir. The flows wait for the caller's Act(). + /// + /// Brake cylinder (or impulse-chamber) pressure for . + /// Time step [s]. + /// Volume taken into the auxiliary reservoir, 0.96 of it drawn from the brake pipe. + double FillBrakeRes(double BCP, double dt) const; // napelnianie pomocniczego z rozdzielacza /// Vents the valve, brake and control reservoirs to zero. - void ForceEmptiness() /*override*/; // wymuszenie bycia pustym + void ForceEmptiness() override; // wymuszenie bycia pustym /// Constructs the ESt distributor and creates the control reservoir. inline TESt(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TBrake(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) @@ -627,16 +646,15 @@ class TESt : public TBrake class TESt3 : public TESt { - private: // double CylFlowSpeed[2][2]; //zmienna nie uzywana public: /// One-step distributor advance for ESt3 (G/P-dependent fill/release curves). /// Net flow exchanged with the brake pipe. - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Constructs the ESt3 distributor. - inline TESt3(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TESt(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) {} + using TESt::TESt; }; /// @@ -660,13 +678,13 @@ class TESt3AL2 : public TESt3 public: /// Initialises the impulse chamber on top of the ESt initialisation. - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// One-step distributor advance for ESt3/AL2 with load-weighing relay. - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Recomputes LoadC for the current vehicle mass. - void PLC(double const mass); // wspolczynnik cisnienia przystawki wazacej + void PLC(double const mass) override; // wspolczynnik cisnienia przystawki wazacej /// Stores the load-weighing parameters. - void SetLP(double const TM, double const LM, double const TBP); // parametry przystawki wazacej + void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej /// Constructs the distributor and creates the impulse chamber. inline TESt3AL2(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TESt3(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) @@ -695,9 +713,9 @@ class TESt4R : public TESt public: /// Initialises the ESt4R; sizes the impulse chamber and selects the R delay. - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// One-step distributor advance for ESt4R (rapid step active above velocity threshold). - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Constructs the distributor and creates the impulse chamber. inline TESt4R(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TESt(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) @@ -713,7 +731,6 @@ class TESt4R : public TESt class TLSt : public TESt4R { - private: // double CylFlowSpeed[2][2]; // zmienna nie używana protected: @@ -726,24 +743,24 @@ class TLSt : public TESt4R public: /// Initialises the LSt; resizes the valve and impulse reservoirs and presets pressures. - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// Sets the auxiliary brake target pressure for the DCV. - void SetLBP(double const P); // cisnienie z hamulca pomocniczego + void SetLBP(double const P) override; // cisnienie z hamulca pomocniczego /// Sets the rapid step ratio (RM = 1 - RMR). /// Reduction ratio (0 disables rapid, > 0 enables). - void SetRM(double const RMR); // ustalenie przelozenia rapida + void SetRM(double const RMR) override; // ustalenie przelozenia rapida /// One-step distributor advance for LSt (DCV + rapid + ED release). - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Computes the high-pressure inflow (replenishes the auxiliary reservoir from the main line). - double GetHPFlow(double const HP, double const dt) /*override*/; // przeplyw - 8 bar + double GetHPFlow(double const HP, double const dt) override; // przeplyw - 8 bar /// Returns the brake-cylinder reference pressure used by the ED brake controller (CVP-BCP * BVM). - virtual double GetEDBCP(); // cisnienie tylko z hamulca zasadniczego, uzywane do hamulca ED w EP09 + double GetEDBCP() override; // cisnienie tylko z hamulca zasadniczego, uzywane do hamulca ED w EP09 /// Sets the ED brake state used to relax the pneumatic brake. /// ED intensity (0..1). - virtual void SetED(double const EDstate); // stan hamulca ED do luzowania + void SetED(double const EDstate) override; // stan hamulca ED do luzowania /// Constructs the LSt distributor. - inline TLSt(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TESt4R(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) {} + using TESt4R::TESt4R; }; /// @@ -774,15 +791,15 @@ class TEStED : public TLSt public: /// Initialises the EStED — sets up Miedzypoj, ImplsRes and the nozzle characteristics. - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// One-step distributor advance for EStED (full EP09 logic with intermediate reservoir). - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Returns ED-brake reference pressure (ImplsRes pressure scaled by load coefficient). - double GetEDBCP() /*override*/; // cisnienie tylko z hamulca zasadniczego, uzywane do hamulca ED + double GetEDBCP() override; // cisnienie tylko z hamulca zasadniczego, uzywane do hamulca ED /// Recomputes LoadC for the current vehicle mass. - void PLC(double const mass); // wspolczynnik cisnienia przystawki wazacej + void PLC(double const mass) override; // wspolczynnik cisnienia przystawki wazacej /// Stores the load-weighing parameters. - void SetLP(double const TM, double const LM, double const TBP); // parametry przystawki wazacej + void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej /// Constructs the distributor and creates the intermediate reservoir. inline TEStED(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TLSt(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) @@ -812,21 +829,21 @@ class TEStEP2 : public TLSt public: /// Initialises the EP2-equipped distributor (impulse chamber, P delay). - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; // inicjalizacja + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; // inicjalizacja /// One-step distributor advance with EP2 EP brake logic. - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Recomputes LoadC for the current vehicle mass. - void PLC(double const mass); // wspolczynnik cisnienia przystawki wazacej + void PLC(double const mass) override; // wspolczynnik cisnienia przystawki wazacej /// Sets EP intensity; if EP is active and LBP < cylinder pressure, latches LBP from cylinder. - void SetEPS(double const nEPS) /*override*/; // stan hamulca EP + void SetEPS(double const nEPS) override; // stan hamulca EP /// Stores the load-weighing parameters. - void SetLP(double const TM, double const LM, double const TBP); // parametry przystawki wazacej + void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej /// EP brake flow integration step. Override in EP1 for proportional control. /// Time step [s]. void virtual EPCalc(double dt); /// Constructs the EP2 distributor. - inline TEStEP2(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TLSt(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) {} + using TLSt::TLSt; }; /// @@ -839,15 +856,13 @@ class TEStEP1 : public TEStEP2 public: /// Proportional EP flow integration step (uses fractional part of EPS as the EP target). - void EPCalc(double dt); + void EPCalc(double dt) override; /// Stores the EP intensity. /// Target EP value (integer part = direction, fractional part = magnitude). void SetEPS(double const nEPS) override; // stan hamulca EP /// Constructs the EP1 distributor. - inline TEStEP1(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TEStEP2(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) - { - } + using TEStEP2::TEStEP2; }; /// @@ -867,21 +882,21 @@ class TCV1 : public TBrake public: /// Initialises the CV1 distributor (sizes ZS, sets pressures, computes BVM). - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// One-step distributor advance for the CV1 baseline. - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Returns the control reservoir (ZS) pressure. - double GetCRP() /*override*/; + double GetCRP() override; /// Updates BrakeStatus based on pre-chamber/cylinder/control reservoir relations and the releaser. /// Cylinder (or impulse) pressure. /// In/out brake pipe flow correction. void CheckState(double const BCP, double &dV1); /// Returns the ZS-filling slide valve opening factor for the given cylinder pressure. - double CVs(double const BP); + double CVs(double const BP) const; /// Returns the ZP-filling slide valve opening factor for the given cylinder pressure. - double BVs(double const BCP); + double BVs(double const BCP) const; /// Vents valve, brake and control reservoirs to zero. - void ForceEmptiness() /*override*/; // wymuszenie bycia pustym + void ForceEmptiness() override; // wymuszenie bycia pustym /// Constructs the CV1 distributor and creates the control reservoir. inline TCV1(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TBrake(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) @@ -922,13 +937,13 @@ class TCV1L_TR : public TCV1 public: /// Initialises the CV1-L-TR (sizes the impulse chamber on top of CV1::Init). - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// One-step distributor advance for CV1-L-TR (impulse chamber + DCV). - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Sets the auxiliary brake target pressure for the DCV. - void SetLBP(double const P); // cisnienie z hamulca pomocniczego + void SetLBP(double const P) override; // cisnienie z hamulca pomocniczego /// Computes the high-pressure (8 bar) inflow used to replenish the auxiliary reservoir. - double GetHPFlow(double const HP, double const dt) /*override*/; // przeplyw - 8 bar + double GetHPFlow(double const HP, double const dt) override; // przeplyw - 8 bar /// Constructs the CV1-L-TR and creates the impulse chamber. inline TCV1L_TR(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TCV1(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) @@ -971,31 +986,31 @@ class TKE : public TBrake public: /// Initialises the KE distributor (control / impulse / auxiliary reservoirs and BVM). - void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) /*override*/; + void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; /// Sets the rapid step ratio (RM = 1 - RMR). - void SetRM(double const RMR); // ustalenie przelozenia rapida + void SetRM(double const RMR) override; // ustalenie przelozenia rapida /// One-step distributor advance for the KE distributor. - double GetPF(double const PP, double const dt, double const Vel) /*override*/; // przeplyw miedzy komora wstepna i PG + double GetPF(double const PP, double const dt, double const Vel) override; // przeplyw miedzy komora wstepna i PG /// Computes the high-pressure (8 bar) inflow used to replenish the auxiliary reservoir. - double GetHPFlow(double const HP, double const dt) /*override*/; // przeplyw - 8 bar + double GetHPFlow(double const HP, double const dt) override; // przeplyw - 8 bar /// Returns the control reservoir (ZS) pressure. - double GetCRP() /*override*/; + double GetCRP() override; /// Updates BrakeStatus from cylinder/pre-chamber/control reservoir pressures (KE-specific thresholds). void CheckState(double const BCP, double &dV1); /// Drives the releaser logic for KE — bleeds the control reservoir while engaged. void CheckReleaser(double const dt); // odluzniacz /// ZS-filling slide valve opening factor for the given cylinder pressure. - double CVs(double const BP); // napelniacz sterujacego + double CVs(double const BP) const; // napelniacz sterujacego /// ZP-filling slide valve opening factor for the given cylinder pressure. - double BVs(double const BCP); // napelniacz pomocniczego + double BVs(double const BCP) const; // napelniacz pomocniczego /// Recomputes LoadC for the current vehicle mass. - void PLC(double const mass); // wspolczynnik cisnienia przystawki wazacej + void PLC(double const mass) override; // wspolczynnik cisnienia przystawki wazacej /// Stores the load-weighing parameters. - void SetLP(double const TM, double const LM, double const TBP); // parametry przystawki wazacej + void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej /// Sets the auxiliary brake target pressure for the DCV. - void SetLBP(double const P); // cisnienie z hamulca pomocniczego + void SetLBP(double const P) override; // cisnienie z hamulca pomocniczego /// Vents valve, brake, control, impulse and secondary auxiliary reservoirs to zero. - void ForceEmptiness() /*override*/; // wymuszenie bycia pustym + void ForceEmptiness() override; // wymuszenie bycia pustym /// Constructs the KE distributor and creates the control / impulse / secondary reservoirs. inline TKE(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TBrake(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) @@ -1077,7 +1092,7 @@ class TDriverHandle /// Unbrake over-pressure [bar]. /// Overload (assimilation) max pressure [bar]. /// Overload pressure decay rate [bar/s]. - virtual void SetParams(bool AO, bool MO, double, double, double OMP, double OPD) {}; // ustawianie jakichs parametrow dla zaworu + virtual void SetParams(bool AO, bool MO, double, double, double OMP, double OPD) { /* no effect for this device type */ } // ustawianie jakichs parametrow dla zaworu /// Sets the manual overcharge button state. /// True while the button is pressed. virtual void OvrldButton(bool Active); // przycisk recznego przeladowania/asymilacji @@ -1089,6 +1104,7 @@ class TDriverHandle { memset(Sounds, 0, sizeof(Sounds)); } + virtual ~TDriverHandle() = default; }; /// @@ -1107,12 +1123,12 @@ class TFV4a : public TDriverHandle public: /// Computes brake pipe flow for the FV4a handle (uses BPT[] table). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and RP to the supplied pressure. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Default constructor. - inline TFV4a() : TDriverHandle() {} + using TDriverHandle::TDriverHandle; }; /// @@ -1143,27 +1159,27 @@ class TFV4aM : public TDriverHandle /// Returns the brake pipe pressure target interpolated from BPT[] for the given handle position. /// /// Handle position. - double LPP_RP(double pos); + double LPP_RP(double pos) const; /// Returns true if pos is within ±0.5 of i_pos (detent comparison). - bool EQ(double pos, double i_pos); + bool EQ(double pos, double i_pos) const; public: /// Computes brake pipe flow for the FV4a/M handle (interpolated BPT, wave modelling, accelerator). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and RP. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Sets the reductor adjustment offset. - void SetReductor(double nAdj) /*override*/; + void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). - double GetSound(int i) /*override*/; + double GetSound(int i) override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Returns the time chamber pressure (TP). - double GetCP(); + double GetCP() override; /// Returns the regulator pressure (5 + TP*0.08 + RedAdj). - double GetRP(); + double GetRP() override; /// Default constructor. - inline TFV4aM() : TDriverHandle() {} + using TDriverHandle::TDriverHandle; }; /// @@ -1193,32 +1209,31 @@ class TMHZ_EN57 : public TDriverHandle static double const pos_table[11]; //= { -2, 10, -1, 0, 0, 2, 9, 10, 0, 0, 0 }; /// Returns the brake pipe pressure target for the given handle position (piecewise). - double LPP_RP(double pos); + double LPP_RP(double pos) const; /// Returns true if pos is within ±0.5 of i_pos. - bool EQ(double pos, double i_pos); + bool EQ(double pos, double i_pos) const; public: /// Computes brake pipe flow for MHZ_EN57 (covers handle positions -1..10 with EP/pneumatic mix). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Sets the reductor adjustment offset. - void SetReductor(double nAdj) /*override*/; + void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). - double GetSound(int i) /*override*/; + double GetSound(int i) override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Returns the regulator pressure (RP). - double GetCP() /*override*/; + double GetCP() override; /// Returns the regulator target (5 + RedAdj). - double GetRP() /*override*/; + double GetRP() override; /// Returns EP brake intensity for the given handle position. - double GetEP(double pos); + double GetEP(double pos) override; /// Configures handle parameters (auto/manual overcharge, over-pressure, overcharge dynamics). - void SetParams(bool AO, bool MO, double OverP, double, double OMP, double OPD); + void SetParams(bool AO, bool MO, double OverP, double, double OMP, double OPD) override; /// Default constructor. - inline TMHZ_EN57(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /// /// MHZ_K5P — Knorr 5-position combined brake handle. @@ -1232,7 +1247,6 @@ class TMHZ_K5P : public TDriverHandle /// Time chamber pressure [bar]. double TP = 0.0; // zbiornik czasowy /// Reductor reservoir pressure [bar]. - double RP = 0.0; // zbiornik redukcyjny /// Reductor adjustment offset. double RedAdj = 0.0; // dostosowanie reduktora cisnienia (krecenie kapturkiem) /// True while filling-stroke / release wave is active. @@ -1249,29 +1263,28 @@ class TMHZ_K5P : public TDriverHandle static double const pos_table[11]; //= { -2, 10, -1, 0, 0, 2, 9, 10, 0, 0, 0 }; /// Returns true if pos is within ±0.5 of i_pos. - bool EQ(double pos, double i_pos); + bool EQ(double pos, double i_pos) const; public: /// Computes brake pipe flow for the K5P 5-position handle (release / cut-off / brake / emergency). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chambers. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Sets the reductor adjustment offset. - void SetReductor(double nAdj) /*override*/; + void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). - double GetSound(int i) /*override*/; + double GetSound(int i) override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Returns CP. - double GetCP() /*override*/; + double GetCP() override; /// Returns the regulator target (5 + TP + RedAdj). - double GetRP() /*override*/; + double GetRP() override; /// Configures handle parameters (auto/manual overcharge, over-pressure, filling-stroke factor, overcharge dynamics). - void SetParams(bool AO, bool MO, double, double, double OMP, double OPD); /*ovveride*/ + void SetParams(bool AO, bool MO, double, double, double OMP, double OPD) override; /// Default constructor. - inline TMHZ_K5P(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /// /// MHZ_6P — 6-position combined brake handle (similar logic to K5P with one more detent). @@ -1285,7 +1298,6 @@ class TMHZ_6P : public TDriverHandle /// Time chamber pressure [bar]. double TP = 0.0; // zbiornik czasowy /// Reductor reservoir pressure [bar]. - double RP = 0.0; // zbiornik redukcyjny /// Reductor adjustment offset. double RedAdj = 0.0; // dostosowanie reduktora cisnienia (krecenie kapturkiem) /// True while filling-stroke / release wave is active. @@ -1302,29 +1314,28 @@ class TMHZ_6P : public TDriverHandle static double const pos_table[11]; //= { -2, 10, -1, 0, 0, 2, 9, 10, 0, 0, 0 }; /// Returns true if pos is within ±0.5 of i_pos. - bool EQ(double pos, double i_pos); + bool EQ(double pos, double i_pos) const; public: /// Computes brake pipe flow for the 6P handle. - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chambers. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Sets the reductor adjustment offset. - void SetReductor(double nAdj) /*override*/; + void SetReductor(double nAdj) override; /// Returns Sounds[i] (or 0 if i > 4). - double GetSound(int i) /*override*/; + double GetSound(int i) override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Returns CP. - double GetCP() /*override*/; + double GetCP() override; /// Returns the regulator target (5 + TP + RedAdj). - double GetRP() /*override*/; + double GetRP() override; /// Configures handle parameters (auto/manual overcharge, over-pressure, filling-stroke factor, overcharge dynamics). - void SetParams(bool AO, bool MO, double, double, double OMP, double OPD); /*ovveride*/ + void SetParams(bool AO, bool MO, double, double, double OMP, double OPD) override; /// Default constructor. - inline TMHZ_6P(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /* FBS2= class(TTDriverHandle) private @@ -1372,17 +1383,17 @@ class TM394 : public TDriverHandle public: /// Computes brake pipe flow for the M394 handle (uses BPT_394). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chamber. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Sets the reductor adjustment offset. - void SetReductor(double nAdj) /*override*/; + void SetReductor(double nAdj) override; /// Returns CP. - double GetCP() /*override*/; + double GetCP() override; /// Returns max(5, CP) + RedAdj. - double GetRP() /*override*/; + double GetRP() override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Default constructor — sets the maximum handle position to 5. inline TM394(void) : TDriverHandle() @@ -1411,17 +1422,17 @@ class TH14K1 : public TDriverHandle public: /// Computes brake pipe flow for the H14K1 handle. - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP and enables the time chambers. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Sets the reductor adjustment offset. - void SetReductor(double nAdj) /*override*/; + void SetReductor(double nAdj) override; /// Returns CP. - double GetCP() /*override*/; + double GetCP() override; /// Returns the regulator target (5 + RedAdj). - double GetRP() /*override*/; + double GetRP() override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Default constructor — sets the maximum handle position to 4. inline TH14K1(void) : TDriverHandle() @@ -1450,21 +1461,20 @@ class TSt113 : public TH14K1 public: /// Computes brake pipe flow for the St113 handle (with EP). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Returns CP. - double GetCP() /*override*/; + double GetCP() override; /// Returns the regulator target (5 + RedAdj). - double GetRP() /*override*/; + double GetRP() override; /// Returns the current EP intensity. - double GetEP() /*override*/; + double GetEP() override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Enables the time chambers (no pressure init). - void Init(double Press) /*override*/; + void Init(double Press) override; /// Default constructor. - inline TSt113(void) : TH14K1() {} -}; + using TH14K1::TH14K1;}; /// /// Test handle — minimal implementation used during development for verifying @@ -1479,13 +1489,12 @@ class Ttest : public TDriverHandle public: /// Computes brake pipe flow using the FV4a-style BPT table for testing. - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises CP. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Default constructor. - inline Ttest(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /// /// FD1 auxiliary brake handle — directly drives the cylinder pressure between @@ -1505,18 +1514,17 @@ class TFD1 : public TDriverHandle double Speed = 0.0; // szybkosc dzialania /// Computes the auxiliary brake outflow for this step. - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises MaxBP and the action speed. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Returns the currently commanded cylinder pressure (BP). - double GetCP() /*override*/; + double GetCP() override; /// Sets the action speed multiplier. void SetSpeed(double nSpeed); // procedure Init(press: real; MaxBP: real); overload; /// Default constructor. - inline TFD1(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /// /// H1405 — Knorr auxiliary brake handle (continuous, independent brake). @@ -1532,16 +1540,15 @@ class TH1405 : public TDriverHandle public: /// Computes the auxiliary brake outflow for this step (proportional to handle deflection). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Initialises MaxBP and enables the time chamber. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Returns the currently commanded cylinder pressure (BP). - double GetCP() /*override*/; + double GetCP() override; // procedure Init(press: real; MaxBP: real); overload; /// Default constructor. - inline TH1405(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /// /// FVel6 — combined EP + pneumatic brake handle (Czech, 6+1 positions). @@ -1559,23 +1566,22 @@ class TFVel6 : public TDriverHandle public: /// Computes brake pipe flow for FVel6 (continuous EP brake plus pneumatic emergency). - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Returns CP. - double GetCP() /*override*/; + double GetCP() override; /// Returns the regulator target (constant 5 bar). - double GetRP() /*override*/; + double GetRP() override; /// Returns the current EP intensity. - double GetEP() /*override*/; + double GetEP() override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Returns Sounds[i] (or 0 if i > 2). - double GetSound(int i) /*override*/; + double GetSound(int i) override; /// Enables the time chambers. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Default constructor. - inline TFVel6(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /// /// FVE408 — newer combined EP + pneumatic brake handle (10 positions). @@ -1594,23 +1600,22 @@ class TFVE408 : public TDriverHandle public: /// Computes brake pipe flow for the FVE408 handle. - double GetPF(double i_bcp, double PP, double HP, double dt, double ep) /*override*/; + double GetPF(double i_bcp, double PP, double HP, double dt, double ep) override; /// Returns CP. - double GetCP() /*override*/; + double GetCP() override; /// Returns the current EP intensity. - double GetEP() /*override*/; + double GetEP() override; /// Returns the regulator target (constant 5 bar). - double GetRP() /*override*/; + double GetRP() override; /// Returns pos_table[i]. - double GetPos(int i) /*override*/; + double GetPos(int i) override; /// Returns Sounds[i] (or 0 if i > 2). - double GetSound(int i) /*override*/; + double GetSound(int i) override; /// Enables the time chamber, disables the EP-time chamber. - void Init(double Press) /*override*/; + void Init(double Press) override; /// Default constructor. - inline TFVE408(void) : TDriverHandle() {} -}; + using TDriverHandle::TDriverHandle;}; /// /// Pneumatic flow rate from one pressure to another through an orifice of area S. diff --git a/README.md b/README.md index 47741a511..675026ccf 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ MaSzyna compiles and runs natively on **Linux** and **Windows**. Other platforms ## Windows -Install **Python 3.14 x64** from [python.org](https://www.python.org/downloads/windows/) and include the optional **Python native development** feature (headers and `.lib` for embedding). Pass `-DPython3_ROOT_DIR="C:\Path\To\Python314"` on the `cmake` line when you want the layout under that directory used for embedding and for copying `Lib` / `DLLs` next to the executable. +Install **Python 3.14 x64** from [python.org](https://www.python.org/downloads/windows/) and include the optional **Python native development** feature (headers and `.lib` for embedding). Pass `-DPython3_ROOT_DIR="C:\Path\To\Python314"` on the `cmake` line when you want the layout under that directory used for embedding and for copying `Lib` / `DLLs` next to the executable. The cab screens are drawn with [Pillow](https://pypi.org/project/pillow/): install it into that Python (`python -m pip install Pillow`) before building, so it is copied along with `Lib`. **AppVeyor CI** builds with the worker image’s preinstalled Python at `C:/Python314-x64` (see [`appveyor.yml`](./appveyor.yml): `-DPython3_ROOT_DIR=...`). diff --git a/application/application.cpp b/application/application.cpp index a6b88ae87..96f578514 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -18,20 +18,25 @@ http://mozilla.org/MPL/2.0/. #include "utilities/utilities.h" #include "simulation/simulation.h" #include "simulation/simulationsounds.h" +#include "simulation/blackboxrecorder.h" #include "vehicle/Train.h" #include "utilities/dictionary.h" #include "scene/sceneeditor.h" #include "rendering/renderer.h" #include "application/uilayer.h" #include "utilities/Logs.h" +#include "world/SleeperWorker.h" #include "rendering/screenshot.h" #include "utilities/translation.h" #include "vehicle/Train.h" #include "utilities/Timer.h" +#include "utilities/framepacer.h" #include "utilities/dictionary.h" #include "version_info.h" +#include "simulation/simulationtest.h" #include #include +#include #include "utilities/translation.h" #if WITH_DISCORD_RPC @@ -74,9 +79,17 @@ extern WNDPROC BaseWindowProc; void focus_callback(GLFWwindow *window, int focus) { + ui_layer::focus_callback(focus); Application.on_focus_change(focus != 0); } +void cursor_enter_callback(GLFWwindow *window, int entered) +{ + if (scripted_input::driving()) + return; + ui_layer::cursor_enter_callback(entered); +} + void framebuffer_resize_callback(GLFWwindow *, int w, int h) { Global.fb_size = glm::ivec2(w, h); @@ -90,28 +103,39 @@ void window_resize_callback(GLFWwindow *, int w, int h) void cursor_pos_callback(GLFWwindow *window, double x, double y) { + if (scripted_input::driving()) + return; + ui_layer::cursor_pos_callback(x, y); Global.cursor_pos = glm::ivec2(x, y); Application.on_cursor_pos(x, y); } void mouse_button_callback(GLFWwindow *window, int button, int action, int mods) { + if (scripted_input::driving()) + return; Application.on_mouse_button(button, action, mods); } void scroll_callback(GLFWwindow *window, double xoffset, double yoffset) { + if (scripted_input::driving()) + return; Application.on_scroll(xoffset, yoffset); } void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods) { + if (scripted_input::driving()) + return; Application.on_key(key, scancode, action, mods); } void char_callback(GLFWwindow *window, unsigned int c) { + if (scripted_input::driving()) + return; Application.on_char(c); } @@ -263,7 +287,11 @@ void eu07_application::DiscordRPCService() } if (currentMode != mode::driver) + { + // the editor and the other modes: nothing to tell, without spinning a core on it + std::this_thread::sleep_for(std::chrono::milliseconds(250)); continue; + } // Discord RPC updater if (simulation::is_ready) @@ -309,6 +337,9 @@ int eu07_application::init(int Argc, char *Argv[]) { int result{0}; + // a test run is known before anything is logged: whoever started it reads its result on the standard output, + // which the log isn't written to then (eu07/maszyna#541) + Global.test.enabled = simulation::parse_test_command_line(std::vector(Argv, Argv + Argc)).enabled; // start logging service std::thread sLoggingService(LogService); Global.threads.emplace("LogService", std::move(sLoggingService)); @@ -367,7 +398,7 @@ int eu07_application::init(int Argc, char *Argv[]) return result; } - if (crashreport_is_pending()) + if (crashreport_is_pending() && false == Global.test.enabled) { // run crashgui as early as possible if ((result = run_crashgui()) != 0) { @@ -408,6 +439,16 @@ int eu07_application::init(int Argc, char *Argv[]) { m_taskqueue.init(); } + crashreport_add_info("luascreens_enabled", Global.luascreens_enabled ? "yes" : "no"); + crashreport_add_info("wasm_enabled", Global.wasm_enabled ? "yes" : "no"); + if (Global.luascreens_enabled || Global.wasm_enabled) + { + m_screenqueue.init(); + if (Global.screens_gpupost) + { + m_screenqueue.set_post_processor(GfxRenderer->Screen_post_processor()); + } + } if ((result = init_modes()) != 0) { ErrorLog("Failed to initialize game modes"); @@ -417,8 +458,12 @@ int eu07_application::init(int Argc, char *Argv[]) #if WITH_DISCORD_RPC // Run DiscordRPC service - std::thread sDiscordRPC(&eu07_application::DiscordRPCService, this); - Global.threads.emplace("DiscordRPC", std::move(sDiscordRPC)); + // not for a test run: it would show the test scenery as the player's presence, and hold up the closing + if (false == Global.test.enabled) + { + std::thread sDiscordRPC(&eu07_application::DiscordRPCService, this); + Global.threads.emplace("DiscordRPC", std::move(sDiscordRPC)); + } #endif if (!init_network()) @@ -468,9 +513,14 @@ bool eu07_application::is_client() const int eu07_application::run() { auto frame{0}; + frame_pacer framepacer; + Timer::subsystem.mainloop_period.start(); // main application loop while (!glfwWindowShouldClose(m_windows.front()) && !m_modestack.empty()) { + // the time from one frame's start to the next, the wait for fpslimit included + Timer::subsystem.mainloop_period.stop(); + Timer::subsystem.mainloop_period.start(); Timer::subsystem.mainloop_total.start(); glfwPollEvents(); @@ -498,7 +548,7 @@ int eu07_application::run() { command_queue::commands_map commands_to_exec; command_queue::commands_map local_commands = simulation::Commands.pop_intercept_queue(); - double slave_sync; + double slave_sync{0.0}; // if we're the server if (m_network && m_network->servers) @@ -562,7 +612,7 @@ int eu07_application::run() if (m_network && m_network->client) { // verify sync - if (sync != slave_sync) + if (sync != slave_sync) // NOSONAR slave_sync is initialised, the PR analysis keeps a stale report of the old declaration { WriteLog("net: desync! calculated: " + std::to_string(sync) + ", received: " + std::to_string(slave_sync), logtype::net); @@ -609,6 +659,7 @@ int eu07_application::run() EditorTerrain.update(Global.pCamera.Pos); m_taskqueue.update(); + m_screenqueue.update(); opengl_texture::reset_unit_cache(); if (!GfxRenderer->Render()) @@ -630,10 +681,11 @@ int eu07_application::run() if (m_network) m_network->update(); - auto const frametime{Timer::subsystem.mainloop_total.stop()}; - if (Global.minframetime.count() != 0.0f && (Global.minframetime - frametime).count() > 0.0f) + Timer::subsystem.mainloop_total.stop(); + // fpslimit: wait for the next frame's slot (eu07/maszyna#416) + if (auto const nextframe{framepacer.next_frame(frame_pacer::clock::now(), Global.minframetime)}) { - std::this_thread::sleep_for(Global.minframetime - frametime); + std::this_thread::sleep_until(*nextframe); } } // Handled by application.exit @@ -683,28 +735,51 @@ void eu07_application::release_python_lock() void eu07_application::exit() { Global.applicationQuitOrder = true; + // each step of the closing in the log, to tell from it where a closing that hangs stops + auto const closing{std::chrono::steady_clock::now()}; + auto const step = [closing](char const *What) { + WriteLog(std::format("Closing: {} at {} ms", What, std::chrono::duration_cast(std::chrono::steady_clock::now() - closing).count())); + }; + step("the sleepers laid in the background"); + // the sleepers laid in the background read the scenery, which goes below + track_sleepers::stop_background(); + step("the black box"); + simulation::Blackbox.close(); + step("the modes"); for (auto &mode : m_modes) mode.reset(); + step("the renderer"); + // the screens' post-processing goes with the renderer + m_screenqueue.set_post_processor(nullptr); GfxRenderer->Shutdown(); m_network.reset(); // SafeDelete( simulation::Train ); + step("the odometers"); + simulation::Vehicles.save_odometers(); + step("the scenery"); SafeDelete(simulation::Region); + step("the ui and the python workers"); ui_layer::shutdown(); + // the python workers detach their GL context on the way out, so they have to be done before the windows they use are destroyed + m_taskqueue.exit(); + m_screenqueue.exit(); + step("the windows"); for (auto *window : m_windows) { glfwDestroyWindow(window); } - m_taskqueue.exit(); glfwPollEvents(); // TODO: This fixes a segfault on Wayland when closing. Remove after updating glfw to 3.5. glfwTerminate(); if (!Global.exec_on_exit.empty()) system(Global.exec_on_exit.c_str()); + step("done"); + StopLogService(); auto it = Global.threads.find("LogService"); if (it != Global.threads.end()) { @@ -927,14 +1002,17 @@ GLFWwindow *eu07_application::window(int const Windowindex, bool visible, int wi } // for index -1 create a new child window - auto const *vmode{glfwGetVideoMode(monitor ? monitor : glfwGetPrimaryMonitor())}; - - // match requested video mode to current to allow for - // fullwindow creation when resolution is the same - glfwWindowHint(GLFW_RED_BITS, vmode->redBits); - glfwWindowHint(GLFW_GREEN_BITS, vmode->greenBits); - glfwWindowHint(GLFW_BLUE_BITS, vmode->blueBits); - glfwWindowHint(GLFW_REFRESH_RATE, vmode->refreshRate); + auto *videomonitor{monitor ? monitor : glfwGetPrimaryMonitor()}; + // a machine without a display (e.g. a test runner) has no monitor to match + if (auto const *vmode{videomonitor ? glfwGetVideoMode(videomonitor) : nullptr}) + { + // match requested video mode to current to allow for + // fullwindow creation when resolution is the same + glfwWindowHint(GLFW_RED_BITS, vmode->redBits); + glfwWindowHint(GLFW_GREEN_BITS, vmode->greenBits); + glfwWindowHint(GLFW_BLUE_BITS, vmode->blueBits); + glfwWindowHint(GLFW_REFRESH_RATE, vmode->refreshRate); + } glfwWindowHint(GLFW_VISIBLE, visible); @@ -945,7 +1023,8 @@ GLFWwindow *eu07_application::window(int const Windowindex, bool visible, int wi if (keep_ownership) m_windows.emplace_back(childwindow); - glfwFocusWindow(m_windows.front()); // restore focus to main window + if (glfwGetWindowAttrib(m_windows.front(), GLFW_VISIBLE)) + glfwFocusWindow(m_windows.front()); // restore focus to main window return childwindow; } @@ -1014,6 +1093,13 @@ void eu07_application::init_debug() void eu07_application::init_console() { #ifdef _WIN32 + if (Global.test.enabled) + { + // a test is started by whoever waits for its result, often reading its output: no console of its own + // (showsystemconsole) pops up and takes stdout away from them, and a console it was started from isn't hidden + return; + } + HWND consoleWnd = ::GetConsoleWindow(); const bool hadConsole = consoleWnd != nullptr; @@ -1105,7 +1191,7 @@ void eu07_application::init_files() #elif __unix__ unlink("log.txt"); unlink("errors.txt"); - mkdir("logs", 0755); + mkdir("logs", 0750); #endif } namespace fs = std::filesystem; @@ -1114,9 +1200,30 @@ int eu07_application::init_settings(int Argc, char *Argv[]) { Global.asVersion = VERSION_INFO; + // a test run is known before the rest of the command line is read (Global.test.enabled, see init()), so a + // command line it can't take ends with the error code of the test, not with 0, which would pass it + auto const testcommandline{simulation::parse_test_command_line(std::vector(Argv, Argv + Argc))}; + if (false == testcommandline.error.empty()) + { + simulation::test().conclude(simulation::test_result::error, testcommandline.error); + return -1; + } + if (testcommandline.timeout.has_value()) + { + Global.test.timeout = *testcommandline.timeout; + Global.test.timeout_from_command_line = true; + } + if (testcommandline.wall_timeout.has_value()) + { + Global.test.wall_timeout = testcommandline.wall_timeout; + Global.test.wall_timeout_from_command_line = true; + } + fs::path iniPath = user_config_path("eu07.ini"); - if (!iniPath.empty() && fs::exists(iniPath)) + // a test reads the settings of the game folder only (and those given with -ini), not the player's own + // (%APPDATA%/MaSzyna, ~/.config/MaSzyna), so it runs the same for whoever runs it + if (false == Global.test.enabled && !iniPath.empty() && fs::exists(iniPath)) { Global.LoadIniFile(iniPath.string().c_str()); } @@ -1126,6 +1233,8 @@ int eu07_application::init_settings(int Argc, char *Argv[]) } // process command line arguments + bool sceneryfromcommandline{false}; + bool editwithoutscenery{false}; for (int i = 1; i < Argc; ++i) { @@ -1136,6 +1245,7 @@ int eu07_application::init_settings(int Argc, char *Argv[]) if (i + 1 < Argc) { Global.SceneryFile = ToLower(Argv[++i]); + sceneryfromcommandline = true; } } else if (token == "-v") @@ -1145,6 +1255,19 @@ int eu07_application::init_settings(int Argc, char *Argv[]) Global.local_start_vehicle = ToLower(Argv[++i]); } } + else if (token == "-edit") + { + // edit session: the scenery is loaded without player vehicle, straight into the editor + Global.editor_session = true; + Global.local_start_vehicle = "ghostview"; + if (i + 1 < Argc && Argv[i + 1][0] != '-') + { + Global.SceneryFile = ToLower(Argv[++i]); + sceneryfromcommandline = true; + } + else + editwithoutscenery = true; + } else if (token == "-seed") { // a number is the seed; anything else is a word that stands for one. said in the @@ -1155,14 +1278,50 @@ int eu07_application::init_settings(int Argc, char *Argv[]) WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed)); } } + else if (token == "--test") + { + // integration test: the scenery runs unattended and the exit code is the result (eu07/maszyna#541), + // taken from the command line above + } + else if (token == "--test-timeout" || token == "--test-wall-timeout") + { + // taken from the command line above, with its value + ++i; + } + else if (token == "-ini") + { + // extra settings file read on top of eu07.ini, so a run can override a few keys + // (window size, physicslog...) without touching the user's own config + if (i + 1 < Argc) + { + Global.LoadIniFile(Argv[++i]); + } + } else { - std::cout << "usage: " << std::string(Argv[0]) << " [-s sceneryfilepath]" + // a test's standard output carries its result only + (Global.test.enabled ? std::cerr : std::cout) << "usage: " << std::string(Argv[0]) << " [-s sceneryfilepath]" << " [-v vehiclename]" - << " [-seed number|word]" << std::endl; + << " [-edit [sceneryfilepath]]" + << " [-seed number|word]" + << " [-ini settingsfile]" + << " [--test [--test-timeout seconds] [--test-wall-timeout seconds]]" << std::endl; + simulation::test().conclude(simulation::test_result::error, std::format("unknown command line argument {}", token)); return -1; } } + if (editwithoutscenery && false == sceneryfromcommandline) + Global.SceneryFile.clear(); + + if (Global.test.enabled) + { + if (false == sceneryfromcommandline || Global.SceneryFile.empty()) + { + simulation::test().conclude(simulation::test_result::error, "--test needs a scenery given with -s"); + return -1; + } + simulation::apply_test_mode_settings(); + } return 0; } @@ -1237,6 +1396,12 @@ int eu07_application::init_glfw() { glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); } + else if (Global.test.enabled) + { + // the null renderer draws nothing, but parts of the ui make textures with gl calls of their own. + // any context will do for them, so none is asked for in particular: a machine without a graphics + // driver (a test runner) has only the basic one of the system + } else { if (!Global.LegacyRenderer) @@ -1288,7 +1453,10 @@ int eu07_application::init_glfw() Global.bFullScreen = true; } - auto *mainwindow = window(-1, true, Global.window_size.x, Global.window_size.y, Global.bFullScreen ? monitor : nullptr, true, false); + // test mode keeps its window hidden: glfw, the ui and the input still need one, but nothing is shown in it. + // so does a selftest of the editor run while the computer is in use for something else: never shown nor focused + bool const shown{false == Global.test.enabled && selftest_script("EU07_EDITOR_SELFTEST_HIDDEN") == nullptr}; + auto *mainwindow = window(-1, shown, Global.window_size.x, Global.window_size.y, Global.bFullScreen && shown ? monitor : nullptr, true, false); if (mainwindow == nullptr) { @@ -1312,7 +1480,9 @@ int eu07_application::init_glfw() #ifdef _WIN32 // setup wrapper for base glfw window proc, to handle copydata messages Hwnd = glfwGetWin32Window(mainwindow); - BaseWindowProc = (WNDPROC)::SetWindowLongPtr(Hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc); + // commands sent by other programs are input from outside, which a test doesn't take + if (false == Global.test.enabled) + BaseWindowProc = (WNDPROC)::SetWindowLongPtr(Hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc); // switch off the topmost flag ::SetWindowPos(Hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); #endif @@ -1326,12 +1496,18 @@ void eu07_application::init_callbacks() auto *window{m_windows.front()}; glfwSetWindowSizeCallback(window, window_resize_callback); glfwSetFramebufferSizeCallback(window, framebuffer_resize_callback); + glfwSetWindowFocusCallback(window, focus_callback); + glfwSetCursorEnterCallback(window, cursor_enter_callback); + if (Global.test.enabled) + { + // a test takes no input: keys and clicks sent to its hidden window would change the run + return; + } glfwSetCursorPosCallback(window, cursor_pos_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetKeyCallback(window, key_callback); glfwSetScrollCallback(window, scroll_callback); glfwSetCharCallback(window, char_callback); - glfwSetWindowFocusCallback(window, focus_callback); } int eu07_application::init_ogl() @@ -1374,6 +1550,11 @@ int eu07_application::init_gfx() // default render path GfxRenderer = gfx_renderer_factory::get_instance()->create("modern"); } + else if (Global.GfxRenderer == "null") + { + // draws nothing and loads no textures (test mode) + GfxRenderer = gfx_renderer_factory::get_instance()->create("null"); + } else if (Global.GfxRenderer == "experimental") { GfxRenderer = gfx_renderer_factory::get_instance()->create(Global.GfxRenderer); @@ -1437,7 +1618,8 @@ int eu07_application::init_data() int eu07_application::init_modes() { - Global.local_random_engine.seed(static_cast(true_random_seed())); + // local cosmetics only (sound pitch, editor placement), never security related + Global.local_random_engine.seed(static_cast(true_random_seed())); // NOSONAR if ((!Global.network_servers.empty() || Global.network_client) && Global.SceneryFile.empty()) { @@ -1479,11 +1661,8 @@ bool eu07_application::init_network() // TODO: sort out this timezone mess std::time_t utc_now = std::time(nullptr); - tm tm_local, tm_utc; - tm *tmp = std::localtime(&utc_now); - memcpy(&tm_local, tmp, sizeof(tm)); - tmp = std::gmtime(&utc_now); - memcpy(&tm_utc, tmp, sizeof(tm)); + std::tm const tm_local = local_tm(utc_now); + std::tm const tm_utc = utc_tm(utc_now); int64_t offset = tm_local.tm_hour * 3600 + tm_local.tm_min * 60 + tm_local.tm_sec - (tm_utc.tm_hour * 3600 + tm_utc.tm_min * 60 + tm_utc.tm_sec); diff --git a/application/application.h b/application/application.h index 11415603b..850b66e1e 100644 --- a/application/application.h +++ b/application/application.h @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "application/applicationmode.h" #include "scripting/PyInt.h" +#include "scripting/scriptscreens.h" #include "network/manager.h" #include "utilities/headtrack.h" #ifdef WITH_UART @@ -49,6 +50,10 @@ public: // frees the python gil and swaps out the main thread void release_python_lock(); + // the screens drawn by scripts (Lua, WebAssembly) + script_screen_queue & + screens() { + return m_screenqueue; } void exit(); void @@ -122,6 +127,7 @@ private: modeptr_array m_modes { nullptr }; // collection of available application behaviour modes mode_stack m_modestack; // current behaviour mode python_taskqueue m_taskqueue; + script_screen_queue m_screenqueue; std::vector m_windows; int m_glfwversion; diff --git a/application/applicationmode.h b/application/applicationmode.h index feea3bdb6..4f32fc5f9 100644 --- a/application/applicationmode.h +++ b/application/applicationmode.h @@ -25,19 +25,19 @@ public: virtual bool update() = 0; // draws mode-specific user interface inline - void render_ui() { + void render_ui() const { if( m_userinterface != nullptr ) { m_userinterface->render(); } } inline - void begin_ui_frame() { + void begin_ui_frame() const { if( m_userinterface != nullptr ) { m_userinterface->begin_ui_frame(); } } inline - void set_progress( float const Progress = 0.f, float const Subtaskprogress = 0.f ) { + void set_progress( float const Progress = 0.f, float const Subtaskprogress = 0.f ) const { if( m_userinterface != nullptr ) { m_userinterface->set_progress( Progress, Subtaskprogress ); } } inline - void set_tooltip( std::string const &Tooltip ) { + void set_tooltip( std::string const &Tooltip ) const { if( m_userinterface != nullptr ) { m_userinterface->set_tooltip( Tooltip ); } } // maintenance method, called when the mode is activated diff --git a/application/driverhints.cpp b/application/driverhints.cpp index afa654cfd..0c6f02cc8 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -38,7 +38,7 @@ void TController::remove_hint( driver_hint const Value ) { m_hints.remove_if( - [=]( auto const &Hint ) { + [Value]( auto const &Hint ) { return std::get(Hint) == Value; } ); } @@ -87,7 +87,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::batteryoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->BatteryStart != start_t::manual || mvOccupied->Power24vIsAvailable == true; } ); break; } @@ -98,7 +98,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::batteryon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->BatteryStart != start_t::manual || mvOccupied->Power24vIsAvailable == false; } ); break; } @@ -111,7 +111,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::cabdeactivation ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->AutomaticCabActivation || mvOccupied->IsCabMaster(); } ); break; } @@ -122,7 +122,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::cabactivation ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->AutomaticCabActivation || (mvOccupied->CabMaster == false && mvOccupied->CabActive == 0); } ); break; } @@ -134,17 +134,27 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::radiooff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->Radio == true; } ); break; } + case driver_hint::radiofuseon: { + if( AIControllFlag ) { + mvOccupied->RadioFuse = true; + } + hint( + Action, + [this](float const /*Parameter*/) { + return mvOccupied->RadioFuse == true; } ); + break; + } case driver_hint::radiochannel: { if( AIControllFlag ) { iRadioChannel = static_cast( Actionparameter ); } hint( Action, - [this](float const Parameter) -> bool { + [this](float const Parameter) { return iRadioChannel == static_cast(Parameter); }, Actionparameter ); break; @@ -156,7 +166,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::radioon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->Radio == false; } ); break; } @@ -168,7 +178,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::oilpumpoff ); hint( Action, - [this](float const Parameter) -> bool { + [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; } ); break; @@ -180,7 +190,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::oilpumpon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvOccupied->OilPump }; return device.start_type != start_t::manual || (device.is_enabled == false && device.is_active == false); } ); break; @@ -193,7 +203,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::fuelpumpoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvOccupied->FuelPump }; return device.start_type != start_t::manual || device.is_enabled == true || device.is_active == true; } ); break; @@ -205,7 +215,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::fuelpumpon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvOccupied->FuelPump }; return device.start_type != start_t::manual || (device.is_enabled == false && device.is_active == false); } ); break; @@ -218,7 +228,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::pantographairsourcesetauxiliary ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->bPantKurek3 == true; } ); break; } @@ -229,7 +239,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::pantographcompressoron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->bPantKurek3 == false; } ); break; } @@ -240,7 +250,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::pantographcompressoroff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->PantCompFlag == true; } ); break; } @@ -251,7 +261,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::pantographcompressoron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->PantCompFlag == false; } ); break; } @@ -262,7 +272,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::pantographsvalveoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->PantsValve.is_active == true; } ); break; } @@ -273,7 +283,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::frontpantographvalveoff ); hint( Action, - [ this ]( float const Parameter ) -> bool { + [ this ]( float const Parameter ) { return mvPantographUnit->Pantographs[end::front].valve.is_active == true || (Parameter > 0 && mvOccupied->Vel > Parameter); }, Actionparameter ); break; @@ -285,7 +295,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::frontpantographvalveon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->Pantographs[end::front].valve.is_active == false; } ); break; } @@ -296,7 +306,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::rearpantographvalveoff ); hint( Action, - [ this ]( float const Parameter ) -> bool { + [ this ]( float const Parameter ) { return mvPantographUnit->Pantographs[end::rear].valve.is_active == true || (Parameter > 0 && mvOccupied->Vel > Parameter); }, Actionparameter ); break; @@ -308,7 +318,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::rearpantographvalveon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->Pantographs[end::rear].valve.is_active == false; } ); break; } @@ -316,11 +326,19 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) case driver_hint::converteron: { if( AIControllFlag ) { mvOccupied->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, + []( TDynamicObject * Vehicle ) { + auto *vehicle { Vehicle->MoverParameters }; + if( vehicle->LineContactorsHeldByLocalConverterSwitch() ) { + vehicle->ConverterAllowLocal = true; } } ); } remove_hint( driver_hint::converteroff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyConverterEnabled == true; } ); break; } @@ -331,7 +349,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::converteron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyConverterExplicitlyEnabled == false; } ); break; } @@ -342,7 +360,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->ConverterOverloadRelayStart != start_t::manual || mvOccupied->ConvOvldFlag == false; } ); break; } @@ -352,7 +370,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->GroundRelayStart != start_t::manual || mvOccupied->GroundRelay == true; } ); break; } @@ -362,7 +380,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->FuseFlag == false; } ); break; } @@ -374,7 +392,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::linebreakeropen ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyLineBreakerOpen == false; } ); break; } @@ -385,7 +403,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::linebreakerclose ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { // TBD, TODO: replace with consist-wide flag set true if any line breaker is closed? return mvControlling->Mains == false; } ); break; @@ -398,7 +416,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::compressoroff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyCompressorEnabled == true; } ); break; } @@ -409,7 +427,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::compressoron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyCompressorExplicitlyEnabled == false; } ); break; } @@ -421,7 +439,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::frontmotorblowersoff ); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { auto const &device { mvOccupied->MotorBlowers[ end::front ] }; return device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false); } ); break; @@ -434,7 +452,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::rearmotorblowersoff ); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { auto const &device { mvOccupied->MotorBlowers[ end::rear ] }; return device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false); } ); break; @@ -447,7 +465,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::springbrakeoff ); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { return mvOccupied->SpringBrake.Activate == true; } ); break; } @@ -458,7 +476,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::springbrakeon ); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { return mvOccupied->SpringBrake.Activate == false; } ); break; } @@ -470,7 +488,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::manualbrakoff ); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { return mvOccupied->LocalBrake != TLocalBrake::ManualBrake || mvOccupied->MBrake == false || mvOccupied->ManualBrakePos == ManualBrakePosNo; } ); break; } @@ -481,7 +499,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::manualbrakon ); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { return mvOccupied->LocalBrake != TLocalBrake::ManualBrake || mvOccupied->MBrake == false || mvOccupied->ManualBrakePos == 0; } ); break; } @@ -490,33 +508,31 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) if( AIControllFlag ) { while( mvControlling->RList[mvControlling->MainCtrlPos].Mn == 0 && mvControlling->IncMainCtrl(1) ) { - ; + // all work is done in the loop header } } remove_master_controller_hints(); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { return mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0; } ); break; } case driver_hint::mastercontrollersetseriesmode: { - if( AIControllFlag ) { - if( mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1 ) { - // limit yourself to series mode - if( mvControlling->ScndCtrlPos ) { - mvControlling->DecScndCtrl( 2 ); - } - while( mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 - && mvControlling->DecMainCtrl(1) ) { - ; // all work is performed in the header - } + if (AIControllFlag && mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1) { + // limit yourself to series mode + if( mvControlling->ScndCtrlPos ) { + mvControlling->DecScndCtrl( 2 ); + } + while( mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 + && mvControlling->DecMainCtrl(1) ) { + // all work is performed in the header } } remove_master_controller_hints(); hint( Action, - [this]( float const Parameter ) -> bool { + [this]( float const /*Parameter*/ ) { return mvControlling->RList[mvControlling->MainCtrlPos].Bn < 2; } ); break; } @@ -527,7 +543,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_master_controller_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->IsMainCtrlNoPowerPos() && mvControlling->IsScndCtrlNoPowerPos(); } ); break; } @@ -535,15 +551,15 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) if( AIControllFlag ) { while( false == mvControlling->EIMDirectionChangeAllow() && mvControlling->DecMainCtrl(1) ) { - ; + // all work is done in the loop header } } remove_master_controller_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->EIMDirectionChangeAllow(); }, - mvControlling->MainCtrlMaxDirChangePos ); + static_cast(mvControlling->MainCtrlMaxDirChangePos) ); break; } case driver_hint::tractiveforcedecrease: { @@ -553,13 +569,13 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_master_controller_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const Parameter) { return std::abs(mvControlling->Ft) <= Parameter; }, - std::min( + static_cast(std::min( 0.0, std::max( std::abs( mvControlling->Ft ) * 0.95, - std::abs( mvControlling->Ft ) - 5.0 ) ) ); + std::abs( mvControlling->Ft ) - 5.0 ) )) ); break; } case driver_hint::tractiveforceincrease: { @@ -575,21 +591,19 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } hint( Action, - [this](float const Parameter) -> bool { + [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()); } ); break; } case driver_hint::bufferscompress: { - if( AIControllFlag ) { - if( std::abs( mvControlling->Ft ) < 50000.0 ) { - IncSpeed(); - } + if (AIControllFlag && std::abs( mvControlling->Ft ) < 50000.0) { + IncSpeed(); } remove_master_controller_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return std::abs(mvControlling->Ft) > 30.0 || (OrderCurrentGet() & Disconnect) == 0; } ); break; } @@ -601,7 +615,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_master_controller_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->IsScndCtrlNoPowerPos(); } ); break; } @@ -613,7 +627,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterpumpoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterPump }; return device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false) || device.is_active == true; } ); break; @@ -625,7 +639,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterpumpon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterPump }; return device.start_type != start_t::manual || (device.is_enabled == false && device.is_active == false); } ); break; @@ -637,7 +651,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterpumpbreakeroff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterPump }; return device.breaker == true; } ); break; @@ -649,7 +663,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterpumpbreakeron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterPump }; return device.breaker == false; } ); break; @@ -661,7 +675,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterheateroff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterHeater }; return device.is_enabled == true; } ); break; @@ -673,7 +687,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterheateron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterHeater }; return device.is_enabled == false; } ); break; @@ -685,7 +699,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterheaterbreakeroff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterHeater }; return device.breaker == true; } ); break; @@ -697,7 +711,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::waterheaterbreakeron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvControlling->WaterHeater }; return device.breaker == false; } ); break; @@ -709,7 +723,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::watercircuitslinkoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->dizel_heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink == true; } ); break; } @@ -720,7 +734,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::watercircuitslinkon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->dizel_heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink == false; } ); break; } @@ -728,7 +742,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // NOTE: this action doesn't have AI component hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return false == IsHeatingTemperatureTooLow; } ); break; } @@ -736,7 +750,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // NOTE: this action doesn't have AI component hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->ScndPipePress > 4.5 || mvControlling->VeselVolume == 0.0; } ); break; } @@ -744,7 +758,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // NOTE: this action doesn't have AI component hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvPantographUnit->PantPress >= (is_emu() ? (mvPantographUnit->PantPressLockActive ? 4.6 : 2.6) : 4.2); } ); break; } @@ -752,7 +766,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // NOTE: this action doesn't have AI component hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return ExchangeTime <= 0; } ); break; } @@ -760,7 +774,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // NOTE: this action doesn't have AI component hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAtPassengerStop == false; } ); break; } @@ -773,19 +787,16 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // driver_hint_brakingforcesetzero // driver_hint_brakingforcelap case driver_hint::trainbrakesetpipeunlock: { - if( AIControllFlag ) { - if( mvOccupied->HandleUnlock != -3 ) { - while( BrakeCtrlPosition >= mvOccupied->HandleUnlock - && BrakeLevelAdd(-1) ) { - // all work is done in the header - ; - } + if (AIControllFlag && mvOccupied->HandleUnlock != -3) { + while( BrakeCtrlPosition >= mvOccupied->HandleUnlock + && BrakeLevelAdd(-1) ) { + // all work is done in the header } } remove_train_brake_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->HandleUnlock == -3 || BrakeCtrlPosition == mvOccupied->HandleUnlock; } ); break; } @@ -797,7 +808,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_train_brake_hints(); hint( Action, - [this](float const Parameter) -> bool { + [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 ( BrakeCtrlPosition == gbh_RP ); } ); break; @@ -815,7 +826,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_train_brake_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsConsistBraked /*|| ( ( OrderCurrentGet() & Disconnect ) == 0 ) */; } ); break; } @@ -830,9 +841,9 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_train_brake_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const Parameter) { return std::abs(mvControlling->Fb) <= Parameter; }, - std::min( 0.0, 0.95 * std::abs( mvControlling->Fb ) ) ); // keep hint until 5% decrease + static_cast(std::min( 0.0, 0.95 * std::abs( mvControlling->Fb ) )) ); // keep hint until 5% decrease break; } case driver_hint::brakingforceincrease: { @@ -846,23 +857,25 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_train_brake_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const Parameter) { return std::abs(mvControlling->Fb) > Parameter || is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_EB), 0.2); }, - std::max( + static_cast(std::max( 0.0, std::max( std::abs( mvControlling->Fb ) * 1.05, - std::abs( mvControlling->Fb ) + 5.0 ) ) ); + std::abs( mvControlling->Fb ) + 5.0 ) )) ); break; } case driver_hint::brakingforcesetzero: { // releases both train and independent brake if( AIControllFlag ) { - while( true == DecBrake() ) { ; } + while( true == DecBrake() ) { + // all work is done in the loop condition + } } remove_train_brake_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return Ready && fReady < 0.4 && is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_RP), 0.2); } ); break; } @@ -877,18 +890,16 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // independent brake case driver_hint::independentbrakeapply: { - if( AIControllFlag ) { - if( mvOccupied->LocalBrakePosA < 1.0 ) { - mvOccupied->IncLocalBrakeLevel( LocalBrakePosNo ); - if (mvOccupied->EIMCtrlEmergency) { - mvOccupied->DecLocalBrakeLevel(1); + if (AIControllFlag && mvOccupied->LocalBrakePosA < 1.0) { + mvOccupied->IncLocalBrakeLevel( LocalBrakePosNo ); + if (mvOccupied->EIMCtrlEmergency) { + mvOccupied->DecLocalBrakeLevel(1); } - } } remove_hint( driver_hint::independentbrakerelease ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const Parameter) { return mvOccupied->LocalBrakePosA >= Parameter; }, ( LocalBrakePosNo - ( mvOccupied->EIMCtrlEmergency ? 1 : 0 ) ) / LocalBrakePosNo ); break; @@ -900,7 +911,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::independentbrakeapply ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->LocalBrakePosA < 0.05; } ); break; } @@ -912,7 +923,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_reverser_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->DirActive * mvOccupied->CabActive > 0; } ); break; } @@ -923,7 +934,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_reverser_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->DirActive * mvOccupied->CabActive < 0; } ); break; } @@ -936,7 +947,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_reverser_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return iDirection == iDirectionOrder; } ); break; } @@ -947,7 +958,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_reverser_hints(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->DirActive == 0; } ); break; } @@ -959,7 +970,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::sandingoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->Sand == 0 || mvControlling->SandDose == true || mvControlling->SlippingWheels == false; } ); break; } @@ -970,7 +981,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::sandingon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->Sand == 0 || mvControlling->SandDose == false; } ); break; } @@ -980,7 +991,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvControlling->ASBType != 1 || (mvControlling->Hamulec->GetBrakeStatus() & b_asb) != 0 || mvControlling->SlippingWheels == false; } ); break; } @@ -992,7 +1003,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::hornoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { // NOTE: we provide slightly larger horn activation window for human driver return fWarningDuration + 5.0 < 0.05 || mvOccupied->WarningSignal != 0; } ); break; @@ -1019,7 +1030,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // TODO: remove other door lock hints hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->Doors.has_lock == false || mvOccupied->Doors.lock_enabled == true; } ); break; } @@ -1031,7 +1042,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::departuresignaloff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->Doors.has_warning == false || mvOccupied->Doors.has_autowarning == true || mvOccupied->DepartureSignal == true || mvOccupied->Vel > 5.0; } ); break; } @@ -1042,7 +1053,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::departuresignalon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->Doors.has_warning == false || mvOccupied->Doors.has_autowarning == true || mvOccupied->DepartureSignal == false; } ); break; } @@ -1055,7 +1066,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorrightclose ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorOpen[side::right] == true; } ); break; } @@ -1067,7 +1078,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorrightopen ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorOpen[side::right] == false; } ); break; } @@ -1079,7 +1090,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorleftclose ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorOpen[side::left] == true; } ); break; } @@ -1091,7 +1102,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorleftopen ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorOpen[side::left] == false; } ); break; } @@ -1102,7 +1113,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorrightpermitoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorPermitActive[side::right] == true; } ); break; } @@ -1113,7 +1124,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorrightpermiton ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorPermitActive[side::right] == false; } ); break; } @@ -1124,7 +1135,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorleftpermitoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorPermitActive[side::left] == true; } ); break; } @@ -1135,7 +1146,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::doorleftpermiton ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return IsAnyDoorPermitActive[side::left] == false; } ); break; } @@ -1148,7 +1159,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::consistlightsoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvOccupied->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; @@ -1161,7 +1172,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::consistlightson ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { auto const &device { mvOccupied->CompartmentLights }; return Global.fLuminance * ConsistShade < 0.35 || device.start_type != start_t::manual || (device.is_enabled == false && device.is_active == false); } ); break; @@ -1174,7 +1185,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::consistheatingoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->HeatingAllow == true; } ); break; } @@ -1185,52 +1196,48 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::consistheatingon ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return mvOccupied->HeatingAllow == false; } ); break; } case driver_hint::securitysystemreset: { - if( AIControllFlag ) { - if (mvOccupied->SecuritySystem.is_blinking()) - mvOccupied->SecuritySystemReset(); - } + if (AIControllFlag && mvOccupied->SecuritySystem.is_blinking()) + mvOccupied->SecuritySystemReset(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return !mvOccupied->SecuritySystem.is_vigilance_blinking(); } ); break; } case driver_hint::shpsystemreset: { - if( AIControllFlag ) { - if (mvOccupied->SecuritySystem.is_cabsignal_blinking()) - mvOccupied->SecuritySystem.cabsignal_reset(); - } + if (AIControllFlag && mvOccupied->SecuritySystem.is_cabsignal_blinking()) + mvOccupied->SecuritySystem.cabsignal_reset(); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return !mvOccupied->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( Actionparameter ); + pVehicles[ end::front ]->attach_coupler_adapter( static_cast(Actionparameter) ); } hint( Action, - [this](float const Parameter) -> bool { + [this](float const Parameter) { auto const &device { pVehicles[ end::front ]->MoverParameters->Couplers[ static_cast( Parameter ) ] }; return device.type() == TCouplerType::Automatic; } ); break; } case driver_hint::couplingadapterremove: { if( AIControllFlag || Global.AITrainman ) { - pVehicles[ end::front ]->remove_coupler_adapter( Actionparameter ); + pVehicles[ end::front ]->remove_coupler_adapter( static_cast(Actionparameter) ); } hint( Action, - [this](float const Parameter) -> bool { + [this](float const Parameter) { auto const &device { pVehicles[ end::front ]->MoverParameters->Couplers[ static_cast( Parameter ) ] }; return false == device.has_adapter(); } ); break; @@ -1245,7 +1252,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::lightsoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return pVehicles[end::front]->has_signal_pc1_on(); } ); break; } @@ -1258,7 +1265,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::lightsoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return pVehicles[end::front]->has_signal_pc2_on(); } ); break; } @@ -1275,7 +1282,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::lightsoff ); hint( Action, - [this](float const Parameter) -> bool { + [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); } ); @@ -1290,7 +1297,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::lightsoff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return pVehicles[end::rear]->has_signal_pc5_on(); } ); break; } @@ -1304,7 +1311,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::headcodetb1 ); hint( Action, - [this](float const Parameter) -> bool { + [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); } ); @@ -1318,7 +1325,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::releaseroff ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return true == mvOccupied->Hamulec->Releaser(); } ); break; } @@ -1329,7 +1336,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) remove_hint( driver_hint::releaseron ); hint( Action, - [this](float const Parameter) -> bool { + [this](float const /*Parameter*/) { return false == mvOccupied->Hamulec->Releaser(); } ); break; } diff --git a/application/driverhints.h b/application/driverhints.h index 7b6130c25..140fe5f98 100644 --- a/application/driverhints.h +++ b/application/driverhints.h @@ -12,7 +12,7 @@ enum class driver_hint { #ifdef DRIVER_HINT_CONTENT #define DRIVER_HINT_DEF(a, b) b, -const char *driver_hints_texts[] = +const char *const driver_hints_texts[] = { #include "application/driverhints_def.h" }; diff --git a/application/driverhints_def.h b/application/driverhints_def.h index f59ed734c..2ce896679 100644 --- a/application/driverhints_def.h +++ b/application/driverhints_def.h @@ -2,6 +2,7 @@ DRIVER_HINT_DEF(batteryon, STRN("Switch on battery")) DRIVER_HINT_DEF(batteryoff, STRN("Switch off battery")) DRIVER_HINT_DEF(radioon, STRN("Switch on radio")) DRIVER_HINT_DEF(radiooff, STRN("Switch off radio")) +DRIVER_HINT_DEF(radiofuseon, STRN("Close radio fuse")) DRIVER_HINT_DEF(radiochannel, STRN("Tune into channel %.0f")) DRIVER_HINT_DEF(oilpumpon, STRN("Switch on oil pump")) DRIVER_HINT_DEF(oilpumpoff, STRN("Switch off oil pump")) diff --git a/application/drivermode.cpp b/application/drivermode.cpp index 80fd3b17d..cde7e80d7 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -17,6 +17,8 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulation.h" #include "simulation/simulationtime.h" #include "simulation/simulationenvironment.h" +#include "simulation/simulationtest.h" +#include "simulation/blackboxrecorder.h" #include "scene/scene.h" #include "rendering/lightarray.h" #include "rendering/particles.h" @@ -159,6 +161,30 @@ bool driver_mode::init() } // mode-specific update of simulation data. returns: false on error, true otherwise +namespace { + +// the camera as the black box tells it: where it is and where it looks, as the heading of a vehicle +blackbox::camera_state blackbox_camera(TCamera const &Camera, std::uint8_t const Mode, int const View) { + blackbox::camera_state state; + state.mode = Mode; + state.view = static_cast(View); + state.position = Camera.Pos; + state.pitch = Camera.Angle.x; + if (Camera.m_owner != nullptr && false == DebugCameraFlag) { + // it looks at a point, then turns by its yaw from there + auto const where{Camera.LookAt - Camera.Pos}; + state.heading = static_cast(std::atan2(where.x, where.z)) + Camera.Angle.y; + } + else { + // the yaw alone: 0 looks towards -z + state.heading = static_cast(std::atan2(-std::sin(Camera.Angle.y), -std::cos(Camera.Angle.y))); + } + state.heading = std::remainder(state.heading, 2.0f * glm::pi()); + return state; +} + +} // namespace + bool driver_mode::update() { @@ -255,6 +281,19 @@ bool driver_mode::update() // variable step simulation time routines + if (false == Global.editor_enter_vehicle.empty()) + { + auto const name{std::move(Global.editor_enter_vehicle)}; + Global.editor_enter_vehicle.clear(); + if (auto *dynamic{simulation::Vehicles.find(name)}) + { + if (false == FreeFlyModeFlag) + InOutKey(); + m_relay.post(user_command::entervehicle, 0.0, simulation::Train ? simulation::Train->id() : 0, GLFW_PRESS, 0, dynamic->GetPosition(), &dynamic->name()); + change_train = dynamic->name(); + } + } + if (!change_train.empty()) { TTrain *train = simulation::Trains.find(change_train); @@ -292,6 +331,22 @@ bool driver_mode::update() simulation::Events.update(); simulation::Region->update_events(); simulation::Lights.update(); + { + // where the user looks from, for the black box + auto const &camera{DebugCameraFlag ? DebugCamera : Camera}; + auto const mode{DebugCameraFlag ? blackbox::camera_modes::debug : + false == FreeFlyModeFlag ? blackbox::camera_modes::cab : + m_externalview ? blackbox::camera_modes::external : + blackbox::camera_modes::free}; + simulation::Blackbox.camera(blackbox_camera(camera, mode, mode == blackbox::camera_modes::external ? m_externalviewmode : 0), + DebugCameraFlag ? nullptr : camera.m_owner); + } + simulation::Blackbox.update(deltatime); + + if (Global.test.enabled && simulation::is_ready) + { + simulation::test().update(deltatime); + } } // render time routines follow: @@ -412,6 +467,14 @@ bool driver_mode::update() simulation::is_ready = simulation::is_ready || (simulation::Train != nullptr && simulation::Train->is_cab_initialized) || Global.local_start_vehicle == "ghostview"; + if (m_editorpending) + { + // edit session starts in the editor. the switch is made after the initial update on purpose, so the + // simulation state is set up the same way as when the editor is entered by hand right after the load + m_editorpending = false; + Application.push_mode(eu07_application::mode::editor); + } + return true; } @@ -457,7 +520,16 @@ void driver_mode::enter() Timer::ResetTimers(); + if (Global.test.enabled) + { + // the test runs as fast as it can compute, in steps of fixed length, so that runs on different machines agree + Timer::set_fixed_step(simulation::test_manager::frame_step); + simulation::test().start(); + } + set_picking(!Global.captureonstart); + + m_editorpending = Global.editor_session; } // maintenance method, called when the mode is deactivated @@ -667,7 +739,7 @@ void driver_mode::update_camera(double const Deltatime) // reset window state, it'll be set again if applicable in a check below Global.CabWindowOpen = false; - if (simulation::Train != nullptr && Camera.m_owner != nullptr && false == DebugCameraFlag) + if (simulation::Train != nullptr && controlled != nullptr && Camera.m_owner != nullptr && false == DebugCameraFlag) { // jeśli jazda w kabinie, przeliczyć trzeba parametry kamery /* @@ -681,7 +753,7 @@ void driver_mode::update_camera(double const Deltatime) auto const lr{m_input.keyboard.key(GLFW_KEY_LEFT) != GLFW_RELEASE}; // Camera.Yaw powinno być wyzerowane, aby po powrocie patrzeć do przodu - Camera.Pos = controlled->GetPosition() + simulation::Train->MirrorPosition(lr); // pozycja lusterka + 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) { diff --git a/application/drivermode.h b/application/drivermode.h index 66ff6936e..e0406043d 100644 --- a/application/drivermode.h +++ b/application/drivermode.h @@ -116,4 +116,5 @@ private: int iPause { 0 }; // wykrywanie zmian w zapauzowaniu command_relay m_relay; std::string change_train; // train name awaiting entering + bool m_editorpending { false }; // scenery was opened for editing, switch to the editor after the initial update }; diff --git a/application/driveruilayer.cpp b/application/driveruilayer.cpp index 0b8463f8c..0b7b0dc46 100644 --- a/application/driveruilayer.cpp +++ b/application/driveruilayer.cpp @@ -74,9 +74,9 @@ void driver_ui::render_menu_contents() if (ImGui::BeginMenu(STR_C("Mode windows"))) { ImGui::MenuItem(m_aidpanel.title.c_str(), "F1", &m_aidpanel.is_open); - ImGui::MenuItem(m_scenariopanel.title.c_str(), "F1", &m_aidpanel.is_open); ImGui::MenuItem(STR_C("Timetable"), "F2", &m_timetablepanel.is_open); - ImGui::MenuItem(m_debugpanel.name().c_str(), "F12", &m_debugpanel.is_open); + ImGui::MenuItem(m_scenariopanel.title.c_str(), "F3", &m_scenariopanel.is_open); + ImGui::MenuItem(m_debugpanel.name().c_str(), "Shift+F12", &m_debugpanel.is_open); ImGui::MenuItem(m_mappanel.name().c_str(), "Tab", &m_mappanel.is_open); ImGui::MenuItem(m_vehiclelist.name().c_str(), nullptr, &m_vehiclelist.is_open); ImGui::MenuItem(m_trainingcardpanel.name().c_str(), nullptr, &m_trainingcardpanel.is_open); @@ -252,7 +252,7 @@ void driver_ui::render_() ImGui::SetNextWindowSize(ImVec2(-1, -1)); if (ImGui::BeginPopupModal(popupheader, nullptr, 0)) { - if (ImGui::Button(STR_C("Resume"), ImVec2(150, 0)) || ImGui::IsKeyReleased(ImGui::GetKeyIndex(ImGuiKey_Escape))) + if (ImGui::Button(STR_C("Resume"), ImVec2(150, 0)) || ImGui::IsKeyReleased(ImGuiKey_Escape)) { m_relay.post(user_command::pausetoggle, 0.0, 0.0, GLFW_RELEASE, 0); } diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 729b854c0..ba8e7556d 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -38,6 +38,26 @@ http://mozilla.org/MPL/2.0/. #include "utilities/uart.h" #endif +#include + +namespace { + +// how close to a broken coupler the camera has to be for the driving aid to offer its repair [m] +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 ) { + 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 }; } + return { vehicle, nearest }; +} + +} // namespace + void drivingaid_panel::update() { @@ -45,6 +65,8 @@ drivingaid_panel::update() { text_lines.clear(); + std::tie( m_brokenvehicle, m_brokenend ) = broken_coupler_nearby( Global.pCamera.Pos ); + auto const *train { simulation::Train }; auto const *controlled { ( train ? train->Dynamic() : nullptr ) }; @@ -52,7 +74,7 @@ drivingaid_panel::update() { || controlled->Mechanik == nullptr ) { return; } auto const *mover = controlled->MoverParameters; - auto const *driver = controlled->Mechanik; + auto const *vehicledriver = controlled->Mechanik; auto const *owner = controlled->ctOwner != nullptr ? controlled->ctOwner : controlled->Mechanik; { // throttle, velocity, speed limits and grade @@ -61,8 +83,7 @@ drivingaid_panel::update() { // grade std::string gradetext; auto const reverser { ( mover->DirActive > 0 ? 1 : -1 ) }; - auto const grade { controlled->VectorFront().y * 100 * ( controlled->DirectionGet() == reverser ? 1 : -1 ) * reverser }; - if( std::abs( grade ) >= 0.25 ) { + 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(), STR_C(" Grade: %.1f%%%%"), @@ -71,54 +92,7 @@ drivingaid_panel::update() { } // next speed limit auto const speedlimit { static_cast( owner->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 - // nie przekraczać rozkladowej - auto const schedulespeedlimit { ( - (owner->OrderCurrentGet() & (Obey_train | Bank)) != 0 && owner->TrainParams.TTVmax > 0.0 ? static_cast( owner->TrainParams.TTVmax ) : - (owner->OrderCurrentGet() & (Obey_train | Bank)) == 0 ? static_cast( owner->fShuntVelocity ) : - -1 ) }; - // first take note of any speed change which should occur after passing potential current speed limit - if( owner->VelLimitLastDist.second > 0 ) { - nextspeedlimit = min_speed( schedulespeedlimit, static_cast( owner->VelLimitLastDist.first ) ); - nextspeedlimitdistance = owner->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 { owner->VelLimitLastDist.second < 0 }; - auto const speedatproximitydistance { min_speed( schedulespeedlimit, static_cast( owner->VelNext ) ) }; - if( speedatproximitydistance == nextspeedlimit ) { - if( noactivespeedlimit ) { - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = owner->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 < owner->VelDesired ) { - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = owner->ActualProximityDist; - } - // otherwise report it only if it's located after our current (lower) limit ends - else if( owner->ActualProximityDist > nextspeedlimitdistance ) { - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = owner->ActualProximityDist; - } - } - else if( noactivespeedlimit ) { // implicit proximity > last, report only if last limit isn't present - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = owner->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( owner->ActualProximityDist == std::abs( owner->TrackObstacle() ) ) { - nextspeedlimit = speedlimit; - } - } + auto const [ nextspeedlimit, nextspeedlimitdistance ] { owner->next_speed_limit() }; std::string nextspeedlimittext; if( nextspeedlimit != speedlimit ) { std::snprintf( @@ -142,8 +116,8 @@ drivingaid_panel::update() { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C("Throttle: %3d+%d %c%s"), - mover->EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * mover->eimic_real)) : driver->Controlling()->MainCtrlPos, - mover->EIMCtrlType > 0 ? driver->Controlling()->MainCtrlPos : driver->Controlling()->ScndCtrlPos, + mover->EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * mover->eimic_real)) : vehicledriver->Controlling()->MainCtrlPos, + mover->EIMCtrlType > 0 ? vehicledriver->Controlling()->MainCtrlPos : vehicledriver->Controlling()->ScndCtrlPos, mover->SpeedCtrlUnit.IsActive ? 'T' : mover->DirActive > 0 ? 'D' : mover->DirActive < 0 ? 'R' : @@ -208,6 +182,30 @@ drivingaid_panel::update() { } } +void +drivingaid_panel::render_contents() { + ImGui::Checkbox(STR_C("expand"), &is_expanded); + + ImGui::SameLine(); + + auto const *driver = (simulation::Train && simulation::Train->Dynamic()) ? simulation::Train->Dynamic()->Mechanik : nullptr; + if (driver && (false == Global.RealisticControlMode || DebugModeFlag)) { + 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); + } + } + + // 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() ); + } + + ui_panel::render_contents(); +} + void scenario_panel::update() { @@ -253,12 +251,7 @@ scenario_panel::render() { if( size_min.x > 0 ) { ImGui::SetNextWindowSizeConstraints( ImVec2S( size_min.x, size_min.y ), ImVec2S( size_max.x, size_max.y ) ); } - auto const panelname { ( - title.empty() ? - m_name : - title ) - + "###" + m_name }; - if( true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { + if( auto const panelname { ( title.empty() ? m_name : title ) + "###" + m_name }; true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { // potential assignment section auto const *owner { ( m_nearest->Mechanik != nullptr && m_nearest->Mechanik->primary() ? @@ -274,21 +267,19 @@ scenario_panel::render() { } // current task for( auto const &line : text_lines ) { - ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), line.data.c_str() ); + ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), "%s", line.data.c_str() ); } // hints - if( owner != nullptr ) { - if( true == ImGui::CollapsingHeader( STR_C("Hints"), ImGuiTreeNodeFlags_DefaultOpen ) ) { - for( auto const &hint : owner->m_hints ) { - auto const isdone { std::get( hint )( std::get( hint ) ) }; - auto const hintcolor{ ( - isdone ? - colors::uitextgreen : - Global.UITextColor ) }; - ImGui::PushStyleColor( ImGuiCol_Text, { hintcolor.r, hintcolor.g, hintcolor.b, hintcolor.a } ); - ImGui::TextWrapped( Translations.lookup_c(driver_hints_texts[(size_t)std::get( hint )], true), std::get( hint ) ); - ImGui::PopStyleColor(); - } + if (owner != nullptr && true == ImGui::CollapsingHeader( STR_C("Hints"), ImGuiTreeNodeFlags_DefaultOpen )) { + for( auto const &hint : owner->m_hints ) { + auto const isdone { std::get( hint )( std::get( hint ) ) }; + auto const hintcolor{ ( + isdone ? + colors::uitextgreen : + Global.UITextColor ) }; + ImGui::PushStyleColor( ImGuiCol_Text, { hintcolor.r, hintcolor.g, hintcolor.b, hintcolor.a } ); + ImGui::TextWrapped( Translations.lookup_c(driver_hints_texts[(size_t)std::get( hint )], true), std::get( hint ) ); + ImGui::PopStyleColor(); } } } @@ -364,8 +355,7 @@ timetable_panel::update() { //odejmij lokomotywy czynne, a przynajmniej aktualną consistmass -= owner->pVehicle->MoverParameters->TotalMass; // subtract potential other half of a two-part vehicle - auto const *previous { owner->pVehicle->Prev( coupling::permanent ) }; - if( previous != nullptr ) { consistmass -= previous->MoverParameters->TotalMass; } + 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; } } @@ -428,13 +418,13 @@ timetable_panel::update() { && i < table.StationIndex && ( tableline->Ah < 0 // pass-through, always valid || tableline->is_maintenance // maintenance stop, always valid - || time.wHour * 60 + time.wMinute + time.wSecond * 0.0167 >= tableline->Dh * 60 + tableline->Dm ) ) }; + || 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 traveltime { ( i < 2 ? " " : - tableline->Ah >= 0 ? to_minutes_str( CompareTime( table.TimeTable[ i - 1 ].Dh, table.TimeTable[ i - 1 ].Dm, tableline->Ah, tableline->Am ), false, 3 ) : - to_minutes_str( std::max( 0.0, CompareTime( table.TimeTable[ i - 1 ].Dh, table.TimeTable[ i - 1 ].Dm, tableline->Dh, tableline->Dm ) - 0.5 ), false, 3 ) ) }; + 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 ) : + to_minutes_str( static_cast(std::max( 0.0, CompareTime( table.TimeTable[ i - 1 ].Dh, table.TimeTable[ i - 1 ].Dm, tableline->Dh, tableline->Dm ) - 0.5 )), false, 3 ) ) }; auto const linecolor { ( i != table.StationStart ? Global.UITextColor : loadchangeinprogress ? colors::uitextred : @@ -486,19 +476,14 @@ timetable_panel::render() { if( size_min.x > 0 ) { ImGui::SetNextWindowSizeConstraints( ImVec2S( size_min.x * horizontalScale, size_min.y ), ImVec2S( size_max.x * horizontalScale, size_max.y ) ); } - auto const panelname { ( - title.empty() ? - m_name : - title ) - + "###" + m_name }; - if( true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { + if( auto const panelname { ( title.empty() ? m_name : title ) + "###" + m_name }; true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { for( auto const &line : text_lines ) { - ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), line.data.c_str() ); + ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), "%s", line.data.c_str() ); } if( is_expanded ) { ImGui::PushStyleVar( ImGuiStyleVar_ItemSpacing, ImVec2( 1, 0 ) ); for( auto const &line : m_tablelines ) { - ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), line.data.c_str() ); + ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), "%s", line.data.c_str() ); } ImGui::PopStyleVar(); } @@ -541,6 +526,7 @@ void debug_panel::update() m_powergridlines.clear(); m_cameralines.clear(); m_rendererlines.clear(); + m_couplerlines.clear(); #ifdef WITH_UART m_uartlines.clear(); #endif @@ -554,6 +540,7 @@ void debug_panel::update() update_section_powergrid( m_powergridlines ); update_section_camera( m_cameralines ); update_section_renderer( m_rendererlines ); + update_section_coupler( m_couplerlines ); #ifdef WITH_UART update_section_uart(m_uartlines); #endif @@ -576,26 +563,18 @@ debug_panel::render() { if( size_min.x > 0 ) { ImGui::SetNextWindowSizeConstraints( ImVec2S( size_min.x, size_min.y ), ImVec2S( size_max.x, size_max.y ) ); } - auto const panelname { ( - title.empty() ? - m_name : - title ) - + "###" + m_name }; - if( true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { + if( auto const panelname { ( title.empty() ? m_name : title ) + "###" + m_name }; true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { // header section for( auto const &line : text_lines ) { - ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), line.data.c_str() ); + ImGui::TextColored( ImVec4( line.color.r, line.color.g, line.color.b, line.color.a ), "%s", line.data.c_str() ); } // sections ImGui::Separator(); - if( true == render_section( "Vehicle", m_vehiclelines ) ) { - if( DebugModeFlag && m_input.mover && m_input.mover->DamageFlag != 0 ) { - if( true == ImGui::Button( "Stop and repair consist" ) ) { - command_relay relay; - relay.post(user_command::resetconsist, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &m_input.vehicle->name()); - } - } + if (true == render_section( "Vehicle", m_vehiclelines ) && DebugModeFlag && m_input.mover && m_input.mover->DamageFlag != 0 && 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()); } + render_section_coupler(); render_section( "Vehicle Engine", m_enginelines ); render_section( "Vehicle AI", m_ailines ); render_section( "Vehicle Scan Table", m_scantablelines ); @@ -611,13 +590,13 @@ debug_panel::render() { render_section_developer(); // Developer tools #ifdef WITH_UART if(true == render_section( "UART", m_uartlines)) { - int ports_num = UartStatus.available_ports.size(); - char **avlports = new char*[ports_num]; + auto ports_num = static_cast(UartStatus.available_ports.size()); + auto avlports = new char*[ports_num]; for (int i=0; i < ports_num; i++) { avlports[i] = (char *) UartStatus.available_ports[i].c_str(); } ImGui::Combo("Port", &UartStatus.selected_port_index, avlports, ports_num); - ImGui::Combo("Baud", &UartStatus.selected_baud_index, uart_baudrates_list, uart_baudrates_list_num); + ImGui::Combo("Baud", &UartStatus.selected_baud_index, uart_baudrates_list, static_cast(uart_baudrates_list_num)); ImGui::Checkbox("Enabled", &UartStatus.enabled); } #endif @@ -625,8 +604,8 @@ debug_panel::render() { ImGui::Separator(); bool flag = DebugModeFlag; if (ImGui::Checkbox("Debug Mode", &flag)) { - command_relay relay; - relay.post(user_command::debugtoggle, 0.0, 0.0, GLFW_RELEASE, 0); + command_relay commandrelay; + commandrelay.post(user_command::debugtoggle, 0.0, 0.0, GLFW_RELEASE, 0); } } @@ -647,8 +626,8 @@ debug_panel::render_section_scenario() { auto fogrange = std::log( Global.fFogEnd ); if( ImGui::SliderFloat( ( to_string( std::exp( fogrange ), 0, 5 ) + " m###fogend" ).c_str(), &fogrange, std::log( 10.0f ), std::log( 50000.0f ), "Fog distance" ) ) { - command_relay relay; - relay.post( + command_relay commandrelay; + commandrelay.post( user_command::setweather, std::clamp( std::exp( fogrange ), 10.0f, 50000.0f ), Global.Overcast, @@ -661,8 +640,8 @@ debug_panel::render_section_scenario() { (to_string(Airtemperature, 1) + " deg C###Airtemperature").c_str(), &Airtemperature, -35.0f, 40.0f, "Air Temperature")) { - command_relay relay; - relay.post( + command_relay commandrelay; + commandrelay.post( user_command::settemperature, std::clamp(Airtemperature, -35.0f, 40.0f), Global.Overcast, @@ -673,8 +652,8 @@ debug_panel::render_section_scenario() { { if( ImGui::SliderFloat( ( to_string( Global.Overcast, 2, 5 ) + " (" + Global.Weather + ")###overcast" ).c_str(), &Global.Overcast, 0.0f, 2.0f, "Cloud cover" ) ) { - command_relay relay; - relay.post( + command_relay commandrelay; + commandrelay.post( user_command::setweather, Global.fFogEnd, std::clamp( Global.Overcast, 0.0f, 2.0f ), @@ -685,8 +664,8 @@ debug_panel::render_section_scenario() { { if( ImGui::SliderFloat( ( to_string( Global.fMoveLight, 0, 5 ) + " (" + Global.Season + ")###movelight" ).c_str(), &Global.fMoveLight, 0.0f, 364.0f, "Day of year" ) ) { - command_relay relay; - relay.post( + command_relay commandrelay; + commandrelay.post( user_command::setdatetime, std::clamp( Global.fMoveLight, 0.0f, 365.0f ), simulation::Time.data().wHour * 60 + simulation::Time.data().wMinute, @@ -695,10 +674,8 @@ debug_panel::render_section_scenario() { } // dynamic material update checkbox ImGui::Checkbox( "Update Item Materials", &Global.UpdateMaterials ); - if( DebugModeFlag ) { - if( ImGui::Checkbox( "Force Daylight", &Global.FakeLight ) ) { - simulation::Environment.on_daylight_change(); - } + if (DebugModeFlag && ImGui::Checkbox( "Force Daylight", &Global.FakeLight )) { + simulation::Environment.on_daylight_change(); } // advanced options, only visible in debug mode if( DebugModeFlag ) { @@ -713,8 +690,8 @@ debug_panel::render_section_scenario() { + ":" + std::string( std::to_string( int( 100 + simulation::Time.data().wMinute ) ).substr( 1, 2 ) ) ) }; if( ImGui::SliderInt( ( timestring + " (" + Global.Period + ")###simulationtime" ).c_str(), &time, 0, 1439, "Time of day" ) ) { - command_relay relay; - relay.post( + command_relay commandrelay; + commandrelay.post( user_command::setdatetime, Global.fMoveLight, std::clamp( time, 0, 1439 ), @@ -836,7 +813,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { mover.HeatingAllow ? 'h' : '.', mover.Hamulec->Releaser() ? '^' : '.', - std::string( m_input.mechanik ? STR(" R") + ( mover.Radio ? std::to_string( m_input.mechanik->iRadioChannel ) : "-" ) : "" ).c_str(), + 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(), // power transfers // 3000v @@ -903,7 +880,7 @@ debug_panel::update_section_vehicle( std::vector &Output ) { mover.LoadFlag, mover.LocalBrakePosA, mover.LocalBrakePosAEIM, - mover.ManualBrakePos / static_cast(ManualBrakePosNo), + static_cast(mover.ManualBrakePos) / static_cast(ManualBrakePosNo), mover.SpringBrake.Activate ? 1.f : 0.f, // cylinders mover.BrakePress, @@ -981,11 +958,11 @@ debug_panel::update_section_vehicle( std::vector &Output ) { if (!std::isnan(last_time)) { double dt = Timer::GetTime() - last_time; - AccN_jerk_graph.update((mover.AccN - last_AccN) / dt); - AccN_acc_graph.update(mover.AccN); + AccN_jerk_graph.update(static_cast((mover.AccN - last_AccN) / dt)); + AccN_acc_graph.update(static_cast(mover.AccN)); } - last_AccN = mover.AccN; + last_AccN = static_cast(mover.AccN); last_time = Timer::GetTime(); } @@ -1002,7 +979,7 @@ void debug_panel::graph_data::update(float val) { void debug_panel::graph_data::render() { ImGui::PushID(this); ImGui::SliderFloat(STR_C("##Range"), &range, 0.5f, 60.0f, "%.1f"); - ImGui::PlotLines("##plot", data.data(), data.size(), pos, nullptr, 0.0f, range, ImVec2(0, 100)); + ImGui::PlotLines("##plot", data.data(), static_cast(data.size()), static_cast(pos), nullptr, 0.0f, range, ImVec2(0, 100)); ImGui::PopID(); } @@ -1047,9 +1024,9 @@ debug_panel::update_vehicle_brake() const { { bdelay_R, "R" }, { bdelay_M, "+Mg" } }; - for( auto const &delay : delays ) { - if( ( mover.BrakeDelayFlag & delay.first ) == delay.first ) { - brakedelay += delay.second; + for( auto const &[delayflag, delayname] : delays ) { + if( ( mover.BrakeDelayFlag & delayflag ) == delayflag ) { + brakedelay += delayname; } } @@ -1057,7 +1034,7 @@ debug_panel::update_vehicle_brake() const { } void -debug_panel::update_section_engine( std::vector &Output ) { +debug_panel::update_section_engine( std::vector &Output ) const { if( m_input.vehicle == nullptr ) { return; } if( m_input.mover == nullptr ) { return; } @@ -1072,9 +1049,9 @@ debug_panel::update_section_engine( std::vector &Output ) { for( int i = 0; i <= 20; ++i ) { std::string parameters = - mover.eimc_labels[ i ] + to_string( mover.eimc[ i ], 2, 9 ) + TMoverParameters::eimc_labels[ i ] + to_string( mover.eimc[ i ], 2, 9 ) + " | " - + mover.eimv_labels[ i ] + to_string( mover.eimv[ i ], 2, 9 ); + + TMoverParameters::eimv_labels[ i ] + to_string( mover.eimv[ i ], 2, 9 ); if( i < 10 ) { parameters += @@ -1084,7 +1061,7 @@ debug_panel::update_section_engine( std::vector &Output ) { parameters += " med:"; } else if( i >= 13 ) { - parameters += " | " + vehicle.MED_labels[ i - 13 ] + to_string( vehicle.MED[ 0 ][ i - 13 ], 2, 9 ); + parameters += " | " + TDynamicObject::MED_labels[ i - 13 ] + to_string( vehicle.MED[ 0 ][ i - 13 ], 2, 9 ); } Output.emplace_back( parameters, Global.UITextColor ); @@ -1112,8 +1089,8 @@ debug_panel::update_section_engine( std::vector &Output ) { { "cdesi: ", mover.dizel_engagestate }, { "cdelt: ", mover.dizel_engagedeltaomega }, { "gears: ", mover.dizel_automaticgearstatus} }; - for( auto const ¶meter : paramvalues ) { - parameterstext += "\n" + parameter.first + to_string( parameter.second, 2, 9 ); + for( auto const &[parametername, parametervalue] : paramvalues ) { + parameterstext += "\n" + parametername + to_string( parametervalue, 2, 9 ); } Output.emplace_back( parameterstext, Global.UITextColor ); @@ -1130,15 +1107,15 @@ debug_panel::update_section_engine( std::vector &Output ) { { "hRtTq: ", mover.hydro_R_Torque } }; - for( auto const ¶meter : hydrovalues ) { - parameterstext += "\n" + parameter.first + to_string( parameter.second, 2, 9 ); + for( auto const &[parametername, parametervalue] : hydrovalues ) { + parameterstext += "\n" + parametername + to_string( parametervalue, 2, 9 ); } Output.emplace_back( parameterstext, Global.UITextColor ); } } void -debug_panel::update_section_ai( std::vector &Output ) { +debug_panel::update_section_ai( std::vector &Output ) const { if( m_input.mover == nullptr ) { return; } if( m_input.mechanik == nullptr ) { return; } @@ -1202,14 +1179,14 @@ debug_panel::update_section_ai( std::vector &Output ) { { mover.RunningTrack.Velmax, "track" } }; std::string restrictionstext; - for( auto const &restriction : restrictions ) { - if( restriction.first < 0.0 ) { continue; } + for( auto const &[restrictionspeed, restrictionsource] : restrictions ) { + if( restrictionspeed < 0.0 ) { continue; } if( false == restrictionstext.empty() ) { restrictionstext += ", "; } restrictionstext += - to_string( restriction.first, 0 ) - + " (" + restriction.second + ")"; + to_string( restrictionspeed, 0 ) + + " (" + restrictionsource + ")"; } if( false == restrictionstext.empty() ) { @@ -1262,7 +1239,7 @@ debug_panel::update_section_ai( std::vector &Output ) { } void -debug_panel::update_section_scantable( std::vector &Output ) { +debug_panel::update_section_scantable( std::vector &Output ) const { if( m_input.mechanik == nullptr ) { return; } @@ -1284,8 +1261,8 @@ debug_panel::update_section_scantable( std::vector &Output ) { #ifdef WITH_UART void -debug_panel::update_section_uart( std::vector &Output ) { - uart_status *status = &UartStatus; +debug_panel::update_section_uart( std::vector &Output ) const { + uart_status const *status = &UartStatus; Output.emplace_back( ("Port: " + status->port_name).c_str(), @@ -1312,7 +1289,7 @@ debug_panel::update_section_uart( std::vector &Output ) { #endif void -debug_panel::update_section_scenario( std::vector &Output ) { +debug_panel::update_section_scenario( std::vector &Output ) const { auto textline = "vehicles: " + to_string( Timer::subsystem.sim_dynamics.average(), 2 ) + " msec" @@ -1326,7 +1303,7 @@ debug_panel::update_section_scenario( std::vector &Output ) { + to_string( simulation::Environment.wind_azimuth(), 0 ) // ma być azymut, czyli 0 na północy i rośnie na wschód + " " + std::string( "N NEE SES SWW NW" ) - .substr( 0 + 2 * std::floor( std::fmod( 8 + ( glm::radians( simulation::Environment.wind_azimuth() ) + 0.5 * M_PI_4 ) / M_PI_4, 8 ) ), 2 ) + .substr( static_cast( 2 * std::floor( std::fmod( 8 + ( glm::radians( simulation::Environment.wind_azimuth() ) + 0.5 * M_PI_4 ) / M_PI_4, 8 ) ) ), 2 ) + ", " + to_string( glm::length( simulation::Environment.wind() ), 1 ) + " m/s"; textline += "\nAir temperature: " + to_string( Global.AirTemperature, 1 ) + " deg C"; @@ -1340,36 +1317,36 @@ debug_panel::update_section_eventqueue( std::vector &Output ) { // current event queue auto const time { Timer::GetTime() }; - auto const *event { simulation::Events.begin() }; + auto const *queuedevent { simulation::Events.begin() }; auto const searchfilter { std::string( m_eventsearch.data() ) }; Output.emplace_back( "Delay: Event:", Global.UITextColor ); - while( event != nullptr + while( queuedevent != nullptr && Output.size() < 30 ) { - if( false == event->m_ignored - && false == event->m_passive + if( false == queuedevent->m_ignored + && false == queuedevent->m_passive && ( false == m_eventqueueactivevehicleonly - || event->m_activator == m_input.vehicle ) ) { + || queuedevent->m_activator == m_input.vehicle ) ) { - auto const label { event->m_name + ( event->m_activator ? " (by: " + event->m_activator->asName + ")" : "" ) }; + auto const label { queuedevent->m_name + ( queuedevent->m_activator ? " (by: " + queuedevent->m_activator->asName + ")" : "" ) }; if( false == searchfilter.empty() && false == contains(label, searchfilter) ) { - event = event->m_next; + queuedevent = queuedevent->m_next; continue; } - auto const delay { " " + to_string( std::max( 0.0, event->m_launchtime - time ), 1 ) }; + auto const delay { " " + to_string( std::max( 0.0, queuedevent->m_launchtime - time ), 1 ) }; textline = delay.substr( delay.length() - 6 ) + " " - + label + ( event->m_sibling ? " (joint event)" : "" ); + + label + ( queuedevent->m_sibling ? " (joint event)" : "" ); Output.emplace_back( textline, Global.UITextColor ); } - event = event->m_next; + queuedevent = queuedevent->m_next; } if( Output.size() == 1 ) { // event queue can be empty either because no event got through active filters, or because it is genuinely empty @@ -1378,7 +1355,7 @@ debug_panel::update_section_eventqueue( std::vector &Output ) { } void -debug_panel::update_section_powergrid( std::vector &Output ) { +debug_panel::update_section_powergrid( std::vector &Output ) const { auto const lowpowercolor { glm::vec4( 164.0f / 255.0f, 132.0f / 255.0f, 84.0f / 255.0f, 1.f ) }; auto const nopowercolor { glm::vec4( 164.0f / 255.0f, 84.0f / 255.0f, 84.0f / 255.0f, 1.f ) }; @@ -1420,7 +1397,7 @@ debug_panel::update_section_powergrid( std::vector &Output ) { } void -debug_panel::update_section_camera( std::vector &Output ) { +debug_panel::update_section_camera( std::vector &Output ) const { if( m_input.camera == nullptr ) { return; } @@ -1440,13 +1417,13 @@ debug_panel::update_section_camera( std::vector &Output ) { + to_string( 180.0 - glm::degrees( camera.Angle.y ), 0 ) // ma być azymut, czyli 0 na północy i rośnie na wschód + " " + std::string( "S SEE NEN NWW SW" ) - .substr( 0 + 2 * floor( fmod( 8 + ( camera.Angle.y + 0.5 * M_PI_4 ) / M_PI_4, 8 ) ), 2 ); + .substr( static_cast( 2 * floor( fmod( 8 + ( camera.Angle.y + 0.5 * M_PI_4 ) / M_PI_4, 8 ) ) ), 2 ); Output.emplace_back( textline, Global.UITextColor ); } void -debug_panel::update_section_renderer( std::vector &Output ) { +debug_panel::update_section_renderer( std::vector &Output ) const { // gfx renderer data auto textline = @@ -1516,6 +1493,172 @@ debug_panel::update_section_renderer( std::vector &Output ) { } +namespace { + +// how far from the camera a coupler shows in the coupler section [m] +constexpr float coupler_pick_radius { 10.f }; + +std::string_view coupler_type_name( TCouplerType const Type ) { + switch( Type ) { + case TCouplerType::Articulated: { return "articulated"; } + case TCouplerType::Bare: { return "bare"; } + case TCouplerType::Chain: { return "chain"; } + case TCouplerType::Screw: { return "screw"; } + case TCouplerType::Automatic: { return "automatic"; } + default: { return "none"; } + } +} + +// the couplerphysics setting of eu07.ini +std::string_view coupler_physics_setting() { + if( Global.coupler_physics_all ) { return "all"; } + return Global.coupler_physics ? "yes" : "no"; +} + +std::string_view coupler_stop_name( int const Stop ) { + if( Stop > 0 ) { return "draw gear solid"; } + if( Stop < 0 ) { return "buffers solid"; } + return "none"; +} + +// a value shown in the Scale of its unit (1000 for kN, 0.001 for mm), dragged within Min and Max of that unit +bool edit_value( char const *Label, double &Value, double const Scale, double const Min, double const Max, char const *Format ) { + auto shown { Value / Scale }; + if( false == ImGui::DragScalar( Label, ImGuiDataType_Double, &shown, static_cast( ( Max - Min ) / 1000.0 ), &Min, &Max, Format ) ) { + return false; + } + Value = std::clamp( shown, Min, Max ) * Scale; + return true; +} + +bool edit_spring( char const *Name, coupler_physics::spring_curve &Curve, double &Unloading ) { + ImGui::PushID( Name ); + ImGui::TextUnformatted( Name ); + auto changed { edit_value( "Stiffness [kN/m]", Curve.stiffness, 1000.0, 100.0, 50000.0, "%.0f" ) }; + changed = edit_value( "Travel [mm]", Curve.travel, 0.001, 5.0, 300.0, "%.0f" ) || changed; + changed = edit_value( "Progression", Curve.progression, 1.0, 0.0, 0.9, "%.2f" ) || changed; + changed = edit_value( "Unloading ratio", Unloading, 1.0, 0.05, 1.0, "%.2f" ) || changed; + ImGui::Text( "End force: %.0f kN", Curve.end_force() / 1000.0 ); + ImGui::PopID(); + return changed; +} + +bool edit_link( coupler_physics::end_parameters &Parameters ) { + auto &link { Parameters.link }; + ImGui::PushID( "link" ); + ImGui::TextUnformatted( "Link" ); + auto changed { ImGui::Checkbox( "Breakable", &link.breakable ) }; + changed = edit_value( "Ultimate force [kN]", link.ultimate, 1000.0, 10.0, 5000.0, "%.0f" ) || changed; + changed = edit_value( "Yield force [kN]", link.yield, 1000.0, 10.0, 5000.0, "%.0f" ) || changed; + link.yield = std::min( link.yield, link.ultimate ); + // the permanent stretch at which the link breaks, which is what the hardening gives + auto stretch { ( link.ultimate - link.yield ) / link.hardening }; + if( edit_value( "Stretch to break [mm]", stretch, 0.001, 1.0, 200.0, "%.1f" ) ) { + link.hardening = std::max( ( link.ultimate - link.yield ) / stretch, 1.0 ); + changed = true; + } + changed = edit_value( "Link stiffness [kN/m]", Parameters.link_stiffness, 1000.0, 1000.0, 2000000.0, "%.0f" ) || changed; + changed = edit_value( "Buffers crush force [kN]", Parameters.crush_force, 1000.0, 100.0, 10000.0, "%.0f" ) || changed; + changed = edit_value( "Restitution of a solid hit", Parameters.solid_restitution, 1.0, 0.05, 0.95, "%.2f" ) || changed; + ImGui::PopID(); + return changed; +} + +bool edit_coupler_parameters( coupler_physics::end_parameters &Parameters ) { + auto changed { edit_value( "Slack [mm]", Parameters.slack, 0.001, -100.0, 300.0, "%.1f" ) }; + changed = edit_value( "Damping [kN s/m]", Parameters.damping, 1000.0, 0.0, 1000.0, "%.1f" ) || changed; + changed = edit_spring( "Buffers", Parameters.buffers, Parameters.buffers_unloading ) || changed; + changed = edit_spring( "Draw gear", Parameters.draw_gear, Parameters.draw_gear_unloading ) || changed; + changed = edit_link( Parameters ) || changed; + return changed; +} + +} // namespace + +void +debug_panel::update_section_coupler( std::vector &Output ) { + + m_coupler = {}; + 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 ) { + 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 &mover { *vehicle->MoverParameters }; + auto const &coupler { mover.Couplers[ m_coupler.end ] }; + auto const &neighbour { mover.Neighbours[ m_coupler.end ] }; + auto const &state { coupler.physics_state }; + + Output.emplace_back( + std::format( "{}, {} end, {} coupler{}", vehicle->name(), nearerfront ? "front" : "rear", coupler_type_name( coupler.type() ), coupler.has_adapter() ? " (adapter)" : "" ), + Global.UITextColor ); + Output.emplace_back( + std::format( + "Model: {} (couplerphysics {}, vehicle {}covered), crash damage {}", + mover.coupler_physics_at( m_coupler.end ) ? "physical" : "legacy", + coupler_physics_setting(), + mover.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 ), + Global.UITextColor ); + } + else { + Output.emplace_back( "Neighbour: none", Global.UITextColor ); + } + Output.emplace_back( std::format( "Force: {:.1f} kN", coupler.CForce / 1000.0 ), Global.UITextColor ); + Output.emplace_back( + std::format( "Draw gear: {:.1f} mm, {:.1f} kN Buffers: {:.1f} mm, {:.1f} kN", state.draw_gear.deflection * 1000.0, state.draw_gear.force / 1000.0, state.buffers.deflection * 1000.0, state.buffers.force / 1000.0 ), + Global.UITextColor ); + Output.emplace_back( + std::format( "Stretch: {:.1f} mm, stop: {}, overloaded for {:.1f} s", state.elongation * 1000.0, coupler_stop_name( state.stop ), coupler.stretch_duration ), + Global.UITextColor ); + if( coupler.broken ) { + Output.emplace_back( "Coupler broken (repair it in the driving aid, F1)", glm::vec4( 1.f, 0.25f, 0.25f, 1.f ) ); + } +} + +bool +debug_panel::render_section_coupler() { + + if( false == render_section( "Coupler", m_couplerlines ) ) { return false; } + // the parameters to try out, in the debug mode, on the simulation itself + if( false == DebugModeFlag || m_coupler.vehicle == nullptr || Application.is_client() ) { return true; } + + ImGui::Separator(); + ImGui::Checkbox( "Physical coupler model", &Global.coupler_physics ); + ImGui::Checkbox( "Physical model for every train", &Global.coupler_physics_all ); + 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 }; + + if( auto parameters { coupler.physics }; edit_coupler_parameters( parameters ) ) { + coupler.physics = parameters; + if( m_couplerbothends && othercoupler != nullptr ) { + othercoupler->physics = parameters; + } + } + if( ImGui::Button( "Reset the stretch of the coupling" ) ) { + // both vehicles keep the state of the pair alike + coupler.physics_state.elongation = 0.0; + if( othercoupler != nullptr ) { + othercoupler->physics_state.elongation = 0.0; + } + } + return true; +} + bool debug_panel::render_section( std::string const &Header, std::vector const &Lines ) { @@ -1526,7 +1669,7 @@ debug_panel::render_section( std::string const &Header, std::vector c } bool -debug_panel::render_section( std::vector const &Lines ) { +debug_panel::render_section( std::vector const &Lines ) const { for( auto const &line : Lines ) { ImGui::PushStyleColor( ImGuiCol_Text, { line.color.r, line.color.g, line.color.b, line.color.a } ); @@ -1537,7 +1680,7 @@ debug_panel::render_section( std::vector const &Lines ) { return true; } -bool debug_panel::render_section_developer() +bool debug_panel::render_section_developer() const { if (false == ImGui::CollapsingHeader("Developer tools")) return false; @@ -1553,7 +1696,7 @@ bool debug_panel::render_section_developer() } bool -debug_panel::render_section_settings() { +debug_panel::render_section_settings() const { if( false == ImGui::CollapsingHeader( "Settings" ) ) { return false; } @@ -1563,9 +1706,9 @@ debug_panel::render_section_settings() { // reflection fidelity ImGui::SliderInt( ( std::to_string( Global.reflectiontune.fidelity ) + "###reflectionfidelity" ).c_str(), &Global.reflectiontune.fidelity, 0, 2, "Reflection fidelity" ); ImGui::SliderInt( ( std::to_string( Global.gfx_shadow_rank_cutoff ) + "###shadowrankcutoff" ).c_str(), &Global.gfx_shadow_rank_cutoff, 1, 3, "Shadow ranks" ); - if( ImGui::SliderFloat( ( to_string( std::abs( Global.gfx_shadow_angle_min ), 2 ) + "###shadowanglecutoff" ).c_str(), &Global.gfx_shadow_angle_min, -1.0, -0.2, "Shadow angle cutoff" ) ) { + if( ImGui::SliderFloat( ( to_string( std::abs( Global.gfx_shadow_angle_min ), 2 ) + "###shadowanglecutoff" ).c_str(), &Global.gfx_shadow_angle_min, -1.0, -0.2f, "Shadow angle cutoff" ) ) { Global.gfx_shadow_angle_min = quantize( Global.gfx_shadow_angle_min, 0.05f ); - }; + } if( DebugModeFlag ) { // sky sliders { @@ -1595,8 +1738,8 @@ debug_panel::render_section_settings() { if (simulation::Train) { float val = simulation::Train->get_radiovolume(); if( ImGui::SliderFloat( ( std::to_string( static_cast( val * 100 ) ) + "%###volumeradio" ).c_str(), &val, 0.0f, 1.0f, "Vehicle radio volume" ) ) { - command_relay relay; - relay.post(user_command::radiovolumeset, val, 0.0, GLFW_PRESS, 0); + command_relay commandrelay; + commandrelay.post(user_command::radiovolumeset, val, 0.0, GLFW_PRESS, 0); } } @@ -1635,12 +1778,7 @@ transcripts_panel::render() { if( size_min.x > 0 ) { ImGui::SetNextWindowSizeConstraints( ImVec2S( size_min.x, size_min.y ), ImVec2S( size_max.x, size_max.y ) ); } - auto const panelname { ( - title.empty() ? - m_name : - title ) - + "###" + m_name }; - if( true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { + if( auto const panelname { ( title.empty() ? m_name : title ) + "###" + m_name }; true == ImGui::Begin( panelname.c_str(), &is_open, flags ) ) { // header section for( auto const &line : text_lines ) { ImGui::TextWrapped( "%s", line.data.c_str() ); diff --git a/application/driveruipanels.h b/application/driveruipanels.h index da4cad879..8c21a6240 100644 --- a/application/driveruipanels.h +++ b/application/driveruipanels.h @@ -20,10 +20,14 @@ public: {} void update() override; + void render_contents() override; private: // members 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 }; }; class timetable_panel : public ui_expandable_panel { @@ -54,7 +58,6 @@ public: private: // members - std::array m_buffer; TDynamicObject const *m_nearest { nullptr }; }; @@ -81,42 +84,53 @@ private: // methods // generate and send section data to provided output void update_section_vehicle( std::vector &Output ); - void update_section_engine( std::vector &Output ); - void update_section_ai( std::vector &Output ); - void update_section_scantable( std::vector &Output ); - void update_section_scenario( std::vector &Output ); + void update_section_engine( std::vector &Output ) const; + void update_section_ai( std::vector &Output ) const; + void update_section_scantable( std::vector &Output ) const; + void update_section_scenario( std::vector &Output ) const; void update_section_eventqueue( std::vector &Output ); - void update_section_powergrid( std::vector &Output ); - void update_section_camera( std::vector &Output ); - void update_section_renderer( std::vector &Output ); + void update_section_powergrid( std::vector &Output ) const; + void update_section_camera( std::vector &Output ) const; + void update_section_renderer( std::vector &Output ) const; + // the coupler nearest to the camera, and the state of its coupling + void update_section_coupler( std::vector &Output ); #ifdef WITH_UART - void update_section_uart( std::vector &Output ); + void update_section_uart( std::vector &Output ) const; #endif // section update helpers std::string update_vehicle_coupler( int 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 ); - bool render_section( std::vector const &Lines ); + bool render_section( std::vector const &Lines ) const; bool render_section_scenario(); bool render_section_eventqueue(); - bool render_section_settings(); - bool render_section_developer(); + // the coupler section, with the parameters of the physical model to try out in the debug mode + bool render_section_coupler(); + bool render_section_settings() const; + bool render_section_developer() const; // members std::array m_buffer; std::array m_eventsearch; input_data m_input; - std::vector - m_vehiclelines, - m_enginelines, - m_ailines, - m_scantablelines, - m_cameralines, - m_scenariolines, - m_eventqueuelines, - m_powergridlines, - m_rendererlines, - m_uartlines; + std::vector m_vehiclelines; + std::vector m_enginelines; + std::vector m_ailines; + std::vector m_scantablelines; + std::vector m_cameralines; + std::vector m_scenariolines; + std::vector m_eventqueuelines; + std::vector m_powergridlines; + std::vector m_rendererlines; + std::vector m_uartlines; + std::vector m_couplerlines; + // the coupler nearest to the camera + struct coupler_pick { + TDynamicObject const *vehicle { nullptr }; + int end { 0 }; + }; + coupler_pick m_coupler; + bool m_couplerbothends { true }; // changes to the parameters apply to the end of the other vehicle of the pair too double last_time = std::numeric_limits::quiet_NaN(); @@ -134,8 +148,6 @@ private: graph_data AccN_acc_graph; float last_AccN; - std::array queue_event_buf = { 0 }; - std::array queue_event_activator_buf = { 0 }; bool m_eventqueueactivevehicleonly { false }; }; diff --git a/application/editorgestures.h b/application/editorgestures.h new file mode 100644 index 000000000..59c73aa63 --- /dev/null +++ b/application/editorgestures.h @@ -0,0 +1,251 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.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 mouse and the keys drawn as pictures: the lessons of the tutorial, the gestures of the tools and of the vertical profile + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include "imgui/imgui.h" +#include "utilities/translation.h" + +ImU32 const kGestureLit{IM_COL32(90, 175, 255, 255)}; + +// the mouse with the part used lit: LMB, RMB, MMB, wheel (with arrows), move (with arrows); the width it took +inline float gesture_mouse(ImDrawList &List, ImVec2 const At, float const Height, std::string const &Part) +{ + auto const width{std::round(Height * 0.68f)}; + auto const line{ImGui::GetColorU32(ImGuiCol_Text)}; + auto const thickness{std::max(1.0f, Height * 0.07f)}; + auto const rounding{width * 0.5f}; + auto const split{At.y + std::round(Height * 0.45f)}; + auto const middle{At.x + width * 0.5f}; + ImVec2 const high{At.x + width, At.y + Height}; + if (Part == "LMB") + List.AddRectFilled(At, ImVec2(middle, split), kGestureLit, rounding, ImDrawFlags_RoundCornersTopLeft); + if (Part == "RMB") + List.AddRectFilled(ImVec2(middle, At.y), ImVec2(high.x, split), kGestureLit, rounding, ImDrawFlags_RoundCornersTopRight); + List.AddRect(At, high, line, rounding, 0, thickness); + List.AddLine(ImVec2(At.x, split), ImVec2(high.x, split), line, thickness); + List.AddLine(ImVec2(middle, At.y), ImVec2(middle, split), line, thickness); + auto const wheel{std::max(3.0f, std::round(width * 0.24f))}; + ImVec2 const wheel_low{middle - wheel * 0.5f, At.y + Height * 0.1f}; + ImVec2 const wheel_high{middle + wheel * 0.5f, At.y + Height * 0.36f}; + List.AddRectFilled(wheel_low, wheel_high, (Part == "MMB" || Part == "wheel") ? kGestureLit : ImGui::GetColorU32(ImGuiCol_WindowBg), wheel * 0.5f); + List.AddRect(wheel_low, wheel_high, line, wheel * 0.5f, 0, thickness * 0.8f); + auto right{high.x}; + auto const arrow{Height * 0.16f}; + if (Part == "wheel") + { + auto const x{right + arrow * 1.6f}; + List.AddTriangleFilled(ImVec2(x - arrow, At.y + arrow * 1.8f), ImVec2(x + arrow, At.y + arrow * 1.8f), ImVec2(x, At.y + arrow * 0.3f), kGestureLit); + List.AddTriangleFilled(ImVec2(x - arrow, high.y - arrow * 1.8f), ImVec2(x + arrow, high.y - arrow * 1.8f), ImVec2(x, high.y - arrow * 0.3f), kGestureLit); + right = x + arrow; + } + if (Part == "move") + { + auto const reach{Height * 0.42f}; + ImVec2 const centre{right + arrow * 0.8f + reach, At.y + Height * 0.5f}; + List.AddLine(ImVec2(centre.x - reach + arrow, centre.y), ImVec2(centre.x + reach - arrow, centre.y), kGestureLit, thickness); + List.AddLine(ImVec2(centre.x, centre.y - reach + arrow), ImVec2(centre.x, centre.y + reach - arrow), kGestureLit, thickness); + List.AddTriangleFilled(ImVec2(centre.x - reach, centre.y), ImVec2(centre.x - reach + arrow * 1.4f, centre.y - arrow), ImVec2(centre.x - reach + arrow * 1.4f, centre.y + arrow), kGestureLit); + List.AddTriangleFilled(ImVec2(centre.x + reach, centre.y), ImVec2(centre.x + reach - arrow * 1.4f, centre.y + arrow), ImVec2(centre.x + reach - arrow * 1.4f, centre.y - arrow), kGestureLit); + List.AddTriangleFilled(ImVec2(centre.x, centre.y - reach), ImVec2(centre.x + arrow, centre.y - reach + arrow * 1.4f), ImVec2(centre.x - arrow, centre.y - reach + arrow * 1.4f), kGestureLit); + List.AddTriangleFilled(ImVec2(centre.x, centre.y + reach), ImVec2(centre.x - arrow, centre.y + reach - arrow * 1.4f), ImVec2(centre.x + arrow, centre.y + reach - arrow * 1.4f), kGestureLit); + right = centre.x + reach; + } + return right - At.x; +} + +// a key cap with its name; the width it took +inline float gesture_key(ImDrawList &List, ImVec2 const At, float const Height, std::string const &Text) +{ + auto const size{ImGui::CalcTextSize(Text.c_str())}; + auto const width{std::max(std::round(size.x + Height * 0.6f), Height)}; + auto const rounding{Height * 0.2f}; + ImVec2 const high{At.x + width, At.y + Height}; + List.AddRectFilled(At, high, ImGui::GetColorU32(ImGuiCol_FrameBg), rounding); + List.AddRect(At, high, ImGui::GetColorU32(ImGuiCol_TextDisabled), rounding, 0, std::max(1.0f, Height * 0.06f)); + List.AddText(ImVec2(std::round(At.x + (width - size.x) * 0.5f), std::round(At.y + (Height - size.y) * 0.5f)), ImGui::GetColorU32(ImGuiCol_Text), Text.c_str()); + return width; +} + +// the words of a gesture as they're drawn: the parts of the mouse, the keys, "+" between them, other words as text +struct gesture_word +{ + enum class kind + { + mouse, + key, + plus, + text + } what; + std::string text; +}; + +// "Ctrl+wheel", "Shift+click x4", "Drag a point", "Q W E": the keys and the parts of the mouse it names, the rest as text +inline std::vector gesture_words(std::string const &Keys) +{ + static char const *const keys[]{"Ctrl", "Shift", "Alt", "Esc", "Del", "Enter", "Backspace", "Tab", "Space", "Home", "End", "PrtScr"}; + auto const mouse = [](std::string const &Word) -> std::string { + if (Word == "LMB" || Word == "click" || Word == "Click" || Word == "Press") + return "LMB"; + if (Word == "RMB" || Word == "MMB" || Word == "wheel") + return Word; + if (Word == "Wheel") + return "wheel"; + if (Word == "Drag" || Word == "drag" || Word == "move") + return "move"; + return {}; + }; + auto const key = [&](std::string const &Word) { + if (Word.size() == 1 && (std::isupper(static_cast(Word[0])) || std::isdigit(static_cast(Word[0])))) + return true; + if (Word.size() >= 2 && Word[0] == 'F' && std::isdigit(static_cast(Word[1]))) + return true; + return std::find_if(std::begin(keys), std::end(keys), [&](char const *Key) { return Word == Key; }) != std::end(keys); + }; + std::vector words; + std::string text; + auto const flush = [&]() { + if (false == text.empty()) + words.push_back({gesture_word::kind::text, text}); + text.clear(); + }; + std::istringstream stream{Keys}; + for (std::string word; stream >> word;) + { + std::vector parts; + std::size_t from{0}; + for (std::size_t plus; (plus = word.find('+', from)) != std::string::npos && plus > from; from = plus + 1) + parts.push_back(word.substr(from, plus - from)); + parts.push_back(word.substr(from)); + bool const all{std::all_of(parts.begin(), parts.end(), [&](std::string const &Part) { return false == mouse(Part).empty() || key(Part); })}; + if (false == all || (parts.size() == 1 && words.empty() == false && words.back().what == gesture_word::kind::text && false == key(parts[0]) && mouse(parts[0]).empty())) + { + text += (text.empty() ? "" : " ") + word; + continue; + } + flush(); + for (std::size_t index = 0; index < parts.size(); ++index) + { + if (index > 0) + words.push_back({gesture_word::kind::plus, "+"}); + if (auto const part{mouse(parts[index])}; false == part.empty()) + words.push_back({gesture_word::kind::mouse, part}); + else + words.push_back({gesture_word::kind::key, parts[index]}); + } + } + flush(); + return words; +} + +// the mouse and the keys of a gesture only, its words left to the text beside it +inline std::vector gesture_picture(std::string const &Keys) +{ + std::vector words; + for (auto const &word : gesture_words(Keys)) + if (word.what != gesture_word::kind::text && (word.what != gesture_word::kind::plus || (false == words.empty() && words.back().what != gesture_word::kind::plus))) + words.push_back(word); + while (false == words.empty() && words.back().what == gesture_word::kind::plus) + words.pop_back(); + return words; +} + +// the picture says all the words of the gesture: keys alone, no mouse nor words +inline bool gesture_keys_only(std::string const &Keys) +{ + auto const words{gesture_words(Keys)}; + return false == words.empty() && std::all_of(words.begin(), words.end(), [](gesture_word const &Word) { return Word.what == gesture_word::kind::key || Word.what == gesture_word::kind::plus; }); +} + +// the gesture drawn in a row; the width it took +inline float gesture_draw(ImDrawList &List, ImVec2 const At, float const Height, std::vector const &Words, ImU32 const Text) +{ + auto const gap{std::round(Height * 0.2f)}; + float x{0.0f}; + for (auto const &word : Words) + { + ImVec2 const place{At.x + x, At.y}; + switch (word.what) + { + case gesture_word::kind::mouse: x += gesture_mouse(List, place, Height, word.text) + gap; break; + case gesture_word::kind::key: x += gesture_key(List, place, Height, word.text) + gap; break; + case gesture_word::kind::plus: + case gesture_word::kind::text: + { + auto const size{ImGui::CalcTextSize(word.text.c_str())}; + List.AddText(ImVec2(place.x, std::round(At.y + (Height - size.y) * 0.5f)), word.what == gesture_word::kind::plus ? ImGui::GetColorU32(ImGuiCol_TextDisabled) : Text, word.text.c_str()); + x += size.x + gap; + break; + } + } + } + return std::max(0.0f, x - gap); +} + +inline float gesture_width(float const Height, std::vector const &Words) +{ + auto const gap{std::round(Height * 0.2f)}; + auto const arrow{Height * 0.16f}; + float x{0.0f}; + for (auto const &word : Words) + { + switch (word.what) + { + case gesture_word::kind::mouse: + x += std::round(Height * 0.68f) + (word.text == "wheel" ? arrow * 2.6f : word.text == "move" ? arrow * 0.8f + Height * 0.84f : 0.0f); + break; + case gesture_word::kind::key: x += std::max(std::round(ImGui::CalcTextSize(word.text.c_str()).x + Height * 0.6f), Height); break; + default: x += ImGui::CalcTextSize(word.text.c_str()).x; break; + } + x += gap; + } + return std::max(0.0f, x - gap); +} + +// rows of gestures, each drawn with its key and what it does beside it; the keys and the texts are the English ones, translated here +inline void gesture_rows(std::vector> const &Rows) +{ + auto *list{ImGui::GetWindowDrawList()}; + auto const font{ImGui::GetFontSize()}; + auto const size{std::round(font * 1.25f)}; + auto const pad{std::round(font * 0.6f)}; + std::vector> pictures; + float column{0.0f}; + for (auto const &row : Rows) + { + pictures.push_back(gesture_picture(row.first)); + column = std::max(column, gesture_width(size, pictures.back())); + } + for (std::size_t i = 0; i < Rows.size(); ++i) + { + auto const at{ImGui::GetCursorScreenPos()}; + auto const line{ImGui::GetTextLineHeight()}; + auto const height{std::max(size, line)}; + gesture_draw(*list, ImVec2(at.x, at.y + std::round((height - size) * 0.5f)), size, pictures[i], ImGui::GetColorU32(ImGuiCol_Text)); + ImGui::Dummy(ImVec2(column, height)); + ImGui::SameLine(0.0f, pad); + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + std::round((height - line) * 0.5f)); + if (false == gesture_keys_only(Rows[i].first)) + { + ImGui::TextColored(ImVec4(1.0f, 0.83f, 0.3f, 1.0f), "%s", STR_C(Rows[i].first)); + ImGui::SameLine(); + } + ImGui::TextWrapped("%s", STR_C(Rows[i].second)); + } +} diff --git a/application/editormode.cpp b/application/editormode.cpp index 46a8edadf..e08e1f0e7 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -8,30 +8,65 @@ http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" +#include "world/TrackSleepers.h" +#include +#include +#include +#include +#include #include "application/editormode.h" +#include "application/editormodeshared.h" +#include "application/editorgestures.h" +#include "scene/scenenodegroups.h" #include "application/editoruilayer.h" +#ifndef _WIN32 +#include +#include +extern char **environ; +#endif +#include "application/editorprojection.h" #include "application/application.h" +#include "editor/editorKilometrage.hpp" #include "editor/editorSettings.hpp" +#include "editor/editorModelSets.hpp" +#include "editor/editorTrackPresets.hpp" +#include "editor/editorIncludeInfo.hpp" +#include "editor/editorGroundMesh.hpp" +#include "editor/editorFormat.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorSwitchStore.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorIcons.hpp" +#include "utilities/translation.h" #include "utilities/Globals.h" +#include "utilities/glmHelpers.h" #include "simulation/simulation.h" #include "simulation/simulationtime.h" #include "simulation/simulationenvironment.h" +#include "simulation/blackboxrecorder.h" #include "utilities/Timer.h" #include "Console.h" #include "rendering/renderer.h" #include "model/AnimModel.h" #include "model/Model3d.h" +#include "world/Track.h" #include "utilities/Float3d.h" #include "scene/scene.h" +#include "scene/scenelayers.h" +#include "scene/sceneterrain.h" +#include "utilities/parser.h" +#include "utilities/utilities.h" #include "imgui/imgui.h" +#include "imgui/imgui_internal.h" #include "imgui/ImGuizmo.h" #include "utilities/Logs.h" #include #include #include +#include #include #include #include @@ -48,6 +83,38 @@ namespace using vec3 = glm::vec3; using dvec2 = glm::dvec2; + // the steps of a frame of the editor timed: a frame whose update takes longer than kSlow tells in the log which of them took + // the time, at most twice a second + class frame_steps + { + public: + void step(char const *Name) + { + auto const now{std::chrono::steady_clock::now()}; + m_steps.emplace_back(Name, std::chrono::duration(now - m_last).count()); + m_last = now; + } + ~frame_steps() + { + constexpr double kSlow{50.0}; // ms + auto const total{std::chrono::duration(std::chrono::steady_clock::now() - m_start).count()}; + static auto told{std::chrono::steady_clock::time_point{}}; + if (total < kSlow || m_start - told < std::chrono::milliseconds{500}) + return; + told = m_start; + std::string text{"Editor: slow frame, update " + std::to_string(static_cast(total)) + " ms:"}; + for (auto const &[name, time] : m_steps) + if (time >= 3.0) + text += " " + std::string{name} + " " + std::to_string(static_cast(time)); + WriteLog(text, logtype::generic); + } + + private: + std::chrono::steady_clock::time_point const m_start{std::chrono::steady_clock::now()}; + std::chrono::steady_clock::time_point m_last{m_start}; + std::vector> m_steps; + }; + inline bool is_release(int state) { return state == GLFW_RELEASE; @@ -58,6 +125,14 @@ namespace return state == GLFW_PRESS; } + // true when the most recent left button press landed in the viewport rather than on an ImGui window. + // valid once ImGui has processed the press (i.e. from mode update onwards), so it's also used to + // discard deferred pick callbacks of a press that leaked past the application's UI filter + inline bool viewport_click() + { + return false == ImGui::GetIO().MouseDownOwned[0]; + } + // tests whether the vertical line through (Px,Pz) passes over triangle abc; if so returns the // surface height at that point through OutY. used by the "snap to ground" (END) feature. inline bool triangle_height_at(glm::dvec3 const &a, glm::dvec3 const &b, glm::dvec3 const &c, @@ -117,6 +192,345 @@ namespace } } + // world transform of a model instance, matching the renderer: translate * rotateY * rotateX * rotateZ * scale + glm::dmat4 instance_matrix(TAnimModel const &Model) + { + glm::dmat4 rootm(1.0); + rootm = glm::translate(rootm, Model.location()); + glm::vec3 const angles = Model.Angles(); + if (angles.y != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.y)), glm::dvec3(0.0, 1.0, 0.0)); + if (angles.x != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.x)), glm::dvec3(1.0, 0.0, 0.0)); + if (angles.z != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.z)), glm::dvec3(0.0, 0.0, 1.0)); + return glm::scale(rootm, glm::dvec3(Model.Scale())); + } + + // even-odd test of a point against a polygon outline projected onto the XZ plane + bool point_in_polygon_xz(std::vector const &Polygon, double const X, double const Z) + { + bool inside = false; + for (std::size_t i = 0, j = Polygon.size() - 1; i < Polygon.size(); j = i++) + { + auto const &a = Polygon[i]; + auto const &b = Polygon[j]; + if ((a.z > Z) != (b.z > Z) && X < (b.x - a.x) * (Z - a.z) / (b.z - a.z) + a.x) + inside = !inside; + } + return inside; + } + + // area of a polygon outline projected onto the XZ plane (shoelace formula) + double polygon_area_xz(std::vector const &Polygon) + { + if (Polygon.size() < 3) + return 0.0; + double sum = 0.0; + for (std::size_t i = 0, j = Polygon.size() - 1; i < Polygon.size(); j = i++) + sum += Polygon[j].x * Polygon[i].z - Polygon[i].x * Polygon[j].z; + return std::abs(sum) * 0.5; + } + + // world triangles bucketed on a uniform XZ grid, for many ground height queries over one area + class triangle_grid + { + public: + triangle_grid(std::vector Triangles, glm::dvec2 const &Min, glm::dvec2 const &Max) : m_triangles(std::move(Triangles)), m_min(Min) + { + glm::dvec2 const extent = glm::max(Max - Min, glm::dvec2(1.0)); + if (false == std::isfinite(extent.x) || false == std::isfinite(extent.y)) + { + m_triangles.clear(); + m_cells.resize(1); + return; + } + // ~8 m cells, coarser for big areas so large terrain triangles don't flood the grid + m_cellsize = std::max(8.0, std::max(extent.x, extent.y) / 128.0); + m_columns = static_cast(std::ceil(extent.x / m_cellsize)) + 1; + m_rows = static_cast(std::ceil(extent.y / m_cellsize)) + 1; + m_cells.resize(static_cast(m_columns) * m_rows); + + for (std::uint32_t idx = 0; idx < m_triangles.size(); ++idx) + { + auto const &t = m_triangles[idx]; + int const c0 = column(std::min({t[0].x, t[1].x, t[2].x})); + int const c1 = column(std::max({t[0].x, t[1].x, t[2].x})); + int const r0 = row(std::min({t[0].z, t[1].z, t[2].z})); + int const r1 = row(std::max({t[0].z, t[1].z, t[2].z})); + for (int r = r0; r <= r1; ++r) + for (int c = c0; c <= c1; ++c) + m_cells[static_cast(r) * m_columns + c].push_back(idx); + } + } + + // highest surface at (X,Z) that isn't above Ceiling. returns: true if there is one, and which triangle it is in Index if asked + bool height_at(double const X, double const Z, double const Ceiling, double &OutY, std::uint32_t *Index = nullptr) const + { + bool found = false; + for (auto const idx : m_cells[static_cast(row(Z)) * m_columns + column(X)]) + { + auto const &t = m_triangles[idx]; + double y; + if (triangle_height_at(t[0], t[1], t[2], X, Z, y) && y <= Ceiling && (!found || y > OutY)) + { + OutY = y; + found = true; + if (Index != nullptr) + *Index = idx; + } + } + return found; + } + + private: + int column(double const X) const + { + double const cell = std::floor((X - m_min.x) / m_cellsize); + return cell > 0.0 ? static_cast(std::min(cell, static_cast(m_columns - 1))) : 0; + } + int row(double const Z) const + { + double const cell = std::floor((Z - m_min.y) / m_cellsize); + return cell > 0.0 ? static_cast(std::min(cell, static_cast(m_rows - 1))) : 0; + } + + std::vector m_triangles; + std::vector> m_cells; + glm::dvec2 m_min; + double m_cellsize{8.0}; + int m_columns{1}; + int m_rows{1}; + }; + + // meshes of the shapes and the models asked about as ground. the ground is asked about a tile at a time, by the orthophoto + // and by the road tools, and without these every question meant going through every triangle of every terrain model in reach + struct ground_record + { + ground_mesh mesh; + // what the mesh was made of, to tell when it has to be made again + std::size_t vertices{0}; + std::size_t indices{0}; + glm::dvec3 origin{0.0}; + TModel3d const *model{nullptr}; + glm::dmat4 matrix{0.0}; + std::uint64_t used{0}; // number of the last question it served + }; + std::unordered_map ground_shapes; // by the geometry of the shape + std::unordered_map ground_models; + std::uint64_t ground_question{0}; + std::size_t ground_held{0}; // triangles in the meshes + std::size_t constexpr ground_limit = 8000000; // triangles kept; some 400 MB with the grids + std::size_t constexpr ground_small = 256; // triangles; anything smaller is quicker to go through than to look up + + // lets go of the meshes left alone the longest, once there's too much of them + void trim_ground_meshes() + { + if (ground_held <= ground_limit) + return; + std::vector ages; + for (auto const &record : ground_shapes) + ages.emplace_back(record.second.used); + for (auto const &record : ground_models) + ages.emplace_back(record.second.used); + std::sort(ages.begin(), ages.end()); + // the older half goes, except for what the current question needed + auto const threshold = std::min(ages[ages.size() / 2], ground_question - 1); + for (auto record = ground_shapes.begin(); record != ground_shapes.end();) + { + if (record->second.used <= threshold) + { + ground_held -= record->second.mesh.size(); + record = ground_shapes.erase(record); + } + else + ++record; + } + for (auto record = ground_models.begin(); record != ground_models.end();) + { + if (record->second.used <= threshold) + { + ground_held -= record->second.mesh.size(); + record = ground_models.erase(record); + } + else + ++record; + } + } + + // forgets the meshes of the shapes, whose geometry can be changed in place (terrain being sculpted) + void forget_ground_shapes() + { + for (auto const &record : ground_shapes) + ground_held -= record.second.mesh.size(); + ground_shapes.clear(); + } + + // appends triangles of a shape node which overlap specified XZ rectangle + void gather_shape_triangles(scene::shape_node const &Shape, glm::dvec2 const &Min, glm::dvec2 const &Max, std::vector &Out, bool const Skiproads = false) + { + auto const &data = Shape.data(); + if (editor_orthophoto::owns(data.geometry)) + return; // the orthophoto laid over the ground isn't ground itself + if (Skiproads && owned_shapes::owns(data.geometry)) + return; // neither are the roads, for the ones which ask where to put a road + if (data.area.radius >= 0.0f) + { + double const r = data.area.radius; + if (data.area.center.x + r < Min.x || data.area.center.x - r > Max.x || data.area.center.z + r < Min.y || data.area.center.z - r > Max.y) + return; + } + + auto const add = [&](glm::dvec3 const &a, glm::dvec3 const &b, glm::dvec3 const &c) { + 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}); + }; + + if (false == data.vertices.empty()) + { + for (std::size_t i = 0; i + 2 < data.vertices.size(); i += 3) + add(data.vertices[i].position, data.vertices[i + 1].position, data.vertices[i + 2].position); + 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 &verts = GfxRenderer->Vertices(data.geometry); + auto const &indices = GfxRenderer->Indices(data.geometry); + auto const count = (indices.empty() ? verts.size() : indices.size()) / 3; + if (count >= ground_small) + { + // a large shape is sorted once, and asked for what's in the rectangle from then on + auto &record = ground_shapes[(static_cast(data.geometry.bank) << 32) | data.geometry.chunk]; + if (record.mesh.size() == 0 || record.vertices != verts.size() || record.indices != indices.size() || record.origin != data.origin) + { + std::vector triangles; + triangles.reserve(count); + if (false == indices.empty()) + { + for (std::size_t i = 0; i + 2 < indices.size(); i += 3) + triangles.push_back({verts[indices[i]].position, verts[indices[i + 1]].position, verts[indices[i + 2]].position}); + } + else + { + for (std::size_t i = 0; i + 2 < verts.size(); i += 3) + triangles.push_back({verts[i].position, verts[i + 1].position, verts[i + 2].position}); + } + ground_held -= record.mesh.size(); + record.mesh.assign(std::move(triangles), data.origin); + ground_held += record.mesh.size(); + record.vertices = verts.size(); + record.indices = indices.size(); + record.origin = data.origin; + } + record.used = ground_question; + record.mesh.collect(Min, Max, Out); + return; + } + auto const to_world = [&](gfx::basic_vertex const &v) { return data.origin + glm::dvec3(v.position); }; + if (false == indices.empty()) + { + for (std::size_t i = 0; i + 2 < indices.size(); i += 3) + add(to_world(verts[indices[i]]), to_world(verts[indices[i + 1]]), to_world(verts[indices[i + 2]])); + } + else + { + for (std::size_t i = 0; i + 2 < verts.size(); i += 3) + add(to_world(verts[i]), to_world(verts[i + 1]), to_world(verts[i + 2])); + } + } + + // ground triangles overlapping an XZ rectangle (Min/Max are x,z). shapes hold the (legacy) terrain, + // model instances at least ModelRadius large (if ModelsAsGround) the terrain tiles + // Heightmap: the heightmap terrain is given as triangles too (for the ones which can ask the terrain for heights, it's a waste) + void gather_ground_triangles(glm::dvec2 const &Min, glm::dvec2 const &Max, bool const ModelsAsGround, float const ModelRadius, std::vector &Out, bool const Skiproads = false, + bool const Heightmap = true) + { + auto const started = std::chrono::steady_clock::now(); + ++ground_question; + glm::dvec2 const center = (Min + Max) * 0.5; + float const radius = static_cast(glm::length(Max - Min) * 0.5); + auto const sections = simulation::Region->sections(glm::dvec3(center.x, 0.0, center.y), radius); // copy, the result is a scratchpad + for (auto *section : sections) + { + for (auto const &shape : section->m_shapes) + gather_shape_triangles(shape, Min, Max, Out, Skiproads); + for (auto &cell : section->m_cells) + { + double const r = cell.m_area.radius; + if (cell.m_area.center.x + r < Min.x || cell.m_area.center.x - r > Max.x || cell.m_area.center.z + r < Min.y || cell.m_area.center.z - r > Max.y) + continue; + for (auto const &shape : cell.m_shapesopaque) + gather_shape_triangles(shape, Min, Max, Out); + if (false == ModelsAsGround) + continue; + for (auto *instance : cell.m_instancesopaque) + { + if (instance == nullptr || instance->Model() == nullptr || instance->radius() < ModelRadius) + continue; + // going through the triangles of a model which doesn't reach the rectangle is all cost and no gain + double const reach = instance->radius(); + if (instance->location().x + reach < Min.x || instance->location().x - reach > Max.x || instance->location().z + reach < Min.y || instance->location().z - reach > Max.y) + continue; + // the model is gone through once, and asked for what's in the rectangle from then on, for as long as it stays put + auto const matrix = instance_matrix(*instance); + auto &record = ground_models[instance]; + if (record.model != instance->Model() || record.matrix != matrix) + { + std::vector modeltriangles; + gather_submodel_triangles(instance->Model()->Root, matrix, modeltriangles); + glm::dvec3 const origin = instance->location(); + std::vector triangles; + triangles.reserve(modeltriangles.size()); + for (auto const &t : modeltriangles) + triangles.push_back({glm::vec3(t[0] - origin), glm::vec3(t[1] - origin), glm::vec3(t[2] - origin)}); + ground_held -= record.mesh.size(); + record.mesh.assign(std::move(triangles), origin); + ground_held += record.mesh.size(); + // a model which isn't loaded yet has nothing to show for itself, and is looked at again the next time + record.model = (record.mesh.size() > 0 ? instance->Model() : nullptr); + record.matrix = matrix; + } + record.used = ground_question; + record.mesh.collect(Min, Max, Out); + } + } + } + // the heightmap terrain answers for itself, with its full grid whatever is drawn of it + if (Heightmap) + EditorTerrain.gather_triangles(Min, Max, Out); + trim_ground_meshes(); + // going through the scenery is the one thing here which can take long enough to be felt; when it does it's worth knowing + auto const elapsed = std::chrono::duration(std::chrono::steady_clock::now() - started).count(); + if (elapsed > 250.0) + WriteLog("editor: gathering the ground took " + std::to_string(static_cast(elapsed)) + " ms, for " + std::to_string(Out.size()) + " triangles; " + std::to_string(ground_held) + " are kept for the next time"); + } + + // ground kept for the road tools, which ask about the same places frame after frame. it's gathered a tile at a time: + // gathering is what takes time, so a place asked about for the first time costs a single tile a frame instead of a stall + struct ground_tile + { + std::unique_ptr grid; + double gathered{0.0}; // when, on the clock of the user interface + int used{0}; // frame it was last asked for + }; + double constexpr ground_tile_size = 256.0; + double constexpr ground_tile_lifetime = 30.0; // older tiles are gathered again when asked for, to catch up with the scenery + std::size_t constexpr ground_tile_limit = 96; + std::map, ground_tile> ground_tiles; + int ground_tile_frame{-1}; // frame the last tile was gathered in without being told to + + // scenery file name without path and extension + std::string scenery_stem() + { + std::string scenery = Global.SceneryFile; + auto const slash = scenery.find_last_of("/\\"); + if (slash != std::string::npos) + scenery = scenery.substr(slash + 1); + auto const dot = scenery.find_last_of('.'); + if (dot != std::string::npos) + scenery = scenery.substr(0, dot); + return scenery.empty() ? "default" : scenery; + } + } bool editor_mode::editormode_input::init() @@ -130,9 +544,151 @@ void editor_mode::editormode_input::poll() } editor_mode::editor_mode() { + alignment_store::reset(); + switch_store::reset(); + kilometrage::reset(); m_userinterface = std::make_shared(); + // the area fill settings live in the node bank window, in the tab of the fill mode + ui()->set_fill_options([this]() { render_area_fill(); }); + ui()->set_gizmo_options([this]() { render_gizmo_options(); }); + ui()->set_toolbar_options([this]() { render_toolbar(); }); + ui()->set_workspace_bar([this]() { render_workspaces(); }); + ui()->set_track_options([this]() { render_track_tool_options(); }, [this]() { render_track_selection(); }); + ui()->set_workspace_options(editor_ui::workspace::roads, [this]() { render_road_tool_options(); }, [this]() { render_road_selection(); }); + ui()->set_workspace_options(editor_ui::workspace::terrain, [this]() { render_terrain_tool_options(); }); + ui()->set_workspace_bank(editor_ui::workspace::terrain, [this]() { render_texture_browser(); }, STR("Textures")); + // a node picked in the scene window is selected as if clicked in the view; a double click flies the camera to it + ui()->set_scene_select([this](scene::basic_node *Node, bool const Focus) { + if (Focus) + start_focus(Node); + std::string reason; + if (Node->from_template() || false == scene::Layers.editable(Node, &reason)) + { + ui()->set_status(format(STR_C("\"%s\" can't be edited: %s"), name_of(*Node).c_str(), reason.c_str()), true); + return; + } + m_track_window_open = false; + ui()->set_mode(nodebank_panel::MODIFY); + m_node = Node; + ui()->set_node(m_node); + }); + ui()->set_array_options([this]() { render_array(); }); + ui()->set_bend_options([this]() { render_bend(); }); + ui()->set_file_actions([this]() { save(); }, [this]() { export_scenery(); }); + ui()->set_new_scenery([this]() { m_newscenery_asked = true; }); + ui()->set_open_scenery([this]() { m_openscenery_asked = true; }); + ui()->set_edit_menu([this]() { render_edit_menu(); }); + ui()->set_tools_menu([this]() { render_track_presets_menu(); }); + ui()->set_menu_options([this]() { + render_object_menu(); + render_view_menu(); + render_map_menu(); + render_help_menu(); + }); + m_roadtool.settings.normalize(); + road_select(nullptr); + ground_sources(m_orthophoto); + ui()->set_base_layers([this]() { render_base_layers(); }); + editor_track::observe(this); } +void editor_mode::ground_sources(editor_orthophoto &Layer) +{ + // the imagery is fitted onto the same ground as the area fill uses, terrain tile models included + // the roads built in the editor aren't ground: the imagery goes under them + Layer.ground_source([](glm::dvec2 const &Min, glm::dvec2 const &Max, bool const Heightmap, std::vector &Out) { + gather_ground_triangles(Min, Max, true, 50.0f, Out, true, Heightmap); + }); + Layer.height_source([](double const X, double const Z, double &Height) { return EditorTerrain.height_at(X, Z, Height); }); + // the imagery often comes before the terrain made from the model: it lies where the terrain will be + Layer.guess_source([this](double const X, double const Z, double &Height) { + if (nmt_ground(X, Z, Height)) + return true; + // asked for, the tile goes onto it once it comes + if (m_nmt.placed()) + m_nmt.request({X - 1.0, Z - 1.0}, {X + 1.0, Z + 1.0}); + return false; + }); +} + +editor_mode::~editor_mode() +{ + editor_track::observe(nullptr); +} + +std::vector editor_mode::ground_heights(std::vector const &Points, bool const Fresh, std::vector *Found) const +{ + std::vector heights; + heights.reserve(Points.size()); + if (Found != nullptr) + Found->assign(Points.size(), 0); + for (auto const &point : Points) + heights.push_back(point.y); + if (Points.empty() || simulation::Region == nullptr) + return heights; + + double const now = ImGui::GetTime(); + int const frame = ImGui::GetFrameCount(); + // surfaces much higher than the point are something it's under, rather than the ground + double constexpr height_tolerance = 50.0; + auto const terrains = active_terrains(); + for (std::size_t i = 0; i < Points.size(); ++i) + { + auto const &p = Points[i]; + if (false == std::isfinite(p.x) || false == std::isfinite(p.y) || false == std::isfinite(p.z)) + continue; + std::pair const key{static_cast(std::floor(p.x / ground_tile_size)), static_cast(std::floor(p.z / ground_tile_size))}; + auto &tile = ground_tiles[key]; + bool const missing = (tile.grid == nullptr); + bool const stale = missing || now < tile.gathered || now - tile.gathered > ground_tile_lifetime; + // told to wait the caller gets every tile it needs, otherwise what's there, with one tile gathered each frame + if (stale && (Fresh ? missing : ground_tile_frame != frame)) + { + glm::dvec2 const tilemin{key.first * ground_tile_size, key.second * ground_tile_size}; + glm::dvec2 const tilemax{tilemin + glm::dvec2{ground_tile_size}}; + std::vector triangles; + // the same ground as the area fill uses, terrain tile models included + gather_ground_triangles(tilemin, tilemax, true, 50.0f, triangles, true); + tile.grid = std::make_unique(std::move(triangles), tilemin, tilemax); + tile.gathered = now; + if (false == Fresh) + ground_tile_frame = frame; + } + tile.used = frame; + + double const ceiling = p.y + height_tolerance; + double y = 0.0; + bool found = (tile.grid != nullptr) && tile.grid->height_at(p.x, p.z, ceiling, y); + for (editor_terrain *terrain : terrains) + { + if (!terrain->contains(p.x, p.z)) + continue; + double const h = terrain->height_at(p.x, p.z); + if (h <= ceiling && (!found || h > y)) + { + y = h; + found = true; + } + } + if (found) + heights[i] = y; + if (Found != nullptr) + (*Found)[i] = found ? 1 : 0; + } + // the tiles left alone the longest go once there are too many + while (ground_tiles.size() > ground_tile_limit) + { + auto oldest = ground_tiles.begin(); + for (auto tile = ground_tiles.begin(); tile != ground_tiles.end(); ++tile) + if (tile->second.used < oldest->second.used) + oldest = tile; + if (oldest->second.used == frame) + break; + ground_tiles.erase(oldest); + } + return heights; +} + editor_ui *editor_mode::ui() const { return static_cast(m_userinterface.get()); @@ -141,6 +697,16 @@ editor_ui *editor_mode::ui() const bool editor_mode::init() { EditorSettings.load(); + Global.EditorOrthoTracks = EditorSettings.top_tracks(); + // the terrain model as the user left it; the settings are read only here, after the mode was made + auto const &model{EditorSettings.terrain_model()}; + m_nmt_state.grow = EditorSettings.terrain_while_laying(); + m_nmt_state.band = std::clamp(model.band, 50.0, 3000.0); + // the formation and the slopes are always made along the tracks: the switch of them is gone, a setting left off by it isn't kept + m_nmt_state.follow = model.follow; + m_terrain_add_count = std::clamp(model.around, 1, 8); + EditorModelSets.load(); + EditorTrackPresets.load(); Camera.Init({0, 15, 0}, {glm::radians(-30.0), glm::radians(180.0), 0}, nullptr); return m_input.init(); } @@ -181,26 +747,24 @@ void editor_mode::start_focus(scene::basic_node *node, double duration) double const len = glm::length(dir); dir = len > 1e-3 ? dir / len : glm::normalize(glm::dvec3(1.0, 0.5, 1.0)); - m_focus_start_pos = Camera.Pos; - m_focus_start_angle = Camera.Angle; - m_focus_target_pos = center + dir * distance; - - // target orientation looks from the target position straight at the object - glm::dvec3 look = center - m_focus_target_pos; - double const looklen = glm::length(look); - if (looklen > 1e-6) - look /= looklen; - m_focus_target_angle = glm::vec3( - static_cast(std::asin(glm::clamp(look.y, -1.0, 1.0))), // pitch - static_cast(std::atan2(-look.x, -look.z)), // yaw - 0.0f); // roll - - m_focus_active = true; - m_focus_time = 0.0; - m_focus_duration = duration; + // looking from there straight at the object + fly_to(center, -dir, distance, duration); } -void editor_mode::snap_to_ground(scene::basic_node *node) +void editor_mode::fly_to(glm::dvec3 const &Target, glm::dvec3 const &Look, double const Distance, double const Duration) +{ + // the camera flown off somewhere leaves the track it rode along + m_ride.leave(); + m_focus_start_pos = Camera.Pos; + m_focus_start_angle = Camera.Angle; + m_focus_target_pos = Target - Look * Distance; + m_focus_target_angle = glm::vec3(static_cast(std::asin(std::clamp(Look.y, -1.0, 1.0))), static_cast(std::atan2(-Look.x, -Look.z)), 0.0f); + m_focus_active = true; + m_focus_time = 0.0; + m_focus_duration = Duration; +} + +void editor_mode::snap_to_ground(scene::basic_node *node, bool const Alone, bool const Joined) { if (!node || !simulation::Region) return; @@ -209,89 +773,25 @@ void editor_mode::snap_to_ground(scene::basic_node *node) if (!simulation::Region->point_inside(origin)) return; - // small tolerance so a node already resting on a surface still snaps cleanly to it - double const epsilon = 0.05; - double bestY = -std::numeric_limits::max(); - bool found = false; - - // record the highest surface that is at or below the node's current position at its (x,z) - auto consider_triangle = [&](glm::dvec3 const &a, glm::dvec3 const &b, glm::dvec3 const &c) { - double y; - if (triangle_height_at(a, b, c, origin.x, origin.z, y) && y <= origin.y + epsilon && y > bestY) - { - bestY = y; - found = true; - } - }; - - auto consider_shapes = [&](std::vector const &shapes) { - for (auto const &shape : shapes) - { - // quick reject: skip shapes whose bounding circle doesn't cover our (x,z) column - auto const &sdata = shape.data(); - double const sdx = origin.x - sdata.area.center.x; - double const sdz = origin.z - sdata.area.center.z; - if (sdx * sdx + sdz * sdz > static_cast(sdata.area.radius) * sdata.area.radius) - continue; - - auto const &verts = sdata.vertices; - for (std::size_t i = 0; i + 2 < verts.size(); i += 3) - consider_triangle(verts[i].position, verts[i + 1].position, verts[i + 2].position); - } - }; - - scene::basic_section &sec = simulation::Region->section(origin); - // section level holds the large opaque geometry, including legacy terrain - consider_shapes(sec.m_shapes); - - // scan a 3x3 neighbourhood of cells for smaller geometry and other model instances below us - for (int dz = -1; dz <= 1; ++dz) - for (int dx = -1; dx <= 1; ++dx) - { - scene::basic_cell &cell = sec.cell(origin, glm::ivec2(dx, dz)); - consider_shapes(cell.m_shapesopaque); - consider_shapes(cell.m_shapestranslucent); - - // other instances are approximated by their bounding sphere, so a node can rest on top of them - for (auto *inst : cell.m_instancesopaque) - { - if (!inst || inst == node) - continue; - glm::dvec3 const ic = inst->location(); - double const r = static_cast(inst->radius()); - double const idx = origin.x - ic.x, idz = origin.z - ic.z; - double const horiz2 = idx * idx + idz * idz; - if (horiz2 < r * r) - { - double const ytop = ic.y + std::sqrt(r * r - horiz2); - if (ytop <= origin.y + epsilon && ytop > bestY) - { - bestY = ytop; - found = true; - } - } - } - } - - // editable terrain patches keep their heightmap on the CPU, so query them directly - for (editor_terrain *terrain : active_terrains()) - { - if (!terrain->contains(origin.x, origin.z)) - continue; - double const y = terrain->height_at(origin.x, origin.z); - if (y <= origin.y + epsilon && y > bestY) - { - bestY = y; - found = true; - } - } - - if (!found) + // the same ground the models are put on when they're inserted: the terrain shapes, the terrain tile models and the terrain + // patches of the editor, under the node, or over it when it went under the ground. the shapes alone and the spheres of the + // models around, which were asked about before, missed the ground of the sceneries made of terrain tile models + glm::dvec3 const target = placement_on_ground(origin); + if (std::abs(target.y - origin.y) < 1e-4) return; push_snapshot(node, EditorSnapshot::Action::Move); - glm::dvec3 target = origin; - target.y = bestY; + if (false == m_history.empty()) + m_history.back().joined = Joined; + if (auto *model = dynamic_cast(node); Alone && model != nullptr && node->group() > 1) + { + // the model of a group goes down by itself, the rest of the group stays + simulation::Region->erase(model); + model->location(target); + simulation::Region->insert(model); + model->mark_dirty(); + return; + } m_editor.translate(node, target, true); // true == apply the computed Y (free vertical move) } @@ -306,32 +806,36 @@ void editor_mode::handle_brush_mouse_hold(int Action, int Button) GfxRenderer->Pick_Node_Callback( [this, mode, rotation_mode, fixed_rotation_value, Action, Button](scene::basic_node * /*node*/) { + // picks are resolved a few frames later; drop the ones queued before the button went up, + // or for a press that turned out to belong to the UI + if (!mouseHold || !viewport_click()) + return; + + // spacing is measured in world space: the mouse offset is camera-relative and the camera may move mid-stroke + glm::dvec3 const newPos = Camera.Pos + clamp_mouse_offset_to_max(GfxRenderer->Mouse_Position()); + if (m_brush_has_last && glm::distance(newPos, oldPos) < ui()->getSpacing()) + return; + + // picked only when a placement is due, so a random pick from a set isn't drawn every tick const std::string *src = ui()->get_active_node_template(); - if (!src) + if (!src || src->starts_with(editor_includes::directive_mark)) // scenery templates are placed one at a time return; - std::string name = "editor_"; - - glm::dvec3 newPos = clamp_mouse_offset_to_max(GfxRenderer->Mouse_Position()); - double distance = glm::distance(newPos, oldPos); - if (distance < ui()->getSpacing()) - return; - - TAnimModel *cloned = simulation::State.create_model(*src, name, Camera.Pos + newPos); + // NOTE: no name for what the brush puts in, as with thousands of nodes the names take their share of the time + // the scenery needs to load. a node which needs one, to be referred to by an event, gets it in the node properties + TAnimModel *cloned = simulation::State.create_model(*src, std::string{}, placement_on_ground(newPos)); oldPos = newPos; + m_brush_has_last = true; if (!cloned) return; - std::string new_name = "editor_" + cloned->uuid.to_string(); + apply_rotation_for_new_node(cloned, rotation_mode, fixed_rotation_value); - cloned->m_name = new_name; - std::string as_text; cloned->export_as_text(as_text); push_snapshot(cloned, EditorSnapshot::Action::Add, as_text); m_node = cloned; - apply_rotation_for_new_node(m_node, rotation_mode, fixed_rotation_value); ui()->set_node(m_node); }); } @@ -388,6 +892,7 @@ void editor_mode::push_snapshot(scene::basic_node *node, EditorSnapshot::Action snap.node_name = node->name(); snap.position = node->location(); snap.uuid = node->uuid; + snap.layer = node->layer(); if (auto *model = dynamic_cast(node)) { @@ -428,27 +933,207 @@ void editor_mode::nullify_history_pointers(scene::basic_node *node) if (!node) return; + if (ui()->node() == node) + ui()->set_node(nullptr); + infra_forget(node); + for (auto *tool : m_tools) + tool->forget(node); + + auto const followed = [node](infra::object_state const &State) { return State.saved.node == node; }; for (auto &s : m_history) { if (s.node_ptr == node) s.node_ptr = nullptr; + for (auto © : s.copies) + { + if (copy.model == node) + copy.model = nullptr; + } + s.infra.erase(std::remove_if(s.infra.begin(), s.infra.end(), followed), s.infra.end()); } for (auto &s : g_redo) { if (s.node_ptr == node) s.node_ptr = nullptr; + s.infra.erase(std::remove_if(s.infra.begin(), s.infra.end(), followed), s.infra.end()); } + + // deleted nodes also drop out of the "undo last fill" set + m_fill_last.erase(std::remove(m_fill_last.begin(), m_fill_last.end(), node), m_fill_last.end()); + // and out of the selection and their group + m_selection.erase(std::remove(m_selection.begin(), m_selection.end(), node), m_selection.end()); + scene::Groups.remove(node); + + // an array no longer follows its settings once the model it was made of is gone + if (m_array.base == node) + m_array.base = nullptr; +} + +void editor_mode::terrain_history_step() +{ + if (false == m_streamer.active()) + return; + // the terrain loaded from the model is taken back as a whole + if (nmt_busy() && false == m_history_busy) + return; + if (m_streamer.recording()) + { + if (terrain_brush() && mouseHold && false == m_history_busy) + return; // the stroke goes on + auto change{m_streamer.end_change()}; + if (false == change.empty()) + { + trim_history(); + EditorSnapshot snap; + snap.action = EditorSnapshot::Action::Terrain; + snap.node_name = STR("terrain"); + if (false == change.chunks.empty()) + { + auto const centre{heightmap::chunk_corner(change.chunks.begin()->first) + glm::dvec2{heightmap::chunk_size * 0.5}}; + snap.position = {centre.x, 0.0, centre.y}; + } + snap.terrain = std::make_shared(std::move(change)); + m_history.push_back(std::move(snap)); + g_redo.clear(); + } + } + m_streamer.begin_change(); +} + +void editor_mode::restore_terrain(EditorSnapshot &Snapshot) +{ + if (Snapshot.terrain == nullptr) + return; + auto opposite{m_streamer.restore(*Snapshot.terrain)}; + Snapshot.terrain = std::make_shared(std::move(opposite)); + forget_ground(); + m_water_selected = -1; + m_water_material_of = -1; } void editor_mode::undo_last() +{ + first_step_done(first_step::undo); + // the warning by the cursor told of the step taken back now: "Ctrl+Z takes it back" is done + ui()->drop_refusal(); + // a change of the terrain made a moment ago is a step of its own before it's taken back + m_history_busy = true; + terrain_history_step(); + m_history_busy = false; + // the changes made together are taken back together, and their models are the selection again + std::vector touched; + while (false == m_history.empty()) + { + auto const joined{m_history.back().joined}; + undo_one(); + if (m_node != nullptr && std::find(touched.begin(), touched.end(), m_node) == touched.end()) + touched.push_back(m_node); + if (false == joined) + break; + } + if (touched.size() > 1) + { + // the one with the gizmo was recorded first, so it's taken back last + m_node = touched.back(); + m_selection.assign(touched.begin(), touched.end() - 1); + ui()->set_node(m_node); + } +} + +std::string editor_mode::refused(std::string Text) +{ + ui()->set_status(Text, true); + return Text; +} + +void editor_mode::drop_step(std::size_t const Step) +{ + if (Step == 0 || m_history.size() != Step) + return; + auto const redo{g_redo.size()}; + undo_one(); + if (g_redo.size() > redo) + g_redo.erase(g_redo.begin() + redo, g_redo.end()); +} + +void editor_mode::undo_one() { if (m_history.empty()) return; + m_nmt_state.restoring = true; + struct restored + { + bool &flag; + ~restored() { flag = false; } + } const restoring{m_nmt_state.restoring}; EditorSnapshot snap = m_history.back(); m_history.pop_back(); + if (snap.action == EditorSnapshot::Action::Terrain) + { + restore_terrain(snap); + g_redo.push_back(std::move(snap)); + return; + } + + if (snap.action == EditorSnapshot::Action::Kilometrage) + { + restore_kilometrage(snap); + g_redo.push_back(std::move(snap)); + return; + } + + if (snap.action == EditorSnapshot::Action::Bend) + { + restore_bend(snap, true); + g_redo.push_back(std::move(snap)); + return; + } + + if (false == snap.sweeps.empty() || false == snap.sweeps_toggled.empty()) + { + restore_sweeps(snap); + g_redo.push_back(std::move(snap)); + return; + } + + if (false == snap.instances.empty() || false == snap.directives.empty()) + { + restore_includes(snap); + if (snap.action != EditorSnapshot::Action::TrackEdit) + { + g_redo.push_back(std::move(snap)); + return; + } + } + + if (snap.instance != 0) + { + restore_include(snap); + g_redo.push_back(std::move(snap)); + return; + } + + if (snap.action == EditorSnapshot::Action::TrackEdit) + { + restore_track_snapshot(snap, g_redo, true); + return; + } + + if (snap.action == EditorSnapshot::Action::RoadEdit) + { + restore_road_snapshot(snap, g_redo, true); + return; + } + + if (snap.action == EditorSnapshot::Action::Array) + { + restore_array_snapshot(std::move(snap), g_redo, true); + return; + } + if (snap.action == EditorSnapshot::Action::Delete) { // undo delete -> recreate model @@ -458,16 +1143,22 @@ void editor_mode::undo_last() redoSnap.serialized = snap.serialized; redoSnap.position = snap.position; redoSnap.node_ptr = nullptr; + redoSnap.uuid = snap.uuid; + redoSnap.layer = snap.layer; + redoSnap.joined = snap.joined; g_redo.push_back(std::move(redoSnap)); TAnimModel *created = simulation::State.create_model(snap.serialized, snap.node_name, snap.position); if (created) { + scene::Layers.move(created, snap.layer); // back to the layer it was deleted from, rather than the active one created->location(snap.position); created->Angles(snap.rotation); m_node = created; m_node->uuid = snap.uuid; // restore original UUID for better tracking (not strictly necessary) add_to_hierarchy(created); + // a node without a name can be found for the redo only this way + g_redo.back().node_ptr = created; ui()->set_node(m_node); } return; @@ -479,8 +1170,10 @@ void editor_mode::undo_last() EditorSnapshot current; current.action = snap.action; + current.joined = snap.joined; current.node_name = snap.node_name; current.node_ptr = target; + current.layer = target->layer(); current.position = target->location(); if (auto *model = dynamic_cast(target)) { @@ -497,9 +1190,7 @@ void editor_mode::undo_last() if (auto *model = dynamic_cast(target)) { - nullify_history_pointers(model); - remove_from_hierarchy(model); - simulation::State.delete_model(model); + erase_model(model); m_node = nullptr; ui()->set_node(nullptr); } @@ -521,13 +1212,104 @@ void editor_mode::undo_last() } void editor_mode::redo_last() +{ + // a change of the terrain made since the undo goes to the history, and the redo steps are dropped with it + m_history_busy = true; + terrain_history_step(); + m_history_busy = false; + // the first of the changes made together is on the top, the others follow it + std::vector touched; + do + { + redo_one(); + if (m_node != nullptr && std::find(touched.begin(), touched.end(), m_node) == touched.end()) + touched.push_back(m_node); + } while (false == g_redo.empty() && g_redo.back().joined); + if (touched.size() > 1) + { + m_node = touched.front(); + m_selection.assign(touched.begin() + 1, touched.end()); + ui()->set_node(m_node); + } +} + +void editor_mode::redo_one() { if (g_redo.empty()) return; + m_nmt_state.restoring = true; + struct restored + { + bool &flag; + ~restored() { flag = false; } + } const restoring{m_nmt_state.restoring}; EditorSnapshot snap = g_redo.back(); g_redo.pop_back(); + if (snap.action == EditorSnapshot::Action::Terrain) + { + restore_terrain(snap); + m_history.push_back(std::move(snap)); + return; + } + + if (snap.action == EditorSnapshot::Action::Kilometrage) + { + restore_kilometrage(snap); + m_history.push_back(std::move(snap)); + return; + } + + if (snap.action == EditorSnapshot::Action::Bend) + { + restore_bend(snap, false); + m_history.push_back(std::move(snap)); + return; + } + + if (false == snap.sweeps.empty() || false == snap.sweeps_toggled.empty()) + { + restore_sweeps(snap); + m_history.push_back(std::move(snap)); + return; + } + + if (false == snap.instances.empty() || false == snap.directives.empty()) + { + restore_includes(snap); + if (snap.action != EditorSnapshot::Action::TrackEdit) + { + m_history.push_back(std::move(snap)); + return; + } + } + + if (snap.instance != 0) + { + restore_include(snap); + m_history.push_back(std::move(snap)); + return; + } + + if (snap.action == EditorSnapshot::Action::TrackEdit) + { + restore_track_snapshot(snap, m_history, false); + return; + } + + if (snap.action == EditorSnapshot::Action::RoadEdit) + { + restore_road_snapshot(snap, m_history, false); + return; + } + + if (snap.action == EditorSnapshot::Action::Array) + { + restore_array_snapshot(std::move(snap), m_history, false); + return; + } + // handle delete redo (re-delete) separately if (snap.action == EditorSnapshot::Action::Delete) { @@ -537,16 +1319,17 @@ void editor_mode::redo_last() hist.serialized = snap.serialized; hist.position = snap.position; hist.uuid = snap.uuid; + hist.layer = snap.layer; + hist.joined = snap.joined; m_history.push_back(std::move(hist)); - scene::basic_node *target = simulation::Instances.find(snap.node_name); + // NOTE: located the way other steps do it, as the name alone doesn't lead to a node which has none + scene::basic_node *target = find_node_by_any(snap.node_ptr, snap.uuid.to_string(), snap.node_name); if (target) { if (auto *model = dynamic_cast(target)) { - nullify_history_pointers(model); - remove_from_hierarchy(model); - simulation::State.delete_model(model); + erase_model(model); m_node = nullptr; ui()->set_node(nullptr); } @@ -558,6 +1341,7 @@ void editor_mode::redo_last() EditorSnapshot hist; hist.action = snap.action; + hist.joined = snap.joined; hist.node_name = snap.node_name; hist.node_ptr = target; @@ -578,6 +1362,7 @@ void editor_mode::redo_last() TAnimModel *created = simulation::State.create_model(snap.serialized, snap.node_name, snap.position); if (created) { + scene::Layers.move(created, snap.layer); created->location(snap.position); created->Angles(snap.rotation); created->Scale(snap.scale); @@ -609,12 +1394,58 @@ void editor_mode::redo_last() bool editor_mode::update() { + frame_steps steps; + Global.editor_tracks = (current_work_area() == work_area::tracks); + selftest_step(); + steps.step("selftest"); + // the drives of the switches go to the tips of their blades once, as the templates of the scenery are known + if (false == m_drives_checked) + { + EditorIncludes.start(); + if (EditorIncludes.scanned()) + { + m_drives_checked = true; + if (auto const moved{drives_to_blade_tips()}; moved > 0) + { + auto const text{format(STR_P("The drive of %zu switch is moved to the tips of its blades", "The drives of %zu switches are moved to the tips of their blades", static_cast(moved)), moved)}; + ui()->set_status(text, false); + WriteLog("Editor: " + text, logtype::generic); + } + } + } + // after the tool has told its own status + if (false == m_orphan_note.empty()) + { + ui()->set_notice(m_orphan_note); + WriteLog("Editor: " + m_orphan_note); + m_orphan_note.clear(); + } + if (m_vehicle.take_leave()) + { + Application.pop_mode(); + return true; + } + + steps.step("start"); Timer::UpdateTimers(true); + move_thrown_switches(); simulation::State.update_clocks(); simulation::Environment.update(); + // bindings are matched with the objects by their locations, before anything gets moved + if (false == m_bindings_loaded && simulation::is_ready) + infra_load(); + // the templates are looked for in the background from the start, for the tools to have them at hand + if (simulation::is_ready) + { + EditorIncludes.start(); + EditorIncludes.poll(); + } auto const deltarealtime = Timer::GetDeltaRenderTime(); + // the whole frame before, drawing included: one slow where its update wasn't took the time drawing + if (deltarealtime > 0.15 && simulation::is_ready) + WriteLog("Editor: slow frame before, " + std::to_string(static_cast(deltarealtime * 1000.0)) + " ms in all", logtype::generic); // reconcile camera fly-mode with the real right-button state. ImGui is always fed the button // events (even when it captures the mouse), so io.MouseDown[1] is authoritative; if a release @@ -625,6 +1456,23 @@ bool editor_mode::update() m_input.mouse.button(GLFW_MOUSE_BUTTON_RIGHT, GLFW_RELEASE); Application.set_cursor(GLFW_CURSOR_NORMAL); } + if (m_ortho_pan && !ImGui::GetIO().MouseDown[2]) + ortho_pan_stop(); + + // same for the left button (brush / sculpt / click placement). the UI filter in the application + // uses io.WantCaptureMouse from the previous frame, so a press on a panel the cursor has just + // moved onto can leak into the viewport, and its release is then swallowed by the UI; the brush + // would keep painting with the button up. by now ImGui has processed this frame's input, so + // MouseDown is the real button state and MouseDownOwned tells whether the press hit the UI. + // (pick callbacks queued by such a press are discarded separately, see viewport_click()) + if (mouseHold && (!ImGui::GetIO().MouseDown[0] || !viewport_click())) + { + mouseHold = false; + m_dragging = false; + m_input.mouse.button(GLFW_MOUSE_BUTTON_LEFT, GLFW_RELEASE); + } + terrain_history_step(); + steps.step("simulation"); // fixed step render time routines (50 Hz) fTime50Hz += deltarealtime; // accumulate even when paused to keep frame reads stable @@ -635,9 +1483,6 @@ bool editor_mode::update() #endif m_userinterface->update(); - // update brush settings visibility depending on panel mode - ui()->toggleBrushSettings(ui()->mode() == nodebank_panel::BRUSH); - if (mouseHold) { // process continuous brush placement @@ -658,55 +1503,223 @@ bool editor_mode::update() } + steps.step("ui"); // variable step routines update_camera(deltarealtime); + steps.step("camera"); + + // drop the selection if its layer was hidden or locked in the meantime + if (m_node != nullptr && false == scene::Layers.editable(m_node)) + { + m_node = nullptr; + m_dragging = false; + ui()->set_node(nullptr); + } + if (m_instance != 0 && false == scene::Layers.removable(m_instance)) + { + select_include(0); + } + if (m_include.changed) + { + // a parameter of the selected include was changed in the node properties + m_include.changed = false; + apply_include(); + } + if (false == m_include.active && false == m_gizmo_using) + { + m_include_gesture = false; + } + // the gizmo let go of a signal while it wasn't drawn + if (false == m_gizmo_using) + signal_gizmo_end(); + // models replaced after changes of includes are destroyed once the renderer can't have them among its pick candidates + for (auto &retired : m_retired) + { + if (--retired.second <= 0) + { + simulation::Instances.purge(retired.first); + } + } + m_retired.erase(std::remove_if(m_retired.begin(), m_retired.end(), [](std::pair const &Retired) { return Retired.second <= 0; }), m_retired.end()); simulation::Region->update_sounds(); audio::renderer.update(Global.iPause ? 0.0 : deltarealtime); GfxRenderer->Update(deltarealtime); + steps.step("renderer"); simulation::is_ready = true; // note: the streamer is advanced centrally in the application main loop (so it runs in every // mode), using the published Global.pCamera; nothing to do here - // continuous terrain sculpting while the left mouse button is held in sculpt mode - if (m_terrain_sculpt && mouseHold) - handle_terrain_sculpt(deltarealtime); + // the brush of the terrain works while the left mouse button is held + if (terrain_brush() && mouseHold) + handle_terrain_brush(deltarealtime); + else + m_terrain_stroke = false; + if (m_terrain_open) + draw_terrain_overlay(); - // debounced auto mesh simplification: once sculpting has settled for a short while, simplify - // any chunk that was edited. holding the brush keeps the timer reset so we don't churn mid-stroke. - if (m_terrain_auto_optimize) + // --- geoportal orthophoto: streamed around the camera, drawn beneath the other overlays --- + // chunks of the terrain come from the files and from the model: the imagery lying at guessed heights goes onto them + // and so do the squares of the model it lies on meanwhile + auto const resident{m_streamer.resident()}; + auto const waiting{m_nmt.waiting()}; + if (resident > m_ortho_resident || waiting < m_ortho_waiting) { - auto const terrains = active_terrains(); - bool any_dirty = false; - for (editor_terrain *terrain : terrains) - if (terrain->dirty()) - { - any_dirty = true; - break; - } - - if (!any_dirty || (m_terrain_sculpt && mouseHold)) - { - m_terrain_idle = 0.0; // actively editing (or nothing pending): hold off - } - else - { - m_terrain_idle += deltarealtime; - if (m_terrain_idle >= 0.5) // settle time - { - for (editor_terrain *terrain : terrains) - if (terrain->dirty()) - terrain->optimize(m_terrain_simplify_error); - m_terrain_idle = 0.0; - } - } + m_orthophoto.ground_arrived(); + for (auto &layer : m_wms) + layer->ground_arrived(); } + m_ortho_resident = resident; + m_ortho_waiting = waiting; + steps.step("terrain"); + m_orthophoto.update(Camera.Pos); + steps.step("orthophoto"); + update_wms_layers(); + steps.step("wms"); + nmt_update(); + keep_nmt_settings(); + steps.step("nmt"); + // what's drawn over the 3d view stays in it, the docks around it are see-through a little + auto *background{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + background->PushClipRect(ImVec2(editor_ui::view_min().x, editor_ui::view_min().y), ImVec2(editor_ui::view_max().x, editor_ui::view_max().y), true); + draw_orthophoto(); + draw_nmt_pending(); + area_update(); + draw_download_area(); + steps.step("imagery"); // --- ImGuizmo: in-viewport transform gizmo for the selected node --- render_gizmo(); + // the tools, the gizmo modes and the axes over the 3d view + render_viewport_overlays(); + m_ride.draw_hud(); + + render_track_inspector(); + steps.step("inspector"); + if (ui()->mode() == nodebank_panel::TRACK) + { + draw_track_lines(); + draw_track_labels(); + draw_track_legend(); + } + else if (Global.EditorOrtho && Global.EditorOrthoTracks > 1) + draw_track_lines(); + if (selected_track()) + draw_track_overlay(); + if (route_active()) + draw_route_overlay(); + if (ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::straights) + draw_straights_overlay(); + steps.step("track lines"); + if (ui()->mode() == nodebank_panel::TRACK) + { + if (m_track_box.active && false == ImGui::GetIO().MouseDown[0]) + finish_track_box(); + update_track_hover(); + steps.step("hover"); + point_drag_update(); + switch_slide_update(); + draw_switch_slide(); + if (m_track_tab == track_tab::turntable) + draw_turntable_overlay(); + if (m_track_tab == track_tab::signals) + { + signal_refresh(); + signal_move_update(); + draw_signal_overlay(); + } + m_parallel.draw_overlay(); + if (m_track_tab == track_tab::lineside) + { + m_hekto.draw_overlay(); + m_fouling.draw_overlay(); + m_vehicle.draw_overlay(); + } + render_track_context(); + steps.step("context"); + update_build_tools(); + steps.step("laying"); + tape_update(); + update_track_intent(); + steps.step("intent"); + draw_track_hover(); + draw_track_set(); + draw_track_spread(); + draw_build_overlay(); + steps.step("laying drawn"); + draw_blade_tips(); + draw_track_intent(); + draw_tape(); + steps.step("track drawn"); + m_speed.update(); + steps.step("speed"); + m_joints.update(); + steps.step("joints"); + if (m_nmt_state.grade_lines_dirty) + { + m_nmt_state.grade_lines_dirty = false; + grade_lines_store(); + } + m_nmt_state.grade_line_replaced.clear(); + m_srk.update(); + kilometrage::follow(m_track_edits); + m_km.update(); + steps.step("srk km"); + draw_track_hints(); + draw_empty_scenery_hint(); + draw_profile_overlay(); + draw_grade_line_pick(); + draw_infra_overlay(); + m_speed.draw_overlay(); + m_joints.draw_overlay(); + m_srk.draw_overlay(); + m_km.draw_overlay(); + steps.step("overlays"); + } + else + { + draw_sweep_overlay(); + m_sweep.open = false; + bend_drag_update(); + draw_bend_overlay(); + } + m_gauge.update(); + m_gauge.render_windows(); + m_minimap.render_windows(); + + // roads: trajectories of the lanes, and the tools of the road window + update_road_tool(); + draw_road_overlay(); + // the roads and the terrain are fields of work, their tools are drawn in the tool options window in place of the edit mode ones + ui()->set_workspace(m_terrain_open ? editor_ui::workspace::terrain : m_roadtool.window ? editor_ui::workspace::roads : editor_ui::workspace::none); + + steps.step("roads"); + // --- array: the one made last is kept in line with its settings --- + update_array(); + + // --- area fill: outline overlay while the mode is active (its settings are drawn in the node bank window) --- + if (ui()->mode() == nodebank_panel::FILL) + draw_area_fill_outline(); + background->PopClipRect(); + draw_ortho_compass(); + + render_new_scenery_popup(); + render_open_scenery_popup(); + render_shortcuts_window(); + render_first_steps(); + render_nmt_prompt(); + render_nmt_banner(); + render_nmt_buried(); + render_empty_scenery_hint(); + render_outside_area_hint(); + render_switch_designer(); + render_environment_window(); + draw_selection_overlay(); + render_context_menu(); + steps.step("windows"); // --- ImGui: Editor Settings & History windows --- if(m_settings_open) @@ -721,371 +1734,1986 @@ bool editor_mode::update() void editor_mode::render_settings() { - ImGui::Begin("Editor Settings", &m_settings_open, ImGuiWindowFlags_AlwaysAutoResize); + ImGui::Begin((std::string(STR_C("Editor Settings")) + "###editorsettings").c_str(), &m_settings_open); - ImGui::TextUnformatted("Camera movement"); - - const char *schemes[] = {"WSAD (new)", "Arrows (legacy)"}; - int current = EditorSettings.movement() == editorSettings::movement_scheme::legacy ? 1 : 0; - if (ImGui::Combo("##movement_scheme", ¤t, schemes, IM_ARRAYSIZE(schemes))) + if (ImGui::BeginTabBar("##editorsettings")) { - EditorSettings.movement(current == 1 ? editorSettings::movement_scheme::legacy - : editorSettings::movement_scheme::wsad); - m_input.keyboard.apply_scheme(); - EditorSettings.save(); + if (ImGui::BeginTabItem(STR_C("General"))) + { + ImGui::TextUnformatted(STR_C("Camera movement")); + + const char *schemes[] = {STR_C("WSAD (new)"), STR_C("Arrows (legacy)")}; + int current = EditorSettings.movement() == editorSettings::movement_scheme::legacy ? 1 : 0; + if (ImGui::Combo("##movement_scheme", ¤t, schemes, IM_ARRAYSIZE(schemes))) + { + EditorSettings.movement(current == 1 ? editorSettings::movement_scheme::legacy + : editorSettings::movement_scheme::wsad); + m_input.keyboard.apply_scheme(); + EditorSettings.save(); + } + + ImGui::Separator(); + ImGui::Checkbox(STR_C("Transform gizmo (ImGuizmo)"), &m_gizmo_enabled); + + ImGui::Separator(); + ImGui::TextUnformatted(STR_C("Colours of the editor")); + const char *palettes[] = {STR_C("Green, as the rest of the simulator"), STR_C("Amber, of the editor")}; + int palette = std::clamp(EditorSettings.palette(), 0, 1); + if (ImGui::Combo("##palette", &palette, palettes, IM_ARRAYSIZE(palettes))) + { + EditorSettings.palette(palette); + EditorSettings.save(); + } + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); } - ImGui::Separator(); - ImGui::Checkbox("Transform gizmo (ImGuizmo)", &m_gizmo_enabled); - - render_terrain_ui(); - ImGui::End(); } +namespace +{ + // point spacings offered for the chunks, as the user reads them + char const *spacing_label(float const Spacing) + { + return Spacing < 0.75f ? "0.5 m" : Spacing < 1.5f ? "1 m" : Spacing < 3.f ? "2 m" : "5 m"; + } + + bool spacing_combo(char const *Label, float &Spacing) + { + bool changed = false; + ImGui::SetNextItemWidth(120.0f); + if (ImGui::BeginCombo(Label, spacing_label(Spacing))) + { + for (auto const spacing : heightmap::spacings) + if (ImGui::Selectable(spacing_label(spacing), spacing == Spacing)) + { + Spacing = spacing; + changed = true; + } + ImGui::EndCombo(); + } + return changed; + } + +} // namespace + void editor_mode::render_terrain_ui() { - ImGui::Separator(); - ImGui::TextUnformatted("Terrain"); - - ImGui::SetNextItemWidth(120.0f); - ImGui::InputInt("Grid cells", &m_terrain_cells); - m_terrain_cells = std::clamp(m_terrain_cells, 1, 512); - ImGui::SetNextItemWidth(120.0f); - ImGui::InputFloat("Cell size (m)", &m_terrain_cellsize); - if (m_terrain_cellsize < 0.1f) - m_terrain_cellsize = 0.1f; - ImGui::SetNextItemWidth(120.0f); - ImGui::InputFloat("Base height (m)", &m_terrain_baseheight); - ImGui::SetNextItemWidth(200.0f); - ImGui::InputText("Texture (optional)", m_terrain_texture, IM_ARRAYSIZE(m_terrain_texture)); - - if (ImGui::Button("Create flat terrain")) + if (false == m_streamer.active()) { - // centre the new patch horizontally on the camera, flat at the requested base height - glm::dvec3 const center(Camera.Pos.x, static_cast(m_terrain_baseheight), Camera.Pos.z); - auto terrain = std::make_unique(); - if (terrain->create(center, m_terrain_cells, m_terrain_cellsize, std::string(m_terrain_texture))) - { - if (m_terrain_auto_optimize) - terrain->optimize(m_terrain_simplify_error); - m_terrains.push_back(std::move(terrain)); - } - else - WriteLog("Editor: failed to create terrain", logtype::generic); + ImGui::TextUnformatted(STR_C("The scenery has no terrain yet")); + // the terrain model makes the terrain itself + if (ImGui::CollapsingHeader(STR_C("Terrain model (NMT)"), ImGuiTreeNodeFlags_DefaultOpen)) + render_nmt_ui(); + ImGui::Spacing(); + ImGui::TextDisabled("%s", STR_C("Or without the real ground:")); + if (ImGui::Button(STR_C("Make an empty, flat terrain"))) + ensure_terrain(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Kept in the folder terrain// and written there with the scenery (Ctrl+S)")); + return; } + // the real terrain first, open: the tracks put onto it from there + if (nmt_busy()) + ImGui::SetNextItemOpen(true); + if (ImGui::CollapsingHeader(STR_C("Terrain model (NMT)"), ImGuiTreeNodeFlags_DefaultOpen)) + render_nmt_ui(); - ImGui::SetNextItemWidth(120.0f); - ImGui::InputInt("Chunks / side", &m_terrain_chunks); - m_terrain_chunks = std::clamp(m_terrain_chunks, 1, 32); - ImGui::SameLine(); - if (ImGui::Button("Create chunked terrain")) - create_chunked_terrain(); - ImGui::TextDisabled("total %d x %d m, %d chunks", - static_cast(m_terrain_chunks * m_terrain_cells * m_terrain_cellsize), - static_cast(m_terrain_chunks * m_terrain_cells * m_terrain_cellsize), - m_terrain_chunks * m_terrain_chunks); - - if (ImGui::Checkbox("Chunk edit mode (LMB add neighbour / Shift = delete)", &m_chunk_edit)) - if (m_chunk_edit) - m_terrain_sculpt = false; // mutually exclusive with sculpting - ImGui::Text("Grid chunks: %zu", m_grid_chunks.size()); - - ImGui::Separator(); - ImGui::TextUnformatted("Streaming (open world, follows camera)"); - ImGui::SetNextItemWidth(120.0f); - ImGui::InputInt("Stream radius", &m_stream_radius); - m_stream_radius = std::clamp(m_stream_radius, 0, 16); - ImGui::Checkbox("Persist edits to disk (16-bit)", &m_stream_persist); - bool streaming = m_streamer.active(); - if (ImGui::Checkbox("Stream terrain", &streaming)) + // the tools are chosen in the toolbar, here are their settings + if (ImGui::CollapsingHeader(STR_C("Chunks"), m_terrain_tool == terrain_tool::chunks ? ImGuiTreeNodeFlags_DefaultOpen : 0)) { - if (streaming) - { - // per-scenery chunk folder so chunks from different sceneries don't collide - std::string scenery = Global.SceneryFile; - auto const slash = scenery.find_last_of("/\\"); - if (slash != std::string::npos) - scenery = scenery.substr(slash + 1); - auto const dot = scenery.find_last_of('.'); - if (dot != std::string::npos) - scenery = scenery.substr(0, dot); - if (scenery.empty()) - scenery = "default"; - m_streamer.directory("editor_terrain/" + scenery); - - m_streamer.configure(m_terrain_cells, m_terrain_cellsize, m_stream_radius, - m_terrain_baseheight, std::string(m_terrain_texture)); - m_streamer.simplify(m_terrain_auto_optimize, m_terrain_simplify_error); - m_streamer.persist(m_stream_persist); - - // hand the authored grid chunks over to streaming: persist them to disk, then drop the - // in-memory meshes so the streamer owns residency (it loads them back within the radius) - for (auto &entry : m_grid_chunks) - if (entry.second) - m_streamer.save_chunk(entry.first.first, entry.first.second, *entry.second); - for (auto &entry : m_grid_chunks) - if (entry.second) - entry.second->destroy(); - m_grid_chunks.clear(); - } - else - { - m_streamer.clear(); // saves modified chunks before dropping them - } - m_streamer.active(streaming); - } - if (m_streamer.active()) - { - // radius / simplify / persist are safe to tweak live; chunk size/base are fixed at toggle - m_streamer.radius(m_stream_radius); - m_streamer.simplify(m_terrain_auto_optimize, m_terrain_simplify_error); - m_streamer.persist(m_stream_persist); - ImGui::Text("Resident chunks: %zu (dir: %s)", m_streamer.resident(), m_streamer.directory().c_str()); - } - - ImGui::Text("Patches: %zu", m_terrains.size()); - - // capture: sample the selected model's geometry into an editable patch and remove the original - if (dynamic_cast(m_node) != nullptr) - { - if (ImGui::Button("Capture selected model as terrain")) - capture_terrain(); - } - else - { - ImGui::TextDisabled("Capture: select a model instance first"); - } - - std::vector const terrains = active_terrains(); - if (!terrains.empty()) - { - ImGui::Separator(); - if (ImGui::Checkbox("Sculpt mode (LMB raise / Shift = lower)", &m_terrain_sculpt)) - if (m_terrain_sculpt) - m_chunk_edit = false; // mutually exclusive with chunk editing + if (spacing_combo(STR_C("Point spacing"), m_terrain_spacing)) + m_streamer.default_spacing(m_terrain_spacing); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Spacing of the grid points of the chunks made.\n" + "A chunk is 250 x 250 m; finer grids take more memory and time to draw.")); ImGui::SetNextItemWidth(120.0f); - ImGui::InputFloat("Brush radius", &m_terrain_brush_radius); - if (m_terrain_brush_radius < 0.5f) - m_terrain_brush_radius = 0.5f; + ImGui::InputFloat(STR_C("Base height (m)"), &m_terrain_baseheight, 0.0f, 0.0f, "%.2f"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Height of the chunks made where there's no ground under them")); ImGui::SetNextItemWidth(120.0f); - ImGui::InputFloat("Brush strength", &m_terrain_brush_strength); - - // one-shot nudge of the most recent manual patch at its centre, handy for a quick test - if (!m_terrains.empty()) - { - auto &terrain = m_terrains.back(); - glm::dvec3 const c = terrain->centre(); - if (ImGui::Button("Raise centre")) - terrain->sculpt(c.x, c.z, m_terrain_brush_radius, m_terrain_brush_strength); - ImGui::SameLine(); - if (ImGui::Button("Lower centre")) - terrain->sculpt(c.x, c.z, m_terrain_brush_radius, -m_terrain_brush_strength); - } - - ImGui::Separator(); - ImGui::TextUnformatted("Optimize (mesh simplification, all patches)"); - ImGui::SetNextItemWidth(120.0f); - ImGui::InputFloat("Flatness tol (m)", &m_terrain_simplify_error); - if (m_terrain_simplify_error < 0.01f) - m_terrain_simplify_error = 0.01f; - ImGui::Checkbox("Auto-optimize after sculpt", &m_terrain_auto_optimize); - if (ImGui::Button("Optimize all")) - for (editor_terrain *t : terrains) - t->optimize(m_terrain_simplify_error); + ImGui::InputInt(STR_C("Chunks along a side"), &m_terrain_add_count); + m_terrain_add_count = std::clamp(m_terrain_add_count, 1, 8); ImGui::SameLine(); - if (ImGui::Button("Full-res all")) - for (editor_terrain *t : terrains) - t->unoptimize(); - - std::size_t tris = 0, full = 0; - for (editor_terrain *t : terrains) + if (ImGui::Button(STR_C("Add around the camera"))) + add_chunks_around(m_terrain_add_count); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Makes the chunks missing around the camera, shaped as the ground under them")); + render_ground_conversion(); + if (dynamic_cast(m_node) != nullptr) { - tris += t->triangles(); - full += t->full_triangles(); + if (ImGui::Button(STR_C("Capture the selected model as terrain"))) + capture_terrain(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The chunks under the model take its shape, and the model is removed")); } - ImGui::Text("Triangles: %zu / %zu", tris, full); + } + + if (ImGui::CollapsingHeader(STR_C("Chunk resolution"), m_terrain_tool == terrain_tool::spacing ? ImGuiTreeNodeFlags_DefaultOpen : 0)) + { + // chunks removed since are no longer selected + for (auto it = m_terrain_selection.begin(); it != m_terrain_selection.end();) + it = m_streamer.exists(*it) ? std::next(it) : m_terrain_selection.erase(it); + if (m_terrain_selection.empty()) + ImGui::TextWrapped("%s", STR_C("No chunk selected. With the Point spacing tool LMB selects the clicked chunk, Ctrl+LMB adds one or takes it away.")); + else + { + bool coarser = false; + std::size_t points = 0, after = 0; + int const cells = heightmap::cells_for(m_terrain_convert_spacing); + ImGui::BeginChild("##chunkselection", ImVec2(0.0f, ImGui::GetTextLineHeightWithSpacing() * std::min(6.0f, static_cast(m_terrain_selection.size()) + 0.5f)), true); + for (auto const &key : m_terrain_selection) + { + auto const centre = heightmap::chunk_corner(key) + glm::dvec2{heightmap::chunk_size * 0.5}; + auto const *chunk = m_streamer.terrain_at(centre.x, centre.y); + if (chunk == nullptr) + { + ImGui::TextDisabled(STR_C("%d,%d: not loaded"), key.first, key.second); + continue; + } + auto const &data = chunk->data(); + coarser |= cells < data.cells; + points += static_cast(data.side()) * data.side(); + after += static_cast(cells + 1) * (cells + 1); + auto const paint = data.paint > 0 ? format(STR_C(", paint every %.2f m"), heightmap::chunk_size / data.paint) : std::string(STR_C(", one material")); + auto const touchups = data.adjust.empty() ? std::string() : std::string(STR_C(", touch-ups")); + ImGui::Text("%d,%d: %s%s%s", key.first, key.second, spacing_label(static_cast(data.spacing())), paint.c_str(), touchups.c_str()); + } + ImGui::EndChild(); + spacing_combo(STR_C("Convert to"), m_terrain_convert_spacing); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Convert"))) + convert_selected_chunks(); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Clear the selection"))) + m_terrain_selection.clear(); + if (ImGui::Button(STR_C("Remove the selected (Del)"))) + remove_selected_chunks(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Takes the selected chunks out of the terrain of the scenery, and out of its files on save; Ctrl+Z brings them back")); + ImGui::Checkbox(STR_C("Paint every 0.5 m with 0.5 m spacing"), &m_terrain_convert_paint); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Chunks converted to 0.5 m get their paint samples every 0.5 m as well (every metre otherwise),\n" + "so the materials can be painted as finely as the ground is shaped")); + if (points > 0) + ImGui::TextDisabled(STR_C("Grid points: %zu -> %zu"), points, after); + if (coarser) + ImGui::TextWrapped("%s", STR_C("A coarser grid can't hold the shapes smaller than its spacing: they're averaged out. " + "The edges of the chunks keep their heights, so the neighbours still meet them. Ctrl+Z takes it back.")); + } + } + + if (terrain_brush() && ImGui::CollapsingHeader(STR_C("Brush"), ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Radius (m)"), &m_terrain_brush_radius, 0.25f, 0.5f, 500.0f, "%.1f"); + m_terrain_brush_radius = std::max(0.5f, m_terrain_brush_radius); + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Strength"), &m_terrain_brush_strength, 0.05f, 0.05f, 50.0f, "%.2f"); + m_terrain_brush_strength = std::max(0.05f, m_terrain_brush_strength); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Sculpting: metres per second at the middle of the brush; smoothing, levelling, painting and restoring: how fast they work")); + if (m_terrain_tool == terrain_tool::sculpt || m_terrain_tool == terrain_tool::smooth || m_terrain_tool == terrain_tool::level) + { + auto touchup = m_streamer.touch_up(); + if (ImGui::Checkbox(STR_C("Touch up over the tracks"), &touchup)) + m_streamer.touch_up(touchup); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("On: the brush shapes the terrain as it's seen, also where the tracks (modifiers) shape it;\n" + "the changes there are kept as touch-ups over the modifiers, and stay when the track changes.\n" + "The Restore tool takes them back.\n" + "Off: the brush shapes only the ground under the modifiers, the tracks keep their formation and slopes.")); + } + if (m_terrain_tool == terrain_tool::level) + { + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Target height (m)"), &m_terrain_target, 0.05f, -1000.0f, 5000.0f, "%.2f"); + ImGui::SameLine(); + if (ImGui::Button(m_terrain_picking ? STR_C("Click in the view...") : STR_C("Pick"))) + m_terrain_picking = false == m_terrain_picking; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The next click takes the height of whatever is under the cursor: terrain, a track, a model.\nCtrl+LMB does the same at any time")); + char const *modes[]{STR_C("Raise and lower"), STR_C("Only raise"), STR_C("Only lower")}; + ImGui::SetNextItemWidth(160.0f); + ImGui::Combo("##levelmode", &m_terrain_level_mode, modes, IM_ARRAYSIZE(modes)); + ImGui::Checkbox(STR_C("Target where the stroke starts"), &m_terrain_target_from_stroke); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Each stroke takes the height of the terrain under the cursor where it starts as its target,\nand drags it along: the ground stroked over is levelled with that point")); + } + } + + if (ImGui::CollapsingHeader(STR_C("Materials"), m_terrain_tool == terrain_tool::paint ? ImGuiTreeNodeFlags_DefaultOpen : 0)) + { + auto const &layers{m_streamer.manifest().layers}; + m_terrain_layer = std::clamp(m_terrain_layer, 0, static_cast(layers.size()) - 1); + for (std::size_t i = 0; i < layers.size(); ++i) + { + auto label{layers[i].size > 0.f ? format("%zu: %s (%.1f m)", i, layers[i].material.c_str(), layers[i].size) : format("%zu: %s", i, layers[i].material.c_str())}; + if (layers[i].rotation != 0.f) + label += format(STR_C(", turned %.0f°"), layers[i].rotation); + if (ImGui::Selectable(label.c_str(), static_cast(i) == m_terrain_layer)) + m_terrain_layer = static_cast(i); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("New chunks are covered with the first material. A texture dragged from the browser onto an entry of the palette takes its place")); + // a material dropped on an entry takes its place, on every chunk painted with it + std::string dropped; + if (material_drop(dropped)) + m_streamer.layer_material(static_cast(i), dropped); + } + if (false == layers.empty()) + { + // the values are kept while dragged and given to the palette once the dragging ends; + // read back from the palette every frame, the release would hand it the old value + if (false == m_terrain_layer_size_dragged) + m_terrain_layer_size = layers[m_terrain_layer].size; + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Repeats every (m)"), &m_terrain_layer_size, 0.1f, 0.0f, 200.0f, "%.1f"); + m_terrain_layer_size_dragged = ImGui::IsItemActive(); + if (ImGui::IsItemDeactivatedAfterEdit()) + m_streamer.layer_size(static_cast(m_terrain_layer), m_terrain_layer_size); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Metres the textures of the chosen material repeat at; 0: as the material gives it, or 8 m")); + if (false == m_terrain_layer_rotation_dragged) + m_terrain_layer_rotation = layers[m_terrain_layer].rotation; + ImGui::SetNextItemWidth(120.0f); + ImGui::SliderFloat(STR_C("Turned by (deg)"), &m_terrain_layer_rotation, -180.0f, 180.0f, "%.0f"); + m_terrain_layer_rotation_dragged = ImGui::IsItemActive(); + if (ImGui::IsItemDeactivatedAfterEdit()) + m_streamer.layer_rotation(static_cast(m_terrain_layer), m_terrain_layer_rotation); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Angle the textures of the chosen material are turned by, on every chunk painted with it.\n" + "Ctrl+click to type it. To have the material turned in one place only, fill it there with an angle of its own.")); + } + texture_field(STR_C("Material"), 160.0f, m_terrain_material, IM_ARRAYSIZE(m_terrain_material), terrain_texture_offer(nullptr)); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Add to the palette")) && m_terrain_material[0] != '\0') + m_terrain_layer = m_streamer.layer(m_terrain_material, m_terrain_material_size); + ImGui::TextDisabled("%s", STR_C("A chunk holds up to 8 materials")); + } + + if (ImGui::CollapsingHeader(STR_C("Fill"), m_terrain_tool == terrain_tool::fill ? ImGuiTreeNodeFlags_DefaultOpen : 0)) + { + auto const &layers{m_streamer.manifest().layers}; + if (false == layers.empty()) + { + auto const &chosen{layers[std::clamp(m_terrain_layer, 0, static_cast(layers.size()) - 1)]}; + ImGui::Text(STR_C("Material: %s (chosen in the palette above)"), chosen.material.c_str()); + } + ImGui::Text(STR_C("Outline: %zu points"), m_paint_outline.size()); + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Edge blur (m)"), &m_paint_feather, 0.1f, 0.0f, 100.0f, m_paint_feather > 0.0f ? "%.1f" : STR_C("sharp")); + m_paint_feather = std::max(0.0f, m_paint_feather); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Metres across the outline the material blends in over, half of them inside the area.\n" + "0: a sharp edge, as sharp as the paint samples go: every metre, or every 0.5 m in chunks converted to 0.5 m with fine paint")); + ImGui::SetNextItemWidth(120.0f); + ImGui::SliderFloat(STR_C("Texture turned by (deg)"), &m_paint_rotation, -180.0f, 180.0f, "%.0f"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The area gets the material turned by this angle: an entry of the palette with the material at that angle\n" + "is used, or added. Ctrl+click to type it")); + ImGui::BeginDisabled(m_paint_outline.size() < 3 || layers.empty()); + if (ImGui::Button(STR_C("Fill the area"))) + fill_terrain_area(); + ImGui::EndDisabled(); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Clear the outline##fill"))) + m_paint_outline.clear(); + } + + if (ImGui::CollapsingHeader(STR_C("Water"), m_terrain_tool == terrain_tool::water ? ImGuiTreeNodeFlags_DefaultOpen : 0)) + { + if (m_terrain_tool == terrain_tool::water) + { + ImGui::Text(STR_C("Outline: %zu points"), m_water_points.size()); + ImGui::SetNextItemWidth(120.0f); + if (ImGui::DragFloat(STR_C("Level (m)"), &m_water_level, 0.01f, -1000.0f, 5000.0f, "%.2f")) + m_water_level_edited = true; + texture_field(STR_C("Material##water"), 160.0f, m_water_material, IM_ARRAYSIZE(m_water_material), terrain_texture_offer(STR_C("The default water material"))); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("The default one: %s, the water material of the terrain"), m_streamer.manifest().water_material.c_str()); + ImGui::BeginDisabled(m_water_points.size() < 3); + if (ImGui::Button(STR_C("Make the water"))) + { + auto water{m_streamer.water()}; + heightmap::water_body body; + body.name = format("water %zu", water.size() + 1); + body.level = m_water_level; + body.material = m_water_material; + for (auto const &point : m_water_points) + body.outline.emplace_back(point.x, point.z); + water.push_back(std::move(body)); + m_streamer.water(std::move(water)); + m_water_selected = static_cast(m_streamer.water().size()) - 1; + m_water_points.clear(); + m_water_level_edited = false; + } + ImGui::EndDisabled(); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Clear the outline"))) + { + m_water_points.clear(); + m_water_level_edited = false; + } + } + auto const &water{m_streamer.water()}; + std::optional removed; + std::optional> dropped; + for (std::size_t i = 0; i < water.size(); ++i) + { + ImGui::PushID(static_cast(i)); + auto const material = water[i].material.empty() ? std::string(STR_C("default material")) : water[i].material; + if (ImGui::Selectable(format(STR_C("%s, %.2f m, %zu points, %s"), water[i].name.c_str(), water[i].level, water[i].outline.size(), material.c_str()).c_str(), static_cast(i) == m_water_selected)) + m_water_selected = static_cast(i); + // a texture dropped on an entry becomes the material of that water + std::string name; + if (material_drop(name)) + dropped = std::make_pair(i, name); + ImGui::PopID(); + } + if (dropped) + { + auto changed{water}; + changed[dropped->first].material = dropped->second; + m_streamer.water(std::move(changed)); + m_water_selected = static_cast(dropped->first); + m_water_material_of = -1; + } + if (m_water_selected >= 0 && m_water_selected < static_cast(water.size())) + { + // the level is changed in the water once the dragging ends + if (false == m_water_level_dragged) + m_water_selected_level = static_cast(water[m_water_selected].level); + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Level of the chosen (m)"), &m_water_selected_level, 0.01f, -1000.0f, 5000.0f, "%.2f"); + m_water_level_dragged = ImGui::IsItemActive(); + if (ImGui::IsItemDeactivatedAfterEdit()) + { + auto changed{water}; + changed[m_water_selected].level = m_water_selected_level; + m_streamer.water(std::move(changed)); + } + // the material and the repeat of its texture, changed once the field is left (or a texture dropped on it) + if (m_water_material_of != m_water_selected) + { + std::snprintf(m_water_selected_material, sizeof(m_water_selected_material), "%s", water[m_water_selected].material.c_str()); + m_water_selected_size = water[m_water_selected].size; + m_water_material_of = m_water_selected; + } + bool retexture = false; + retexture |= texture_field(STR_C("Material of the chosen"), 160.0f, m_water_selected_material, IM_ARRAYSIZE(m_water_selected_material), terrain_texture_offer(STR_C("The default water material"))); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Chosen from the textures, or dragged from the texture browser.\nThe default one: %s, the water material of the terrain"), m_streamer.manifest().water_material.c_str()); + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Texture repeats every (m)##water"), &m_water_selected_size, 0.1f, 0.0f, 500.0f, "%.1f"); + m_water_selected_size = std::max(0.0f, m_water_selected_size); + retexture |= ImGui::IsItemDeactivatedAfterEdit(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Metres the texture of the water repeats at; 0: as the material gives it, or 8 m")); + if (retexture) + { + auto changed{water}; + changed[m_water_selected].material = m_water_selected_material; + changed[m_water_selected].size = m_water_selected_size; + m_streamer.water(std::move(changed)); + } + if (ImGui::Button(STR_C("Remove the chosen water"))) + removed = static_cast(m_water_selected); + } + if (removed) + { + auto changed{water}; + changed.erase(changed.begin() + *removed); + m_streamer.water(std::move(changed)); + m_water_selected = -1; + m_water_material_of = -1; + } + // the material of the bodies of water which don't name their own + auto defaultmaterial{m_streamer.manifest().water_material}; + auto const redefault{texture_field(STR_C("Default water material"), 160.0f, defaultmaterial, terrain_texture_offer(nullptr))}; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Material of the bodies of water which don't name their own")); + if (redefault) + m_streamer.water_material(defaultmaterial); + } + + if (ImGui::CollapsingHeader(STR_C("Modifiers"))) + { + auto const &modifiers{m_streamer.modifiers()}; + if (modifiers.empty()) + ImGui::TextWrapped("%s", STR_C("None. The vertical profile of the tracks makes them: the terrain follows the formation and the slopes of the route.")); + std::optional removed, baked; + for (auto const &modifier : modifiers) + { + ImGui::PushID(modifier.name.c_str()); + ImGui::TextUnformatted(format(STR_C("%s, %zu points"), modifier.name.c_str(), modifier.points.size()).c_str()); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Bake"))) + baked = modifier.name; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The ground keeps the shape the modifier gives it, and the modifier is removed:\n" + "from then on the terrain there is shaped by hand like anywhere else, and no longer follows the track")); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Remove"))) + removed = modifier.name; + ImGui::PopID(); + } + if (auto const touchups = m_streamer.touched_up(); touchups > 0) + ImGui::TextDisabled(STR_C("Touch-ups over the modifiers: %zu points (of the chunks in memory)"), touchups); + if (baked) + { + m_streamer.bake_modifier(*baked); + ground_tiles.clear(); + forget_ground_shapes(); + } + if (removed) + { + m_streamer.remove_modifier(*removed); + ground_tiles.clear(); + forget_ground_shapes(); + } + } + + auto const files{format(STR_C("Folder: %s"), m_streamer.directory().c_str()) + "\n" + format(STR_C("Chunks in memory: %zu%s"), m_streamer.resident(), m_streamer.modified() ? STR_C(", changes not saved yet") : "")}; + auto const drawing{ImGui::CollapsingHeader(STR_C("Drawing and files"))}; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", files.c_str()); + if (drawing) + { + ImGui::TextDisabled("%s", files.c_str()); + auto detail{m_streamer.detail()}; + ImGui::SetNextItemWidth(160.0f); + if (ImGui::SliderFloat(STR_C("Detail"), &detail, 30.0f, 400.0f, "%.0f")) + m_streamer.detail(detail); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How far the full grid of the chunks reaches: metres of distance per metre of the drawn grid. Further away the grid is coarser")); + bool compress{m_streamer.manifest().compress}; + if (ImGui::Checkbox(STR_C("Compress the files (zstd)"), &compress)) + m_streamer.compress(compress); + ImGui::TextDisabled("%s", STR_C("The terrain is written with the scenery (Ctrl+S).")); + } + if (false == m_terrain_status.empty()) + ImGui::TextWrapped("%s", m_terrain_status.c_str()); +} + +void editor_mode::draw_terrain_overlay() +{ + if (false == m_streamer.active()) + return; + screen_projection const projection; + auto *drawlist = ImGui::GetBackgroundDrawList(); + // the cursor where a click would put the point: the ground along the ray through the cursor in this frame + glm::dvec3 cursor{Camera.Pos}; + bool const hovering = false == ImGui::GetIO().WantCaptureMouse && cursor_on_ground(cursor); + auto const ground = [&](double const X, double const Z, double const Fallback) { + double height; + return m_streamer.height_at(X, Z, height) ? height : Fallback; + }; + auto const polyline = [&](std::vector const &Points, ImU32 const Color, bool const Closed, float const Thickness) { + auto const count = Points.size(); + for (std::size_t i = 0; i + (Closed ? 0 : 1) < count; ++i) + { + ImVec2 from, to; + if (projection.project(Points[i], from) && projection.project(Points[(i + 1) % count], to)) + drawlist->AddLine(from, to, Color, Thickness); + } + }; + + // the brush aimed at the ground itself along the ray through the cursor + glm::dvec3 brushcentre = cursor; + bool const onground = false == ImGui::GetIO().WantCaptureMouse && terrain_cursor(brushcentre); + if (terrain_brush() && onground) + { + auto const cursor = brushcentre; + std::vector circle; + for (int i = 0; i < 64; ++i) + { + auto const angle = i * 6.283185307179586 / 64.0; + auto const x = cursor.x + std::cos(angle) * m_terrain_brush_radius; + auto const z = cursor.z + std::sin(angle) * m_terrain_brush_radius; + circle.emplace_back(x, ground(x, z, cursor.y) + 0.1, z); + } + auto const color = m_terrain_tool == terrain_tool::paint ? IM_COL32(120, 230, 120, 220) + : m_terrain_tool == terrain_tool::smooth ? IM_COL32(120, 200, 255, 220) + : m_terrain_tool == terrain_tool::restore ? IM_COL32(230, 120, 230, 220) + : IM_COL32(255, 180, 80, 220); + polyline(circle, color, true, 2.0f); + if (m_terrain_tool == terrain_tool::level) + { + // the target: the rim of the brush at its height, joined with the ground, and the height by the cursor + auto const target = static_cast(m_terrain_target); + std::vector level; + for (auto const &point : circle) + level.emplace_back(point.x, target, point.z); + ImU32 const levelcolor = IM_COL32(255, 230, 90, 230); + polyline(level, levelcolor, true, 1.5f); + for (std::size_t i = 0; i < circle.size(); i += circle.size() / 8) + { + ImVec2 from, to; + if (projection.project(circle[i], from) && projection.project(level[i], to)) + drawlist->AddLine(from, to, IM_COL32(255, 230, 90, 120), 1.0f); + } + ImVec2 label; + if (projection.project(glm::dvec3{cursor.x, target, cursor.z}, label)) + { + double ground{cursor.y}; + m_streamer.height_at(cursor.x, cursor.z, ground); + auto const text = format("%.2f m (%+.2f)", target, target - ground); + drawlist->AddText(ImVec2(label.x + 12.0f, label.y - 8.0f), levelcolor, text.c_str()); + } + } + } + // outline of a chunk, laid over the ground + auto const chunk_outline = [&](heightmap::chunk_key const &Key, double const Fallback, ImU32 const Color, float const Thickness) { + auto const low = heightmap::chunk_corner(Key); + std::vector square; + auto const edge = [&](glm::dvec2 const &From, glm::dvec2 const &To) { + for (int i = 0; i < 25; ++i) + { + auto const point = From + (To - From) * (i / 25.0); + square.emplace_back(point.x, ground(point.x, point.y, Fallback) + 0.2, point.y); + } + }; + auto const size = heightmap::chunk_size; + edge(low, low + glm::dvec2{size, 0.0}); + edge(low + glm::dvec2{size, 0.0}, low + glm::dvec2{size}); + edge(low + glm::dvec2{size}, low + glm::dvec2{0.0, size}); + edge(low + glm::dvec2{0.0, size}, low); + polyline(square, Color, true, Thickness); + }; + if (m_terrain_tool == terrain_tool::spacing) + for (auto const &key : m_terrain_selection) + chunk_outline(key, cursor.y, IM_COL32(90, 220, 255, 230), 3.0f); + if ((m_terrain_tool == terrain_tool::chunks || m_terrain_tool == terrain_tool::spacing) && hovering) + { + auto const key = heightmap::chunk_at(cursor.x, cursor.z); + auto const exists = m_streamer.exists(key); + chunk_outline(key, cursor.y, exists ? IM_COL32(255, 255, 255, 200) : IM_COL32(255, 230, 90, 200), 2.0f); + ImVec2 label; + if (exists && projection.project(cursor, label)) + { + auto const *chunk = m_streamer.terrain_at(cursor.x, cursor.z); + if (chunk != nullptr) + { + auto const &data = chunk->data(); + auto text = std::string(spacing_label(static_cast(data.spacing()))); + if (m_terrain_tool == terrain_tool::spacing) + { + if (data.paint > 0) + text += format(STR_C(", paint every %.2f m"), heightmap::chunk_size / data.paint); + if (m_terrain_selection.count(key) != 0) + text += STR(" (selected)"); + } + drawlist->AddText(ImVec2(label.x + 14.0f, label.y - 14.0f), IM_COL32(255, 255, 255, 230), text.c_str()); + } + } + } + // the bodies of water, and the one being outlined + auto const &water = m_streamer.water(); + for (std::size_t i = 0; i < water.size(); ++i) + { + std::vector outline; + for (auto const &point : water[i].outline) + outline.emplace_back(point.x, water[i].level, point.y); + polyline(outline, static_cast(i) == m_water_selected ? IM_COL32(120, 200, 255, 255) : IM_COL32(60, 120, 220, 160), true, static_cast(i) == m_water_selected ? 2.5f : 1.5f); + } + if (m_terrain_tool == terrain_tool::fill && false == m_paint_outline.empty()) + { + // laid over the ground, the edges followed every few metres + std::vector outline; + auto const closed = m_paint_outline.size() >= 3; + for (std::size_t i = 0; i + (closed ? 0 : 1) < m_paint_outline.size(); ++i) + { + auto const &from = m_paint_outline[i]; + auto const &to = m_paint_outline[(i + 1) % m_paint_outline.size()]; + auto const steps = std::clamp(static_cast(glm::distance(glm::dvec2{from.x, from.z}, glm::dvec2{to.x, to.z}) / 4.0), 1, 200); + for (int k = 0; k < steps; ++k) + { + auto const point = from + (to - from) * (static_cast(k) / steps); + outline.emplace_back(point.x, ground(point.x, point.z, point.y) + 0.15, point.z); + } + } + if (false == closed) + outline.push_back(m_paint_outline.back() + glm::dvec3{0.0, 0.15, 0.0}); + polyline(outline, IM_COL32(250, 200, 90, 255), false, 2.0f); + for (auto const &point : m_paint_outline) + { + ImVec2 dot; + if (projection.project(point + glm::dvec3{0.0, 0.15, 0.0}, dot)) + drawlist->AddCircleFilled(dot, 4.0f, IM_COL32(250, 200, 90, 255)); + } + } + if (m_terrain_tool == terrain_tool::water && false == m_water_points.empty()) + { + std::vector outline; + for (auto const &point : m_water_points) + outline.emplace_back(point.x, m_water_level, point.z); + polyline(outline, IM_COL32(120, 220, 255, 255), m_water_points.size() >= 3, 2.0f); + for (auto const &point : outline) + { + ImVec2 dot; + if (projection.project(point, dot)) + drawlist->AddCircleFilled(dot, 4.0f, IM_COL32(120, 220, 255, 255)); + } + } +} + +void editor_mode::load_orthophoto_settings() +{ + std::string const scenery = scenery_stem(); + if (scenery == m_orthophoto_scenery) + return; + m_orthophoto_scenery = scenery; + // a scenery of its own: nobody chose for it yet, unless the user or the scenery keeps the orthophoto on or off + m_orthophoto_chosen = false; + // the height of the terrain model against the tracks of the scenery, as it was fitted or typed in last + m_nmt_state.offset = 0.0; + m_nmt_state.fitted = false; + std::as_const(EditorSettings).terrain_model_offset(scenery, m_nmt_state.offset, m_nmt_state.fitted); + + auto const &stored = EditorSettings.orthophoto(); + editor_orthophoto::config config = m_orthophoto.settings(); + config.radius = stored.radius; + config.height = stored.height; + config.opacity = stored.opacity; + config.year = stored.year; + config.hires = stored.hires; + config.drape = stored.drape; + config.lift = stored.lift; + config.in_scene = stored.in_scene; + config.north = 0.0; + config.east = 0.0; + m_georeference_read = false; + read_georeference(); + if (false == std::as_const(EditorSettings).orthophoto_origin(scenery, config.north, config.east) && m_georeference) + { + config.north = m_georeference_origin.x; + config.east = m_georeference_origin.y; + } + auto enabled{m_orthophoto.enabled()}; + m_orthophoto_mark.clear(); + if (auto const marked{scene::Layers.empty() ? std::vector{} : scene::Layers.marked(scene::layer_handle{1}, "//$o")}; false == marked.empty() && editor_orthophoto::read_mark(marked.front(), config, enabled)) + { + m_orthophoto_mark = marked.front(); + m_orthophoto.enabled(enabled); + m_orthophoto_chosen = true; + WriteLog(format("Editor: the map settings of the scenery, orthophoto %s", enabled ? "on" : "off")); + } + // the user's choice stands over the scenery's; turned on only where the scenery lies on the map, a fictional one has nothing to + // show, and there it's left to the terrain model once the scenery is placed + if (auto const on{stored.on}; on.has_value() && (false == *on || config.north != 0.0 || config.east != 0.0)) + { + m_orthophoto.enabled(*on); + m_orthophoto_chosen = true; + WriteLog(format("Editor: the orthophoto %s, as the user left it", *on ? "on" : "off")); + } + m_orthophoto.settings(config); + m_orthophoto_origin_edit = {config.north, config.east}; + // the area the imagery and the terrain model are downloaded in, none in a scenery which has none + m_orthophoto_area_mark = scene::Layers.empty() ? std::vector{} : scene::Layers.marked(scene::layer_handle{1}, "//$z"); + m_orthophoto.area(editor_orthophoto::read_area(m_orthophoto_area_mark)); + if (false == m_orthophoto.area().empty()) + WriteLog(format("Editor: the download area of the scenery, %zu points, %d tiles of the orthophoto", m_orthophoto.area().size(), m_orthophoto.stats().area_tiles)); +} + +void editor_mode::save_orthophoto_settings() +{ + editor_orthophoto::config const &config = m_orthophoto.settings(); + auto &stored = EditorSettings.orthophoto(); + stored.radius = config.radius; + stored.height = config.height; + stored.opacity = config.opacity; + stored.year = config.year; + stored.hires = config.hires; + stored.drape = config.drape; + stored.lift = config.lift; + stored.in_scene = config.in_scene; + if (config.north != 0.0 || config.east != 0.0) + EditorSettings.orthophoto_origin(m_orthophoto_scenery, config.north, config.east); + EditorSettings.save(); +} + +void editor_mode::choose_orthophoto(bool const On) +{ + m_orthophoto.enabled(On); + m_orthophoto_chosen = true; + EditorSettings.orthophoto().on = On; + EditorSettings.save(); +} + +void editor_mode::keep_nmt_settings() +{ + // not while a number is being typed in, which changes it at every key + if (ImGui::IsAnyItemActive()) + return; + auto const &state{m_nmt_state}; + auto &stored{EditorSettings.terrain_model()}; + auto changed{stored.band != state.band || stored.around != m_terrain_add_count || stored.shape != state.shape || stored.follow != state.follow}; + stored.band = state.band; + stored.around = m_terrain_add_count; + stored.shape = state.shape; + stored.follow = state.follow; + // the offset of the model is the scenery's, fitted to its tracks or typed in + if (false == m_orthophoto_scenery.empty()) + { + double offset{0.0}; + bool fitted{false}; + std::as_const(EditorSettings).terrain_model_offset(m_orthophoto_scenery, offset, fitted); + if (offset != state.offset || fitted != state.fitted) + { + EditorSettings.terrain_model_offset(m_orthophoto_scenery, state.offset, state.fitted); + changed = true; + } + } + if (changed) + EditorSettings.save(); +} + +void editor_mode::render_orthophoto_ui() +{ + load_orthophoto_settings(); + + editor_orthophoto::config config = m_orthophoto.settings(); + bool changed = false; // apply to the layer + bool persist = false; // and store in the editor settings + + ImGui::TextUnformatted(STR_C("Scenery origin (0,0,0) in PUWG 1992 / EPSG:2180")); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("PUWG 1992 (EPSG:2180): the coordinate system of the maps of Poland, in metres; the numbers as on geoportal.gov.pl")); + // geodetic convention, as displayed by geoportal.gov.pl: X grows north, Y grows east. + // applied once editing ends, so half-typed numbers don't trigger downloads + ImGui::SetNextItemWidth(160.0f); + ImGui::InputDouble(STR_C("X (northing, m)"), &m_orthophoto_origin_edit.x, 0.0, 0.0, "%.2f"); + bool const northedited = ImGui::IsItemDeactivatedAfterEdit(); + ImGui::SetNextItemWidth(160.0f); + ImGui::InputDouble(STR_C("Y (easting, m)"), &m_orthophoto_origin_edit.y, 0.0, 0.0, "%.2f"); + bool const eastedited = ImGui::IsItemDeactivatedAfterEdit(); + if (northedited || eastedited) + { + config.north = m_orthophoto_origin_edit.x; + config.east = m_orthophoto_origin_edit.y; + changed = true; + persist = true; + } + if (m_georeference) + { + ImGui::TextDisabled("%s", m_georeference_line.c_str()); + ImGui::TextDisabled(STR_C("in the scenery file: Y (easting) %.0f m, X (northing) %.0f m"), m_georeference_origin.y, m_georeference_origin.x); + if (config.north != m_georeference_origin.x || config.east != m_georeference_origin.y) + { + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Use it"))) + { + m_orthophoto_origin_edit.x = m_georeference_origin.x; + config.north = m_orthophoto_origin_edit.x; + m_orthophoto_origin_edit.y = m_georeference_origin.y; + config.east = m_orthophoto_origin_edit.y; + changed = true; + persist = true; + } + } + } + if (config.north == 0.0 && config.east == 0.0) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.2f, 1.0f), STR_C("Enter the origin of this scenery first")); + else + ImGui::TextDisabled(STR_C("Camera at X %.1f Y %.1f"), config.north + Camera.Pos.z, config.east - Camera.Pos.x); + + ImGui::Separator(); + ImGui::SetNextItemWidth(160.0f); + changed |= ImGui::SliderInt(STR_C("Distance (tiles)"), &config.radius, 0, editor_orthophoto::max_radius); + persist |= ImGui::IsItemDeactivatedAfterEdit(); + ImGui::SameLine(); + int const span = static_cast((2 * config.radius + 1) * editor_orthophoto::tile_size); + ImGui::TextDisabled("%d x %d m", span, span); + + // ImGui 1.73 has no public disabled state yet, the internal item flag does the job + auto const begin_disabled = [](bool Disabled) { + if (!Disabled) + return; + ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); + }; + auto const end_disabled = [](bool Disabled) { + if (!Disabled) + return; + ImGui::PopStyleVar(); + ImGui::PopItemFlag(); + }; + + auto const stats = m_orthophoto.stats(); + if (stats.failed > 0 || stats.area_failed > 0) + { + ImGui::Text(STR_C("Tiles: %d shown, %d loading, %d failed"), stats.resident, stats.loading, stats.failed); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Retry"))) + m_orthophoto.retry_failed(); + } + + ImGui::Separator(); + render_download_area_ui(stats); + ImGui::Separator(); + + if (ImGui::TreeNode(STR_C("More settings"))) + { + // one choice of three, what it means under it: drawn over the view (laid on the ground, where there's none at the height), a + // surface of the scene on the ground, or a flat sheet in the scene; flat over the view says nothing more than on the ground + enum class look + { + overlay, + ground, + sheet + }; + auto const current{false == config.in_scene ? look::overlay : config.drape ? look::ground : look::sheet}; + auto const choice = [&](char const *Label, look const Look) { + // the Better Renderer doesn't pick up geometry added in the editor: in the scene the photos wouldn't show at all + auto const disabled{Global.NvRenderer && Look != look::overlay && current != Look}; + begin_disabled(disabled); + if (ImGui::RadioButton(Label, current == Look) && current != Look) + { + config.in_scene = Look != look::overlay; + config.drape = Look != look::sheet; + changed = true; + persist = true; + } + end_disabled(disabled); + }; + auto const explain = [](char const *Text) { + ImGui::Indent(); + ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + 360.0f); + ImGui::TextDisabled("%s", Text); + ImGui::PopTextWrapPos(); + ImGui::Unindent(); + }; + + ImGui::TextUnformatted(STR_C("Show the photos")); + choice(STR_C("Over the view"), look::overlay); + choice(STR_C("On the terrain, in the scene"), look::ground); + choice(STR_C("A flat sheet in the scene"), look::sheet); + switch (current) + { + case look::overlay: + explain(STR_C("The photos are drawn over the whole view, over the tracks and models as well: lower the opacity to see " + "what's under them. The quickest way to compare the scenery with the map.")); + break; + case look::ground: + explain(STR_C("The photos lie on the terrain as its surface: tracks and models standing on them cover them, the scene lights " + "them, and fully opaque the mouse places objects on them as on the ground.")); + break; + case look::sheet: + explain(STR_C("One flat sheet at the height below, in the scene: for a scenery with no terrain yet. Where there is " + "terrain, it cuts through the sheet.")); + break; + } + if (Global.NvRenderer && current != look::overlay) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.2f, 1.0f), "%s", STR_C("The Better Renderer doesn't show them in the scene: pick \"Over the view\"")); + + if (config.drape) + { + if (ImGui::Button(STR_C("Refit"))) + { + // the ground was edited: what's kept of it has to go as well + ground_tiles.clear(); + forget_ground_shapes(); + m_orthophoto.refit(); + for (auto &layer : m_wms) + layer->refit(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Samples the ground again, after it was edited")); + // the lift only matters where the scene can cover the photos + if (config.in_scene) + { + ImGui::SetNextItemWidth(160.0f); + changed |= ImGui::DragFloat(STR_C("Lift above ground (m)"), &config.lift, 0.01f, 0.0f, 50.0f, "%.2f"); + persist |= ImGui::IsItemDeactivatedAfterEdit(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Raises the photos above the ground.\n" + "Whatever is lower than this, the rails and the sleepers too, ends up under them: keep it small.")); + } + } + ImGui::SetNextItemWidth(160.0f); + changed |= ImGui::DragFloat(config.drape ? STR_C("Height where there's no ground (m)") : STR_C("Height (m)"), &config.height, 0.1f, -1000.0f, 3000.0f, "%.2f"); + persist |= ImGui::IsItemDeactivatedAfterEdit(); + ImGui::Spacing(); + + ImGui::SetNextItemWidth(160.0f); + changed |= ImGui::SliderFloat(STR_C("Opacity"), &config.opacity, 0.0f, 1.0f, "%.2f"); + persist |= ImGui::IsItemDeactivatedAfterEdit(); + if (config.in_scene && ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("In the scene the opacity is part of the textures: the tiles are read again from the cache\n" + "shortly after the slider stops, which takes a moment.")); + + // newest imagery, or the newest imagery taken up to the end of the selected year + int const thisyear = static_cast(std::chrono::year_month_day{std::chrono::floor(std::chrono::system_clock::now())}.year()); + std::string const yearlabel = config.year ? std::to_string(config.year) : std::string(STR_C("Newest")); + ImGui::SetNextItemWidth(160.0f); + if (ImGui::BeginCombo(STR_C("Photo year"), yearlabel.c_str())) + { + if (ImGui::Selectable(STR_C("Newest"), config.year == 0)) + { + config.year = 0; + changed = true; + persist = true; + } + for (int year = thisyear; year >= editor_orthophoto::oldest_year; --year) + { + if (ImGui::Selectable(std::to_string(year).c_str(), config.year == year)) + { + config.year = year; + changed = true; + persist = true; + } + } + ImGui::EndCombo(); + } + + if (ImGui::Checkbox(STR_C("4K tiles where available"), &config.hires)) + { + changed = true; + persist = true; + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("4096 px tiles (~6 cm/px) from the high-resolution orthophoto, for the tiles around the camera.\n" + "Areas it doesn't cover use the standard imagery. Each 4K tile takes ~85 MB of video memory.")); + + ImGui::Separator(); + if (stats.failed == 0) + ImGui::Text(STR_C("Tiles: %d shown, %d loading, %d failed"), stats.resident, stats.loading, stats.failed); + if (!editor_orthophoto::can_download()) + ImGui::TextDisabled(STR_C("This build has no HTTP client, only cached tiles are shown")); + ImGui::TextDisabled(STR_C("Cache: %s"), editor_orthophoto::cache_directory().c_str()); + if (ImGui::Button(STR_C("Clear cache"))) + m_orthophoto.clear_cache(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Deletes downloaded tiles from disk. They are fetched again around the camera.")); + ImGui::TreePop(); + } + + if (changed) + m_orthophoto.settings(config); + if (persist) + save_orthophoto_settings(); + + ImGui::TextDisabled(STR_C("Imagery: GUGiK, geoportal.gov.pl")); +} + +void editor_mode::draw_orthophoto() +{ + if (false == m_orthophoto.enabled() && std::none_of(m_wms.begin(), m_wms.end(), [](auto const &Layer) { return Layer->enabled(); })) + return; + // the camera was just published to the renderer (update_camera), so build the view from it rather than + // from the renderer's previous frame; camera-relative rotation, same projection as the other overlays + glm::dmat4 viewmatrix{1.0}; + Camera.SetMatrix(viewmatrix); + glm::mat4 const view = glm::mat4(glm::mat3(viewmatrix)); + ImGuiIO const &io = ImGui::GetIO(); + float const aspect = io.DisplaySize.y > 0.0f ? io.DisplaySize.x / io.DisplaySize.y : 1.0f; + auto const projection{editor_mode::projection_matrix(aspect) * view}; + m_orthophoto.draw(projection, Camera.Pos, io.DisplaySize.x, io.DisplaySize.y); + // the WMS layers over it, the top one of the list last + for (auto layer{m_wms.rbegin()}; layer != m_wms.rend(); ++layer) + (*layer)->draw(projection, Camera.Pos, io.DisplaySize.x, io.DisplaySize.y); +} + +void editor_mode::draw_ortho_compass() const +{ + if (false == Global.EditorOrtho) + return; + screen_projection const projection; + ImVec2 north_from, north_to, east_from, east_to; + glm::dvec3 const eye{Camera.Pos}; + if (false == projection.project(eye + glm::dvec3{0.0, 0.0, -80.0}, north_from) || false == projection.project(eye + glm::dvec3{0.0, 0.0, 80.0}, north_to) || + false == projection.project(eye + glm::dvec3{80.0, 0.0, 0.0}, east_from) || false == projection.project(eye + glm::dvec3{-80.0, 0.0, 0.0}, east_to)) + return; + auto const dir = [](ImVec2 const From, ImVec2 const To) { + ImVec2 const d{To.x - From.x, To.y - From.y}; + auto const length{std::sqrt(d.x * d.x + d.y * d.y)}; + return length > 1e-3f ? ImVec2{d.x / length, d.y / length} : ImVec2{0.0f, -1.0f}; + }; + auto const north{dir(north_from, north_to)}; + auto const east{dir(east_from, east_to)}; + ImVec2 const south{-north.x, -north.y}; + ImVec2 const west{-east.x, -east.y}; + + ImGuiIO const &io = ImGui::GetIO(); + float const radius{36.0f}; + float const margin{16.0f}; + // in the corner of the view, where the buttons of the toolbar and the hints along its bottom aren't + ImVec2 const center{editor_ui::view_max().x - margin - radius - 14.0f, editor_ui::view_max().y - margin - radius - 54.0f}; + auto *drawlist{ImGui::GetForegroundDrawList()}; + drawlist->AddCircleFilled(center, radius + 14.0f, IM_COL32(0, 0, 0, 180), 48); + drawlist->AddCircle(center, radius - 6.0f, IM_COL32(255, 255, 255, 50), 48, 1.2f); + drawlist->AddCircleFilled(center, 3.0f, IM_COL32(255, 255, 255, 200), 12); + + auto const at = [&](ImVec2 const Unit, float const Length) { return ImVec2{center.x + Unit.x * Length, center.y + Unit.y * Length}; }; + ImVec2 const side{-north.y * 5.0f, north.x * 5.0f}; + drawlist->AddTriangleFilled(at(north, radius - 14.0f), ImVec2{center.x + side.x, center.y + side.y}, ImVec2{center.x - side.x, center.y - side.y}, IM_COL32(230, 70, 55, 255)); + drawlist->AddTriangleFilled(at(south, radius - 18.0f), ImVec2{center.x + side.x, center.y + side.y}, ImVec2{center.x - side.x, center.y - side.y}, IM_COL32(210, 210, 210, 210)); + + auto const letter = [&](char const *Text, ImVec2 const Unit, ImU32 const Color) { + auto const size{ImGui::CalcTextSize(Text)}; + auto const p{at(Unit, radius + 2.0f)}; + drawlist->AddText(ImVec2(p.x - size.x * 0.5f, p.y - size.y * 0.5f), Color, Text); + }; + letter("N", north, IM_COL32(255, 90, 70, 255)); + letter("E", east, IM_COL32(230, 230, 230, 230)); + letter("S", south, IM_COL32(190, 190, 190, 180)); + letter("W", west, IM_COL32(230, 230, 230, 230)); +} + +void editor_mode::forget_ground() +{ + ground_tiles.clear(); + forget_ground_shapes(); +} + +void editor_mode::forget_ground_in(glm::dvec2 const &Min, glm::dvec2 const &Max) +{ + for (auto tile{ground_tiles.begin()}; tile != ground_tiles.end();) + { + glm::dvec2 const low{tile->first.first * ground_tile_size, tile->first.second * ground_tile_size}; + if (low.x <= Max.x && low.x + ground_tile_size >= Min.x && low.y <= Max.y && low.y + ground_tile_size >= Min.y) + tile = ground_tiles.erase(tile); + else + ++tile; } } editor_terrain *editor_mode::terrain_at(double X, double Z) { - for (auto &terrain : m_terrains) - if (terrain && terrain->contains(X, Z)) - return terrain.get(); - double const size = chunk_grid_size(); - auto const it = m_grid_chunks.find({static_cast(std::floor(X / size)), static_cast(std::floor(Z / size))}); - if (it != m_grid_chunks.end() && it->second && it->second->contains(X, Z)) - return it->second.get(); return m_streamer.terrain_at(X, Z); } -std::vector editor_mode::active_terrains() +std::vector editor_mode::active_terrains() const { std::vector out; - out.reserve(m_terrains.size() + m_grid_chunks.size() + m_streamer.resident()); - for (auto &terrain : m_terrains) - if (terrain) - out.push_back(terrain.get()); - for (auto &entry : m_grid_chunks) - if (entry.second) - out.push_back(entry.second.get()); + out.reserve(m_streamer.resident()); m_streamer.collect(out); return out; } -void editor_mode::add_grid_chunk(int Cx, int Cz) +bool editor_mode::ensure_terrain() { - std::pair const key{Cx, Cz}; - if (m_grid_chunks.count(key)) - return; // already occupied - - double const size = chunk_grid_size(); - int const cells = std::clamp(m_terrain_cells, 1, 256); - glm::dvec3 const center((Cx + 0.5) * size, static_cast(m_terrain_baseheight), (Cz + 0.5) * size); - - auto terrain = std::make_unique(); - if (!terrain->create(center, cells, m_terrain_cellsize, std::string(m_terrain_texture))) - return; - if (m_terrain_auto_optimize) - terrain->optimize(m_terrain_simplify_error); - m_grid_chunks[key] = std::move(terrain); + if (m_streamer.active()) + return true; + auto const name = scenery_stem(); + if (name.empty()) + return false; + m_streamer.open(name); + m_terrain_spacing = m_streamer.manifest().spacing; + return m_streamer.active(); } -void editor_mode::remove_grid_chunk(int Cx, int Cz) +bool editor_mode::add_chunk_from_ground(heightmap::chunk_key const &Key, float const Spacing, std::uint16_t const Layer) { - auto const it = m_grid_chunks.find({Cx, Cz}); - if (it == m_grid_chunks.end()) - return; - if (it->second) - it->second->destroy(); - m_grid_chunks.erase(it); -} - -void editor_mode::handle_chunk_edit_click(bool DeleteMode) -{ - // world point under the cursor; must land on existing geometry to give a valid depth - glm::dvec3 const world = Camera.Pos + GfxRenderer->Mouse_Position(); - double const size = chunk_grid_size(); - int const cx = static_cast(std::floor(world.x / size)); - int const cz = static_cast(std::floor(world.z / size)); - bool const streaming = m_streamer.active(); - - if (DeleteMode) - { - if (streaming) - m_streamer.remove_chunk(cx, cz); - else - remove_grid_chunk(cx, cz); - return; - } - - // if the clicked cell holds a chunk, target the neighbour nearest the clicked edge (the empty - // side); otherwise fill the clicked cell - bool const occupied = streaming - ? m_streamer.terrain_at(world.x, world.z) != nullptr - : m_grid_chunks.count({cx, cz}) > 0; - int tcx = cx, tcz = cz; - if (occupied) - { - double const lx = world.x - cx * size, lz = world.z - cz * size; - double const dw = lx, de = size - lx, dn = lz, ds = size - lz; - double const nearest = std::min({dw, de, dn, ds}); - if (nearest == dw) - tcx = cx - 1; - else if (nearest == de) - tcx = cx + 1; - else if (nearest == dn) - tcz = cz - 1; - else - tcz = cz + 1; - } - - if (streaming) - m_streamer.add_chunk(tcx, tcz); - else - add_grid_chunk(tcx, tcz); -} - -void editor_mode::create_chunked_terrain() -{ - int const chunks = std::clamp(m_terrain_chunks, 1, 32); - double const size = chunk_grid_size(); - - // snap the field to the global chunk grid (so it aligns with manual/streamed chunks), centred - // on the camera's chunk - int const ccx = static_cast(std::floor(Camera.Pos.x / size)); - int const ccz = static_cast(std::floor(Camera.Pos.z / size)); - int const half = chunks / 2; - - int created = 0; - for (int dz = 0; dz < chunks; ++dz) - for (int dx = 0; dx < chunks; ++dx) + if (m_streamer.exists(Key)) + return false; + auto const low = heightmap::chunk_corner(Key); + auto const high = low + glm::dvec2{heightmap::chunk_size}; + // the ground under the chunk, the edges of the neighbouring chunks included, so the new one meets them + std::vector triangles; + gather_ground_triangles(low - glm::dvec2{1.0}, high + glm::dvec2{1.0}, true, 50.0f, triangles, true); + triangle_grid const ground(std::move(triangles), low - glm::dvec2{1.0}, high + glm::dvec2{1.0}); + auto const cells = heightmap::cells_for(Spacing); + auto const side = static_cast(cells) + 1; + auto const step = heightmap::chunk_size / cells; + std::vector heights(side * side, 0.0); + std::vector found(side * side, 0); + bool any = false; + for (std::size_t iz = 0; iz < side; ++iz) + for (std::size_t ix = 0; ix < side; ++ix) { - int const cx = ccx - half + dx, cz = ccz - half + dz; - if (!m_grid_chunks.count({cx, cz})) + auto const index = iz * side + ix; + if (ground.height_at(low.x + ix * step, low.y + iz * step, std::numeric_limits::max(), heights[index])) + found[index] = 1, any = true; + } + // past the edge of the ground the chunk is carried on level with the nearest point of it + if (any) + fill_from_nearest(heights, found, side); + else + std::fill(heights.begin(), heights.end(), m_terrain_baseheight); + auto const added = m_streamer.add_chunk(Key.first, Key.second, Spacing, [&](double const X, double const Z) { + auto const ix = static_cast(std::clamp(std::lround((X - low.x) / step), 0, cells)); + auto const iz = static_cast(std::clamp(std::lround((Z - low.y) / step), 0, cells)); + return static_cast(heights[iz * side + ix]); + }, Layer); + if (added) + { + ground_tiles.clear(); + forget_ground_shapes(); + } + return added; +} + +void editor_mode::add_chunks_around(int const Count) +{ + if (false == ensure_terrain()) + return; + auto const centre = heightmap::chunk_at(Camera.Pos.x, Camera.Pos.z); + auto const first = -(Count - 1) / 2; + int made = 0; + for (int dz = 0; dz < Count; ++dz) + for (int dx = 0; dx < Count; ++dx) + if (add_chunk_from_ground({centre.first + first + dx, centre.second + first + dz}, m_terrain_spacing)) + ++made; + m_terrain_status = format(STR_C("%d chunks made"), made); +} + +void editor_mode::handle_terrain_click(bool const Shift) +{ + glm::dvec3 world; + if (false == cursor_on_ground(world)) + return; // nothing under the cursor + switch (m_terrain_tool) + { + case terrain_tool::chunks: + { + if (false == ensure_terrain()) + return; + auto const key = heightmap::chunk_at(world.x, world.z); + if (Shift) + { + if (m_streamer.exists(key)) { - add_grid_chunk(cx, cz); - ++created; + m_streamer.remove_chunk(key.first, key.second); + ground_tiles.clear(); + forget_ground_shapes(); + m_terrain_status = format(STR_C("Chunk %d,%d removed"), key.first, key.second); + } + return; + } + // a click on a chunk adds the neighbour by the nearest edge, a click outside fills the clicked place + auto target = key; + if (m_streamer.exists(key)) + { + auto const low = heightmap::chunk_corner(key); + double const west = world.x - low.x, east = heightmap::chunk_size - west, south = world.z - low.y, north = heightmap::chunk_size - south; + double const nearest = std::min({west, east, south, north}); + if (nearest == west) + --target.first; + else if (nearest == east) + ++target.first; + else if (nearest == south) + --target.second; + else + ++target.second; + } + m_terrain_status = add_chunk_from_ground(target, m_terrain_spacing) ? format(STR_C("Chunk %d,%d made"), target.first, target.second) : std::string(STR_C("There's a chunk there already")); + break; + } + case terrain_tool::spacing: + { + // a click selects the chunk, Ctrl adds it to the selection or takes it away + auto const key = heightmap::chunk_at(world.x, world.z); + if (false == m_streamer.exists(key)) + { + if (false == Global.ctrlState) + m_terrain_selection.clear(); + return; + } + if (false == Global.ctrlState) + m_terrain_selection = {key}; + else if (m_terrain_selection.erase(key) == 0) + m_terrain_selection.insert(key); + m_terrain_status = format(STR_C("Chunks selected: %zu"), m_terrain_selection.size()); + break; + } + case terrain_tool::fill: + { + if (Shift) + { + if (false == m_paint_outline.empty()) + m_paint_outline.pop_back(); + return; + } + m_paint_outline.push_back(placement_on_ground(world)); + break; + } + case terrain_tool::water: + { + if (Shift) + { + if (false == m_water_points.empty()) + m_water_points.pop_back(); + return; + } + auto const point = placement_on_ground(world); + // the water reaches the lowest point of its shore, unless given by hand + if (false == m_water_level_edited) + m_water_level = m_water_points.empty() ? static_cast(point.y) : std::min(m_water_level, static_cast(point.y)); + m_water_points.push_back(point); + break; + } + default: + break; + } +} + +namespace +{ + // takes the shapes of specified terrain files and materials out of the scene. returns: the count of the shapes + std::size_t drop_terrain_shapes(std::set const &Files, std::set const &Materials) + { + std::size_t dropped = 0; + auto const dropping = [&](scene::shape_node const &Shape) { + auto const &data = Shape.data(); + bool const drop = Files.count(data.terrainfile) != 0 && Materials.count(data.material) != 0; + dropped += drop ? 1 : 0; + return drop; + }; + for (std::size_t i = 0; i < sq(scene::EU07_REGIONSIDESECTIONCOUNT); ++i) + { + auto *section = simulation::Region->get_section(i); + if (section == nullptr) + continue; + section->m_shapes.erase(std::remove_if(section->m_shapes.begin(), section->m_shapes.end(), dropping), section->m_shapes.end()); + for (auto &cell : section->m_cells) + { + cell.m_shapesopaque.erase(std::remove_if(cell.m_shapesopaque.begin(), cell.m_shapesopaque.end(), dropping), cell.m_shapesopaque.end()); + cell.m_shapestranslucent.erase(std::remove_if(cell.m_shapestranslucent.begin(), cell.m_shapestranslucent.end(), dropping), cell.m_shapestranslucent.end()); } } + return dropped; + } +} // namespace - WriteLog("Editor: created chunked terrain with " + std::to_string(created) + " chunks", logtype::generic); +void editor_mode::load_ground_files() +{ + auto &conversion{m_ground_conversion}; + conversion.files.clear(); + conversion.triangles.clear(); + conversion.materials.clear(); + conversion.names.clear(); + conversion.chosen.clear(); + std::map lookup; + auto const &references{scene::terrain_file::references()}; + for (std::size_t index = 0; index < references.size(); ++index) + { + ground_conversion::source source; + source.file = references[index].file; + source.reference = static_cast(index + 1); + source.first = conversion.triangles.size(); + source.good = scene::terrain_file::read_triangles( + references[index], + [&](std::string const &Material, std::array const &Triangle) { + auto found{lookup.find(Material)}; + if (found == lookup.end()) + { + found = lookup.emplace(Material, static_cast(conversion.names.size())).first; + conversion.names.push_back(Material); + } + conversion.triangles.push_back(Triangle); + conversion.materials.push_back(found->second); + }, + &source.message, &source.text); + if (false == source.good) + { + // what was read before the failure doesn't count + conversion.triangles.resize(source.first); + conversion.materials.resize(source.first); + source.chosen = false; + } + source.count = conversion.triangles.size() - source.first; + conversion.files.push_back(std::move(source)); + } + // the terrain files hold the ground, all of it is taken unless told otherwise + for (std::size_t index = 0; index < conversion.names.size(); ++index) + conversion.chosen.insert(index); } -void editor_mode::save_scene_with_terrain() +std::string editor_mode::convert_ground() { - // commit authored terrain so the scenery streams it on load. if not already streaming, hand the - // manual grid chunks over to the streamer (same as toggling Stream terrain on) - if (!m_streamer.active()) + auto &conversion{m_ground_conversion}; + if (simulation::Region == nullptr || conversion.chosen.empty()) + return {}; + if (false == ensure_terrain()) + return STR_C("The heightmap terrain can't be opened"); + double const size = heightmap::chunk_size; + int const cells = heightmap::cells_for(m_terrain_spacing); + double const cellsize = size / cells; + + // the chosen triangles of the chosen files + std::vector triangles; + std::vector materials; + std::set files; + for (auto const &source : conversion.files) { - std::string scenery = Global.SceneryFile; - auto const slash = scenery.find_last_of("/\\"); - if (slash != std::string::npos) - scenery = scenery.substr(slash + 1); - auto const dot = scenery.find_last_of('.'); - if (dot != std::string::npos) - scenery = scenery.substr(0, dot); - if (scenery.empty()) - scenery = "default"; + if (false == source.good || false == source.chosen) + continue; + files.insert(source.reference); + for (auto index = source.first; index < source.first + source.count; ++index) + { + if (conversion.chosen.count(conversion.materials[index]) == 0) + continue; + triangles.push_back(conversion.triangles[index]); + materials.push_back(conversion.materials[index]); + } + } + if (triangles.empty()) + return STR_C("The chosen files and materials have no triangles"); - m_streamer.directory("editor_terrain/" + scenery); - m_streamer.configure(m_terrain_cells, m_terrain_cellsize, m_stream_radius, m_terrain_baseheight, - std::string(m_terrain_texture)); - m_streamer.simplify(m_terrain_auto_optimize, m_terrain_simplify_error); - m_streamer.persist(true); - - for (auto &entry : m_grid_chunks) - if (entry.second) - m_streamer.save_chunk(entry.first.first, entry.first.second, *entry.second); - for (auto &entry : m_grid_chunks) - if (entry.second) - entry.second->destroy(); - m_grid_chunks.clear(); - m_streamer.active(true); + // the triangles reaching each chunk + std::map> buckets; + for (std::uint32_t i = 0; i < triangles.size(); ++i) + { + auto const &t = triangles[i]; + // a triangle which only touches the edge of a chunk gives it nothing but the edge, which the chunk on the other side has + auto const margin{1e-3}; + auto const low{heightmap::chunk_at(std::min({t[0].x, t[1].x, t[2].x}) + margin, std::min({t[0].z, t[1].z, t[2].z}) + margin)}; + auto const high{heightmap::chunk_at(std::max({t[0].x, t[1].x, t[2].x}) - margin, std::max({t[0].z, t[1].z, t[2].z}) - margin)}; + for (int x = low.first; x <= high.first; ++x) + for (int z = low.second; z <= high.second; ++z) + buckets[{x, z}].push_back(i); } - m_streamer.flush(); // save resident edited chunks to disk + // palette entries of the materials, added as they're needed + std::map palette; + auto const layer_of = [&](std::uint16_t const Material) { + auto const found{palette.find(Material)}; + if (found != palette.end()) + return found->second; + auto const layer{m_streamer.layer(conversion.names[Material])}; + palette.emplace(Material, layer); + return layer; + }; - // export scenery; the exported .scm now carries an `editorterrain` directive (streamer is active) - simulation::State.export_as_text(Global.SceneryFile); - WriteLog("Editor: saved scene + terrain", logtype::generic); + std::size_t made = 0, skipped = 0; + std::size_t const side = static_cast(cells) + 1; + auto const samples{heightmap::default_paint_samples}; + std::size_t const paintside = static_cast(samples) + 1; + double const paintstep = size / samples; + for (auto const &bucket : buckets) + { + auto const &key = bucket.first; + if (m_streamer.exists(key)) + { + ++skipped; + continue; + } + auto const low{heightmap::chunk_corner(key)}; + std::vector local; + std::vector localmaterials; + for (auto const i : bucket.second) + { + local.push_back(triangles[i]); + localmaterials.push_back(materials[i]); + } + triangle_grid const ground(std::move(local), low - glm::dvec2{1.0}, low + glm::dvec2{size + 1.0}); + auto const ceiling{std::numeric_limits::max()}; + // heights of the grid points; where there's no ground they're taken from the nearest point which has some + std::vector heights(side * side, 0.0); + std::vector found(side * side, 0); + bool any = false; + for (std::size_t iz = 0; iz < side; ++iz) + for (std::size_t ix = 0; ix < side; ++ix) + { + auto const index = iz * side + ix; + if (ground.height_at(low.x + ix * cellsize, low.y + iz * cellsize, ceiling, heights[index])) + found[index] = 1, any = true; + } + if (false == any) + continue; + fill_from_nearest(heights, found, side); + // the material on top at each paint sample + std::vector paint(paintside * paintside, 0); + std::vector painted(paintside * paintside, 0); + std::map counts; + for (std::size_t iz = 0; iz < paintside; ++iz) + for (std::size_t ix = 0; ix < paintside; ++ix) + { + double height; + std::uint32_t triangle; + if (false == ground.height_at(low.x + ix * paintstep, low.y + iz * paintstep, ceiling, height, &triangle)) + continue; + auto const index = iz * paintside + ix; + paint[index] = localmaterials[triangle]; + painted[index] = 1; + ++counts[paint[index]]; + } + if (counts.empty()) + { + // the points of the grid hit the ground, the samples in between didn't; the nearest triangle covers the chunk + counts[localmaterials.front()] = 1; + std::fill(paint.begin(), paint.end(), localmaterials.front()); + } + else + fill_from_nearest(paint, painted, paintside); + // a chunk holds up to 8 materials, the ones covering the most; the rest is given to the one covering the most + std::vector> ranking; + for (auto const &count : counts) + ranking.emplace_back(count.second, count.first); + std::sort(ranking.begin(), ranking.end(), [](auto const &A, auto const &B) { return A.first > B.first; }); + if (ranking.size() > heightmap::max_chunk_layers) + ranking.resize(heightmap::max_chunk_layers); + + auto data{heightmap::chunk_data::make_flat(key, m_terrain_spacing, 0.f)}; + for (std::size_t index = 0; index < data->heights.size(); ++index) + data->heights[index] = static_cast(heights[index]); + std::map slots; + for (std::size_t slot = 0; slot < ranking.size(); ++slot) + { + data->layers[slot] = layer_of(ranking[slot].second); + slots.emplace(ranking[slot].second, slot); + } + if (ranking.size() > 1) + { + auto const plane{paintside * paintside}; + data->paint = samples; + data->weights.assign(plane * ranking.size(), 0); + for (std::size_t index = 0; index < plane; ++index) + { + auto const slot{slots.find(paint[index])}; + data->weights[(slot != slots.end() ? slot->second : 0) * plane + index] = 255; + } + } + if (m_streamer.add_chunk(std::move(data))) + ++made; + } + forget_ground(); + + // the converted ground goes from the scene, and from the text files on save + std::set handles; + for (auto const material : conversion.chosen) + if (material < conversion.names.size()) + handles.insert(GfxRenderer->Fetch_Material(conversion.names[material])); + auto const dropped = drop_terrain_shapes(files, handles); + std::set layers; + std::size_t binary = 0; + for (auto const &source : conversion.files) + { + if (false == source.good || false == source.chosen) + continue; + if (false == source.text) + { + ++binary; + continue; + } + auto const textfile{source.file + ".txtf"}; + for (std::size_t layer = 1; layer <= scene::Layers.size(); ++layer) + { + auto name{scene::Layers.layer(static_cast(layer)).name}; + replace_slashes(name); + if (name.ends_with(textfile)) + layers.insert(static_cast(layer)); + } + } + auto const erased = scene::Layers.erase_shapes(handles, &layers); + auto summary = format(STR_C("Ground converted: %zu chunks of heightmap terrain made, %zu shapes taken out of the scene, %zu triangle nodes go from the terrain files on save"), made, dropped, erased.first); + if (skipped > 0) + summary += format(STR_C(", %zu chunks kept as there was terrain already"), skipped); + if (erased.second > 0) + summary += format(STR_C(", %zu nodes stay as their files can't be rewritten"), erased.second); + if (binary > 0) + summary += format(STR_C(". %zu of the files are binary (.btf) without their text: their triangles come back with the next load, until the files are taken out of the terrain directive"), binary); + WriteLog("Editor: " + summary, logtype::generic); + return summary; } -void editor_mode::handle_terrain_sculpt(double Deltatime) +bool editor_mode::save() { - // world point under the cursor (Mouse_Position is camera-relative, like the brush placement uses) - glm::dvec3 const world = Camera.Pos + GfxRenderer->Mouse_Position(); - // only sculpt when the cursor is actually over terrain (avoids editing on a stale depth read) + if (scene::Layers.empty()) + { + // without the sources tracked during the load there's no telling where the changes belong + ui()->set_status(STR("The scenery wasn't opened for editing. Start the simulator with: -edit "), true); + return false; + } + first_step_done(first_step::save); + + // the heightmap terrain is kept in files of its own, the scenery only needs the directive which loads it, in a layer of its own + std::vector rootstatements; + std::map> statements; + if (m_streamer.active()) + { + std::string error; + if (false == m_streamer.save(&error)) + { + ui()->set_status(format(STR_C("The terrain couldn't be saved: %s"), error.c_str()), true); + return false; + } + if (false == scene::Layers.terrain_directive()) + { + auto const directive{"heightmap_terrain " + m_streamer.name() + " endheightmap_terrain"}; + if (auto const layer{output_layer("teren")}; layer != null_handle) + statements[layer].push_back(directive); + else + rootstatements.push_back(directive); + } + } + + if (m_profile.changed) + profile_store(); + switch_store::tidy(); + switch_store::settle(); + infra_store(); + m_srk.store(); + if (false == m_saved_camera.has_value() || glm::distance(m_saved_camera->first, glm::dvec3{Camera.Pos}) > 0.5 || glm::distance(m_saved_camera->second, glm::vec3{Camera.Angle}) > 0.01f) + { + m_saved_camera = std::make_pair(glm::dvec3{Camera.Pos}, glm::vec3{Camera.Angle}); + scene::Layers.mark(scene::layer_handle{1}, "//$c", {format("%.3f %.3f %.3f %.5f %.5f", Camera.Pos.x, Camera.Pos.y, Camera.Pos.z, Camera.Angle.x, Camera.Angle.y)}); + } + if (auto const map{editor_orthophoto::mark(m_orthophoto.settings(), m_orthophoto.enabled(), m_orthophoto.settings().north != 0.0 || m_orthophoto.settings().east != 0.0)}; false == m_orthophoto_scenery.empty() && map != m_orthophoto_mark && (m_orthophoto.enabled() || false == m_orthophoto_mark.empty())) + { + m_orthophoto_mark = map; + scene::Layers.mark(scene::layer_handle{1}, "//$o", {map}); + } + if (auto const area{editor_orthophoto::area_lines(m_orthophoto.area())}; false == m_orthophoto_scenery.empty() && area != m_orthophoto_area_mark) + { + m_orthophoto_area_mark = area; + scene::Layers.mark(scene::layer_handle{1}, "//$z", area); + } + auto const terrainadded{false == rootstatements.empty() || false == statements.empty()}; + auto const controls{turntable_controls(rootstatements)}; + auto const noses{nose_controls(rootstatements)}; + std::vector trailing; + auto const placed{m_vehicle.trainset_lines(trailing)}; + if (placed == 0) + starter_trainset(trailing); + auto const result = scene::Layers.save(rootstatements, trailing, statements); + if (result.success && controls) + m_turntable_included = true; + if (result.success && noses) + m_nose_included = true; + if (result.success && placed > 0) + m_vehicle.trainsets_written(); + if (result.success && placed == 0 && trailing.size() == 3) + { + std::istringstream header{trailing.front()}; + std::string keyword; + std::string timetable; + std::string track; + double offset{0.0}; + header >> keyword >> timetable >> track >> offset; + if (auto *path{simulation::Paths.find(track)}; path != nullptr && simulation::Vehicles.find("wmb10-6457") == nullptr) + simulation::State.insert_trainset("wmb10-6457", path, offset, trailing[1] + "\n"); + } + if (result.success && terrainadded) + { + scene::Layers.terrain_directive(true); + } + ui()->set_status(result.message, false == result.success); + WriteLog("Editor: " + result.message, logtype::generic); + return result.success; +} + +void editor_mode::toggle_include(scene::instance_handle const Instance) +{ + if (false == scene::Layers.tracked(Instance)) + return; + auto const &included = scene::Layers.instance(Instance); + if (included.dead) + { + // its directive is gone from the scenery file, and the place it was at with it + ui()->set_status(format(STR_C("Include of \"%s\" was removed from the saved scenery, this can't be taken back"), included.file->c_str()), true); + return; + } + scene::Layers.removed(Instance, false == included.removed); + m_drives_standing.reset(); + ui()->set_status(format(included.removed ? STR_C("Include of \"%s\" removed") : STR_C("Include of \"%s\" restored"), included.file->c_str())); +} + +void editor_mode::restore_include(EditorSnapshot &Snapshot) +{ + if (Snapshot.serialized.empty()) + { + // the include was placed or removed; either is taken back by flipping its removal + toggle_include(Snapshot.instance); + select_include(0); + return; + } + // parameters of the include were changed. the snapshot holds the directive to go back to, and leaves with the current one + auto current = scene::Layers.directive(Snapshot.instance); + if (current.empty() || scene::Layers.instance(Snapshot.instance).dead) + { + ui()->set_status(format(STR_C("Include of \"%s\" is gone from the scenery, the change can't be taken back"), Snapshot.node_name.c_str()), true); + return; + } + set_include_directive(Snapshot.instance, Snapshot.serialized); + Snapshot.serialized = std::move(current); + select_include(scene::Layers.removable(Snapshot.instance) ? Snapshot.instance : 0); +} + +void editor_mode::restore_includes(EditorSnapshot &Snapshot) +{ + std::size_t gone{0}; + for (auto const instance : Snapshot.instances) + { + if (false == scene::Layers.tracked(instance) || scene::Layers.instance(instance).dead) + { + ++gone; + continue; + } + scene::Layers.removed(instance, false == scene::Layers.instance(instance).removed); + } + m_drives_standing.reset(); + for (auto &entry : Snapshot.directives) + { + auto current = scene::Layers.directive(entry.first); + if (current.empty() || scene::Layers.instance(entry.first).dead) + { + ++gone; + continue; + } + set_include_directive(entry.first, entry.second); + entry.second = std::move(current); + } + select_include(0); + ui()->set_status(gone > 0 ? format(STR_C("Includes gone from the saved scenery, they can't be taken back: %zu"), gone) : format(STR_C("Includes restored: %zu"), Snapshot.instances.size() + Snapshot.directives.size()), gone > 0); +} + +void editor_mode::select_include(scene::instance_handle const Instance) +{ + m_instance = (scene::Layers.tracked(Instance) ? Instance : 0); + m_include = include_selection{}; + m_include_gesture = false; + if (m_instance == 0) + { + ui()->set_include(nullptr); + return; + } + auto const &included = scene::Layers.instance(m_instance); + m_include.instance = m_instance; + m_include.target = *included.file; + // NOTE: a template without a usable description is still presented, with its parameters unnamed + std::string error; + editor_includes::load(*included.file, m_include.info, error); + if (false == editor_includes::parse_directive(scene::Layers.directive(m_instance), m_include.target, m_include.values)) + { + m_include.values.clear(); + m_include.issue = STR_C("The directive of the include can't be read from the scenery file, its parameters can't be changed"); + } + // with a rotation or a scale in effect the parameters don't translate to a location in the scene in a single way, + // see place_include() + m_include.placement = (included.context.rotation == glm::vec3{0.f} && included.context.scale == glm::vec3{1.f}); + ui()->set_include(&m_include); +} + +void editor_mode::set_include_directive(scene::instance_handle const Instance, std::string const &Directive) +{ + m_drives_standing.reset(); + std::string file; + std::vector values; + if (scene::Layers.tracked(Instance) && editor_includes::parse_directive(Directive, file, values) && scene::Layers.instance(Instance).file != nullptr && + editor_includes::normalized(file) == editor_includes::normalized(*scene::Layers.instance(Instance).file)) + file.clear(); + if (false == scene::Layers.modify(Instance, Directive, file)) + return; + std::vector retired; + simulation::State.rebuild_include(Instance, retired); + // the pick of the renderer is resolved a few frames after it's requested, and can still deliver one of these + for (auto *model : retired) + { + nullify_history_pointers(model); + m_retired.emplace_back(model, 120); + } +} + +void editor_mode::apply_include() +{ + if (m_instance == 0 || false == m_include.issue.empty()) + return; + for (auto const &value : m_include.values) + { + if (value == "end" || value.find_first_of("\"\r\n") != std::string::npos) + { + // either would cut the directive short + ui()->set_status(STR_C("A parameter of an include can't be \"end\", or have a quotation mark in it"), true); + select_include(m_instance); // back to the values of the directive + return; + } + } + auto before = scene::Layers.directive(m_instance); + if (false == m_include.info.signal_kind.empty() + && std::ranges::any_of(m_include.info.parameters, [](auto const &Parameter) { return Parameter.id == 6 && Parameter.role == "texture"; })) + { + // the drawn plate of a signal follows its name; a plate picked from the textures stays, and so does a drawn one given + // another name by hand. While the name is cleared or one the plate can't carry, the plate keeps the last name, and + // follows again once a usable name is typed. No plate, or the texture named like the signal the editor gave before the + // plates were drawn, become the drawn one. The look, the index and the m of the plate go with it + std::string file; + std::vector previous; + if (editor_includes::parse_directive(before, file, previous) && previous.size() >= 6 && m_include.values.size() >= 6) + { + auto const look{signal_plate_style(previous[5])}; + auto const carried = [&](std::string const &Name) { return Name != "none" && signal_plate_drawn(signal_plate(Name, look)); }; + if (previous[0] != m_include.values[0] && m_include.values[5] == previous[5] && carried(m_include.values[0]) + && (previous[5] == signal_plate(previous[0], look) || (false == carried(previous[0]) && signal_plate_drawn(previous[5])) || signal_plate_blank(previous[0], previous[5]))) + m_include.values[5] = signal_plate(m_include.values[0], look); + } + } + auto const directive = editor_includes::compose_directive(m_include.target, m_include.values); + if (directive == before) + return; + std::string read_before; + std::string read_after; + // a signal renamed: its indicators are named after it + std::string name_before; + glm::dvec3 standing{0.0}; + // the signal templates known, though no signal tool looked for them yet + if (m_include.info.category == "signal") + signal_scan(true); + if (false == m_include.info.signal_read.empty() || signal_template_of(m_include.target) != nullptr) + { + std::string file; + std::vector previous; + if (editor_includes::parse_directive(before, file, previous)) + { + if (false == m_include.info.signal_read.empty()) + { + read_before = editor_includes::substitute(m_include.info.signal_read, previous); + read_after = editor_includes::substitute(m_include.info.signal_read, m_include.values); + } + if (previous.size() >= 4 && false == m_include.values.empty() && previous.front() != m_include.values.front()) + { + name_before = previous.front(); + standing = scene::Layers.instance(m_instance).context.offset + glm::dvec3{std::strtod(previous[1].c_str(), nullptr), std::strtod(previous[2].c_str(), nullptr), std::strtod(previous[3].c_str(), nullptr)}; + } + } + } + if (false == m_include_gesture) + { + // a single undo step for the whole drag + EditorSnapshot snap; + snap.instance = m_instance; + snap.node_name = *scene::Layers.instance(m_instance).file; + snap.serialized = std::move(before); + if (read_before != read_after) + signal_renamed(read_before, read_after, snap); + m_history.push_back(std::move(snap)); + g_redo.clear(); + m_include_gesture = true; + } + else if (read_before != read_after && false == m_history.empty()) + signal_renamed(read_before, read_after, m_history.back()); + set_include_directive(m_instance, directive); + if (false == name_before.empty() && false == m_history.empty()) + { + std::vector> carried; + signal_indicators_renamed(name_before, m_include.values.front(), standing, carried); + history_add_directives(m_history.back(), carried); + } +} + +void editor_mode::place_include(std::string const &File, int const RotationMode, float const FixedRotation) +{ + if (scene::Layers.empty()) + { + // the directive has to go to a scenery file, and without the sources tracked there's no telling which + ui()->set_status(STR_C("Scenery templates can be placed only in a scenery opened for editing (-edit)"), true); + WriteLog("Editor: scenery templates can be placed only in a scenery opened for editing (-edit)", logtype::generic); + return; + } + include_info info; + std::string issue; + auto const parameters = editor_includes::parameter_count(File); + if (false == editor_includes::load(File, info, issue) || false == editor_includes::complete(info, parameters, &issue)) + { + ui()->set_status(format(STR_C("Template \"%s\" can't be placed: %s"), File.c_str(), issue.c_str()), true); + return; + } + + // the directive is added to the file of the active layer, and has to make sense with the placement in effect where it goes + auto const layer = scene::Layers.resolve(scene::Layers.active()); + if (std::string reason; false == scene::Layers.accepts(layer, &reason)) + { + ui()->set_status(format(STR_C("Template \"%s\" can't be placed: %s"), File.c_str(), (reason.empty() ? std::string{STR_C("there's no active layer to put it in")} : format(STR_C("the active layer can't take it, %s"), reason.c_str())).c_str()), true); + return; + } + auto const context = scene::Layers.layer(layer).context_insert(); + if (context.rotation != glm::vec3{0.f} || context.scale != glm::vec3{1.f}) + { + // a template can pass its parameters to an origin directive, which isn't affected by these, or straight to + // the nodes, which are. there's no single set of parameter values which puts both at the cursor + ui()->set_status(format(STR_C("Template \"%s\" can't be placed: the file of the active layer would receive it with a rotation or a scale in effect. Pick another layer"), File.c_str()), true); + return; + } + glm::dvec3 const location = placement_on_ground(Camera.Pos + clamp_mouse_offset_to_max(GfxRenderer->Mouse_Position())); + std::optional yaw; + if (RotationMode == functions_panel::RANDOM) + yaw = static_cast(LocalRandom(0.0, 360.0)); + else if (RotationMode == functions_panel::FIXED) + yaw = FixedRotation; + + auto const directive = editor_includes::directive(File, info, parameters, context.to_local(location), yaw); + auto const instance = scene::Layers.place(layer, File, directive); + if (instance == 0) + { + ui()->set_status(format(STR_C("Template \"%s\" can't be placed in the active layer"), File.c_str()), true); + return; + } + // show the models of the template right away. the rest of it comes into play when the saved scenery is loaded + auto const preview = simulation::State.preview_include(directive, context, layer, instance); + + EditorSnapshot snap; + snap.instance = instance; + snap.node_name = File; + m_history.push_back(std::move(snap)); + g_redo.clear(); + select_include(instance); + + ui()->set_status(format(STR_C("\"%s\" placed in layer \"%s\", models shown: %d"), info.name.c_str(), scene::Layers.layer(layer).name.c_str(), static_cast(preview.first)) + + (preview.second > 0 ? format(STR_C(", other statements of the template, working once the scenery is saved and loaded again: %d"), static_cast(preview.second)) : std::string{})); +} + +void editor_mode::export_scenery() +{ + // hiding a layer clears the visibility flag of its nodes, and the flag is a part of exported node data. + // show the hidden layers for the duration of the export, so the files get the visibility defined in the scenery + auto const hiddenlayers = scene::Layers.hidden(); + for (auto const layer : hiddenlayers) + scene::Layers.visible(layer, true); + + simulation::State.export_as_text(Global.SceneryFile); + + for (auto const layer : hiddenlayers) + scene::Layers.visible(layer, false); +} + +void editor_mode::handle_terrain_brush(double Deltatime) +{ + // the ground itself along the ray through the cursor in this frame + glm::dvec3 world; + if (false == terrain_cursor(world)) + return; + // only when the cursor is over the terrain if (terrain_at(world.x, world.z) == nullptr) return; - double const rate = m_terrain_brush_strength * Deltatime; // metres applied this frame - double const signedrate = Global.shiftState ? -rate : rate; - // apply to every chunk the brush touches; each patch clips to its own bounds, so a stroke - // crossing a chunk boundary edits both and shared-edge vertices stay in sync - for (editor_terrain *terrain : active_terrains()) - terrain->sculpt(world.x, world.z, m_terrain_brush_radius, signedrate); + double const rate = m_terrain_brush_strength * Deltatime; + bool shaped = false; + switch (m_terrain_tool) + { + case terrain_tool::sculpt: + shaped = m_streamer.sculpt(world.x, world.z, m_terrain_brush_radius, Global.shiftState ? -rate : rate); + break; + case terrain_tool::smooth: + shaped = m_streamer.smooth(world.x, world.z, m_terrain_brush_radius, std::min(1.0, rate * 0.5)); + break; + case terrain_tool::level: + { + if (false == m_terrain_stroke && m_terrain_target_from_stroke) + { + double height; + if (m_streamer.height_at(world.x, world.z, height)) + m_terrain_target = static_cast(height); + } + m_terrain_stroke = true; + shaped = m_streamer.level(world.x, world.z, m_terrain_brush_radius, m_terrain_target, std::min(1.0, rate * 0.5), m_terrain_level_mode); + break; + } + case terrain_tool::paint: + m_streamer.paint(world.x, world.z, m_terrain_brush_radius, std::min(1.0, rate * 0.25), Global.shiftState ? std::uint16_t{0} : static_cast(m_terrain_layer)); + break; + case terrain_tool::restore: + shaped = m_streamer.restore_stitching(world.x, world.z, m_terrain_brush_radius, std::min(1.0, rate * 0.5)); + break; + default: + break; + } + if (shaped) + { + // what the road tools know about the ground is no longer true + ground_tiles.clear(); + forget_ground_shapes(); + } +} + +bool editor_mode::cursor_on_ground(glm::dvec3 &World) +{ + if (m_streamer.active() && terrain_cursor(World)) + return true; + // no terrain under the ray: the depth read back under the cursor, as before, where it hit anything + if (false == GfxRenderer->Mouse_Hit()) + return false; + World = Camera.Pos + GfxRenderer->Mouse_Position(); + return true; +} + +bool editor_mode::terrain_cursor(glm::dvec3 &World) const +{ + // along the ray through the cursor as it is in this frame: the depth read back lags a frame behind + ImGuiIO const &io = ImGui::GetIO(); + if (io.DisplaySize.x <= 0.0f || io.DisplaySize.y <= 0.0f) + return false; + auto const inverse = glm::inverse(editor_mode::projection_matrix(io.DisplaySize.x / io.DisplaySize.y) * GfxRenderer->Camera_View_Matrix()); + glm::vec2 const ndc{io.MousePos.x / io.DisplaySize.x * 2.0f - 1.0f, 1.0f - io.MousePos.y / io.DisplaySize.y * 2.0f}; + // two points of the ray, whatever the depth range of the projection + auto const point = [&](float const Depth) { + auto const clip = inverse * glm::vec4(ndc, Depth, 1.0f); + return glm::dvec3{glm::vec3{clip} / clip.w}; + }; + auto const direction = point(0.5f) - point(0.0f); + if (glm::length(direction) < 1e-9) + return false; + // the top view sees from 10 km behind the plane of the camera (the near plane of its projection): the ray starts there, + // so the ground higher than the camera is met too + auto const back{Global.EditorOrtho ? 10000.0 : 0.0}; + auto const along{glm::normalize(direction)}; + return m_streamer.raycast(GfxRenderer->Camera_Position() + point(0.0f) - along * back, along, 5000.0 + back, World); +} + +void editor_mode::fill_terrain_area() +{ + auto const &layers = m_streamer.manifest().layers; + if (m_paint_outline.size() < 3 || layers.empty()) + return; + auto const chosen = layers[std::clamp(m_terrain_layer, 0, static_cast(layers.size()) - 1)]; + // the material turned by its own angle is another entry of the palette + auto const rotation = static_cast(std::remainder(static_cast(m_paint_rotation), 360.0)); + auto const layer = chosen.rotation == rotation ? static_cast(std::clamp(m_terrain_layer, 0, static_cast(layers.size()) - 1)) + : m_streamer.layer(chosen.material, chosen.size, rotation); + std::vector outline; + for (auto const &point : m_paint_outline) + outline.emplace_back(point.x, point.z); + auto const filled = m_streamer.fill(outline, m_paint_feather, layer); + m_terrain_status = filled ? format(STR_C("Area filled with %s"), chosen.material.c_str()) : std::string(STR_C("Nothing filled: no chunk under the outline, or no room for another material")); + if (filled) + m_paint_outline.clear(); +} + +void editor_mode::remove_selected_chunks() +{ + // one step of the history, as the terrain changed in a frame goes + std::size_t removed{0}; + for (auto const &key : m_terrain_selection) + if (m_streamer.exists(key)) + { + m_streamer.remove_chunk(key.first, key.second); + ++removed; + } + m_terrain_selection.clear(); + if (removed > 0) + { + ground_tiles.clear(); + forget_ground_shapes(); + } + m_terrain_status = format(STR_P("%zu chunk removed, Ctrl+Z brings it back", "%zu chunks removed, Ctrl+Z brings them back", removed), removed); +} + +void editor_mode::convert_selected_chunks() +{ + // with 0.5 m spacing the paint can be as fine, the other spacings keep a sample per metre + auto const paint = m_terrain_convert_paint ? (m_terrain_convert_spacing < 0.75f ? heightmap::default_paint_samples * 2 : heightmap::default_paint_samples) : 0; + std::size_t converted = 0; + for (auto const &key : m_terrain_selection) + if (m_streamer.spacing(key.first, key.second, m_terrain_convert_spacing, paint)) + ++converted; + if (converted > 0) + { + ground_tiles.clear(); + forget_ground_shapes(); + } + m_terrain_status = format(STR_C("Chunks converted to %s: %zu of %zu"), spacing_label(m_terrain_convert_spacing), converted, m_terrain_selection.size()); +} + +bool editor_mode::pick_terrain_target() +{ + glm::dvec3 world; + if (false == cursor_on_ground(world)) + return false; // nothing under the cursor + m_terrain_target = static_cast(world.y); + m_terrain_status = format(STR_C("Target height: %.2f m"), m_terrain_target); + return true; } void editor_mode::capture_terrain() @@ -1096,19 +3724,11 @@ void editor_mode::capture_terrain() WriteLog("Editor: select a model instance to capture as terrain", logtype::generic); return; } - - // instance world transform, matching the renderer: translate * rotateY * rotateX * rotateZ * scale - glm::dmat4 rootm(1.0); - rootm = glm::translate(rootm, model->location()); - glm::vec3 const angles = model->Angles(); - if (angles.y != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.y)), glm::dvec3(0.0, 1.0, 0.0)); - if (angles.x != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.x)), glm::dvec3(1.0, 0.0, 0.0)); - if (angles.z != 0.0f) rootm = glm::rotate(rootm, glm::radians(static_cast(angles.z)), glm::dvec3(0.0, 0.0, 1.0)); - glm::vec3 const scale = model->Scale(); - rootm = glm::scale(rootm, glm::dvec3(scale)); + if (false == ensure_terrain()) + return; std::vector tris; - gather_submodel_triangles(model->pModel->Root, rootm, tris); + gather_submodel_triangles(model->pModel->Root, instance_matrix(*model), tris); if (tris.empty()) { WriteLog("Editor: selected model has no readable geometry to capture", logtype::generic); @@ -1116,104 +3736,2811 @@ void editor_mode::capture_terrain() } // horizontal bounds of the captured geometry - glm::dvec3 lo(std::numeric_limits::max()); - glm::dvec3 hi(-std::numeric_limits::max()); + glm::dvec2 lo(std::numeric_limits::max()); + glm::dvec2 hi(-std::numeric_limits::max()); for (auto const &t : tris) for (auto const &p : t) { - lo.x = std::min(lo.x, p.x); lo.y = std::min(lo.y, p.y); lo.z = std::min(lo.z, p.z); - hi.x = std::max(hi.x, p.x); hi.y = std::max(hi.y, p.y); hi.z = std::max(hi.z, p.z); + lo = glm::min(lo, glm::dvec2(p.x, p.z)); + hi = glm::max(hi, glm::dvec2(p.x, p.z)); } + triangle_grid const surface(std::move(tris), lo - glm::dvec2(1.0), hi + glm::dvec2(1.0)); - glm::dvec3 const center((lo.x + hi.x) * 0.5, lo.y, (lo.z + hi.z) * 0.5); - double const extent = std::max(hi.x - lo.x, hi.z - lo.z); - int const cells = std::max(1, m_terrain_cells); - float const cellsize = static_cast(std::max(0.1, extent / cells)); - - // sampler: highest captured triangle at (x,z) - auto const sampler = [&tris](double X, double Z, double &OutY) -> bool { - double best = -std::numeric_limits::max(); - bool found = false; - for (auto const &t : tris) - { - double const minx = std::min({t[0].x, t[1].x, t[2].x}); - double const maxx = std::max({t[0].x, t[1].x, t[2].x}); - double const minz = std::min({t[0].z, t[1].z, t[2].z}); - double const maxz = std::max({t[0].z, t[1].z, t[2].z}); - if (X < minx || X > maxx || Z < minz || Z > maxz) - continue; - double y; - if (triangle_height_at(t[0], t[1], t[2], X, Z, y) && (!found || y > best)) - { - best = y; - found = true; - } - } - if (found) - OutY = best; - return found; - }; - - auto terrain = std::make_unique(); - if (!terrain->create(center, cells, cellsize, std::string(m_terrain_texture), sampler)) - { - WriteLog("Editor: terrain capture failed", logtype::generic); - return; - } - m_terrains.push_back(std::move(terrain)); + // the chunks under the model are made where missing, then take its shape wherever it has any + auto const first = heightmap::chunk_at(lo.x, lo.y); + auto const last = heightmap::chunk_at(hi.x, hi.y); + for (int cz = first.second; cz <= last.second; ++cz) + for (int cx = first.first; cx <= last.first; ++cx) + add_chunk_from_ground({cx, cz}, m_terrain_spacing); + m_streamer.reshape(lo, hi, [&](double X, double Z, float &Height) { + double y; + if (false == surface.height_at(X, Z, std::numeric_limits::max(), y)) + return false; + Height = static_cast(y); + return true; + }); + ground_tiles.clear(); + forget_ground_shapes(); // remove the original instance (recorded as a deletion so it can be undone) std::string as_text; model->export_as_text(as_text); push_snapshot(model, EditorSnapshot::Action::Delete, as_text); - nullify_history_pointers(model); - remove_from_hierarchy(model); m_node = nullptr; m_dragging = false; ui()->set_node(nullptr); - simulation::State.delete_model(model); + erase_model(model); +} + +// the ground under a point the cursor landed on. the orthophoto laid over the ground catches the cursor like any +// other surface, so the point can hang over the ground by as much as the orthophoto is lifted, or lie on the flat sheet +// the orthophoto makes where it's not fitted to the ground. what's put in the scenery is to stand on the ground itself +glm::dvec3 editor_mode::placement_on_ground(glm::dvec3 Location) +{ + return ground_at(Location); +} + +glm::dvec3 editor_mode::ground_at(glm::dvec3 Location) const +{ + double constexpr reach = 2.0; // the ground is asked about this far around the point + double constexpr slack = 0.5; // a surface this far over the point still is what the cursor landed on + double constexpr height_tolerance = 50.0; // with nothing there or lower, how far up the ground is looked for + float constexpr terrain_model_radius = 50.0f; // the same models count as ground as for the area fill and the orthophoto + + if (false == std::isfinite(Location.x) || false == std::isfinite(Location.y) || false == std::isfinite(Location.z)) + return Location; + glm::dvec2 const bmin{Location.x - reach, Location.z - reach}; + glm::dvec2 const bmax{Location.x + reach, Location.z + reach}; + std::vector triangles; + gather_ground_triangles(bmin, bmax, true, terrain_model_radius, triangles); + triangle_grid const ground(std::move(triangles), bmin, bmax); + auto const terrains = active_terrains(); + for (double const ceiling : {Location.y + slack, Location.y + height_tolerance}) + { + double y = -std::numeric_limits::max(); + bool found = ground.height_at(Location.x, Location.z, ceiling, y); + for (editor_terrain *terrain : terrains) + { + if (!terrain->contains(Location.x, Location.z)) + continue; + double const h = terrain->height_at(Location.x, Location.z); + if (h <= ceiling && (!found || h > y)) + { + y = h; + found = true; + } + } + if (found) + { + Location.y = y; + break; + } + } + // with no ground found the point stays where the cursor landed + return Location; +} + +// puts every instance of the model the selected node shows on the ground under it +void editor_mode::drop_model_instances() +{ + auto *selected = dynamic_cast(m_node); + if (selected == nullptr || selected->Model() == nullptr) + { + ui()->set_status(STR("Select a model in the scene first"), true); + return; + } + if (selected->radius() >= 50.0f) + { + // it'd be put on top of itself + ui()->set_status(format(STR_C("\"%s\" is large enough to count as ground itself, so there's nothing to put it on"), selected->Model()->NameGet().c_str()), true); + return; + } + std::vector instances; + std::vector points; + int locked = 0; + for (auto *instance : simulation::Instances.sequence()) + { + if (instance == nullptr || instance->Model() != selected->Model()) + continue; + if (instance->from_template() || false == scene::Layers.editable(instance)) + { + // placed by a template, or on a layer which is hidden or locked + ++locked; + continue; + } + instances.push_back(instance); + points.push_back(instance->location()); + } + // the ground the road tools use: terrain shapes, large models and the terrain made in the editor, without the roads and the orthophoto. + // a point with nothing under it comes back with the height it has + auto const heights = ground_heights(points, true); + int moved = 0; + for (std::size_t idx = 0; idx < instances.size(); ++idx) + { + if (std::abs(heights[idx] - points[idx].y) < 0.001) + continue; + auto *instance = instances[idx]; + // one step of the history for each instance + push_snapshot(instance, EditorSnapshot::Action::Move); + auto location = points[idx]; + location.y = heights[idx]; + simulation::Region->erase(instance); + instance->location(location); + simulation::Region->insert(instance); + instance->mark_dirty(); + ++moved; + } + std::string status = format(STR_C("%d of %d copies of \"%s\" put on the ground"), moved, static_cast(instances.size()), selected->Model()->NameGet().c_str()); + if (moved > 0) + status += STR_C("; Ctrl+Z takes them back one at a time"); + if (locked > 0) + status += format(STR_C(". Left alone, placed by a template or on a layer which can't be edited: %d"), locked); + ui()->set_status(status); +} + +void editor_mode::read_georeference() +{ + if (m_georeference_read) + return; + m_georeference_read = true; + m_georeference = false; + m_georeference_line.clear(); + // the name of the scenery is kept in lower case, the file may have capitals in its name + std::filesystem::path file{Global.asCurrentSceneryPath + Global.SceneryFile}; + std::error_code error; + if (false == std::filesystem::exists(file, error)) + { + for (std::filesystem::directory_iterator entry{Global.asCurrentSceneryPath, error}, end; entry != end; entry.increment(error)) + { + std::string name; + try + { + name = entry->path().filename().string(); + } + catch (std::exception const &) + { + continue; + } + std::transform(name.begin(), name.end(), name.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + if (name == Global.SceneryFile) + { + file = entry->path(); + break; + } + } + } + std::ifstream stream(file); + std::string line; + for (int count = 0; count < 200 && std::getline(stream, line); ++count) + { + auto const mark = line.find("//$g"); + if (mark == std::string::npos) + continue; + // Rainsted writes the origin of the scenery as: //$g , in kilometres + std::istringstream words(line.substr(mark + 4)); + std::string system; + double east{0.0}; + double north{0.0}; + if (false == static_cast(words >> system >> east >> north) || system.find("1992") == std::string::npos) + continue; + auto const scale = (east < 10000.0 && north < 10000.0) ? 1000.0 : 1.0; + m_georeference_origin = {north * scale, east * scale}; + m_georeference_line = line.substr(mark); + if (false == m_georeference_line.empty() && m_georeference_line.back() == '\r') + m_georeference_line.pop_back(); + m_georeference = true; + break; + } +} + +void editor_mode::render_map_menu() +{ + if (false == ImGui::BeginMenu(STR_C("Map"))) + return; + if (ImGui::MenuItem(STR_C("Minimap"), "Ctrl+M", m_minimap.is_open())) + m_minimap.toggle(); + ImGui::Separator(); + bool enabled = m_orthophoto.enabled(); + if (ImGui::MenuItem(STR_C("Orthophoto"), nullptr, enabled)) + choose_orthophoto(false == enabled); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Aerial imagery of geoportal.gov.pl under the scenery, laid out by the origin of the scenery")); + // the settings among the base layers in the layers window + if (ImGui::MenuItem(STR_C("Orthophoto settings..."), nullptr, orthophoto_settings_open())) + { + ui()->show_layers(); + m_orthophoto_window = true; + } + ImGui::EndMenu(); +} + +bool editor_mode::orthophoto_settings_open() const +{ + // drawn open in the layers window in this frame or in the last one + return ImGui::GetCurrentContext() != nullptr && ImGui::GetFrameCount() - m_orthophoto_frame <= 1; +} + +void editor_mode::render_base_layers() +{ + auto &stored{EditorSettings.wms_layers()}; + bool save{false}; + // the WMS layers of the user's, the top one first, each drawn over the ones under it + int moved{-1}; + int removed{-1}; + for (int i = 0; i < static_cast(stored.size()); ++i) + { + auto &entry{stored[static_cast(i)]}; + ImGui::PushID(i + 1); + save |= ImGui::Checkbox("##visible", &entry.visible); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Show or hide the layer")); + ImGui::SameLine(); + if (ImGui::TreeNode("##wms", "%s", entry.title.empty() ? entry.layers.c_str() : entry.title.c_str())) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", entry.url.c_str()); + ImGui::TextDisabled(STR_C("Layers: %s"), entry.layers.c_str()); + ImGui::PopTextWrapPos(); + ImGui::SetNextItemWidth(160.0f); + ImGui::SliderFloat(STR_C("Opacity"), &entry.opacity, 0.0f, 1.0f, "%.2f"); + save |= ImGui::IsItemDeactivatedAfterEdit(); + if (false == entry.terms.empty()) + { + ImGui::TextUnformatted(STR_C("Terms of the service:")); + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", entry.terms.c_str()); + ImGui::PopTextWrapPos(); + } + if (i > 0) + { + if (ImGui::SmallButton(STR_C("Up"))) + moved = i - 1; + ImGui::SameLine(); + } + if (i + 1 < static_cast(stored.size())) + { + if (ImGui::SmallButton(STR_C("Down"))) + moved = i; + ImGui::SameLine(); + } + if (ImGui::SmallButton(STR_C("Remove"))) + removed = i; + ImGui::TreePop(); + } + ImGui::PopID(); + } + // a layer swapped with the one under it, or one taken away; the ones of the view go along + if (moved >= 0 && moved + 1 < static_cast(stored.size())) + { + std::swap(stored[static_cast(moved)], stored[static_cast(moved) + 1]); + if (moved + 1 < static_cast(m_wms.size())) + std::swap(m_wms[static_cast(moved)], m_wms[static_cast(moved) + 1]); + save = true; + } + if (removed >= 0) + { + stored.erase(stored.begin() + removed); + if (removed < static_cast(m_wms.size())) + { + m_wms[static_cast(removed)]->enabled(false); + m_wms[static_cast(removed)]->detach_scene(); + m_wms.erase(m_wms.begin() + removed); + } + save = true; + } + if (save) + EditorSettings.save(); + + // the orthophoto at the bottom, its settings opened here from the map menu too + ImGui::PushID("orthophoto"); + bool enabled{m_orthophoto.enabled()}; + if (ImGui::Checkbox("##visible", &enabled)) + choose_orthophoto(enabled); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Aerial imagery of geoportal.gov.pl under the scenery, laid out by the origin of the scenery")); + ImGui::SameLine(); + if (m_orthophoto_window) + { + ImGui::SetNextItemOpen(true); + m_orthophoto_window = false; + } + if (ImGui::TreeNode("##settings", "%s", STR_C("Orthophoto (geoportal.gov.pl)"))) + { + m_orthophoto_frame = ImGui::GetFrameCount(); + render_orthophoto_ui(); + ImGui::TreePop(); + } + ImGui::PopID(); + + // the terrain of the model under the tracks laid, as the terrain panel has it too + if (ImGui::Checkbox(STR_C("Terrain of the model right away while laying"), &m_nmt_state.grow)) + { + EditorSettings.terrain_while_laying(m_nmt_state.grow); + EditorSettings.save(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Where the terrain of the scenery ends, the terrain model is made under the tracks as they're laid, around the cursor from the first point placed; " + "the chunks there are stay as they are. Off, it's made only when asked for")); + + render_wms_adding(); +} + +void editor_mode::render_wms_adding() +{ + auto &adding{m_wms_adding}; + ImGui::PushID("wmsadding"); + if (false == ImGui::TreeNode("##add", "%s", STR_C("Add a WMS layer"))) + { + ImGui::PopID(); + return; + } + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("The address of a WMS service drawing in PUWG 1992 (EPSG:2180). Its tiles are kept in memory only and asked for only around the camera; " + "what the service allows is up to you, its terms are shown below")); + ImGui::PopTextWrapPos(); + ImGui::SetNextItemWidth(-1.0f); + auto const entered{ImGui::InputTextWithHint("##url", "https://...", adding.url.data(), adding.url.size(), ImGuiInputTextFlags_EnterReturnsTrue)}; + std::string const url{adding.url.data()}; + if ((ImGui::Button(STR_C("Read the layers")) || entered) && false == adding.reading.valid() && false == url.empty()) + { + adding.info.reset(); + adding.ticked.clear(); + adding.service = url; + adding.reading = std::async(std::launch::async, [url]() { return editor_orthophoto::describe(url); }); + } + if (adding.reading.valid()) + { + if (adding.reading.wait_for(std::chrono::seconds(0)) == std::future_status::ready) + { + adding.info = adding.reading.get(); + adding.ticked.assign(adding.info->layers.size(), 0); + } + else + ImGui::TextDisabled("%s", STR_C("Reading the capabilities of the service...")); + } + if (adding.info.has_value()) + { + auto const &info{*adding.info}; + ImGui::PushTextWrapPos(0.0f); + if (false == info.error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.45f, 0.4f, 1.0f), STR_C("The service can't be read: %s"), info.error.c_str()); + if (false == info.title.empty()) + ImGui::TextUnformatted(info.title.c_str()); + if (false == info.terms.empty()) + { + ImGui::TextUnformatted(STR_C("Terms of the service:")); + ImGui::TextDisabled("%s", info.terms.c_str()); + } + if (false == info.puwg && false == info.layers.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.2f, 1.0f), "%s", STR_C("The service doesn't draw in PUWG 1992 (EPSG:2180), the editor can't lay it out")); + ImGui::PopTextWrapPos(); + if (false == info.layers.empty()) + { + ImGui::SetNextItemWidth(-1.0f); + ImGui::InputTextWithHint("##filter", STR_C("Filter the layers"), adding.filter.data(), adding.filter.size()); + auto const filter{ToLower(adding.filter.data())}; + ImGui::BeginChild("##layers", ImVec2(0.0f, std::min(200.0f, ImGui::GetFrameHeightWithSpacing() * static_cast(info.layers.size()) + 4.0f)), true); + for (std::size_t i = 0; i < info.layers.size(); ++i) + { + auto const &[name, title]{info.layers[i]}; + auto const label{title.empty() || title == name ? name : title + " (" + name + ")"}; + if (false == filter.empty() && ToLower(label).find(filter) == std::string::npos) + continue; + bool ticked{adding.ticked[i] != 0}; + ImGui::PushID(static_cast(i)); + if (ImGui::Checkbox(label.c_str(), &ticked)) + adding.ticked[i] = ticked ? 1 : 0; + ImGui::PopID(); + } + ImGui::EndChild(); + std::string layers; + for (std::size_t i = 0; i < info.layers.size(); ++i) + if (adding.ticked[i] != 0) + layers += (layers.empty() ? "" : ",") + info.layers[i].first; + auto const ready{info.puwg && false == layers.empty()}; + if (false == ready) + { + ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); + ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f); + } + auto const add{ImGui::Button(STR_C("Add")) && ready}; + if (false == ready) + { + ImGui::PopStyleVar(); + ImGui::PopItemFlag(); + } + if (add) + { + editorSettings::wms_layer entry; + entry.url = adding.service; + entry.layers = layers; + entry.title = info.title.empty() ? layers : info.title; + entry.terms = info.terms; + // on top of the others + EditorSettings.wms_layers().insert(EditorSettings.wms_layers().begin(), entry); + EditorSettings.save(); + adding.info.reset(); + adding.ticked.clear(); + adding.url.fill('\0'); + adding.filter.fill('\0'); + } + } + } + ImGui::TreePop(); + ImGui::PopID(); +} + +void editor_mode::update_wms_layers() +{ + auto const &stored{EditorSettings.wms_layers()}; + // a layer added or removed: the ones of the view made again, as the settings have them + auto same{m_wms.size() == stored.size()}; + for (std::size_t i = 0; same && i < stored.size(); ++i) + same = m_wms[i]->settings().service == stored[i].url && m_wms[i]->settings().layers == stored[i].layers; + if (false == same) + { + for (auto &layer : m_wms) + { + layer->enabled(false); + layer->detach_scene(); + } + m_wms.clear(); + for (auto const &entry : stored) + { + auto layer{std::make_unique()}; + auto config{layer->settings()}; + config.service = entry.url; + config.layers = entry.layers; + config.hires = false; + config.year = 0; + config.in_scene = false; + layer->settings(config); + ground_sources(*layer); + m_wms.push_back(std::move(layer)); + } + } + // laid out by the origin of the scenery and onto the ground as the orthophoto is, around the camera as far as it + load_orthophoto_settings(); + auto const &base{m_orthophoto.settings()}; + auto const placed{base.north != 0.0 || base.east != 0.0}; + for (std::size_t i = 0; i < m_wms.size(); ++i) + { + auto &layer{*m_wms[i]}; + auto config{layer.settings()}; + if (config.north != base.north || config.east != base.east || config.radius != base.radius || config.drape != base.drape || config.lift != base.lift || config.height != base.height || + config.opacity != stored[i].opacity) + { + config.north = base.north; + config.east = base.east; + config.radius = base.radius; + config.drape = base.drape; + config.lift = base.lift; + config.height = base.height; + config.opacity = stored[i].opacity; + layer.settings(config); + } + layer.enabled(stored[i].visible && placed); + layer.update(Camera.Pos); + } +} + +void editor_mode::render_view_menu() +{ + if (false == ImGui::BeginMenu(STR_C("View"))) + return; + if (ImGui::MenuItem(STR_C("Top view, orthographic"), "O", Global.EditorOrtho)) + toggle_ortho(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The view straight down without perspective, as on a map; again for the camera as it was")); + if (ImGui::BeginMenu(STR_C("Tracks in the top view"))) + { + render_top_tracks_choice(false); + ImGui::EndMenu(); + } + if (ImGui::BeginMenu(STR_C("Track colours"))) + { + char const *const names[]{"Plain", "By the radius", "By the speed", "By the grade"}; + for (int i = 0; i < 4; ++i) + if (ImGui::MenuItem(STR_C(names[i]), nullptr, static_cast(m_track_colouring) == i)) + m_track_colouring = static_cast(i); + ImGui::EndMenu(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The tracks of the track mode coloured by their radius, speed or grade, with the legend in the corner")); + ImGui::MenuItem(STR_C("Track labels in the top view"), nullptr, &m_track_labels); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Zoomed in from above, the curves get their radius and length and the switches their name and type, as on a plan; where they'd crowd, some are left out")); + ImGui::MenuItem(STR_C("Show lanes"), nullptr, &m_roadtool.lanes); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The lanes of the roads drawn as the paths the vehicles take")); + if (ImGui::MenuItem(STR_C("Cursor drawn into the picture (streams)"), nullptr, m_draw_cursor)) + { + m_draw_cursor = !m_draw_cursor; + ui_layer::draw_cursor(m_draw_cursor); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The pointer drawn by the editor into the frame instead of the one of the system: seen by those watching a stream\n" + "or a recording of the window (Discord, OBS, the capture of the system), which leave the system pointer out")); + if (ImGui::MenuItem(STR_C("Structure gauge"), nullptr, m_gauge.is_open())) + m_gauge.toggle(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Checks which models enter the structure gauge of the tracks and the clearance over the roads (skrajnia budowli)")); + ImGui::Separator(); + ImGui::MenuItem(STR_C("Weather and time"), nullptr, &m_environment_open); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Time of day, day of the year, visibility, clouds and air temperature, as the scenery is seen in the editor")); + ImGui::EndMenu(); +} + +void editor_mode::render_environment_window() +{ + if (false == m_environment_open) + return; + ImGui::SetNextWindowSize(ImVec2(420.0f * Global.ui_scale, 0.0f), ImGuiCond_FirstUseEver); + if (ImGui::Begin((std::string(STR_C("Weather and time")) + "###environment").c_str(), &m_environment_open, ImGuiWindowFlags_NoCollapse)) + { + // what the setdatetime, setweather and settemperature commands do in the driver mode; the editor doesn't take commands + auto const set_date_time = [](int const Yearday, int const Minute) { + simulation::Time.set_time(Yearday, Minute); + auto const weather{Global.Weather}; + simulation::Environment.compute_season(Yearday); + if (weather != Global.Weather) + { + // HACK: force re-calculation of precipitation, as the command does + Global.Overcast = std::clamp(Global.Overcast - 0.0001f, 0.0f, 2.0f); + } + simulation::Environment.update_moon(); + }; + // the names of the period, season and weather end with a colon, being keys of other lookups + auto const name = [](std::string Text) { + if (false == Text.empty() && Text.back() == ':') + Text.pop_back(); + return Text; + }; + auto const &time{simulation::Time.data()}; + auto minute{time.wHour * 60 + time.wMinute}; + auto const clock{format("%02d:%02d (%s)", time.wHour, time.wMinute, name(Global.Period).c_str())}; + if (ImGui::SliderInt((std::string(STR_C("Time of day")) + "###timeofday").c_str(), &minute, 0, 1439, clock.c_str())) + set_date_time(static_cast(std::round(Global.fMoveLight)), std::clamp(minute, 0, 1439)); + auto yearday{Global.fMoveLight}; + auto const day{format("%.0f (%s)", Global.fMoveLight, name(Global.Season).c_str())}; + if (ImGui::SliderFloat((std::string(STR_C("Day of the year")) + "###dayofyear").c_str(), &yearday, 0.0f, 364.0f, day.c_str())) + set_date_time(static_cast(std::round(std::clamp(yearday, 0.0f, 365.0f))), time.wHour * 60 + time.wMinute); + ImGui::Separator(); + auto visibility{std::log(Global.fFogEnd)}; + auto const fog{format("%.0f m", Global.fFogEnd)}; + if (ImGui::SliderFloat((std::string(STR_C("Visibility")) + "###visibility").c_str(), &visibility, std::log(10.0f), std::log(50000.0f), fog.c_str())) + { + Global.fFogEnd = std::clamp(std::exp(visibility), 10.0f, 50000.0f); + simulation::Environment.compute_weather(); + } + auto overcast{Global.Overcast}; + auto const clouds{format("%.2f (%s)", Global.Overcast, name(Global.Weather).c_str())}; + if (ImGui::SliderFloat((std::string(STR_C("Clouds")) + "###overcast").c_str(), &overcast, 0.0f, 2.0f, clouds.c_str())) + { + Global.Overcast = std::clamp(overcast, 0.0f, 2.0f); + simulation::Environment.compute_weather(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Up to 1 the sky clouds over, past it rain or snow falls, by the air temperature")); + auto temperature{Global.AirTemperature}; + auto const air{format("%.1f °C", Global.AirTemperature)}; + if (ImGui::SliderFloat((std::string(STR_C("Air temperature")) + "###airtemperature").c_str(), &temperature, -35.0f, 40.0f, air.c_str())) + { + Global.AirTemperature = std::clamp(temperature, -35.0f, 40.0f); + simulation::Environment.compute_weather(); + } + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled)); + ImGui::TextWrapped("%s", STR_C("Seen in the editor only; the scenery keeps its own time and weather")); + ImGui::PopStyleColor(); + } + ImGui::End(); +} + +void editor_mode::render_new_scenery_popup() +{ + if (m_newscenery_asked) + { + ImGui::OpenPopup(STR_C("New scenery##restart")); + m_newscenery_asked = false; + } + if (false == ImGui::BeginPopupModal(STR_C("New scenery##restart"), nullptr, ImGuiWindowFlags_AlwaysAutoResize)) + return; + ImGui::TextUnformatted(STR_C("The editor starts again, with the wizard of a new scenery.")); + auto const editsession{false == scene::Layers.empty()}; + if (false == m_history.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.3f, 1.0f), "%s", STR_C("What isn't saved of this scenery is lost.")); + if (editsession && ImGui::Button(STR_C("Save and start the wizard"))) + { + if (save() && false == restart_for_new_scenery()) + ui()->set_status(STR_C("The editor couldn't be started again"), true); + ImGui::CloseCurrentPopup(); + } + if (editsession) + ImGui::SameLine(); + if (ImGui::Button(STR_C("Start the wizard"))) + { + if (false == restart_for_new_scenery()) + ui()->set_status(STR_C("The editor couldn't be started again"), true); + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button(STR_C("Cancel"))) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); +} + +bool editor_mode::restart_for_new_scenery() +{ + return restart_editor(std::string{}); +} + +bool editor_mode::restart_editor(std::string const &Scenery) +{ +#ifdef _WIN32 + _putenv("EU07_EDITOR_SELFTEST="); + wchar_t path[MAX_PATH]; + if (GetModuleFileNameW(nullptr, path, MAX_PATH) == 0) + return false; + std::wstring command{L"\"" + std::wstring{path} + L"\" -edit"}; + if (false == Scenery.empty()) + command += L" \"" + std::filesystem::path(Scenery).wstring() + L"\""; + STARTUPINFOW startup{}; + startup.cb = sizeof(startup); + PROCESS_INFORMATION process{}; + if (false == CreateProcessW(nullptr, command.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startup, &process)) + return false; + CloseHandle(process.hThread); + CloseHandle(process.hProcess); +#else + unsetenv("EU07_EDITOR_SELFTEST"); + char path[4096]; + auto const size{readlink("/proc/self/exe", path, sizeof(path) - 1)}; + if (size <= 0) + return false; + path[size] = '\0'; + char edit[]{"-edit"}; + std::string scenery{Scenery}; + char *arguments[]{path, edit, scenery.empty() ? nullptr : scenery.data(), nullptr}; + posix_spawnattr_t attributes; + posix_spawnattr_init(&attributes); + posix_spawnattr_setflags(&attributes, POSIX_SPAWN_SETSID); + pid_t child; + auto const result{posix_spawn(&child, path, nullptr, &attributes, arguments, environ)}; + posix_spawnattr_destroy(&attributes); + if (result != 0) + return false; +#endif + WriteLog(Scenery.empty() ? std::string{"Editor: started again for a new scenery"} : "Editor: started again with scenery " + Scenery); + Application.queue_quit(true); + return true; +} + +void editor_mode::render_open_scenery_popup() +{ + auto const lower = [](std::string Text) { + std::transform(Text.begin(), Text.end(), Text.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return Text; + }; + if (m_openscenery_asked) + { + m_openscenery_asked = false; + m_openscenery_list.clear(); + m_openscenery_choice.clear(); + std::error_code error; + for (std::filesystem::directory_iterator entry{Global.asCurrentSceneryPath, error}, end; entry != end; entry.increment(error)) + { + std::string name; + try + { + name = entry->path().filename().string(); + } + catch (std::exception const &) + { + continue; + } + std::error_code status; + if (entry->is_regular_file(status) && name.size() > 4 && lower(name.substr(name.size() - 4)) == ".scn" && name.front() != '$') + m_openscenery_list.emplace_back(name); + } + std::sort(m_openscenery_list.begin(), m_openscenery_list.end(), [&](std::string const &A, std::string const &B) { return lower(A) < lower(B); }); + ImGui::OpenPopup(STR_C("Open scenery##restart")); + } + if (false == ImGui::BeginPopupModal(STR_C("Open scenery##restart"), nullptr, ImGuiWindowFlags_AlwaysAutoResize)) + return; + ImGui::TextUnformatted(STR_C("The editor starts again with the scenery chosen below.")); + ImGui::SetNextItemWidth(360.0f); + if (ImGui::IsWindowAppearing()) + ImGui::SetKeyboardFocusHere(); + ImGui::InputTextWithHint("##opensearch", STR_C("search"), m_openscenery_search, sizeof(m_openscenery_search)); + std::string const text{lower(m_openscenery_search)}; + ImGui::BeginChild("##openlist", ImVec2(360.0f, ImGui::GetTextLineHeightWithSpacing() * 14.0f), true); + for (auto const &name : m_openscenery_list) + { + if (false == text.empty() && lower(name).find(text) == std::string::npos) + continue; + if (ImGui::Selectable(name.c_str(), name == m_openscenery_choice, ImGuiSelectableFlags_AllowDoubleClick)) + { + m_openscenery_choice = name; + if (ImGui::IsMouseDoubleClicked(0) && false == restart_editor(name)) + ui()->set_status(STR_C("The editor couldn't be started again"), true); + } + } + ImGui::EndChild(); + auto const editsession{false == scene::Layers.empty()}; + if (false == m_history.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.3f, 1.0f), "%s", STR_C("What isn't saved of this scenery is lost.")); + auto const chosen{false == m_openscenery_choice.empty()}; + if (chosen && editsession && ImGui::Button(STR_C("Save and open"))) + { + if (save() && false == restart_editor(m_openscenery_choice)) + ui()->set_status(STR_C("The editor couldn't be started again"), true); + ImGui::CloseCurrentPopup(); + } + if (chosen && editsession) + ImGui::SameLine(); + if (chosen && ImGui::Button(STR_C("Open"))) + { + if (false == restart_editor(m_openscenery_choice)) + ui()->set_status(STR_C("The editor couldn't be started again"), true); + ImGui::CloseCurrentPopup(); + } + if (chosen) + ImGui::SameLine(); + if (ImGui::Button(STR_C("Cancel"))) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); +} + +void editor_mode::terrain_workspace(bool const Open) +{ + m_terrain_open = Open; + if (false == Open) + m_terrain_tool = terrain_tool::none; + else if (m_streamer.active()) + m_terrain_spacing = m_streamer.manifest().spacing; +} + +editor_mode::texture_offer editor_mode::terrain_texture_offer(char const *None) +{ + return {STR_C("In the palette and on the water of this terrain:"), + [this]() { + std::vector list; + auto const add = [&](std::string const &Name, char const *Note) { + if (Name.empty() || Name == "none" || std::any_of(list.begin(), list.end(), [&](texture_use const &Use) { return Use.name == Name; })) + return; + list.push_back({null_handle, Name, 0, Note}); + }; + for (auto const &layer : m_streamer.manifest().layers) + add(layer.material, STR_C("In the palette of the terrain")); + add(m_streamer.manifest().water_material, STR_C("The default water material")); + for (auto const &body : m_streamer.water()) + add(body.material, STR_C("On a body of water")); + return list; + }, + None, ""}; +} + +void editor_mode::render_terrain_tool_options() +{ + // the orthophoto has its settings among the base layers in the layers window, see render_base_layers() + render_terrain_ui(); +} + +void editor_mode::render_object_menu() +{ + if (ImGui::BeginMenu(STR_C("Objects"))) + { + auto const *selected = dynamic_cast(m_node); + if (ImGui::MenuItem(STR_C("Put all instances of the selected model on the ground"), nullptr, false, selected != nullptr && selected->Model() != nullptr)) + drop_model_instances(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + ImGui::SetTooltip("%s", STR_C("Select a model in the scene. Every instance of the same model file is moved straight up or down\n" + "to the ground under it: terrain, large models and terrain made in the editor.")); + ImGui::EndMenu(); + } +} + +void editor_mode::add_area_fill_point() +{ + // the ground along the ray through the cursor in this frame + glm::dvec3 world; + if (false == cursor_on_ground(world)) + return; // no ground under the cursor + + // the outline gives the fill the height to look for the ground at, and the height of what it finds no ground for + m_fill_points.push_back(placement_on_ground(world)); +} + +void editor_mode::undo_last_area_fill() +{ + // nullify_history_pointers() removes deleted nodes from m_fill_last, so work on a copy + auto const created = std::move(m_fill_last); + m_fill_last.clear(); + + for (TAnimModel *model : created) + { + if (model == nullptr) + continue; + if (m_node == model) + { + m_node = nullptr; + ui()->set_node(nullptr); + } + erase_model(model); + } + m_fill_status = format(STR_C("Removed %zu objects of the last fill"), created.size()); +} + +void editor_mode::run_area_fill() +{ + // limits keeping a single click from freezing the editor for too long + std::size_t constexpr max_objects = 20000; + // large model instances (e.g. terrain tiles) are treated as ground, smaller ones (houses, trees) are not + float constexpr terrain_model_radius = 50.0f; + // ground is searched up to this far above the height interpolated from the outline points, + // so hills inside the outline are found but bridges or roofs high above it are not + double constexpr height_tolerance = 50.0; + + if (m_fill_points.size() < 3) + { + m_fill_status = STR("Outline needs at least 3 points"); + return; + } + + // model package + std::vector package; + if (m_fill_source.kind == model_set_ref::source::manual) + package = m_fill_custom; + else + for (auto const *entry : ui()->nodebank().set_entries(m_fill_source)) + package.push_back(*entry); + package.erase(std::remove_if(package.begin(), package.end(), [](std::string const &Template) { return Template.empty(); }), package.end()); + if (package.empty()) + { + m_fill_status = STR("Selected model package is empty"); + return; + } + + // area bounds + glm::dvec2 bmin(std::numeric_limits::max()); + glm::dvec2 bmax(-std::numeric_limits::max()); + for (auto const &p : m_fill_points) + { + bmin = glm::min(bmin, glm::dvec2(p.x, p.z)); + bmax = glm::max(bmax, glm::dvec2(p.x, p.z)); + } + double const area = polygon_area_xz(m_fill_points); + auto const target = static_cast(std::min(std::round(area / 10000.0 * std::max(0.0f, m_fill_density)), max_objects)); + if (target == 0) + { + m_fill_status = STR("Density too low for this area, nothing to place"); + return; + } + + // scatter points: random samples inside the outline, rejecting the ones closer than the minimal spacing + // to an already accepted point (checked on a hashed grid with cell size == spacing) + double const spacing = std::max(0.0f, m_fill_min_spacing); + std::unordered_map> occupancy; + auto const cell_key = [](std::int64_t const X, std::int64_t const Z) { return (X << 32) ^ (Z & 0xffffffff); }; + std::vector points; + points.reserve(target); + for (std::size_t attempt = 0; attempt < target * 30 && points.size() < target; ++attempt) + { + glm::dvec2 const p(LocalRandom(bmin.x, bmax.x), LocalRandom(bmin.y, bmax.y)); + if (false == point_in_polygon_xz(m_fill_points, p.x, p.y)) + continue; + if (spacing > 0.0) + { + auto const cx = static_cast(std::floor(p.x / spacing)); + auto const cz = static_cast(std::floor(p.y / spacing)); + bool free = true; + for (std::int64_t dz = -1; dz <= 1 && free; ++dz) + for (std::int64_t dx = -1; dx <= 1 && free; ++dx) + { + auto const lookup = occupancy.find(cell_key(cx + dx, cz + dz)); + if (lookup == occupancy.end()) + continue; + for (auto const idx : lookup->second) + if (glm::distance(points[idx], p) < spacing) + { + free = false; + break; + } + } + if (!free) + continue; + occupancy[cell_key(cx, cz)].push_back(points.size()); + } + points.push_back(p); + } + + // ground geometry within the area + std::vector triangles; + gather_ground_triangles(bmin, bmax, m_fill_models_as_ground, terrain_model_radius, triangles); + triangle_grid const ground(std::move(triangles), bmin, bmax); + auto const terrains = active_terrains(); + + auto const rotation_mode = m_fill_random_rotation ? functions_panel::RANDOM : ui()->rot_mode(); + auto const fixed_rotation_value = ui()->rot_val(); + float const scalemin = std::max(0.01f, std::min(m_fill_scale_min, m_fill_scale_max)); + float const scalemax = std::max(0.01f, std::max(m_fill_scale_min, m_fill_scale_max)); + + std::vector created; + created.reserve(points.size()); + std::size_t unsupported = 0; + for (auto const &p : points) + { + // reference height: the outline points, weighted by inverse squared distance + double weights = 0.0, reference = 0.0; + for (auto const &v : m_fill_points) + { + double const w = 1.0 / std::max(1e-6, glm::length2(glm::dvec2(v.x, v.z) - p)); + weights += w; + reference += w * v.y; + } + reference /= weights; + double const ceiling = reference + height_tolerance; + + double y = -std::numeric_limits::max(); + bool found = ground.height_at(p.x, p.y, ceiling, y); + for (editor_terrain *terrain : terrains) + { + if (!terrain->contains(p.x, p.y)) + continue; + double const h = terrain->height_at(p.x, p.y); + if (h <= ceiling && (!found || h > y)) + { + y = h; + found = true; + } + } + if (!found) + { + y = reference; + ++unsupported; + } + + glm::dvec3 const location(p.x, y, p.y); + if (!simulation::Region->point_inside(location)) + continue; + + auto const &src = package[package.size() > 1 ? std::min(package.size() - 1, static_cast(LocalRandom(0.0, static_cast(package.size())))) : 0]; + // NOTE: no names here either, same as with the brush + TAnimModel *cloned = simulation::State.create_model(src, std::string{}, location); + if (!cloned) + continue; + apply_rotation_for_new_node(cloned, rotation_mode, fixed_rotation_value); + if (scalemin != 1.0f || scalemax != 1.0f) + cloned->Scale(static_cast(LocalRandom(scalemin, scalemax))); + created.push_back(cloned); + } + + // a new fill replaces the "last fill" undo set; the previous objects stay in the scene + m_fill_last = std::move(created); + + m_fill_status = format(STR_C("Placed %zu of %zu objects"), m_fill_last.size(), static_cast(target)); + if (points.size() < target) + m_fill_status += STR_C(" (limited by min. spacing)"); + if (unsupported > 0) + m_fill_status += format(STR_C(", without ground under them (height from the outline): %zu"), unsupported); + WriteLog("Editor: area fill - " + m_fill_status, logtype::generic); +} + +void editor_mode::draw_area_fill_outline() const +{ + if (m_fill_points.empty()) + return; + + // same camera-relative view and clean perspective the transform gizmo uses + ImGuiIO const &io = ImGui::GetIO(); + glm::mat4 const view = GfxRenderer->Camera_View_Matrix(); + glm::dvec3 const camerapos = GfxRenderer->Camera_Position(); + float const aspect = io.DisplaySize.y > 0.0f ? io.DisplaySize.x / io.DisplaySize.y : 1.0f; + glm::mat4 const viewprojection = editor_mode::projection_matrix(aspect) * view; + + auto const to_clip = [&](glm::dvec3 const &Point) { return viewprojection * glm::vec4(glm::vec3(Point - camerapos), 1.0f); }; + auto const to_screen = [&](glm::vec4 const &Clip) { + return ImVec2((Clip.x / Clip.w * 0.5f + 0.5f) * io.DisplaySize.x, (0.5f - Clip.y / Clip.w * 0.5f) * io.DisplaySize.y); + }; + float constexpr nearw = 0.1f; + + ImDrawList *drawlist = ImGui::GetBackgroundDrawList(ImGui::GetMainViewport()); + ImU32 const edgecolor = IM_COL32(255, 200, 40, 230); + ImU32 const closingcolor = IM_COL32(255, 200, 40, 110); + + std::size_t const count = m_fill_points.size(); + for (std::size_t i = 0; i < count; ++i) + { + bool const closing = (i + 1 == count); + if (closing && count < 3) + break; + glm::vec4 a = to_clip(m_fill_points[i]); + glm::vec4 b = to_clip(m_fill_points[(i + 1) % count]); + // clip the edge against the near plane, so points behind the camera don't flip across the screen + if (a.w < nearw && b.w < nearw) + continue; + if (a.w < nearw) + a = glm::mix(a, b, (nearw - a.w) / (b.w - a.w)); + else if (b.w < nearw) + b = glm::mix(b, a, (nearw - b.w) / (a.w - b.w)); + drawlist->AddLine(to_screen(a), to_screen(b), closing ? closingcolor : edgecolor, 2.0f); + } + for (std::size_t i = 0; i < count; ++i) + { + glm::vec4 const c = to_clip(m_fill_points[i]); + if (c.w < nearw) + continue; + drawlist->AddCircleFilled(to_screen(c), i == 0 ? 6.0f : 4.0f, i == 0 ? IM_COL32(255, 90, 40, 255) : edgecolor); + } +} + +void editor_mode::render_area_fill() +{ + ImGui::TextDisabled(STR_C("LMB: add outline point Backspace: remove last point")); + double const area = polygon_area_xz(m_fill_points); + // the square sign written as its utf-8 bytes: the game is built without /utf-8 where it has the debug symbols + ImGui::Text(STR_C("Points: %zu Area: %.0f m\xC2\xB2 (%.2f ha)"), m_fill_points.size(), area, area / 10000.0); + if (ImGui::Button(STR_C("Remove last point")) && !m_fill_points.empty()) + m_fill_points.pop_back(); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Clear outline"))) + m_fill_points.clear(); + + ImGui::Separator(); + + // model package: a hand-assembled list, a user-defined set or a node bank group + auto &bank = ui()->nodebank(); + bank.set_combo(STR_C("Model set"), m_fill_source, STR_C("Custom list")); + if (m_fill_source.kind == model_set_ref::source::manual) + bank.manual_list("fillset", m_fill_custom, m_fill_custom_idx); + else + ImGui::TextDisabled(STR_C("%zu templates in set"), bank.set_entries(m_fill_source).size()); + + ImGui::Separator(); + + ImGui::SetNextItemWidth(120.0f); + ImGui::InputFloat(STR_C("Density (objects/ha)"), &m_fill_density, 10.0f, 100.0f, "%.1f"); + m_fill_density = std::max(0.0f, m_fill_density); + ImGui::PushID("areafill"); + if (ImGui::TreeNode(STR_C("More settings"))) + { + ImGui::SetNextItemWidth(120.0f); + ImGui::InputFloat(STR_C("Min. spacing (m)"), &m_fill_min_spacing, 0.5f, 2.0f, "%.1f"); + m_fill_min_spacing = std::max(0.0f, m_fill_min_spacing); + ImGui::SetNextItemWidth(200.0f); + ImGui::DragFloatRange2(STR_C("Scale"), &m_fill_scale_min, &m_fill_scale_max, 0.01f, 0.1f, 5.0f, "min %.2f", "max %.2f"); + ImGui::Checkbox(STR_C("Random rotation"), &m_fill_random_rotation); + if (!m_fill_random_rotation) + ui()->render_rotation_controls(); + ImGui::Checkbox(STR_C("Large models count as ground (terrain tiles)"), &m_fill_models_as_ground); + ImGui::TreePop(); + } + ImGui::PopID(); + + ImGui::Text(STR_C("Estimated objects: %.0f"), std::round(area / 10000.0 * m_fill_density)); + + if (ImGui::Button(STR_C("Fill area"))) + run_area_fill(); + ImGui::SameLine(); + std::string const undolabel = format(STR_C("Undo last fill (%zu)"), m_fill_last.size()); + if (ImGui::Button(undolabel.c_str()) && !m_fill_last.empty()) + undo_last_area_fill(); + + if (!m_fill_status.empty()) + ImGui::TextUnformatted(m_fill_status.c_str()); +} + +glm::vec3 editor_mode::array_size(TAnimModel const &Base) +{ + auto *model = Base.Model(); + if (model == nullptr) + return glm::vec3{0.0f}; + if (m_array.sized == model) + return m_array.size; + // the triangles the other tools take for the ground, left where the model has them + std::vector triangles; + gather_submodel_triangles(model->Root, glm::dmat4{1.0}, triangles); + if (triangles.empty()) + return glm::vec3{0.0f}; // not loaded yet, or nothing to it; it's asked about again the next time + glm::dvec3 low{std::numeric_limits::max()}; + glm::dvec3 high{-std::numeric_limits::max()}; + for (auto const &triangle : triangles) + { + for (auto const &vertex : triangle) + { + low = glm::min(low, vertex); + high = glm::max(high, vertex); + } + } + m_array.sized = model; + m_array.size = glm::vec3{high - low}; + return m_array.size; +} + +glm::dvec3 editor_mode::array_offset(TAnimModel const &Base) +{ + auto const &settings = m_array.settings; + glm::dvec3 offset{0.0}; + if (settings.relative) + offset += glm::dvec3{settings.relative_offset * array_size(Base) * Base.Scale()}; + if (settings.constant) + offset += glm::dvec3{settings.constant_offset}; + return offset; +} + +int editor_mode::array_count(double const Step) const +{ + auto const &settings = m_array.settings; + if (settings.fit == 0) + return std::clamp(settings.count, 1, array_tool::limit); + if (Step < array_tool::minimal_step) + return 1; + // the model, and a copy for each whole offset the length takes + return static_cast(std::min(array_tool::limit, std::floor(std::max(0.0f, settings.length) / Step + 1e-6) + 1.0)); +} + +std::vector> editor_mode::array_placements(TAnimModel &Base) +{ + // a model this large counts as ground itself, and would be put on top of its own copies + float constexpr terrain_model_radius = 50.0f; + + std::vector> places; + auto const &settings = m_array.settings; + auto const offset = array_offset(Base); + auto const count = array_count(glm::length(offset)); + if (count < 2 || glm::length(offset) < array_tool::minimal_step) + return places; + + // the offset goes along the axes of the model, which is turned the way the renderer does it: around y, then x, then z + auto angles = Base.Angles(); + glm::dmat4 turned{1.0}; + turned = glm::rotate(turned, glm::radians(static_cast(angles.y)), glm::dvec3{0.0, 1.0, 0.0}); + turned = glm::rotate(turned, glm::radians(static_cast(angles.x)), glm::dvec3{1.0, 0.0, 0.0}); + turned = glm::rotate(turned, glm::radians(static_cast(angles.z)), glm::dvec3{0.0, 0.0, 1.0}); + auto step = glm::dvec3{turned * glm::dvec4{offset, 0.0}}; + auto location = Base.location(); + places.reserve(count - 1); + for (int idx = 1; idx < count; ++idx) + { + // each copy is turned against the one before it, and leads to the next one the way it faces + location += step; + if (false == simulation::Region->point_inside(location)) + break; // the row ends at the edge of the region, nodes past it are left out of the scene + if (settings.turn != 0.0f) + { + step = glm::rotateY(step, glm::radians(static_cast(settings.turn))); + angles.y = clamp_circular(angles.y + settings.turn, 360.0f); + } + places.emplace_back(location, angles); + } + + if (settings.ground && Base.radius() < terrain_model_radius) + { + // the ground the road tools use. a copy with nothing under it stays at the height the offset gave it + std::vector points; + points.reserve(places.size() + 1); + points.push_back(Base.location()); + for (auto const &place : places) + points.push_back(place.first); + std::vector found; + auto const heights = ground_heights(points, true, &found); + if (found[0]) + { + auto const clearance = points[0].y - heights[0]; + for (std::size_t idx = 0; idx < places.size(); ++idx) + { + if (found[idx + 1]) + places[idx].first.y = heights[idx + 1] + clearance; + } + } + } + return places; +} + +bool editor_mode::array_live() const +{ + // the model the array was made of is still selected, and the array is the last thing done + return m_array.base != nullptr && m_array.base == m_node && false == m_history.empty() && m_history.size() == m_array.step && + m_history.back().action == EditorSnapshot::Action::Array; +} + +void editor_mode::make_array() +{ + auto *base = dynamic_cast(m_node); + if (base == nullptr || false == scene::Layers.editable(base)) + return; + auto const step = glm::length(array_offset(*base)); + if (step < array_tool::minimal_step) + { + m_array.status = STR("The offsets come to nothing, the copies would sit in the model"); + return; + } + if (array_count(step) < 2) + { + m_array.status = (m_array.settings.fit == 0 ? STR("An array of one is the model itself, nothing to make") : STR("The length takes no copy, nothing to make")); + return; + } + + // a single undo step for the whole array, whatever is done to it while it follows the settings + trim_history(); + EditorSnapshot snap; + snap.action = EditorSnapshot::Action::Array; + snap.node_name = base->name(); + snap.position = base->location(); + snap.layer = base->layer(); + m_history.push_back(std::move(snap)); + g_redo.clear(); + m_array.base = base; + m_array.step = m_history.size(); + shape_array(); +} + +void editor_mode::shape_array() +{ + auto *base = m_array.base; + auto &copies = m_history.back().copies; + auto const places = array_placements(*base); + + // the copies there's no place for anymore go + while (copies.size() > places.size()) + { + auto *model = copies.back().model; + copies.pop_back(); + if (model == nullptr) + continue; + erase_model(model); + } + + std::string definition; + for (std::size_t idx = 0; idx < places.size(); ++idx) + { + TAnimModel *model = nullptr; + if (idx < copies.size()) + { + model = copies[idx].model; + m_editor.translate(model, places[idx].first, true); // true: the height is set as well + } + else + { + if (definition.empty()) + base->export_as_text(definition); + // NOTE: no names for the copies, same as with the brush + model = simulation::State.create_model(definition, std::string{}, places[idx].first); + if (model == nullptr) + break; + // the copies go where the model is, rather than to the active layer + scene::Layers.move(model, base->layer()); + EditorSnapshot::array_copy copy; + copy.model = model; + copy.uuid = model->uuid; + copies.push_back(std::move(copy)); + } + model->Angles(places[idx].second); + model->Scale(base->Scale()); + } + + m_array.applied = m_array.settings; + m_array.location = base->location(); + m_array.angles = base->Angles(); + m_array.scale = base->Scale(); + if (copies.size() < places.size()) + m_array.status = format(STR_C("Only %zu of %zu copies could be made"), copies.size(), places.size()); + else if (copies.empty()) + m_array.status = STR("No copies with these settings"); + else + m_array.status = format(STR_C("The model and %zu copies; Ctrl+Z takes the array back"), copies.size()); +} + +void editor_mode::update_array() +{ + if (m_array.base == nullptr) + return; + if (false == array_live()) + { + // once left, the copies are models like any other + m_array.base = nullptr; + return; + } + auto const *base = m_array.base; + if (m_array.settings == m_array.applied && base->location() == m_array.location && base->Angles() == m_array.angles && base->Scale() == m_array.scale) + return; + shape_array(); +} + +void editor_mode::restore_array_snapshot(EditorSnapshot Snapshot, std::vector &Opposite, bool const Undo) +{ + // either way the array is done with following the settings + m_array.base = nullptr; + for (auto © : Snapshot.copies) + { + if (Undo) + { + // NOTE: a copy which was deleted and brought back is another model by now, found by its uuid + auto *model = dynamic_cast(find_node_by_any(copy.model, copy.uuid.to_string(), std::string{})); + copy.model = nullptr; + copy.serialized.clear(); + if (model == nullptr) + continue; // deleted since, and stays that way + // the copy is brought back the way it is now, with whatever was done to it since the array was made + model->export_as_text(copy.serialized); + copy.name = model->name(); + copy.position = model->location(); + copy.rotation = model->Angles(); + copy.scale = model->Scale(); + if (m_node == model) + { + m_node = nullptr; + m_dragging = false; + ui()->set_node(nullptr); + } + erase_model(model); + } + else + { + if (copy.serialized.empty()) + continue; + auto *model = simulation::State.create_model(copy.serialized, copy.name, copy.position); + if (model == nullptr) + continue; + scene::Layers.move(model, Snapshot.layer); + model->Angles(copy.rotation); + model->Scale(copy.scale); + model->uuid = copy.uuid; + add_to_hierarchy(model); + copy.model = model; + } + } + Opposite.push_back(std::move(Snapshot)); +} + +void editor_mode::render_array() +{ + auto &settings = m_array.settings; + auto *selected = dynamic_cast(m_node); + if (selected != nullptr && false == scene::Layers.editable(selected)) + selected = nullptr; + + ImGui::PushID("array"); + ImGui::TextDisabled(STR_C("Copies of the selected model, set out in a row")); + ImGui::RadioButton(STR_C("Fixed count"), &settings.fit, 0); + ImGui::SameLine(); + ImGui::RadioButton(STR_C("Fit length"), &settings.fit, 1); + ImGui::SetNextItemWidth(120.0f); + if (settings.fit == 0) + { + ImGui::InputInt(STR_C("Count"), &settings.count); + settings.count = std::clamp(settings.count, 1, array_tool::limit); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Number of the models in the array, the selected one included")); + } + else + { + ImGui::InputFloat(STR_C("Length (m)"), &settings.length, 1.0f, 10.0f, "%.2f"); + settings.length = std::max(0.0f, settings.length); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("As many copies are made as fit in this length, measured along the row")); + } + + ImGui::SetNextItemWidth(120.0f); + ImGui::DragFloat(STR_C("Turn per copy (deg)"), &settings.turn, 0.1f, -180.0f, 180.0f, "%.2f"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Each copy is turned by this much around the vertical axis against the one before it,\n" + "and the row bends with them into an arc")); + if (ImGui::TreeNode(STR_C("More settings"))) + { + ImGui::Checkbox(STR_C("Relative offset"), &settings.relative); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Distance between the copies as a part of the size of the model, along its axes: x, y (up), z.\n" + "1 along an axis puts the copies end to end")); + if (settings.relative) + { + ImGui::SetNextItemWidth(200.0f); + ImGui::DragFloat3(STR_C("x size"), &settings.relative_offset.x, 0.01f, 0.0f, 0.0f, "%.3f"); + } + ImGui::Checkbox(STR_C("Constant offset"), &settings.constant); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Distance between the copies in metres, along the axes of the model: x, y (up), z.\n" + "With both offsets on the copies are set apart by their sum")); + if (settings.constant) + { + ImGui::SetNextItemWidth(200.0f); + ImGui::DragFloat3("m", &settings.constant_offset.x, 0.05f, 0.0f, 0.0f, "%.3f"); + } + ImGui::Checkbox(STR_C("Follow the ground"), &settings.ground); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The copies are put as high over the ground as the model is, instead of level with it.\n" + "Not for the models large enough to count as ground themselves")); + ImGui::TreePop(); + } + + if (selected != nullptr) + { + auto const size = array_size(*selected) * selected->Scale(); + auto const step = glm::length(array_offset(*selected)); + ImGui::TextDisabled(STR_C("Model %.2f x %.2f x %.2f m, %d in the array, %.2f m apart"), size.x, size.y, size.z, array_count(step), step); + } + + if (array_live()) + { + // NOTE: kept away from the place of the other button, a click too many on which would make the array twice + ImGui::TextDisabled(STR_C("The array follows the settings")); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Done"))) + m_array.base = nullptr; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The copies stay the way they are. Selecting or changing anything else does the same")); + } + else if (selected != nullptr) + { + if (ImGui::Button(STR_C("Make array"))) + make_array(); + } + else + { + ImGui::TextDisabled(STR_C("Select a model to make an array of")); + } + if (false == m_array.status.empty()) + ImGui::TextUnformatted(m_array.status.c_str()); + ImGui::PopID(); +} + +void editor_mode::choose_edit_mode(nodebank_panel::edit_mode const Mode) +{ + // an edit mode is the field of work instead of the tracks, roads or terrain + m_track_window_open = false; + m_roadtool.window = false; + terrain_workspace(false); + if (Mode != nodebank_panel::MODIFY) + m_selection.clear(); + ui()->set_mode(Mode); +} + +editor_mode::work_area editor_mode::current_work_area() const +{ + // the terrain is shown over the tracks, see the tool options window + if (m_terrain_open) + return work_area::terrain; + if (m_track_window_open) + return work_area::tracks; + if (m_roadtool.window) + return work_area::roads; + return work_area::surroundings; +} + +void editor_mode::choose_work_area(work_area const Area) +{ + switch (Area) + { + case work_area::surroundings: + // the edit mode used last + choose_edit_mode(ui()->nodebank().mode); + break; + case work_area::tracks: + terrain_workspace(false); + show_track_tab(m_track_tab); + break; + case work_area::roads: + m_track_window_open = false; + terrain_workspace(false); + m_roadtool.window = true; + break; + case work_area::terrain: + m_track_window_open = false; + m_roadtool.window = false; + terrain_workspace(true); + break; + } +} + +void editor_mode::render_workspaces() +{ + struct area + { + char const *label; + work_area which; + editor_icons::icon picture; + char const *tooltip; + }; + area const areas[] = { + {STR_C("Surroundings"), work_area::surroundings, editor_icons::icon::work_surroundings, STR_C("Models around the line: select, insert, brush, area fill, copy to the node bank")}, + {STR_C("Tracks"), work_area::tracks, editor_icons::icon::work_tracks, STR_C("Tracks and switches, signals, kilometrage and posts along the track, checks of the line")}, + {STR_C("Roads"), work_area::roads, editor_icons::icon::work_roads, STR_C("Roads and junctions, level crossings, the points where the traffic comes and goes")}, + {STR_C("Terrain"), work_area::terrain, editor_icons::icon::work_terrain, STR_C("Heightmap terrain: chunks, sculpting, painting, water, orthophoto")}, + }; + char const *const keys[] = {"F2", "F3", "F4", "F5"}; + auto const current{current_work_area()}; + auto const &style{ImGui::GetStyle()}; + auto *list{ImGui::GetWindowDrawList()}; + // bigger and bold, with the font made for it if there's one, or drawn twice a pixel apart + auto *font{ui_layer::font_bold != nullptr ? ui_layer::font_bold : ImGui::GetFont()}; + auto const fontsize{ui_layer::font_bold != nullptr ? ui_layer::font_bold->FontSize : ImGui::GetFontSize() * 1.25f}; + auto const height{ImGui::GetWindowHeight()}; + auto const padding{style.FramePadding.x * 3.0f}; + // the icon of the field of work before its name + auto const iconside{editor_icons::size()}; + auto const spacing{style.ItemInnerSpacing.x * 1.5f}; + render_toolbar_caption(STR_C("Work modes")); + for (auto const &entry : areas) + { + auto const text{font->CalcTextSizeA(fontsize, FLT_MAX, 0.0f, entry.label)}; + ImVec2 const size{text.x + iconside + spacing + padding * 2.0f, height}; + auto const position{ImGui::GetCursorScreenPos()}; + ImGui::PushID(static_cast(entry.which)); + if (ImGui::InvisibleButton("##area", size)) + choose_work_area(entry.which); + ImGui::PopID(); + auto const hovered{ImGui::IsItemHovered()}; + auto const chosen{entry.which == current}; + ImVec2 const end{position.x + size.x, position.y + size.y}; + if (chosen || hovered) + list->AddRectFilled(position, end, ImGui::GetColorU32(chosen ? ImGuiCol_Header : ImGuiCol_HeaderHovered)); + if (chosen) + list->AddRectFilled(ImVec2(position.x, end.y - 3.0f), end, ImGui::GetColorU32(ImGuiCol_CheckMark)); + ImVec2 const textposition{position.x + padding + iconside + spacing, position.y + (height - text.y) * 0.5f}; + auto const color{ImGui::GetColorU32(chosen ? ImGuiCol_Text : ImGuiCol_TextDisabled)}; + editor_icons::draw(list, entry.picture, ImVec2(position.x + padding + iconside * 0.5f, position.y + height * 0.5f), color); + list->AddText(font, fontsize, textposition, color, entry.label); + if (ui_layer::font_bold == nullptr) + list->AddText(font, fontsize, ImVec2(textposition.x + 1.0f, textposition.y), color, entry.label); + if (hovered) + ImGui::SetTooltip("%s [%s]", entry.tooltip, keys[static_cast(entry.which)]); + ImGui::SameLine(0.0f, style.ItemSpacing.x); + } +} + +void editor_mode::render_toolbar() +{ + // the modes of the gizmo and the top view are over the 3d view, see render_viewport_overlays() + render_toolbar_tools(); +} + +void editor_mode::render_edit_menu() +{ + if (false == ImGui::BeginMenu(STR_C("Edit"))) + return; + if (ImGui::MenuItem(STR_C("Undo"), "Ctrl+Z", false, false == m_history.empty())) + undo_last(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Takes the last change back")); + if (ImGui::MenuItem(STR_C("Redo"), "Ctrl+Y", false, false == g_redo.empty())) + redo_last(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Makes the change taken back again")); + ImGui::Separator(); + auto const selected{m_node != nullptr}; + if (ImGui::MenuItem(STR_C("Delete"), STR_C("Del"), false, selected || m_instance != 0)) + delete_selected(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Deletes what's selected: a model, tracks, a road piece or point, a signal, an include of a scenery template")); + auto const models{dynamic_cast(m_node) != nullptr && ui()->mode() != nodebank_panel::TRACK}; + if (ImGui::MenuItem(STR_C("Copy"), "Ctrl+C", false, models)) + copy_selection(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Copies the selected models with their groups")); + if (ImGui::MenuItem(STR_C("Paste"), "Ctrl+V", false, false == m_clipboard.empty())) + paste_clipboard(cursor_ground()); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Puts the copied models at the cursor, around it as they were around the selected one; Ctrl+RMB in the view pastes them where it was clicked")); + ImGui::Separator(); + if (ImGui::MenuItem(STR_C("Group together"), "Ctrl+G", false, models && selected_nodes().size() > 1)) + group_selection(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The selected models move together from now on; a click on one selects them all. Shift+LMB adds a model to the selection")); + // Delete above may have just dropped the node, selected is from before it + if (ImGui::MenuItem(STR_C("Ungroup"), "Ctrl+Shift+G", false, m_node != nullptr && m_node->group() > 1)) + ungroup_selection(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The models of the group move each by itself again")); + if (ImGui::MenuItem(STR_C("Drop to the ground"), "End", false, selected)) + drop_selection_to_ground(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Puts each selected model, also each model of their groups, down onto the terrain or the object under it")); + if (ImGui::MenuItem(STR_C("Fly to the selected"), "F", false, selected)) + start_focus(m_node, 0.6); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The camera flies to the selected model and looks at it")); + if (ImGui::MenuItem(STR_C("Find a track by its name"), "Ctrl+F")) + { + terrain_workspace(false); + show_track_tab(m_track_window_open ? m_track_tab : track_tab::path); + m_track_search.focus = true; + } + if (ImGui::MenuItem(STR_C("Bend the selected along the track"), "B", false, ui()->mode() != nodebank_panel::TRACK)) + bend_shortcut(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Bends the selected model, e.g. a platform edge or a fence, along the nearest track; the settings are in the inspector")); + ImGui::EndMenu(); +} + +void editor_mode::render_help_menu() +{ + if (false == ImGui::BeginMenu(STR_C("Help"))) + return; + ImGui::MenuItem(STR_C("Keyboard shortcuts"), "F1", &m_shortcuts_open); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The keys of the editor, for each field of work")); + ImGui::MenuItem(STR_C("Tutorial"), nullptr, &m_first_steps_open); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Short lessons: the camera, laying track, curves, the radius at the bends, correcting a curve, joining, switches, switch templates, signals and posts, a whole line step by step, fixing, the gizmo, the grade line, terrain, older sceneries, saving and driving")); + ImGui::EndMenu(); +} + +void editor_mode::first_step_done(first_step const Step) +{ + m_first_steps_done[static_cast(Step)] = true; +} + +void editor_mode::open_kilometrage() +{ + choose_work_area(work_area::tracks); + show_track_tab(track_tab::kilometrage); +} + +namespace +{ + +void tutorial_input(char const *Keys, char const *Text, float const Column) +{ + auto &list{*ImGui::GetWindowDrawList()}; + auto const at{ImGui::GetCursorScreenPos()}; + auto const height{std::round(ImGui::GetTextLineHeight() * 1.45f)}; + auto const gap{std::round(height * 0.2f)}; + float x{0.0f}; + std::istringstream words{Keys}; + for (std::string word; words >> word;) + { + ImVec2 const place{at.x + x, at.y}; + if (word == "+") + { + auto const size{ImGui::CalcTextSize("+")}; + list.AddText(ImVec2(place.x, std::round(at.y + (height - size.y) * 0.5f)), ImGui::GetColorU32(ImGuiCol_TextDisabled), "+"); + x += size.x + gap; + } + else if (word == "LMB" || word == "RMB" || word == "MMB" || word == "wheel" || word == "move") + x += gesture_mouse(list, place, height, word) + gap; + else + x += gesture_key(list, place, height, word) + gap; + } + ImGui::Dummy(ImVec2(std::max(x, Column), height)); + ImGui::SameLine(); + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + std::round((height - ImGui::GetTextLineHeight()) * 0.5f)); + ImGui::TextWrapped("%s", STR_C(Text)); +} + +// a window that grew past the bottom or the right of the screen is moved back onto it +void keep_on_screen(char const *Name) +{ + auto const *window{ImGui::FindWindowByName(Name)}; + if (window == nullptr) + return; + auto const display{ImGui::GetIO().DisplaySize}; + ImVec2 position{window->Pos}; + position.x = std::max(0.0f, std::min(position.x, display.x - window->Size.x)); + position.y = std::max(20.0f, std::min(position.y, display.y - window->Size.y)); + if (position.x != window->Pos.x || position.y != window->Pos.y) + ImGui::SetNextWindowPos(position); +} + +// the strip of the profile: the ground, the track as it lies, the grade line over them with a point of it dragged up and down, +// the grades on both sides of it following +void tutorial_profile_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time) +{ + auto const width{High.x - Low.x}; + auto const height{High.y - Low.y}; + auto const x_of = [&](float const Share) { return Low.x + width * (0.06f + 0.88f * Share); }; + auto const y_of = [&](float const Level) { return Low.y + height * (0.82f - 0.6f * Level); }; + std::vector ground; + for (int i = 0; i <= 60; ++i) + { + auto const share{i / 60.0f}; + ground.emplace_back(x_of(share), y_of(0.25f + 0.35f * std::sin(share * 5.2f + 0.6f) * 0.5f + 0.18f * share)); + } + auto const flags{List.Flags}; + List.Flags &= ~ImDrawListFlags_AntiAliasedFill; + for (std::size_t i = 0; i + 1 < ground.size(); ++i) + List.AddQuadFilled(ground[i], ground[i + 1], ImVec2(ground[i + 1].x, High.y), ImVec2(ground[i].x, High.y), IM_COL32(110, 85, 55, 70)); + List.Flags = flags; + List.AddPolyline(ground.data(), static_cast(ground.size()), IM_COL32(170, 130, 80, 220), 0, 1.5f); + auto const lift{static_cast(0.5 + 0.5 * std::sin(Time * 1.6))}; + std::array const points{ImVec2(x_of(0.0f), y_of(0.32f)), ImVec2(x_of(0.38f), y_of(0.42f)), ImVec2(x_of(0.66f), y_of(0.35f + 0.4f * lift)), ImVec2(x_of(1.0f), y_of(0.55f))}; + List.AddPolyline(points.data(), static_cast(points.size()), IM_COL32(170, 170, 170, 160), 0, 1.0f); + List.AddPolyline(points.data(), static_cast(points.size()), IM_COL32(90, 220, 110, 255), 0, 2.5f); + for (std::size_t i = 0; i < points.size(); ++i) + List.AddCircleFilled(points[i], i == 2 ? 6.0f : 4.5f, i == 2 ? kGestureLit : IM_COL32(250, 210, 80, 255)); + List.AddCircle(points[2], 9.0f, kGestureLit, 0, 1.5f); + for (std::size_t i = 0; i + 1 < points.size(); ++i) + { + auto const grade{-(points[i + 1].y - points[i].y) / (points[i + 1].x - points[i].x) * 40.0f}; + auto const text{std::format("{:+.1f}", std::abs(grade) < 0.05f ? 0.0f : grade)}; + ImVec2 const middle{(points[i].x + points[i + 1].x) * 0.5f, (points[i].y + points[i + 1].y) * 0.5f - ImGui::GetTextLineHeight() - 2.0f}; + List.AddText(ImVec2(middle.x - ImGui::CalcTextSize(text.c_str()).x * 0.5f, middle.y), i == 0 ? IM_COL32(200, 200, 200, 255) : IM_COL32(255, 255, 255, 255), text.c_str()); + } + gesture_mouse(List, ImVec2(points[2].x + 12.0f, points[2].y + 10.0f), height * 0.18f, "LMB"); +} + +// the points of a switch clicked one after another: its start, the ends of its two tracks, the way on, the points along the diverging track +void tutorial_template_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time) +{ + auto const width{High.x - Low.x}; + auto const height{High.y - Low.y}; + auto const at = [&](float const X, float const Y) { return ImVec2(Low.x + width * X, Low.y + height * Y); }; + auto const curve = [&](float const Share) { return at(0.08f + 0.70f * Share, 0.72f - 0.42f * Share * Share); }; + auto const shown{static_cast(std::fmod(static_cast(Time), 10.0f))}; + std::vector line; + for (int i = 0; i <= 24; ++i) + line.push_back(curve(static_cast(i) / 24.0f)); + List.AddLine(at(0.08f, 0.72f), at(0.78f, 0.72f), IM_COL32(150, 150, 150, 130), 3.0f); + List.AddPolyline(line.data(), static_cast(line.size()), IM_COL32(150, 150, 150, 130), ImDrawFlags_None, 3.0f); + std::array const points{at(0.08f, 0.72f), at(0.78f, 0.72f), curve(1.0f), at(0.94f, 0.14f), curve(0.28f), curve(0.5f), curve(0.72f), curve(0.88f)}; + if (shown >= 1) + List.AddLine(points[0], points[1], IM_COL32(255, 255, 255, 230), 1.5f); + if (shown >= 3) + List.AddLine(points[2], points[3], IM_COL32(90, 200, 255, 230), 1.5f); + for (int i = 0; i < static_cast(points.size()) && i <= shown; ++i) + { + List.AddCircleFilled(points[i], 4.0f, i < 4 ? IM_COL32(255, 225, 60, 255) : IM_COL32(120, 255, 120, 255)); + if (i < 4) + List.AddText(ImVec2(points[i].x + 6.0f, points[i].y - 18.0f), IM_COL32(255, 255, 255, 255), std::to_string(i + 1).c_str()); + } + if (shown >= 8) + List.AddPolyline(line.data(), static_cast(line.size()), IM_COL32(255, 90, 200, 255), ImDrawFlags_None, 2.0f); +} + +// the radius of the curve at a bend: the two straights clicked stay, the curve between them grows from sharp to gentle and back +void tutorial_corner_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time) +{ + auto const width{High.x - Low.x}; + auto const height{High.y - Low.y}; + glm::vec2 const from{Low.x + width * 0.04f, Low.y + height * 0.80f}; + glm::vec2 const vertex{Low.x + width * 0.50f, Low.y + height * 0.18f}; + glm::vec2 const to{Low.x + width * 0.96f, Low.y + height * 0.80f}; + auto const point = [](glm::vec2 const Point) { return ImVec2(Point.x, Point.y); }; + List.AddLine(point(from), point(vertex), IM_COL32(150, 150, 150, 130), 1.0f); + List.AddLine(point(vertex), point(to), IM_COL32(150, 150, 150, 130), 1.0f); + List.AddCircleFilled(point(vertex), 4.0f, IM_COL32(255, 255, 255, 255)); + // there and back in 8 s, a moment at each end + auto const cycle{std::fmod(static_cast(Time), 8.0f) / 8.0f}; + auto const swing{std::clamp(1.3f - std::abs(cycle * 2.0f - 1.0f) * 1.6f, 0.0f, 1.0f)}; + auto const share{swing * swing * (3.0f - 2.0f * swing)}; + auto const in{glm::normalize(from - vertex)}; + auto const out{glm::normalize(to - vertex)}; + auto const tangent{glm::mix(0.12f, 0.92f, share) * glm::length(from - vertex)}; + auto const half{std::acos(glm::dot(in, out)) * 0.5f}; + auto const centre{vertex + glm::normalize(in + out) * (tangent / std::cos(half))}; + auto const start{vertex + in * tangent}; + auto const end{vertex + out * tangent}; + auto const begin{std::atan2(start.y - centre.y, start.x - centre.x)}; + auto sweep{std::atan2(end.y - centre.y, end.x - centre.x) - begin}; + while (sweep > glm::pi()) + sweep -= glm::two_pi(); + while (sweep < -glm::pi()) + sweep += glm::two_pi(); + auto const radius{glm::length(start - centre)}; + std::vector line{point(from)}; + for (int i = 0; i <= 32; ++i) + { + auto const angle{begin + sweep * static_cast(i) / 32.0f}; + line.push_back(ImVec2(centre.x + radius * std::cos(angle), centre.y + radius * std::sin(angle))); + } + line.push_back(point(to)); + List.AddPolyline(line.data(), static_cast(line.size()), IM_COL32(230, 190, 90, 255), ImDrawFlags_None, 3.0f); + auto const label{format(STR_C("R %.0f m: %s"), glm::mix(300.0, 6000.0, static_cast(share)), share < 0.5f ? STR_C("a sharp curve, a slow train") : STR_C("a gentle curve, a fast train"))}; + List.AddText(ImVec2(Low.x + (width - ImGui::CalcTextSize(label.c_str()).x) * 0.5f, High.y - ImGui::GetTextLineHeight() - 4.0f), IM_COL32(235, 235, 235, 255), label.c_str()); +} + +// the route of the grade line picked on the map: a click lights up the whole line through the track, Shift and a box only the +// tracks between the outermost ones in it; beside it the strip with a point of the line dragged +void tutorial_route_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time) +{ + auto const split{std::round(Low.x + (High.x - Low.x) * 0.48f)}; + tutorial_profile_sketch(List, ImVec2(split + 6.0f, Low.y), High, Time); + List.AddLine(ImVec2(split + 2.0f, Low.y + 6.0f), ImVec2(split + 2.0f, High.y - 6.0f), ImGui::GetColorU32(ImGuiCol_Border), 1.0f); + auto const width{split - Low.x}; + auto const height{High.y - Low.y}; + auto const at = [&](float const X, float const Y) { return ImVec2(Low.x + width * X, Low.y + height * Y); }; + auto const mix = [](ImVec2 const A, ImVec2 const B, float const T) { return ImVec2(A.x + (B.x - A.x) * T, A.y + (B.y - A.y) * T); }; + auto const ease = [](float const T) { auto const t{std::clamp(T, 0.0f, 1.0f)}; return t * t * (3.0f - 2.0f * t); }; + // the joints of the tracks of the line, and a siding going off it at a switch + std::array const joints{at(0.04f, 0.72f), at(0.18f, 0.64f), at(0.32f, 0.54f), at(0.46f, 0.48f), at(0.60f, 0.46f), at(0.74f, 0.42f), at(0.88f, 0.32f), at(0.98f, 0.24f)}; + int constexpr tracks{7}; + List.AddBezierQuadratic(joints[3], at(0.58f, 0.52f), at(0.80f, 0.66f), IM_COL32(130, 130, 130, 200), 2.0f); + auto const cycle{static_cast(std::fmod(Time, 8.0))}; + bool const boxing{cycle >= 4.0f}; + int first{0}; + int last{tracks - 1}; + bool lit{false}; + ImVec2 cursor; + if (false == boxing) + { + auto const target{mix(joints[4], joints[5], 0.5f)}; + cursor = mix(at(0.75f, 0.92f), target, ease(cycle / 1.0f)); + lit = cycle > 1.3f; + } + else + { + auto const corner{at(0.29f, 0.28f)}; + auto const drag{ease((cycle - 4.6f) / 1.5f)}; + auto const other{mix(corner, at(0.72f, 0.70f), drag)}; + cursor = cycle < 4.6f ? mix(at(0.75f, 0.92f), corner, ease((cycle - 4.0f) / 0.6f)) : other; + if (cycle >= 4.6f && cycle < 6.6f) + { + List.AddRectFilled(corner, other, IM_COL32(90, 175, 255, 40)); + List.AddRect(corner, other, kGestureLit, 0.0f, 0, 1.5f); + } + lit = cycle >= 6.2f; + first = 2; + last = 4; + gesture_key(List, ImVec2(Low.x + 6.0f, Low.y + 6.0f), std::round(ImGui::GetTextLineHeight() * 1.3f), "Shift"); + } + for (int i = 0; i < tracks; ++i) + { + auto const on{lit && i >= first && i <= last}; + List.AddLine(joints[i], joints[i + 1], on ? IM_COL32(90, 220, 110, 255) : IM_COL32(170, 170, 170, 220), on ? 4.0f : 2.0f); + } + for (auto const &joint : joints) + List.AddCircleFilled(joint, 2.5f, IM_COL32(220, 220, 220, 255)); + gesture_mouse(List, ImVec2(cursor.x + 2.0f, cursor.y + 2.0f), std::round(height * 0.16f), "LMB"); + auto const caption{boxing ? STR_C("Shift + a box: between the outermost tracks") : STR_C("LMB on a track: its whole line")}; + List.AddText(ImVec2(Low.x + 6.0f, High.y - ImGui::GetTextLineHeight() - 4.0f), IM_COL32(230, 230, 230, 230), caption); +} + +// a signal put by a track: pressed beside it and dragged along, the arrow tells the way of the trains which see it; then the +// hectometre posts of the line stand up one after the other +void tutorial_signal_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time) +{ + auto const width{High.x - Low.x}; + auto const height{High.y - Low.y}; + auto const at = [&](float const X, float const Y) { return ImVec2(Low.x + width * X, Low.y + height * Y); }; + auto const ease = [](float const T) { auto const t{std::clamp(T, 0.0f, 1.0f)}; return t * t * (3.0f - 2.0f * t); }; + auto const cycle{static_cast(std::fmod(Time, 8.0))}; + // the track seen from above: sleepers and the two rails + auto const middle{at(0.0f, 0.5f).y}; + auto const gauge{height * 0.07f}; + for (int sleeper = 0; sleeper < 40; ++sleeper) + { + auto const x{at(0.02f + 0.025f * static_cast(sleeper), 0.0f).x}; + List.AddLine(ImVec2(x, middle - gauge * 1.6f), ImVec2(x, middle + gauge * 1.6f), IM_COL32(110, 90, 70, 255), 3.0f); + } + List.AddLine(ImVec2(Low.x, middle - gauge), ImVec2(High.x, middle - gauge), IM_COL32(200, 200, 205, 255), 2.0f); + List.AddLine(ImVec2(Low.x, middle + gauge), ImVec2(High.x, middle + gauge), IM_COL32(200, 200, 205, 255), 2.0f); + auto const line{ImGui::GetTextLineHeight()}; + if (cycle < 4.0f) + { + // pressed beside the track, dragged along it + auto const press{at(0.32f, 0.67f)}; + auto const drag{ease((cycle - 1.0f) / 1.4f)}; + ImVec2 const cursor{cycle < 1.0f ? ImVec2(press.x + (1.0f - ease(cycle)) * width * 0.3f, press.y + (1.0f - ease(cycle)) * height * 0.2f) : ImVec2(press.x + width * 0.3f * drag, press.y)}; + if (cycle >= 1.0f) + { + ImVec2 const tip{cursor.x, press.y}; + List.AddLine(press, tip, IM_COL32(255, 210, 60, 255), 3.0f); + if (drag > 0.2f) + List.AddTriangleFilled(ImVec2(tip.x + 8.0f, tip.y), ImVec2(tip.x - 4.0f, tip.y - 7.0f), ImVec2(tip.x - 4.0f, tip.y + 7.0f), IM_COL32(255, 210, 60, 255)); + } + if (cycle >= 2.6f) + { + // the signal by the track: the mast and the head with its lights + auto const foot{at(0.32f, 0.98f)}; + List.AddLine(foot, ImVec2(foot.x, foot.y - height * 0.06f), IM_COL32(200, 200, 200, 255), 3.0f); + ImVec2 const head_low{foot.x - height * 0.04f, foot.y - height * 0.27f}; + ImVec2 const head_high{foot.x + height * 0.04f, foot.y - height * 0.06f}; + List.AddRectFilled(head_low, head_high, IM_COL32(25, 25, 25, 255), height * 0.03f); + List.AddRect(head_low, head_high, IM_COL32(150, 150, 150, 255), height * 0.03f); + std::array const lights{IM_COL32(230, 60, 50, 255), IM_COL32(70, 210, 90, 255), IM_COL32(240, 240, 240, 255)}; + for (std::size_t i = 0; i < lights.size(); ++i) + List.AddCircleFilled(ImVec2(foot.x, head_low.y + height * (0.04f + 0.065f * static_cast(i))), height * 0.025f, lights[i]); + List.AddText(ImVec2(foot.x - height * 0.06f - ImGui::CalcTextSize("S1").x, foot.y - line), IM_COL32(255, 255, 255, 230), "S1"); + } + gesture_mouse(List, ImVec2(cursor.x + 2.0f, cursor.y + 2.0f), std::round(height * 0.16f), "LMB"); + List.AddText(ImVec2(Low.x + 6.0f, Low.y + 4.0f), IM_COL32(230, 230, 230, 230), STR_C("LMB by the track, drag along: the way the trains run")); + return; + } + // the hectometre posts of the line, one after the other + auto const shown{static_cast((cycle - 4.3f) / 0.35f) + 1}; + for (int i = 0; i < std::min(shown, 9); ++i) + { + auto const x{at(0.07f + 0.105f * static_cast(i), 0.0f).x}; + auto const foot{middle - gauge * 3.2f}; + List.AddRectFilled(ImVec2(x - 3.0f, foot - height * 0.14f), ImVec2(x + 3.0f, foot), IM_COL32(240, 240, 240, 255), 1.0f); + auto const text{std::format("12.{}", i + 1)}; + auto const size{ImGui::CalcTextSize(text.c_str())}; + List.AddText(ImVec2(std::round(x - size.x * 0.5f), foot - height * 0.14f - size.y - 1.0f), IM_COL32(255, 220, 120, 255), text.c_str()); + } + List.AddText(ImVec2(Low.x + 6.0f, High.y - line - 4.0f), IM_COL32(230, 230, 230, 230), STR_C("B: posts every 100 m along the whole line at once")); +} + +// a vehicle seen from the side, drawn simply: the body with its windows on two bogies +void tutorial_vehicle(ImDrawList &List, ImVec2 const Low, ImVec2 const High, ImU32 const Body, bool const Locomotive) +{ + auto const width{High.x - Low.x}; + auto const height{High.y - Low.y}; + auto const wheel{height * 0.14f}; + ImVec2 const body_high{High.x, High.y - wheel * 1.6f}; + List.AddRectFilled(Low, body_high, Body, height * 0.12f); + auto const windows{Locomotive ? 2 : 5}; + for (int i = 0; i < windows; ++i) + { + // a locomotive has a window at each end, a coach a row of them + auto window_x{Low.x + width * (0.08f + 0.18f * static_cast(i))}; + if (Locomotive) + window_x = (i == 0 ? Low.x + width * 0.06f : High.x - width * 0.2f); + auto const size{Locomotive ? width * 0.14f : width * 0.12f}; + List.AddRectFilled(ImVec2(window_x, Low.y + height * 0.15f), ImVec2(window_x + size, Low.y + height * 0.42f), IM_COL32(30, 40, 50, 255), 2.0f); + } + for (float const share : {0.22f, 0.78f}) + { + ImVec2 const middle{Low.x + width * share, High.y - wheel}; + List.AddCircleFilled(ImVec2(middle.x - wheel * 1.1f, middle.y), wheel, IM_COL32(40, 40, 40, 255)); + List.AddCircleFilled(ImVec2(middle.x + wheel * 1.1f, middle.y), wheel, IM_COL32(40, 40, 40, 255)); + } +} + +// the trainset tool: a double click on the list puts a vehicle into the train, the train grows on the track, Place and drive +// and it runs off +void tutorial_trainset_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time) +{ + auto const width{High.x - Low.x}; + auto const height{High.y - Low.y}; + auto const at = [&](float const X, float const Y) { return ImVec2(Low.x + width * X, Low.y + height * Y); }; + auto const cycle{static_cast(std::fmod(Time, 9.0))}; + std::array const colours{IM_COL32(200, 60, 50, 255), IM_COL32(60, 120, 70, 255), IM_COL32(70, 100, 160, 255)}; + auto const line{ImGui::GetTextLineHeight()}; + // the list: the side view of each vehicle and its name + for (std::size_t i = 0; i < colours.size(); ++i) + { + auto const slot{static_cast(i)}; + auto const top{0.08f + 0.28f * slot}; + // lit while it's double clicked + if (cycle > 0.8f + 1.4f * slot && cycle < 1.2f + 1.4f * slot) + List.AddRectFilled(at(0.02f, top - 0.02f), at(0.40f, top + 0.24f), IM_COL32(90, 175, 255, 70), 3.0f); + tutorial_vehicle(List, at(0.03f, top), at(0.16f, top + 0.2f), colours[i], i == 0); + List.AddRectFilled(at(0.19f, top + 0.03f), at(0.36f, top + 0.03f + line / height * 0.6f), IM_COL32(220, 220, 220, 200), 2.0f); + List.AddRectFilled(at(0.19f, top + 0.12f), at(0.31f, top + 0.12f + line / height * 0.5f), IM_COL32(150, 150, 150, 160), 2.0f); + } + // the cursor goes down the list double clicking, then to the button + auto const row{std::min(2, static_cast(std::max(0.0f, cycle - 0.4f) / 1.4f))}; + ImVec2 cursor{at(0.30f, 0.16f + 0.28f * static_cast(row))}; + auto const added{std::clamp(static_cast((cycle - 0.8f) / 1.4f) + 1, 0, 3)}; + auto const button_low{at(0.55f, 0.08f)}; + auto const button_high{at(0.95f, 0.30f)}; + if (cycle > 4.6f) + cursor = ImVec2((button_low.x + button_high.x) * 0.5f, (button_low.y + button_high.y) * 0.5f); + bool const pressed{cycle > 5.2f && cycle < 5.6f}; + List.AddRectFilled(button_low, button_high, pressed ? IM_COL32(60, 170, 75, 255) : IM_COL32(50, 140, 64, 255), 4.0f); + auto const label{STR_C("Place and drive")}; + auto const size{ImGui::CalcTextSize(label)}; + List.AddText(ImVec2(std::round((button_low.x + button_high.x - size.x) * 0.5f), std::round((button_low.y + button_high.y - size.y) * 0.5f)), IM_COL32(255, 255, 255, 255), label); + // the track and the train on it, the head on the left; after the button it runs off + auto const rail{at(0.0f, 0.86f).y}; + List.AddLine(ImVec2(at(0.44f, 0.0f).x, rail), ImVec2(High.x, rail), IM_COL32(170, 170, 170, 255), 2.0f); + auto const run{cycle > 5.6f ? (cycle - 5.6f) * (cycle - 5.6f) * width * 0.06f : 0.0f}; + auto const car{width * 0.15f}; + List.PushClipRect(ImVec2(at(0.44f, 0.0f).x, Low.y), High, true); + for (std::size_t i = 0; i < static_cast(added); ++i) + { + auto const front{at(0.46f, 0.0f).x + (car + 3.0f) * static_cast(i) - run}; + tutorial_vehicle(List, ImVec2(front, rail - height * 0.24f), ImVec2(front + car, rail), colours[i], i == 0); + } + List.PopClipRect(); + gesture_mouse(List, ImVec2(cursor.x + 2.0f, cursor.y + 2.0f), std::round(height * 0.16f), "LMB"); + if (cycle < 4.6f) + List.AddText(ImVec2(cursor.x + height * 0.16f, cursor.y), IM_COL32(255, 220, 120, 255), "x2"); +} + +// the terrain model under the tracks: the track laid level sinks onto the ground along, the formation and the slopes under it +void tutorial_terrain_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High, double const Time) +{ + auto const width{High.x - Low.x}; + auto const height{High.y - Low.y}; + auto const phase{static_cast(std::fmod(Time * 0.3, 1.4))}; + auto const settle{std::clamp(phase / 0.8f, 0.0f, 1.0f)}; + auto const eased{settle * settle * (3.0f - 2.0f * settle)}; + auto const ground_at = [&](float const Share) { return 0.45f + 0.22f * std::sin(Share * 4.0f) + 0.08f * std::sin(Share * 13.0f); }; + auto const smooth_at = [&](float const Share) { return 0.45f + 0.18f * std::sin(Share * 4.0f); }; + auto const x_of = [&](float const Share) { return Low.x + width * Share; }; + auto const y_of = [&](float const Level) { return Low.y + height * (0.95f - 0.75f * Level); }; + int constexpr steps{80}; + std::vector ground; + std::vector track; + for (int i = 0; i <= steps; ++i) + { + auto const share{static_cast(i) / steps}; + ground.emplace_back(x_of(share), y_of(ground_at(share))); + track.emplace_back(x_of(share), y_of(0.55f + (smooth_at(share) + 0.04f - 0.55f) * eased)); + } + auto const flags{List.Flags}; + List.Flags &= ~ImDrawListFlags_AntiAliasedFill; + for (int i = 0; i < steps; ++i) + { + std::array const quad{ground[i], ground[i + 1], ImVec2(ground[i + 1].x, High.y), ImVec2(ground[i].x, High.y)}; + List.AddConvexPolyFilled(quad.data(), static_cast(quad.size()), IM_COL32(95, 120, 70, 120)); + } + if (eased > 0.99f) + for (int i = 0; i < steps; ++i) + { + auto const fill{track[i].y < ground[i].y}; + List.AddQuadFilled(track[i], track[i + 1], ground[i + 1], ground[i], fill ? IM_COL32(190, 150, 90, 150) : IM_COL32(60, 45, 30, 150)); + } + List.Flags = flags; + List.AddPolyline(ground.data(), static_cast(ground.size()), IM_COL32(150, 190, 110, 255), 0, 1.5f); + List.AddPolyline(track.data(), static_cast(track.size()), IM_COL32(230, 230, 230, 255), 0, 3.0f); + auto const label{eased > 0.99f ? STR_C("embankment and cutting") : STR_C("the terrain model")}; + List.AddText(ImVec2(Low.x + 6.0f, Low.y + 4.0f), IM_COL32(220, 220, 220, 200), label); +} + +} // namespace + +// a lesson of the tutorial: its clip or sketch, the mouse and the keys it teaches, the steps to try and the button under it +struct editor_mode::tutorial_lesson +{ + // what the button under a lesson does: opens the tool the lesson is about, or switches the view + enum class trial { reading, top, lay, turnout, select, profile, terrain, plan, trainset, signals, station }; + struct input + { + char const *keys; + char const *text; + }; + struct goal + { + first_step step; + char const *text; + }; + char const *title; + char const *clip; + std::vector inputs; + std::vector goals; + trial action; + void (*sketch)(ImDrawList &, ImVec2, ImVec2, double){nullptr}; +}; + +std::vector const &editor_mode::tutorial_lessons() +{ + using trial = tutorial_lesson::trial; + static std::vector const lessons{ + {"Looking around", + "camera", + {{"RMB + move", "Hold the right mouse button and move the mouse to look around"}, + {"RMB + W S A D", "Keep holding the right button and press W S A D to fly around; E takes you up, Q down"}, + {"O", "Switches between the view from above, like a map, and the normal 3D view"}, + {"wheel", "Zooms in and out at the mouse pointer"}, + {"MMB + move", "Press the wheel down and drag to move the view, from above and in 3D"}, + {"Y", "Rides the camera along the track under the mouse pointer, as from a train; Y again gets off. The tools keep working on the way"}, + {"RMB + W S A D", "While riding: W and S drive, Shift faster; A and D jump to the next track on the left or right; Z picks the way at the next switch"}, + {"F", "Flies to what you have selected"}}, + {{first_step::look, "Look around with the right mouse button held"}, {first_step::top, "Press O: from above to 3D, or back"}, {first_step::ride, "Ride along a track with Y"}}, + trial::top}, + {"Laying track", + "lay", + {{"F3", "Opens Tracks, the part of the editor where track is laid"}, + {"L", "Turns laying on"}, + {"LMB", "Click the ground where the track should start, or the end of a track to carry it on"}, + {"LMB", "Click again wherever the track should turn; the curves are made for you. Until you press Enter it is only a line, not a track"}, + {"Enter", "Lays the track along the line. To carry on, click its end"}, + {"Backspace", "Removes the last point you clicked"}, + {"Esc", "Throws away the points not laid yet, but only when pressed twice within 3 seconds: the first press just warns. With no points left, Esc stops laying"}}, + {{first_step::tracks, "Open Tracks (F3)"}, {first_step::lay, "Turn laying on (L)"}, {first_step::laid, "Click a few points and press Enter"}}, + trial::lay}, + {"Curves", + "curves", + {{"LMB", "Every place where the line turns gets a curve, as big as fits. An orange label means the curve breaks the rules for the speed set in the panel"}, + {"Tab", "To copy a curve from the aerial photo: press Tab, then click points along the middle of the curve; it ends at the last one"}, + {"Alt", "Hold it while clicking: the direction jumps in steps of 15 degrees, or to the angle of a switch to a straight track nearby"}, + {"0 1 2 3", "After the first point: type a number and press Enter, and the next straight piece is that many metres long"}, + {"wheel", "The wheel alone zooms, as everywhere"}}, + {{first_step::bend, "Lay a track that turns"}, {first_step::trace, "Press Tab to copy a curve from the photo"}}, + trial::lay}, + {"Radius of the curves at the bends", + nullptr, + {{"LMB", "Where the line turns, two straight pieces meet at a corner no train could take, so the editor rounds it off with a curve"}, + {"R", "The radius tells how big the curve is, in metres: the bigger it is, the gentler the curve and the faster a train can go round it"}, + {"R", "The editor picks the biggest curve that fits between your points. A slight turn gets only a gentle easing in and out; a sharper one gets a real curve, eased in and out, with the outer rail raised, as the railway rules say"}, + {"LMB", "Points too close together leave little room, so the curve comes out smaller. When it no longer meets the rules, its label turns orange: click the points further apart"}, + {"R L h", "The label of a curve: R is the radius, L the length of the easing into it, h how much higher the outer rail is, in millimetres. A slight turn with no real curve reads 2xL"}}, + {{first_step::bend, "Lay a track that turns and read the label of its curve"}}, + trial::lay, + tutorial_corner_sketch}, + {"Correcting a curve", + "plan", + {{"G", "Turns Plan on. Click a curve to see how it is built; its corner point and its size can be dragged in the view"}, + {"LMB + move", "The strip in the panel shows how much the track turns along the way. Drag a flat part of it up or down to change how sharp that curve is"}, + {"LMB + move", "Drag a sloping part sideways: the easing into the curve gets longer or shorter"}, + {"wheel", "Over the strip, the wheel changes it in small steps"}, + {"LMB", "Apply to the scenery: the tracks are laid again as the plan shows"}}, + {{first_step::plan, "Open the plan of a curve"}, {first_step::plan_band, "Change the curve on the strip"}, {first_step::plan_apply, "Apply the change"}}, + trial::plan}, + {"Joining tracks", + "join", + {{"LMB + move", "Press on the loose end of a track (a pink ring while laying) and drag: a new track comes out of it"}, + {"LMB", "Let go on another loose end: a curve joins the two tracks"}, + {"LMB", "While laying, a click on a loose end joins your track to it exactly, with no gap"}, + {"Ctrl + wheel", "Over the other end: makes the joining curve bigger or smaller"}, + {"Shift + wheel", "Over the other end: tries another way of joining"}}, + {{first_step::join, "Join two loose ends"}, {first_step::wheel, "Change the size of the joining curve with Ctrl+wheel"}}, + trial::lay}, + {"Switches", + "switch", + {{"T", "Turns Switch on. The tiles at the top choose what you put in: a switch, a slip switch or a crossing"}, + {"LMB", "Click the track the switch should go into"}, + {"LMB + move", "Press on it and drag: along the track sets which way the switch points, sideways which side it branches off to; let go to lay it"}, + {"LMB + move", "Drag from a straight track onto the track beside it: two switches joining them (a crossover). Over a crossover going the other way you get a double or a scissors one"}, + {"LMB + move", "Drag from a straight across several tracks running alongside and let go on the farthest: a row of switches leading onto each of them (a switch ladder)"}, + {"Esc", "Back to selecting"}}, + {{first_step::turnout, "Put a switch into a track"}}, + trial::turnout}, + {"Switch templates", + nullptr, + {{"T", "In Switch, the Template editor... button: ready switch shapes and your own. Point at a number to see on the drawing what it means"}, + {"LMB", "To copy a switch from the aerial photo: Click off the view..., then click where the switch starts, the end of its straight track, the end of its branching track and one point further along that branch"}, + {"LMB", "Then at least 3 points along the branching track: its shape and size follow them"}, + {"Backspace", "Removes the last point; Esc stops clicking"}, + {"O", "The view from above; the aerial photo is turned on in the Layers panel"}, + {"LMB", "Make the template: the new switch lies on the photo where it was clicked and changes as its numbers change"}}, + {{first_step::template_open, "Open the template editor"}, {first_step::template_clicked, "Make a template by clicking in the view"}}, + trial::turnout, + tutorial_template_sketch}, + {"Signals and posts", + nullptr, + {{"I", "Turns Signals on. Click a kind of signal in its list; it shows the signals this scenery has"}, + {"LMB", "Click beside a track: the signal stands on that side"}, + {"LMB + move", "Press beside the track and drag along it: the signal faces the trains going the way you dragged"}, + {"LMB + move", "Drag a signal that already stands: it slides along its track"}, + {"X", "Turns Kilometrage on. Click a track where you know the km, by a post or a station: the posts every 100 m and the block signals are numbered after it"}, + {"B", "Things beside the track: posts every 100 m along a whole line at once, the W17 signs by the switches (how far a wagon may stand) and trains. The posts take their numbers from the km set with X, or from the km you type in their panel for the place you clicked"}}, + {{first_step::signal, "Put up a signal"}, {first_step::posts, "Put up the posts along a line"}}, + trial::signals, + tutorial_signal_sketch}, + {"A whole line, step by step", + nullptr, + {{"1", "Lay the tracks of the line (L), and the switches (T) where the stations are"}, + {"2", "Kilometrage (X): click a track where you know the km, by a post or at a station. One point is enough: the posts, the stations and the block signals count from it"}, + {"3", "Station (under More): click a switch of the station, then give its name, its code and the number of the line"}, + {"4", "Station signals (under More): Set the signals puts up the entry, exit and shunting signals of the whole station at once"}, + {"5", "Line block (under More): the block signals on the line out of each station, once the stations are set"}, + {"6", "Posts (B): click the line, then Place the posts, every 100 m along all of it"}, + {"7", "Save with Ctrl+S, put a train on the track and drive: the last lesson"}}, + {}, + trial::station}, + {"Selecting and fixing", + "edit", + {{"Esc", "Turns selecting on"}, + {"LMB", "Click a track to select it; its ends show"}, + {"LMB + move", "Drag an end: where tracks meet, the ones beside follow; a loose end pulls out a new track, or with Ctrl moves by itself"}, + {"RMB", "Click a track: a menu of what can be done with it"}, + {"Del", "Deletes what is selected"}, + {"Ctrl + Z", "Undoes the last change; Ctrl+Y brings it back"}, + {"Q W E", "Handles on the track to move, turn, lengthen or bend it: the next lesson"}}, + {{first_step::select, "Select a track"}, {first_step::undo, "Undo a change"}}, + trial::select}, + {"Editing with the gizmo", + "gizmo", + {{"Q", "Shows arrows on the selected track: drag one to move the track"}, + {"W", "Shows rings: drag one to turn the track, to tilt it up or down, or to raise one rail; the tracks joined to it follow"}, + {"E", "Shows handles that make the track longer at its loose end; a curve stays as sharp as it was"}, + {"LMB + move", "With the handles out there are also points that bend the track: drag one and the track bends after it"}, + {"LMB", "Click a point of the track to put the handles there: Q then moves that point only, W turns the whole track around it"}, + {"Ctrl", "Hold it while dragging to move in even steps"}, + {"Esc", "Lets go of the point; the arrow button above the view hides the handles again"}}, + {{first_step::gizmo, "Show the handles with Q, W or E"}, {first_step::vector, "Bend a track by one of its points, or move it with the handles"}}, + trial::select}, + {"The grade line", + nullptr, + {{"P", "Turns Profile on. Click a track: below the view you see how its whole line goes up and down"}, + {"Shift + LMB", "A click adds another track; a box drawn from empty ground takes the tracks inside it. The route runs between the outermost of them, through the switches"}, + {"LMB + move", "Drag a point of the line: the slopes on both sides of it change with it"}, + {"LMB LMB", "Double-click the line to add a point"}, + {"Del", "Removes the chosen point"}, + {"LMB", "Tracks running side by side share one line: change it, press Apply to the scenery, and the tracks beside it (blue) change too"}, + {"LMB", "To give the route open in Profile a line of its own, press Take off the common grade line"}, + {"Ctrl + wheel", "Over the chart: stretches it up and down, so the slopes are easier to see"}, + {"RMB + move", "Over the chart: moves along the line"}}, + {{first_step::profile, "Open the profile of a track"}, {first_step::profile_point, "Move or add a point"}, {first_step::profile_apply, "Apply it: the tracks take the new heights"}}, + trial::profile, + tutorial_route_sketch}, + {"Terrain from the terrain model", + nullptr, + {{"L", "In a new, empty scenery the first L asks whether you want the real ground of the place or a flat plane"}, + {"F5", "Opens Terrain; the real ground (the terrain model) is in its panel"}, + {"LMB", "Step 1, Location: show where the scenery is, with a click on the map or by typing the place"}, + {"LMB", "Step 2, before there are tracks: Load around the camera brings the ground of that spot from geoportal.gov.pl"}, + {"LMB", "Step 2, once there are tracks: Tracks onto the terrain puts the tracks not fitted yet onto the real ground; Terrain under the tracks brings the ground up or down to them; The terrain of the model only loads the ground along them and leaves the tracks alone"}, + {"F3", "The terrain to some of the tracks only: select them (F3), Terrain in the inspector"}, + {"LMB", "A new track partly under the ground: the message above the view has Fit the ground to the track; one click builds the bank or the cutting along it"}, + {"", "A line you shaped by hand in Profile stays as it is, even when all the tracks are fitted anew, unless you tick that the ones edited by hand go too"}, + {"", "Tracks close side by side (under 5.1 m apart) get one common line of heights; a track crossing others where the ground is low on both sides goes under them"}, + {"Ctrl + Z", "Takes the changes back"}}, + {{first_step::terrain, "Open Terrain (F5)"}, {first_step::nmt, "Load the real ground"}}, + trial::terrain, + tutorial_terrain_sketch}, + {"Sceneries made before", + nullptr, + {{"LMB", "Some tracks can't be changed, for example ones put in from a ready .inc file or lying on a locked layer: the Inspector says why"}, + {"T", "Switches laid earlier keep their shape; a template picked for one in the Inspector gives it the ready shape"}, + {"P", "Heights saved by an older editor are read as they were saved"}, + {"Ctrl + S", "Saving writes only what was changed; the rest of the files stays as it was"}}, + {}, + trial::reading}, + {"Saving and driving", + nullptr, + {{"Ctrl + S", "Saves the scenery"}, + {"LMB", "The trainset tool (the button below): click the track where the train should stand"}, + {"LMB LMB", "Double-click a vehicle in the list to add it to the train; click a vehicle in the train to move it, turn it round or take it out"}, + {"LMB", "Place and drive: the train stands on the track and you sit in the cab"}}, + {{first_step::save, "Save the scenery"}, {first_step::drive, "Drive on the new track"}}, + trial::trainset, + tutorial_trainset_sketch}, + }; + return lessons; +} + +bool editor_mode::tutorial_done(tutorial_lesson const &Lesson) const +{ + return false == Lesson.goals.empty() && std::ranges::all_of(Lesson.goals, [this](tutorial_lesson::goal const &Goal) { return m_first_steps_done[static_cast(Goal.step)]; }); +} + +void editor_mode::note_first_steps() +{ + if (ui()->mode() == nodebank_panel::TRACK) + first_step_done(first_step::tracks); + if (m_lay.active) + first_step_done(first_step::lay); + if (ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::path && selected_track() != nullptr) + first_step_done(first_step::select); + if (current_work_area() == work_area::terrain) + first_step_done(first_step::terrain); + if (ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::route && false == m_route.chain.tracks.empty()) + first_step_done(first_step::plan); + if (ui()->mode() == nodebank_panel::TRACK && m_track_gizmo_on) + first_step_done(first_step::gizmo); + if (m_track_gizmo_using || (m_point_drag.moved && m_track_point.valid() && false == editor_track::is_end(m_track_point.kind))) + first_step_done(first_step::vector); + if (m_ride.active()) + first_step_done(first_step::ride); +} + +char const *editor_mode::tutorial_of_tool() +{ + auto const &lessons{tutorial_lessons()}; + // the first of the lessons named whose steps aren't all reached yet + auto const undone = [&](std::initializer_list const Titles) { + for (auto const *title : Titles) + if (auto const found{std::ranges::find_if(lessons, [title](tutorial_lesson const &Lesson) { return std::string_view{title} == Lesson.title; })}; + found != lessons.end() && false == tutorial_done(*found)) + return title; + return ""; + }; + if (m_lay.active) + return undone({"Laying track", "Radius of the curves at the bends", "Curves", "Joining tracks"}); + if (current_work_area() == work_area::terrain) + return undone({"Terrain from the terrain model"}); + if (ui()->mode() != nodebank_panel::TRACK) + return ""; + switch (m_track_tab) + { + case track_tab::turnout: + return undone({m_switch_designer.open ? "Switch templates" : "Switches"}); + case track_tab::profile: + return undone({"The grade line"}); + case track_tab::route: + case track_tab::straights: + return undone({"Correcting a curve"}); + case track_tab::signals: + case track_tab::kilometrage: + return undone({"Signals and posts"}); + case track_tab::station: + case track_tab::station_signals: + case track_tab::line_block: + return undone({"A whole line, step by step"}); + default: + return ""; + } +} + +void editor_mode::follow_tutorial() +{ + auto const &lessons{tutorial_lessons()}; + auto const open_lesson = [&](std::string_view const Title) { + if (auto const found{std::ranges::find_if(lessons, [Title](tutorial_lesson const &Lesson) { return Title == Lesson.title; })}; found != lessons.end()) + m_tutorial_page = static_cast(found - lessons.begin()); + }; + // the lesson of what's being done now, the next one once its steps are reached; opened when that changes, so a page turned by + // hand stays + if (auto const *followed{tutorial_of_tool()}; m_tutorial_followed != followed) + { + m_tutorial_followed = followed; + open_lesson(followed); + } + if (m_tutorial_goto != nullptr) + { + open_lesson(m_tutorial_goto); + m_tutorial_goto = nullptr; + } + m_tutorial_page = std::clamp(m_tutorial_page, 0, static_cast(lessons.size()) - 1); + auto const &lesson{lessons[m_tutorial_page]}; + if (lesson.clip == nullptr) + m_tutorial_clip.close(); + else if (auto const path{std::string{"lang/editor_tutorial/"} + lesson.clip + ".gif"}; path != m_tutorial_clip.path()) + { + m_tutorial_clip.open(path); + m_tutorial_since = ImGui::GetTime(); + } +} + +void editor_mode::render_first_steps() +{ + if (false == m_first_steps_open) + { + if (false == m_tutorial_clip.path().empty()) + m_tutorial_clip.close(); + return; + } + note_first_steps(); + follow_tutorial(); + auto const &lessons{tutorial_lessons()}; + auto const &lesson{lessons[m_tutorial_page]}; + auto const scale{Global.ui_scale}; + ImGui::SetNextWindowPos(ImVec2(ImGui::GetIO().DisplaySize.x * 0.5f, ImGui::GetIO().DisplaySize.y * 0.5f), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f)); + ImGui::SetNextWindowBgAlpha(1.0f); + ImGui::SetNextWindowSizeConstraints(ImVec2(0.0f, 0.0f), ImVec2(FLT_MAX, ImGui::GetIO().DisplaySize.y - 60.0f)); + keep_on_screen("###tutorial"); + if (ImGui::Begin((std::string(STR_C("Tutorial")) + "###tutorial").c_str(), &m_first_steps_open, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize)) + { + // floating it's as wide as the clips; docked it takes the width of its dock, the texts wrapped to it + auto const width{ImGui::IsWindowDocked() ? std::max(160.0f * scale, ImGui::GetContentRegionAvail().x) : 520.0f * scale}; + ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + width); + ImGui::TextDisabled(STR_C("Lesson %d of %d"), m_tutorial_page + 1, static_cast(lessons.size())); + ImGui::SameLine(); + ImGui::TextColored(ImVec4(0.55f, 0.8f, 1.0f, 1.0f), "%s", STR_C(lesson.title)); + render_tutorial_media(lesson, width); + render_tutorial_goals(lesson); + render_tutorial_trial(lesson); + ImGui::PopTextWrapPos(); + ImGui::Separator(); + render_tutorial_pages(); + } + ImGui::End(); +} + +void editor_mode::render_tutorial_media(tutorial_lesson const &Lesson, float const Width) +{ + if (Lesson.clip != nullptr && false == m_tutorial_clip.missing()) + { + // the room of a clip still loading, as the clips are recorded: 520 x 325 + auto const height{Width * 325.0f / 520.0f}; + if (auto const texture{m_tutorial_clip.texture(ImGui::GetTime() - m_tutorial_since)}; texture != 0) + { + auto const shown{Width * static_cast(m_tutorial_clip.height()) / static_cast(std::max(1, m_tutorial_clip.width()))}; + ImGui::Image(static_cast(texture), ImVec2(Width, shown)); + if (ImGui::IsItemClicked()) + m_tutorial_since = ImGui::GetTime(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Click: play it from the start")); + } + else + { + auto const at{ImGui::GetCursorScreenPos()}; + ImGui::GetWindowDrawList()->AddRectFilled(at, ImVec2(at.x + Width, at.y + height), ImGui::GetColorU32(ImGuiCol_FrameBg)); + ImGui::Dummy(ImVec2(Width, height)); + } + } + if (Lesson.sketch != nullptr) + { + auto const at{ImGui::GetCursorScreenPos()}; + ImVec2 const end{at.x + Width, at.y + std::round(Width * 0.36f)}; + auto *list{ImGui::GetWindowDrawList()}; + list->AddRectFilled(at, end, ImGui::GetColorU32(ImGuiCol_FrameBg), 4.0f); + list->PushClipRect(at, end, true); + Lesson.sketch(*list, at, end, ImGui::GetTime()); + list->PopClipRect(); + ImGui::Dummy(ImVec2(Width, end.y - at.y)); + } +} + +void editor_mode::render_tutorial_goals(tutorial_lesson const &Lesson) +{ + ImGui::SeparatorText(STR_C("Mouse and keys")); + for (auto const &entry : Lesson.inputs) + tutorial_input(entry.keys, entry.text, 150.0f * Global.ui_scale); + if (false == Lesson.goals.empty()) + ImGui::SeparatorText(STR_C("Try it")); + for (auto const &entry : Lesson.goals) + { + bool const reached{m_first_steps_done[static_cast(entry.step)]}; + ImGui::TextColored(reached ? ImVec4(0.4f, 0.9f, 0.4f, 1.0f) : ImGui::GetStyleColorVec4(ImGuiCol_Text), "%s", reached ? "[x]" : "[ ]"); + ImGui::SameLine(); + if (reached) + ImGui::TextDisabled("%s", STR_C(entry.text)); + else + ImGui::TextWrapped("%s", STR_C(entry.text)); + } + if (Lesson.action == tutorial_lesson::trial::lay && ui()->mode() == nodebank_panel::TRACK && false == GfxRenderer->Mouse_Hit()) + ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), "%s", STR_C("There is no ground under the mouse: the track will lie flat at height 0. Real ground: F5")); +} + +void editor_mode::render_tutorial_trial(tutorial_lesson const &Lesson) +{ + using trial = tutorial_lesson::trial; + if (Lesson.action == trial::top) + { + if (ImGui::Button(Global.EditorOrtho ? STR_C("3D view (O)") : STR_C("Top view, orthographic (O)"))) + toggle_ortho(); + return; + } + if (Lesson.action == trial::terrain) + { + ImGui::BeginDisabled(current_work_area() == work_area::terrain); + if (ImGui::Button(STR_C("Terrain (F5)"))) + choose_work_area(work_area::terrain); + ImGui::EndDisabled(); + return; + } + // a tool of Tracks: the tab its button opens, and the one beside it which counts as that tool open as well + struct tool_button + { + char const *label; + track_tab tab; + track_tab also; + }; + tool_button button{}; + switch (Lesson.action) + { + case trial::lay: + button = {STR_C("Lay track (L)"), track_tab::lay, track_tab::lay}; + break; + case trial::turnout: + button = {STR_C("The switch tool (T)"), track_tab::turnout, track_tab::turnout}; + break; + case trial::select: + button = {STR_C("The select tool (Esc)"), track_tab::path, track_tab::path}; + break; + case trial::profile: + button = {STR_C("The profile tool (P)"), track_tab::profile, track_tab::profile}; + break; + case trial::signals: + button = {STR_C("The signals tool (I)"), track_tab::signals, track_tab::signals}; + break; + case trial::station: + button = {STR_C("The station tool"), track_tab::station, track_tab::station_signals}; + break; + case trial::plan: + button = {STR_C("The plan tool (G)"), track_tab::straights, track_tab::route}; + break; + case trial::trainset: + button = {STR_C("The trainset tool"), track_tab::lineside, track_tab::lineside}; + break; + default: + return; + } + // the trainset tool is open only with its part of the tab expanded + auto const in_use{ui()->mode() == nodebank_panel::TRACK && (m_track_tab == button.tab || m_track_tab == button.also) && (Lesson.action != trial::trainset || m_vehicle.tab().open)}; + ImGui::BeginDisabled(in_use); + if (ImGui::Button(button.label)) + { + choose_work_area(work_area::tracks); + show_track_tab(button.tab); + if (Lesson.action == trial::trainset) + m_vehicle.tab().expand = true; + } + ImGui::EndDisabled(); +} + +void editor_mode::render_tutorial_pages() +{ + auto const &lessons{tutorial_lessons()}; + auto const count{static_cast(lessons.size())}; + ImGui::BeginDisabled(m_tutorial_page == 0); + if (ImGui::Button(STR_C("< Back"))) + --m_tutorial_page; + ImGui::EndDisabled(); + ImGui::SameLine(); + auto const dot{ImGui::GetFrameHeight()}; + for (int index = 0; index < count; ++index) + { + ImGui::PushID(index); + auto const at{ImGui::GetCursorScreenPos()}; + if (ImGui::InvisibleButton("##lesson", ImVec2(dot * 0.8f, dot))) + m_tutorial_page = index; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C(lessons[index].title)); + ImVec2 const centre{at.x + dot * 0.4f, at.y + dot * 0.5f}; + auto const colour{tutorial_done(lessons[index]) ? IM_COL32(100, 230, 100, 255) : ImGui::GetColorU32(ImGuiCol_TextDisabled)}; + if (index == m_tutorial_page) + ImGui::GetWindowDrawList()->AddCircle(centre, dot * 0.3f, kGestureLit, 0, 2.0f); + ImGui::GetWindowDrawList()->AddCircleFilled(centre, dot * 0.17f, colour); + ImGui::PopID(); + ImGui::SameLine(0.0f, 0.0f); + } + ImGui::SameLine(); + if (m_tutorial_page + 1 < count) + { + if (ImGui::Button(STR_C("Next >"))) + ++m_tutorial_page; + } + else if (ImGui::Button(STR_C("Close"))) + m_first_steps_open = false; + bool show{EditorSettings.first_steps()}; + if (ImGui::Checkbox(STR_C("Show when the editor opens"), &show)) + { + EditorSettings.first_steps(show); + EditorSettings.save(); + } +} + +void editor_mode::render_shortcuts_window() +{ + if (false == m_shortcuts_open) + return; + struct shortcut + { + char const *keys; + char const *action; + }; + struct group + { + char const *title; + std::vector shortcuts; + }; + static std::vector const groups{ + {"General", + {{"F1", "This list of shortcuts"}, + {"Ctrl+S", "Save the scenery"}, + {"Ctrl+Z / Ctrl+Y", "Undo / redo"}, + {"Ctrl+Space", "Unpin all docks for the most of the view, or pin them back"}, + {"F9", "Log"}, + {"PrtScr", "Screenshot"}, + {"Ctrl+Shift+F11", "Export scenery dump"}, + {"F11", "Leave the editor"}, + {"F10", "Quit the simulator"}}}, + {"Fields of work", {{"F2", "Surroundings"}, {"F3", "Tracks"}, {"F4", "Roads"}, {"F5", "Terrain"}}}, + {"Camera", + {{"RMB held, mouse", "Look around"}, + {"RMB held, W S A D", "Fly forwards, back, left, right (arrows in the legacy scheme)"}, + {"RMB held, E / Q", "Fly up / down (Page Up / Page Down in the legacy scheme)"}, + {"F", "Fly to the selected"}, + {"O", "Top view, orthographic"}}}, + {"Ride along the track", + {{"Y", "Ride along the track under the cursor, the tools working on; Y again leaves"}, + {"RMB held, W / S", "Drive; Shift faster, Ctrl+W / Ctrl+Down much faster"}, + {"RMB held, A / D", "Next track on the left / right"}, + {"Z", "The way at the next switch (it isn't thrown)"}, + {"RMB held, E / Q; wheel", "Higher / lower"}, + {"Ctrl+M", "Minimap, stations by their W4"}}}, + {"Gizmo", + {{"Q / W / E", "Translate / rotate / scale; in the tracks they bring the hidden gizmo out"}, + {"R", "Local space"}, + {"Ctrl held while dragging", "Snap to the step set in the gizmo settings"}, + {"Tool options, Gizmo, Off", "Hides the gizmo, so nothing moves by chance; in the tracks it is hidden until Q, W or E"}}}, + {"Surroundings", + {{"1 2 3 4 5", "Select, insert, brush, area fill, copy to bank"}, + {"LMB", "Select a model, or place one in the insert and brush modes"}, + {"Shift+LMB", "Add a model to the selection, or take it out"}, + {"Ctrl+RMB", "Menu of the selection at the cursor"}, + {"Ctrl+C / Ctrl+V", "Copy the selected models / paste them at the cursor"}, + {"Ctrl+G / Ctrl+Shift+G", "Group the selected models / take their group apart"}, + {"End", "Drop the selected onto the ground, each model of a group by itself"}, + {"Del", "Delete the selected"}, + {"B", "Bend the selected along the track"}, + {"Backspace", "Area fill: take the last point of the outline back"}}}, + {"Tracks", + {{"Esc", "Select tool; cancels what's going on first"}, + {"L / T / U", "Lay track / switch / turntable"}, + {"H", "Throw the selected switch over to its other path, in the editor only"}, + {"G (C)", "Plan: a straight, its ends and the middle; a curve, its vertex and radius"}, + {"I / X / B", "Signals / kilometrage / posts along the track"}, + {"P / V / J", "Profile / speed / joints"}, + {"Ctrl+F", "Find a track by its name"}, + {"Shift+LMB", "Add a track to the selection, drag: a box"}, + {"RMB on a track", "What can be done with it"}, + {"K", "Split the selected track at the cursor, a break of the grade at the height of the ground"}, + {"L, LMB, LMB...", "Lay track: each click a bend of the straights, eased with a large curve; Enter lays them; a click on a free end goes on from it"}, + {"Tab while laying", "The points clicked next go along the middle of a curve seen on the photo, which ends at the last one; Tab again: back to the bends"}, + {"Drag from a free end", "Lead a track out of it: a straight, an arc and a straight where a curve is traced (Tab); onto another free end: join the two"}, + {"Ctrl+wheel", "Dragging from a free end: radius"}, + {"Shift+wheel", "Dragging over another free end: another way to join"}, + {"0-9 while laying", "Type the length of the next straight, Enter puts the point"}, + {"Alt held while laying", "The direction in steps of 15 degrees, or 1:9, 1:6.6... to a straight track; the first click with Alt goes onto the axis of the track"}, + {"N", "Parallel track: LMB on a track, then the side and the spacing"}, + {"Shift+LMB on a track in L", "The Parallel tool (N) with it"}, + {"Enter / Backspace", "Laying track: lay the points clicked / take back the last point"}, + {"Esc twice while laying", "Drop the points clicked and not laid yet"}, + {"Del", "Delete the selected tracks"}}}, + {"Plan of a curve", + {{"G, LMB on a curve", "Its design: the vertex and the radius to drag in the view, the curvature in the panel"}, + {"Drag a plateau of the curvature band", "The radius of that arc"}, + {"Drag a ramp sideways", "The length of the transition curve"}, + {"Wheel over the band", "The radius by 5%, a transition by 5 m"}, + {"Apply to the scenery", "Lay the paths by the design; Ctrl+Z takes it back"}}}, + {"Trainset", + {{"B, Trainset, LMB on a track", "Where the train stands"}, + {"LMB LMB on the list", "Adds the vehicle to the train"}, + {"LMB on a vehicle of the train", "Moves it, turns it around or takes it out"}, + {"Place and drive", "Puts the train on the track and gives the cab at once"}}}, + {"Vertical profile", + {{"P, LMB on a track", "The grade line of its whole line, in the strip under the view"}, + {"Shift+LMB box", "The route between the outermost of the tracks, through the switches"}, + {"LMB + move on a point", "Change the grade before and after it"}, + {"LMB LMB on the line", "Add a point"}, + {"Del", "Remove the chosen point"}, + {"Wheel", "Zoom along the line"}, + {"Ctrl+wheel", "Stretch the heights"}, + {"RMB + move", "Move the view along the line"}, + {"Apply in the scenery", "Write the heights into the tracks; Ctrl+Z takes them back"}}}, + {"Roads", + {{"Esc", "Finish the road being built"}, + {"Ctrl held", "Build: straight ahead"}, + {"Shift+LMB", "Select: add a point, or take it out"}, + {"K", "Split the road at the cursor, or make a point there"}, + {"Del", "Delete the selected"}}}, + {"Terrain", {{"LMB", "Sculpt: raise; smooth: even out; chunks: add one"}, {"Shift+LMB", "Sculpt: lower; chunks: delete one"}}}, + }; + ImGui::SetNextWindowSize(ImVec2(620.0f * Global.ui_scale, 560.0f * Global.ui_scale), ImGuiCond_FirstUseEver); + keep_on_screen("###shortcuts"); + // it floats over the view, read better on a solid background + ImGui::SetNextWindowBgAlpha(0.97f); + if (ImGui::Begin((std::string(STR_C("Keyboard shortcuts")) + "###shortcuts").c_str(), &m_shortcuts_open, ImGuiWindowFlags_NoCollapse)) + { + static char filter[64]{}; + ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x * 0.6f); + ImGui::InputTextWithHint("##shortcutfilter", STR_C("Find: a key or what it does"), filter, sizeof(filter)); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Tutorial"))) + m_first_steps_open = true; + auto const lower = [](std::string Text) { + std::transform(Text.begin(), Text.end(), Text.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return Text; + }; + auto const wanted{lower(filter)}; + auto const matches = [&](shortcut const &Item) { return wanted.empty() || lower(STR_C(Item.keys)).find(wanted) != std::string::npos || lower(STR_C(Item.action)).find(wanted) != std::string::npos; }; + auto const picture{std::round(ImGui::GetTextLineHeight() * 1.15f)}; + for (auto const &entry : groups) + { + if (std::none_of(entry.shortcuts.begin(), entry.shortcuts.end(), matches)) + continue; + ImGui::SeparatorText(STR_C(entry.title)); + if (false == ImGui::BeginTable(entry.title, 2, ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp)) + continue; + ImGui::TableSetupColumn("##keys", ImGuiTableColumnFlags_WidthFixed, 250.0f * Global.ui_scale); + ImGui::TableSetupColumn("##action", ImGuiTableColumnFlags_WidthStretch, 1.0f); + for (auto const &item : entry.shortcuts) + { + if (false == matches(item)) + continue; + ImGui::TableNextColumn(); + auto const words{gesture_picture(item.keys)}; + if (false == words.empty()) + { + auto const at{ImGui::GetCursorScreenPos()}; + auto const drawn{gesture_draw(*ImGui::GetWindowDrawList(), at, picture, words, ImGui::GetColorU32(ImGuiCol_Text))}; + ImGui::Dummy(ImVec2(drawn, picture)); + ImGui::SameLine(); + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + std::round((picture - ImGui::GetTextLineHeight()) * 0.5f)); + } + if (words.empty() || false == gesture_keys_only(item.keys)) + ImGui::TextColored(ImGui::GetStyleColorVec4(ImGuiCol_CheckMark), "%s", STR_C(item.keys)); + else + ImGui::NewLine(); + ImGui::TableNextColumn(); + if (false == words.empty()) + ImGui::SetCursorPosY(ImGui::GetCursorPosY() + std::round((picture - ImGui::GetTextLineHeight()) * 0.5f)); + ImGui::TextWrapped("%s", STR_C(item.action)); + } + ImGui::EndTable(); + } + } + ImGui::End(); +} + +bool editor_mode::gizmo_shown() const +{ + return ui()->mode() == nodebank_panel::TRACK ? m_track_gizmo_on : m_gizmo_enabled; +} + +void editor_mode::render_gizmo_options() +{ + if (ImGui::Button(Global.EditorOrtho ? STR_C("3D view (O)") : STR_C("Top view, orthographic (O)"))) + toggle_ortho(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", Global.EditorOrtho ? STR_C("Wheel zooms. Hold the wheel and drag to pan.") : STR_C("Top-down orthographic view")); + if (Global.EditorOrtho) + { + ImGui::SameLine(); + ImGui::SetNextItemWidth(120.0f); + ImGui::SliderFloat(STR_C("Extent (m), wheel / MMB pan"), &Global.EditorOrthoExtent, 5.0f, 50000.0f, "%.0f", ImGuiSliderFlags_Logarithmic); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Wheel zooms. Hold the wheel and drag to pan.")); + ImGui::SameLine(); + render_top_tracks_choice(true); + } + if (ui()->mode() == nodebank_panel::TRACK && m_track_tab != track_tab::path && m_track_tab != track_tab::turnout && m_track_tab != track_tab::turntable && m_track_tab != track_tab::signals && + m_track_tab != track_tab::lineside) + return; + auto &enabled{ui()->mode() == nodebank_panel::TRACK ? m_track_gizmo_on : m_gizmo_enabled}; + int op{enabled ? static_cast(m_gizmo_op) : -1}; + if (segmented("gizmo", op, + {{-1, STR_C("Off"), "The gizmo hidden: the selected things won't move by chance"}, + {static_cast(gizmo_operation::translate), STR_C("Translate (Q)"), "Arrows which move the selected thing"}, + {static_cast(gizmo_operation::rotate), STR_C("Rotate (W)"), "Rings which turn the selected thing"}, + {static_cast(gizmo_operation::scale), STR_C("Scale (E)"), "Handles which scale the selected thing; a track is lengthened"}})) + { + enabled = op >= 0; + if (enabled) + m_gizmo_op = static_cast(op); + } + if (!enabled) + return; + if (terrain_brush() || terrain_clicking()) + { + ImGui::TextDisabled(STR_C("Suspended while editing terrain")); + return; + } + + if (m_gizmo_op != gizmo_operation::scale) // ImGuizmo always scales in local space + ImGui::Checkbox(STR_C("Local space (R)"), &m_gizmo_local); + if (m_gizmo_op == gizmo_operation::translate) + { + ImGui::SetNextItemWidth(120.0f); + ImGui::InputFloat(STR_C("Snap (hold Ctrl)"), &m_gizmo_snap); + if (m_gizmo_snap < 0.0f) + m_gizmo_snap = 0.0f; + } + if (m_instance != 0) + { + auto const located = editor_includes::parameter_with_role(m_include.info, "pos.x") != 0 || editor_includes::parameter_with_role(m_include.info, "pos.y") != 0 || + editor_includes::parameter_with_role(m_include.info, "pos.z") != 0; + ImGui::TextDisabled("%s", false == located ? STR_C("Include selected, no position parameters described") : + false == m_include.placement ? STR_C("Include selected, no gizmo under rotate or scale") : + STR_C("Include selected, axes as its template allows")); + } + else if (!m_node && ui()->mode() != nodebank_panel::TRACK) + ImGui::TextDisabled(STR_C("No node selected")); } void editor_mode::render_gizmo() { + if (straights_active()) + { + render_straight_gizmo(); + return; + } + + if (route_active()) + { + render_route_gizmo(); + return; + } + // the transform gizmo is suppressed while editing terrain, so the brush/chunk tool owns the mouse - if (!m_gizmo_enabled || m_terrain_sculpt || m_chunk_edit) + if (!gizmo_shown() || terrain_brush() || terrain_clicking()) + { + m_gizmo_using = false; + m_track_gizmo_using = false; + return; + } + + if (ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::path && m_track_set.size() >= 2) + { + render_track_set_gizmo(); + return; + } + + if (!m_node && m_instance == 0) { m_gizmo_using = false; return; } - // compact control window: lets the user pick the transform mode without keyboard shortcuts - ImGui::Begin("Gizmo", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoFocusOnAppearing); - int op = static_cast(m_gizmo_op); - ImGui::RadioButton("Translate (Q)", &op, static_cast(gizmo_operation::translate)); - ImGui::SameLine(); - ImGui::RadioButton("Rotate (W)", &op, static_cast(gizmo_operation::rotate)); - ImGui::SameLine(); - ImGui::RadioButton("Scale (E)", &op, static_cast(gizmo_operation::scale)); - m_gizmo_op = static_cast(op); - - if (m_gizmo_op != gizmo_operation::scale) // ImGuizmo always scales in local space - ImGui::Checkbox("Local space (R)", &m_gizmo_local); - if (m_gizmo_op == gizmo_operation::translate) + if (selected_track()) { - ImGui::SetNextItemWidth(120.0f); - ImGui::InputFloat("Snap (hold Ctrl)", &m_gizmo_snap); - if (m_gizmo_snap < 0.0f) - m_gizmo_snap = 0.0f; - } - if (!m_node) - ImGui::TextDisabled("No node selected"); - ImGui::End(); - - if (!m_node) - { - m_gizmo_using = false; + // in the track modes the whole path is moved only while selecting, or the switch in its mode + if (ui()->mode() != nodebank_panel::TRACK || (m_track_tab == track_tab::path && false == m_point_drag.active) || (m_track_tab == track_tab::turnout && selected_track()->eType == tt_Switch)) + render_track_gizmo(); + else + m_track_gizmo_using = false; return; } ImGuizmo::BeginFrame(); - ImGuizmo::SetOrthographic(false); + ImGuizmo::SetOrthographic(Global.EditorOrtho); ImGuiIO const &io = ImGui::GetIO(); ImGuizmo::SetRect(0.0f, 0.0f, io.DisplaySize.x, io.DisplaySize.y); @@ -1226,9 +6553,14 @@ void editor_mode::render_gizmo() // the engine's own projection bakes in reverse-Z (and screen orientation), which ImGuizmo // doesn't expect; rebuild a clean, standard perspective that matches the rendered view. // for the main viewport the engine uses a symmetric frustum with this exact fov/aspect. - float const fovy = glm::radians(Global.FieldOfView / Global.ZoomFactor); float const aspect = io.DisplaySize.y > 0.0f ? io.DisplaySize.x / io.DisplaySize.y : 1.0f; - glm::mat4 const projection = glm::perspective(fovy, aspect, 0.1f, 10000.0f); + glm::mat4 const projection = editor_mode::projection_matrix(aspect); + + if (!m_node) + { + render_include_gizmo(view, projection, camerapos); + return; + } // rotation/scale are only meaningful for instanced models; other node types translate only TAnimModel *model = dynamic_cast(m_node); @@ -1269,15 +6601,20 @@ void editor_mode::render_gizmo() snapvalue = glm::vec3(0.1f); float const *snap = Global.ctrlState && snapvalue.x > 0.0f ? glm::value_ptr(snapvalue) : nullptr; + // the change of this frame alone: a turn is taken from it, not from the angles the whole matrix decomposes into, + // which can't tell a turn of more than 90 degrees about the vertical axis (it comes out as 180 - angle with the + // other two axes flipped, and the model turned back and forth while dragged one way) + glm::mat4 delta(1.0f); ImGuizmo::Manipulate(glm::value_ptr(view), glm::value_ptr(projection), - operation, mode, glm::value_ptr(matrix), nullptr, snap); + operation, mode, glm::value_ptr(matrix), glm::value_ptr(delta), snap); if (ImGuizmo::IsUsing()) { // record a single undo snapshot at the start of the drag if (!m_gizmo_using) { - push_snapshot(m_node, action); + // the models selected along with it and their groups go into the same step of the history + selection_snapshots(action); m_gizmo_using = true; } @@ -1286,9 +6623,13 @@ void editor_mode::render_gizmo() if (operation == ImGuizmo::ROTATE && model) { - // apply the rotation delta relative to the model's current orientation - glm::vec3 const newangles(newrotation[0], newrotation[1], newrotation[2]); - m_editor.rotate(model, newangles - model->Angles(), 0.0f); + // the turn of this frame, small, so its angles decompose with no ambiguity + float deltatranslation[3], deltarotation[3], deltascale[3]; + ImGuizmo::DecomposeMatrixToComponents(glm::value_ptr(delta), deltatranslation, deltarotation, deltascale); + auto const wrapped = [](float Angle) { return Angle - 360.0f * std::floor((Angle + 180.0f) / 360.0f); }; + glm::vec3 const turned{wrapped(deltarotation[0]), wrapped(deltarotation[1]), wrapped(deltarotation[2])}; + m_editor.rotate(model, turned, 0.0f); + selection_follow(glm::dvec3(0.0), turned, model->location()); } else if (operation == ImGuizmo::SCALE && model) { @@ -1298,7 +6639,9 @@ void editor_mode::render_gizmo() { glm::dvec3 const newworldpos = camerapos + glm::dvec3(newtranslation[0], newtranslation[1], newtranslation[2]); // pass Snaptoground == true so the gizmo's Y component is applied (free 3D move) + auto const before{m_node->location()}; m_editor.translate(m_node, newworldpos, true); + selection_follow(m_node->location() - before, glm::vec3(0.0f), m_node->location()); } } else @@ -1307,9 +6650,246 @@ void editor_mode::render_gizmo() } } +void editor_mode::render_include_gizmo(glm::mat4 const &View, glm::mat4 const &Projection, glm::dvec3 const &Camerapos) +{ + m_gizmo_using = false; + if (false == m_include.placement || false == m_include.issue.empty()) + return; + + // parameters of the template the gizmo can drive, as indices of their values; -1 where the template has none + static char const *const positionroles[] = {"pos.x", "pos.y", "pos.z"}; + static char const *const rotationroles[] = {"rot.x", "rot.y", "rot.z"}; + auto const numeric_parameter = [this](char const *Role, double &Value) { + auto const index = editor_includes::parameter_with_role(m_include.info, Role) - 1; + if (index < 0 || index >= static_cast(m_include.values.size())) + return -1; + auto const &text = m_include.values[index]; + char *end = nullptr; + auto const number = std::strtod(text.c_str(), &end); + if (text.empty() || *end != '\0') + return -1; + Value = number; + return index; + }; + int position[3], rotation[3]; + double location[3] = {0.0, 0.0, 0.0}, angles[3] = {0.0, 0.0, 0.0}; + auto positions = 0, rotations = 0; + for (auto axis = 0; axis < 3; ++axis) + { + position[axis] = numeric_parameter(positionroles[axis], location[axis]); + rotation[axis] = numeric_parameter(rotationroles[axis], angles[axis]); + positions += (position[axis] >= 0 ? 1 : 0); + rotations += (rotation[axis] >= 0 ? 1 : 0); + } + if (positions == 0) + return; // nothing tells where the include is + + // only the axes the template has parameters for can be manipulated. a signal stands on the ground by its track: it is moved in + // the plan, at the height it has + // not waited for: a scan started again while a signal is selected would stop the editor for its whole length + if (m_include.info.category == "signal") + signal_scan(false); + auto const signal{signal_template_of(m_include.target) != nullptr}; + auto operation = 0; + for (auto axis = 0; axis < 3; ++axis) + { + if (m_gizmo_op == gizmo_operation::translate && position[axis] >= 0 && false == (signal && axis == 1)) + operation |= (ImGuizmo::TRANSLATE_X << axis); + else if (m_gizmo_op == gizmo_operation::rotate && rotation[axis] >= 0) + operation |= (ImGuizmo::ROTATE_X << axis); + } + if (operation == 0) + return; + auto const translating = (m_gizmo_op == gizmo_operation::translate); + + // the parameters are relative to the origin in effect at the directive + auto const &offset = scene::Layers.instance(m_instance).context.offset; + glm::vec3 const relativepos = glm::vec3(offset + glm::dvec3{location[0], location[1], location[2]} - Camerapos); + float const translation[3] = {relativepos.x, relativepos.y, relativepos.z}; + float const rotationangles[3] = {static_cast(angles[0]), static_cast(angles[1]), static_cast(angles[2])}; + float const scale[3] = {1.0f, 1.0f, 1.0f}; + glm::mat4 matrix(1.0f); + ImGuizmo::RecomposeMatrixFromComponents(translation, rotationangles, scale, glm::value_ptr(matrix)); + + // moving along the axes of the include would need all three of them + ImGuizmo::MODE const mode = (m_gizmo_local && (false == translating || positions == 3)) ? ImGuizmo::LOCAL : ImGuizmo::WORLD; + glm::vec3 const snapvalue(translating ? m_gizmo_snap : 5.0f); + float const *snap = Global.ctrlState && snapvalue.x > 0.0f ? glm::value_ptr(snapvalue) : nullptr; + + // in the signal tool a press on the mast drags the signal along its track: the gizmo, whose up axis runs along the + // mast, gives way over a signal and while one is dragged + auto const yield{ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::signals && false == ImGuizmo::IsUsing() && (m_signal.moving || m_signal.placing || signal_hit() >= 0)}; + ImGuizmo::Enable(false == yield); + ImGuizmo::Manipulate(glm::value_ptr(View), glm::value_ptr(Projection), static_cast(operation), mode, glm::value_ptr(matrix), nullptr, snap); + ImGuizmo::Enable(true); + + if (false == ImGuizmo::IsUsing()) + { + signal_gizmo_end(); + return; + } + m_gizmo_using = true; + signal_gizmo_begin(); + + float newtranslation[3], newrotation[3], newscale[3]; + ImGuizmo::DecomposeMatrixToComponents(glm::value_ptr(matrix), newtranslation, newrotation, newscale); + if (translating) + { + glm::dvec3 const newlocation = Camerapos + glm::dvec3{newtranslation[0], newtranslation[1], newtranslation[2]} - offset; + for (auto axis = 0; axis < 3; ++axis) + { + if (position[axis] >= 0) + m_include.values[position[axis]] = editor_includes::number(newlocation[axis]); + } + } + else + { + if (rotations == 1) + { + // the decomposition spreads a turn of more than a quarter over all three angles; + // with a single axis to turn around the angle is taken straight from the matrix + newrotation[0] = glm::degrees(std::atan2(matrix[1][2], matrix[1][1])); + newrotation[1] = glm::degrees(std::atan2(-matrix[0][2], matrix[0][0])); + newrotation[2] = glm::degrees(std::atan2(matrix[0][1], matrix[0][0])); + } + for (auto axis = 0; axis < 3; ++axis) + { + if (rotation[axis] >= 0) + m_include.values[rotation[axis]] = editor_includes::number(clamp_circular(newrotation[axis])); + } + } + apply_include(); + signal_gizmo_step(); +} + +glm::mat4 editor_mode::projection_matrix(float const Aspect) +{ + if (Global.EditorOrtho) + { + auto const height{Global.EditorOrthoExtent}; + return glm::ortho(-height * Aspect, height * Aspect, -height, height, -10000.0f, 10000.0f); + } + return glm::perspective(glm::radians(Global.FieldOfView / Global.ZoomFactor), Aspect, 0.1f, 10000.0f); +} + +void editor_mode::toggle_ortho() +{ + // the view from above isn't one from the track, the ride ends + m_ride.leave(); + Global.EditorOrtho = !Global.EditorOrtho; + // either way: a scenery made in the wizard opens seen from above already + first_step_done(first_step::top); + if (Global.EditorOrtho) + { + m_ortho_pitch = Camera.Angle.x; + Camera.Angle.x = -M_PI_2; + Camera.Angle.z = 0.0; + } + else + { + Camera.Angle.x = m_ortho_pitch; + ortho_pan_stop(); + camera_above_ground(); + } +} + +void editor_mode::ortho_pan_to(double const Horizontal, double const Vertical) +{ + auto const &io{ImGui::GetIO()}; + if (io.DisplaySize.y <= 0.0f) + return; + auto const dx{Horizontal - m_ortho_pan_cursor.x}; + auto const dy{Vertical - m_ortho_pan_cursor.y}; + m_ortho_pan_cursor = {Horizontal, Vertical}; + auto const scale{Global.EditorOrtho ? 2.0 * static_cast(Global.EditorOrthoExtent) / static_cast(io.DisplaySize.y) : m_pan_metres}; + // looked at from the side, a pixel up the screen is more of the ground than one across + auto const along{Global.EditorOrtho ? 1.0 : 1.0 / std::max(0.25, std::abs(std::sin(static_cast(Camera.Angle.x))))}; + auto const world{RotateY(glm::dvec3{dx * scale, 0.0, dy * scale * along}, static_cast(Camera.Angle.y))}; + m_ride.leave(); + Camera.Pos.x -= world.x; + Camera.Pos.z -= world.z; + Camera.Velocity = {}; + m_focus_active = false; + Global.pCamera = Camera; +} + +void editor_mode::ortho_pan_stop() +{ + m_ortho_pan = false; +} + +void editor_mode::on_scroll(double const Xoffset, double const Yoffset) +{ + if (false == ImGui::GetIO().WantCaptureMouse && track_wheel(Yoffset != 0.0 ? Yoffset : Xoffset)) + return; + // riding along the track the wheel the tools left raises and lowers the camera over the rails + if (m_ride.active()) + { + if (false == ImGui::GetIO().WantCaptureMouse && Yoffset != 0.0) + m_ride.wheel(std::clamp(Yoffset, -2.0, 2.0)); + return; + } + // a swipe on a touchpad goes on after the cursor left the window, with no place for the ray under it + if (ImGui::GetIO().WantCaptureMouse || Yoffset == 0.0 || false == ImGui::IsMousePosValid()) + return; + // a fast swipe on a touchpad can come as one big step + auto const notches{std::clamp(Yoffset, -2.0, 2.0)}; + if (false == Global.EditorOrtho) + { + // in 3D the camera flies along the ray under the cursor, by a share of the distance to what it points at; + // a touchpad sends many small steps, together they come to the same + screen_projection const projection; + glm::dvec3 origin; + glm::dvec3 direction; + projection.ray(ImGui::GetIO().MousePos, origin, direction); + // with nothing under the cursor, the ground under the camera stands for it: the level 0 can lie far below the terrain + std::vector found; + auto const below{ground_heights({Camera.Pos}, false, &found)}; + auto const ground{found[0] != 0 ? below[0] : 0.0}; + auto const height{std::max(2.0, std::abs(Camera.Pos.y - ground))}; + glm::dvec3 level; + auto distance{std::min(GfxRenderer->Mouse_Hit() ? glm::length(GfxRenderer->Mouse_Position()) : projection.on_level(ImGui::GetIO().MousePos, ground, level) ? glm::distance(level, origin) : 2.0 * height, 20000.0)}; + // backing away from a point on the horizon would throw the camera kilometres up + if (notches < 0.0) + distance = std::min(distance, std::max(100.0, 4.0 * height)); + auto step{distance * (1.0 - std::pow(0.85, notches))}; + // no nearer than 2 m to the point, not through it + if (notches > 0.0) + step = std::max(0.0, std::min(step, distance - 2.0)); + // a point under the cursor which isn't a number, as one on a broken path, moves the camera nowhere + if (false == std::isfinite(step) || glm::any(glm::isnan(direction)) || glm::any(glm::isinf(direction))) + return; + Camera.Pos += direction * step; + Global.pCamera = Camera; + return; + } + auto const before{Global.EditorOrthoExtent}; + auto const after{std::clamp(before * static_cast(std::pow(0.85, notches)), 5.0f, 50000.0f)}; + screen_projection const projection; + glm::dvec3 origin; + glm::dvec3 direction; + projection.ray(ImGui::GetIO().MousePos, origin, direction); + auto const scale{static_cast(after) / static_cast(before)}; + Camera.Pos.x = origin.x + (Camera.Pos.x - origin.x) * scale; + Camera.Pos.z = origin.z + (Camera.Pos.z - origin.z) * scale; + Global.EditorOrthoExtent = after; + Global.pCamera = Camera; +} + void editor_mode::update_camera(double const Deltatime) { Camera.Update(); + if (Global.EditorOrtho) + { + Camera.Angle.x = -M_PI_2; + Camera.Angle.z = 0.0; + } + // riding along the track the camera goes where the track takes it, a framing doesn't fly it off + if (m_ride.active()) + { + m_focus_active = false; + m_ride.advance(Camera, Deltatime, m_input.mouse.button(GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS); + } // focus animation runs after Camera.Update() so it overrides any residual velocity/rotation; // it smoothly drives both position and orientation toward the framed object @@ -1341,13 +6921,69 @@ void editor_mode::update_camera(double const Deltatime) // reset window state (will be set again if UI requires it) Global.CabWindowOpen = false; + // a camera at no finite place, as a zoom or a framing aimed at a broken path could put it, draws nothing sane and can + // stall the graphics card: it goes back to where it last was + auto const number = [](auto const &Vector) { return false == glm::any(glm::isnan(Vector)) && false == glm::any(glm::isinf(Vector)); }; + if (number(Camera.Pos) && number(Camera.Angle)) + { + m_camera_finite_pos = Camera.Pos; + m_camera_finite_angle = Camera.Angle; + m_camera_finite = true; + } + else if (m_camera_finite) + { + WriteLog("Editor: the camera went to no finite place, back where it was", logtype::generic); + Camera.Pos = m_camera_finite_pos; + Camera.Angle = m_camera_finite_angle; + Camera.Velocity = glm::dvec3(0.0); + m_focus_active = false; + } + // publish camera back to global copy Global.pCamera = Camera; } +glm::dvec3 editor_mode::camera_look() const +{ + return {-std::sin(Camera.Angle.y), 0.0, -std::cos(Camera.Angle.y)}; +} + +void editor_mode::ride_enter() +{ + // the track under the cursor, else the one nearest the ground under it, else the one nearest the camera + auto under{track_under_cursor(nullptr, 30.0f)}; + auto *track{under.track}; + auto path{under.path}; + auto point{under.point}; + if (track == nullptr && ImGui::IsMousePosValid()) + { + point = std::as_const(*this).cursor_ground(); + track = kilometrage::track_near(point, 30.0, path); + } + if (track == nullptr) + { + point = Camera.Pos; + track = kilometrage::track_near(point, 200.0, path); + } + if (false == m_ride.enter(track, path, point, camera_look(), true)) + ui()->set_status(STR_C("No track nearby"), true); +} + void editor_mode::enter() { m_statebackup = {Global.pCamera, FreeFlyModeFlag, Global.ControlPicking}; + // the editor changes the tracks, their sleepers are worked out as they're needed + track_sleepers::lay_in_background(false); + // the editor may remove the tracks and the vehicles the recording refers to: it ends here + simulation::Blackbox.close(); + // the cursor drawn into the picture is the editor's: back on when it comes back, if it was chosen + ui_layer::draw_cursor(m_draw_cursor); + + if (simulation::Region != nullptr) + { + // the editor works with geometry of the whole scenery, including the parts of binary terrain which weren't needed so far + simulation::Region->load_terrain(); + } Camera = Global.pCamera; @@ -1366,24 +7002,119 @@ void editor_mode::enter() } } + if (Global.editor_session && false == m_opened_at_track) + { + m_opened_at_track = true; + auto const saved{scene::Layers.empty() ? std::vector{} : scene::Layers.marked(scene::layer_handle{1}, "//$c")}; + if (false == saved.empty()) + { + std::istringstream values(saved.front()); + glm::dvec3 position{0.0}; + glm::vec3 angle{0.0f}; + if (values >> position.x >> position.y >> position.z >> angle.x >> angle.y) + { + Camera.Pos = position; + Camera.Angle = angle; + Camera.m_owner = nullptr; + FreeFlyModeFlag = true; + Global.pCamera = Camera; + m_saved_camera = {position, angle}; + WriteLog("Editor: camera where it was at the last save"); + } + } + for (auto *track : simulation::Paths.sequence()) + { + if (m_saved_camera.has_value() || track == nullptr || track->m_editorremoved || track->m_paths.empty()) + continue; + auto const &path{track->m_paths.front()}; + auto const start{path.points[segment_data::point::start]}; + auto const end{path.points[segment_data::point::end]}; + auto const centre{0.5 * (start + end)}; + glm::dvec3 along{end.x - start.x, 0.0, end.z - start.z}; + along = glm::length(along) > 1e-6 ? glm::normalize(along) : glm::dvec3{0.0, 0.0, 1.0}; + glm::dvec3 const side{-along.z, 0.0, along.x}; + Camera.Pos = centre - along * 30.0 + side * 15.0 + glm::dvec3{0.0, 20.0, 0.0}; + auto const look{glm::normalize(centre - Camera.Pos)}; + Camera.Angle = glm::vec3(static_cast(std::asin(std::clamp(look.y, -1.0, 1.0))), static_cast(std::atan2(-look.x, -look.z)), 0.0f); + Camera.m_owner = nullptr; + FreeFlyModeFlag = true; + Global.pCamera = Camera; + WriteLog("Editor: camera at the first track, " + track->name()); + break; + } + if (false == m_saved_camera.has_value() && simulation::Paths.sequence().empty()) + { + std::vector found; + auto const ground{ground_heights({glm::dvec3{0.0, 5000.0, 0.0}}, true, &found).front()}; + Camera.Pos = glm::dvec3{0.0, (found.front() != 0 ? ground : 0.0) + 60.0, 0.0}; + // facing north, the top view with the north up as on a map: the yaw 0 looks along -z, to the south + Camera.Angle = glm::vec3(glm::radians(-45.0f), glm::pi(), 0.0f); + Camera.m_owner = nullptr; + FreeFlyModeFlag = true; + if (false == Global.EditorOrtho) + { + Global.EditorOrthoExtent = 150.0f; + toggle_ortho(); + } + Global.pCamera = Camera; + choose_work_area(work_area::tracks); + WriteLog("Editor: camera over the origin of the empty scenery"); + } + m_first_steps_open = EditorSettings.first_steps(); + } + Global.ControlPicking = true; EditorModeFlag = true; + load_orthophoto_settings(); + m_orthophoto.area_paused(m_area_paused); + m_nmt.prefetch_paused(m_area_paused); + Application.set_cursor(GLFW_CURSOR_NORMAL); } void editor_mode::exit() { + m_ride.leave(); + track_sleepers::lay_in_background(true); + // the driver's view has no menu to switch the drawn cursor off: the system one there + ui_layer::draw_cursor(false); + Global.editor_tracks = false; EditorModeFlag = false; Global.ControlPicking = m_statebackup.picking; FreeFlyModeFlag = m_statebackup.freefly; Global.pCamera = m_statebackup.camera; + commit_track_drag(true); + m_track_gizmo_using = false; + m_track_drag.clear(); + m_track_drag_points.clear(); + m_track_snap = {}; + m_track_point = {}; + m_route = {}; + m_route_dragging = false; + if (Global.EditorOrtho) + toggle_ortho(); + g_redo.clear(); m_history.clear(); + m_orphans.clear(); + m_fill_last.clear(); + m_orthophoto.cancel_pending(); + m_orthophoto.detach_scene(); // the layer is an editor aid, keep it out of the other modes + for (auto &layer : m_wms) + { + layer->cancel_pending(); + layer->detach_scene(); + } + // the download of the area held while the scenery is driven, it goes on once the editor is back + m_orthophoto.area_paused(true); + m_nmt.prefetch_paused(true); + scene::Layers.show_all(); // likewise for hidden scenery layers, the other modes get the scenery as it was defined // drop selection so a stale/dangling node pointer isn't used on the next editor session m_node = nullptr; + select_include(0); m_gizmo_using = false; ui()->set_node(nullptr); @@ -1395,6 +7126,78 @@ void editor_mode::exit() } } +void editor_mode::delete_model(TAnimModel *model, bool const Joined) +{ + // record deletion for undo (serialize full node) + std::string as_text; + + model->export_as_text(as_text); + std::string debug = "Deleting node: " + as_text + "\nSerialized data:\n"; + push_snapshot(model, EditorSnapshot::Action::Delete, as_text); + if (false == m_history.empty()) + m_history.back().joined = Joined; + WriteLog(debug, logtype::generic); + + erase_model(model); +} + +void editor_mode::erase_model(TAnimModel *model) +{ + nullify_history_pointers(model); + remove_from_hierarchy(model); + if (m_node == model) + { + m_node = nullptr; + m_dragging = false; + } + simulation::State.delete_model(model); +} + +void editor_mode::delete_selected() +{ + // what's selected: a road piece or point, a signal, an include of a scenery template, a model, tracks + if (road_delete()) + return; + if (m_instance != 0 && signal_delete(m_instance)) + return; + if (m_instance != 0) + { + // include of a scenery template. what it shows goes out of sight, the directive is erased on save + scene::Layers.removed(m_instance, true); + EditorSnapshot snap; + snap.instance = m_instance; + snap.node_name = *scene::Layers.instance(m_instance).file; + m_history.push_back(std::move(snap)); + g_redo.clear(); + ui()->set_status(format(STR_C("Include of \"%s\" removed, Ctrl+Z brings it back. Its directive is erased when the scenery is saved"), scene::Layers.instance(m_instance).file->c_str())); + select_include(0); + return; + } + TAnimModel *model = dynamic_cast(m_node); + if (model) + { + // the models of the selection go together, one step of the history + auto joined{false}; + for (auto *node : selected_nodes()) + { + if (auto *selected = dynamic_cast(node)) + { + delete_model(selected, joined); + joined = true; + } + } + m_selection.clear(); + } + else if (ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::path && m_track_set.size() >= 2) + { + track_set_delete(); + } + else if (selected_track() != nullptr) + { + delete_selected_track(); + } +} + void editor_mode::on_key(int const Key, int const Scancode, int const Action, int const Mods) { #ifndef __unix__ @@ -1404,29 +7207,157 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in #endif bool anyModifier = Mods & (GLFW_MOD_SHIFT | GLFW_MOD_CONTROL | GLFW_MOD_ALT); + if (Action == GLFW_RELEASE && Key >= 0 && Key <= GLFW_KEY_LAST) + { + input::keys[Key] = GLFW_RELEASE; + if (Key == GLFW_KEY_LEFT_SHIFT || Key == GLFW_KEY_RIGHT_SHIFT) + input::key_shift = false; + if (Key == GLFW_KEY_LEFT_CONTROL || Key == GLFW_KEY_RIGHT_CONTROL) + input::key_ctrl = false; + if (Key == GLFW_KEY_LEFT_ALT || Key == GLFW_KEY_RIGHT_ALT) + input::key_alt = false; + } + // first give UI a chance to handle the key if (!anyModifier && m_userinterface->on_key(Key, Action)) return; + // riding along the track the keys drive the camera; Y starts the ride on the track under the cursor + if (false == ImGui::GetIO().WantTextInput) + { + std::string status; + auto const taken{m_ride.key(Key, Action, Mods, camera_look(), m_input.mouse.button(GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS, status)}; + if (false == status.empty()) + ui()->set_status(status, m_ride.active()); + if (taken) + { + // the right button held to drive isn't a click for the menu of the track under the cursor + m_track_context.armed = false; + return; + } + // not with a button held: a drag going on would lose its release to the ride + if (Key == GLFW_KEY_Y && Action == GLFW_PRESS && false == anyModifier && false == m_ride.active() && m_input.mouse.button(GLFW_MOUSE_BUTTON_RIGHT) != GLFW_PRESS && m_input.mouse.button(GLFW_MOUSE_BUTTON_LEFT) != GLFW_PRESS) + { + ride_enter(); + return; + } + } + + if (ui()->mode() == nodebank_panel::TRACK && is_press(Action) && (Mods & (GLFW_MOD_CONTROL | GLFW_MOD_ALT)) == 0 && typed_key(Key)) + return; + // gizmo transform shortcuts (Q/W/E/R) — only when the camera isn't being flown (RMB up). // handled before the camera keyboard step because Q/W/E are also the fly-mode movement keys, // which would otherwise consume them. if (!anyModifier && is_press(Action) && m_input.mouse.button(GLFW_MOUSE_BUTTON_RIGHT) != GLFW_PRESS) { + if (ui()->mode() == nodebank_panel::TRACK && false == m_track_gizmo_using && false == m_straights.dragging && false == m_switch.placing && track_shortcut(Key)) + return; bool handled = true; switch (Key) { - case GLFW_KEY_Q: m_gizmo_op = gizmo_operation::translate; break; - case GLFW_KEY_W: m_gizmo_op = gizmo_operation::rotate; break; - case GLFW_KEY_E: m_gizmo_op = gizmo_operation::scale; break; + case GLFW_KEY_O: toggle_ortho(); break; + // in the tracks they also bring the gizmo out, hidden until then + case GLFW_KEY_Q: m_gizmo_op = gizmo_operation::translate; m_track_gizmo_on |= ui()->mode() == nodebank_panel::TRACK; break; + case GLFW_KEY_W: m_gizmo_op = gizmo_operation::rotate; m_track_gizmo_on |= ui()->mode() == nodebank_panel::TRACK; break; + case GLFW_KEY_E: m_gizmo_op = gizmo_operation::scale; m_track_gizmo_on |= ui()->mode() == nodebank_panel::TRACK; break; case GLFW_KEY_R: m_gizmo_local = !m_gizmo_local; break; + case GLFW_KEY_B: handled = ui()->mode() != nodebank_panel::TRACK && bend_shortcut(); break; + case GLFW_KEY_F1: m_shortcuts_open = !m_shortcuts_open; break; + // the fields of work in the order of their row + case GLFW_KEY_F2: choose_work_area(work_area::surroundings); break; + case GLFW_KEY_F3: choose_work_area(work_area::tracks); break; + case GLFW_KEY_F4: choose_work_area(work_area::roads); break; + case GLFW_KEY_F5: choose_work_area(work_area::terrain); break; + // the edit modes in the order of the toolbar; in the track mode the digits typed as a value were taken already + case GLFW_KEY_1: handled = ui()->mode() != nodebank_panel::TRACK; if (handled) choose_edit_mode(nodebank_panel::MODIFY); break; + case GLFW_KEY_2: handled = ui()->mode() != nodebank_panel::TRACK; if (handled) choose_edit_mode(nodebank_panel::ADD); break; + case GLFW_KEY_3: handled = ui()->mode() != nodebank_panel::TRACK; if (handled) choose_edit_mode(nodebank_panel::BRUSH); break; + case GLFW_KEY_4: handled = ui()->mode() != nodebank_panel::TRACK; if (handled) choose_edit_mode(nodebank_panel::FILL); break; + case GLFW_KEY_5: handled = ui()->mode() != nodebank_panel::TRACK; if (handled) choose_edit_mode(nodebank_panel::COPY); break; default: handled = false; break; } if (handled) return; } + // the minimap with the stations + if (Global.ctrlState && false == Global.shiftState && Key == GLFW_KEY_M) + { + if (is_press(Action)) + m_minimap.toggle(); + return; + } + + // all docks unpinned and hidden at the edges, for the most of the view, or pinned back + if (Global.ctrlState && false == Global.shiftState && Key == GLFW_KEY_SPACE) + { + if (is_press(Action)) + ui()->toggle_docks(); + return; + } + + // the selection: copy, paste at the cursor, group and ungroup. ahead of the camera keys, the letters may be bound there + if (Global.ctrlState && (Key == GLFW_KEY_C || Key == GLFW_KEY_V || Key == GLFW_KEY_G) && ui()->mode() != nodebank_panel::TRACK && false == m_roadtool.window) + { + if (is_press(Action)) + { + if (Key == GLFW_KEY_C) + copy_selection(); + else if (Key == GLFW_KEY_V) + paste_clipboard(cursor_ground()); + else if (Global.shiftState) + ungroup_selection(); + else + group_selection(); + } + return; + } + + // the properties of a track copied and pasted on the selected ones + if (Global.ctrlState && Global.shiftState && (Key == GLFW_KEY_C || Key == GLFW_KEY_V) && ui()->mode() == nodebank_panel::TRACK) + { + if (is_press(Action) && false == ImGui::GetIO().WantTextInput) + { + auto const tracks{selected_tracks()}; + if (Key == GLFW_KEY_C) + { + // the selected track, or the one under the cursor when there are more of them + auto *from{tracks.size() == 1 ? tracks.front() : m_hover.track}; + if (from != nullptr) + copy_track_style(*from); + else + ui()->set_status(STR_C("Select one track, or point at one, to take its properties"), true); + } + else if (m_track_style.values.empty()) + ui()->set_status(STR_C("Take the properties of a track first: Ctrl+Shift+C"), true); + else if (tracks.empty()) + ui()->set_status(STR_C("Select the tracks to set the properties on"), true); + else + paste_track_style(tracks); + } + return; + } + + // save; checked ahead of the camera keys, which have S bound to moving back + if (Global.ctrlState && false == Global.shiftState && Key == GLFW_KEY_S) + { + if (is_press(Action)) + save(); + return; + } + + if (Global.ctrlState && false == Global.shiftState && Key == GLFW_KEY_F && ui()->mode() == nodebank_panel::TRACK) + { + if (is_press(Action)) + { + show_track_tab(m_track_tab); + m_track_search.focus = true; + } + return; + } + // then internal input handling if (m_input.keyboard.key(Key, Action)) return; @@ -1434,7 +7365,9 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in if (Action == GLFW_RELEASE) return; - // shortcuts: undo/redo + // shortcuts: undo/redo. not in the middle of a drag, it would go on from the state which was undone + if (Global.ctrlState && (Key == GLFW_KEY_Z || Key == GLFW_KEY_Y) && is_press(Action) && (m_track_gizmo_using || m_track_set_using || m_straights.dragging || m_extend.active || m_switch.placing || m_point_drag.active || m_handle_drag.active || m_roadtool.lifting)) + return; if (Global.ctrlState && Key == GLFW_KEY_Z && is_press(Action)) { undo_last(); @@ -1459,7 +7392,7 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in } else if (Global.ctrlState && Global.shiftState) { - simulation::State.export_as_text(Global.SceneryFile); + export_scenery(); } break; @@ -1471,37 +7404,141 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in break; case GLFW_KEY_DELETE: + // the chunks of the terrain selected, where the terrain is the field of work; else what's selected in the scenery + if (is_press(Action) && m_terrain_open && false == m_terrain_selection.empty()) + remove_selected_chunks(); + else if (is_press(Action)) + delete_selected(); + break; + + case GLFW_KEY_ESCAPE: + // an open list or menu takes this Esc for itself, the selection behind it stays + if (ImGui::IsPopupOpen("", ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel)) + break; + // the switch being clicked off the view given up + if (is_press(Action) && m_switch_designer.open && m_switch_designer.picking) + { + m_switch_designer.picking = false; + break; + } + // the download area being drawn given up, the one before stays + if (is_press(Action) && m_area_drawing.active) + { + area_finish(false); + break; + } if (is_press(Action)) { - TAnimModel *model = dynamic_cast(m_node); - if (model) + road_cancel(); + } + // the first Esc drops what is going on in the track mode, the next one goes back to the selection + if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK) + { + if (m_tape.active) + m_tape = {}; + else if (m_route.trace.active && route_active()) + route_trace_end(false); + else if (m_lay.active && false == m_lay.points.empty()) + lay_escape(); + else if (m_track_style.picking) + m_track_style.picking = false; + else if (m_profile.picking) + m_profile.picking = false; + else if (track_busy()) + { + cancel_track_tools(); + m_straights.tool = 0; + } + else if (m_track_tab == track_tab::signals && m_signal.picking_read) + m_signal.picking_read = false; + else if (m_track_tab == track_tab::signals && m_signal.armed) + m_signal.armed = false; + else if (m_track_tab == track_tab::path && m_track_set.size() >= 2) + select_tracks({}); + else if (m_track_tab != track_tab::path) + show_track_tab(track_tab::path); + else if (selected_track() != nullptr) { - // record deletion for undo (serialize full node) - std::string as_text; - - model->export_as_text(as_text); - std::string debug = "Deleting node: " + as_text + "\nSerialized data:\n"; - push_snapshot(model, EditorSnapshot::Action::Delete, as_text); - WriteLog(debug, logtype::generic); - - // clear history pointers referencing this model before actually deleting it - nullify_history_pointers(model); - remove_from_hierarchy(model); - m_node = nullptr; - m_dragging = false; + m_track_point = {}; ui()->set_node(nullptr); - simulation::State.delete_model(model); } } break; - case GLFW_KEY_F: - if (is_press(Action)) + case GLFW_KEY_TAB: + // a switch dragged from a free end and bent: its diverging track the other way than the main one, or the same way + if (is_press(Action) && false == anyModifier && m_switch.placing && m_switch.free && false == ImGui::GetIO().WantTextInput) { - if(!m_node) - break; + m_switch.one_sided = false == m_switch.one_sided; + break; + } + // laying: the bends of straights or a curve traced, for the points clicked from now on + if (is_press(Action) && false == anyModifier && ui()->mode() == nodebank_panel::TRACK && m_lay.active && false == ImGui::GetIO().WantTextInput) + lay_switch_mode(); + break; + case GLFW_KEY_BACKSPACE: + // the switch being clicked off the view: the last point taken back + if (m_switch_designer.open && m_switch_designer.picking) + { + if (is_press(Action) && false == m_switch_designer.clicks.empty()) + { + m_switch_designer.clicks.pop_back(); + switch_designer_measure(); + } + break; + } + // the download area: the last point taken back + if (is_press(Action) && m_area_drawing.active) + { + if (false == m_area_drawing.points.empty()) + m_area_drawing.points.pop_back(); + break; + } + // area fill: remove the last outline point + if (is_press(Action) && ui()->mode() == nodebank_panel::FILL && !m_fill_points.empty()) + m_fill_points.pop_back(); + if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK && m_lay.active && !m_lay.points.empty()) + lay_back(); + if (is_press(Action) && m_route.trace.active && route_active() && !m_route.trace.points.empty()) + { + m_route.trace.points.pop_back(); + route_trace_fit(); + } + break; + + case GLFW_KEY_ENTER: + case GLFW_KEY_KP_ENTER: + // the download area closed, from three points on + if (is_press(Action) && m_area_drawing.active) + { + if (m_area_drawing.points.size() >= 3) + area_finish(true); + break; + } + if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK && m_lay.active) + lay_enter(); + if (is_press(Action) && m_route.trace.active && route_active()) + route_trace_end(true); + break; + + case GLFW_KEY_K: + if (is_press(Action) && road_split()) + { + break; + } + if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK && selected_track() != nullptr) + { + auto const under{split_spot()}; + if (under.track != nullptr) + split_track_at(*under.track, under.point); + } + break; + + case GLFW_KEY_F: + if (is_press(Action) && m_node) + { // start smooth focus camera on selected node start_focus(m_node, 0.6); } @@ -1513,7 +7550,7 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in // Unreal-style "snap to floor": drop the selected node onto the surface below it. // works against triangle geometry (shape_node terrain / opaque shapes); once a proper // editable terrain mesh exists, dropping onto it works without further changes here. - snap_to_ground(m_node); + drop_selection_to_ground(); } break; @@ -1524,6 +7561,8 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in void editor_mode::on_cursor_pos(double const Horizontal, double const Vertical) { + if (m_ortho_pan) + ortho_pan_to(Horizontal, Vertical); // object transforms are handled by the gizmo now; here we only forward the cursor to the // mouse input, which rotates the camera while the right mouse button is held (panning mode) m_input.mouse.position(Horizontal, Vertical); @@ -1538,23 +7577,94 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const return; } - // in chunk-edit mode the left button adds a neighbouring chunk (Shift = delete the clicked one) - if (m_chunk_edit && Button == GLFW_MOUSE_BUTTON_LEFT) + // a switch being clicked off the view for the template editor takes the left button + if (m_switch_designer.open && m_switch_designer.picking && Button == GLFW_MOUSE_BUTTON_LEFT) { + // on the terrain under the cursor, then on the level of the first point: no track or ballast in the view catches the point if (is_press(Action)) - handle_chunk_edit_click(Global.shiftState); + switch_designer_click(m_switch_designer.clicks.empty() ? cursor_terrain(std::as_const(*this).cursor_ground().y) : cursor_level(m_switch_designer.clicks.front().y)); m_input.mouse.button(Button, Action); return; } - // in terrain sculpt mode the left button paints the terrain instead of picking nodes - if (m_terrain_sculpt && Button == GLFW_MOUSE_BUTTON_LEFT) + // the download area drawn on the map takes the left button while it's drawn + if (m_area_drawing.active && Button == GLFW_MOUSE_BUTTON_LEFT) { + if (is_press(Action)) + area_click(Global.shiftState); + else + m_area_drawing.dragged = -1; + m_input.mouse.button(Button, Action); + return; + } + + // the chunk, spacing and water tools of the terrain work on a click (Shift: the other way round) + if (terrain_clicking() && Button == GLFW_MOUSE_BUTTON_LEFT) + { + if (is_press(Action)) + handle_terrain_click(Global.shiftState); + m_input.mouse.button(Button, Action); + return; + } + + // with a brush of the terrain the left button works the brush instead of picking nodes + if (terrain_brush() && Button == GLFW_MOUSE_BUTTON_LEFT) + { + if (m_terrain_tool == terrain_tool::level && is_press(Action) && (Global.ctrlState || m_terrain_picking)) + { + // a click which picks the target height doesn't level anything + pick_terrain_target(); + m_terrain_picking = false; + mouseHold = false; + m_input.mouse.button(Button, Action); + return; + } mouseHold = is_press(Action); m_input.mouse.button(Button, Action); return; } + // with the road window open the left button works its tools, whichever edit mode is on but the track one + if (m_roadtool.window && Button == GLFW_MOUSE_BUTTON_LEFT && ui()->mode() != nodebank_panel::TRACK) + { + // Alt+LMB on a point: its height (and the other selected ones') dragged up or down + if (is_press(Action) && Global.altState && false == ImGui::GetIO().WantCaptureMouse && road_lift_start()) + { + m_input.mouse.button(Button, Action); + return; + } + if (false == is_press(Action) && m_roadtool.lifting) + { + road_lift_finish(); + m_input.mouse.button(Button, Action); + return; + } + if (is_press(Action)) + { + // NOTE: the pick is resolved a few frames later, by then it's known whether the press was meant for the UI + GfxRenderer->Pick_Node_Callback([this](scene::basic_node * /*node*/) { + if (viewport_click()) + road_click(); + }); + } + m_input.mouse.button(Button, Action); + return; + } + + if (Button == GLFW_MOUSE_BUTTON_LEFT && is_press(Action) && false == m_bend.picking && ui()->mode() != nodebank_panel::TRACK && (bend_drag_start(Mods) || bend_click())) + { + m_input.mouse.button(Button, Action); + return; + } + + if (m_bend.picking && Button == GLFW_MOUSE_BUTTON_LEFT && ui()->mode() != nodebank_panel::TRACK) + { + if (is_press(Action)) + bend_pick(Global.pCamera.Pos + GfxRenderer->Mouse_Position()); + m_input.mouse.button(Button, Action); + return; + } + if (Button == GLFW_MOUSE_BUTTON_LEFT) { @@ -1565,24 +7675,76 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const if (is_press(Action)) { mouseHold = true; - m_node = nullptr; + m_brush_has_last = false; // every brush stroke starts with a placement - // delegate node picking behaviour depending on current panel mode + // in area fill mode the left button only adds outline points, it doesn't touch the selection + if (mode == nodebank_panel::FILL) + { + GfxRenderer->Pick_Node_Callback([this](scene::basic_node * /*node*/) { + if (viewport_click()) + add_area_fill_point(); + }); + m_input.mouse.button(Button, Action); + return; + } + + if (mode == nodebank_panel::TRACK) + { + track_press(track_intent_at(Mods)); + m_input.mouse.button(Button, Action); + return; + } + + // delegate node picking behaviour depending on current panel mode. + // NOTE: the pick is resolved a few frames later, often after the button was already released, + // so the callback mustn't depend on the button still being held + // Shift+LMB adds a model to the selection, or takes it out + auto const additive{mode == nodebank_panel::MODIFY && (Mods & GLFW_MOD_SHIFT) != 0}; GfxRenderer->Pick_Node_Callback( - [this, mode, rotation_mode, fixed_rotation_value](scene::basic_node *node) { - // ignore picks that are beyond allowed placement distance - if (node) { + [this, mode, rotation_mode, fixed_rotation_value, additive](scene::basic_node *node) { + // the press turned out to be meant for the UI + if (!viewport_click()) + return; + + auto *const previous{m_node}; + m_node = nullptr; + select_include(0); + ui()->set_node(additive ? previous : nullptr); + + // in a scenery opened for editing selection has its limits. nodes of locked layers are off limits. + // nodes defined by a scenery template can't be rewritten one by one on save, so a click on one + // selects the include of the template as a whole + if (node && mode == nodebank_panel::MODIFY) + { + std::string reason; + if (node->from_template() && scene::Layers.removable(node->m_instance, &reason)) + { + select_include(node->m_instance); + ui()->set_status(format(STR_C("Include of \"%s\" selected. Its parameters are in the inspector, Del removes it from the scenery"), scene::Layers.instance(m_instance).file->c_str())); + node = nullptr; + } + else if (node->from_template() || false == scene::Layers.editable(node, &reason)) + { + ui()->set_status(format(STR_C("\"%s\" can't be edited: %s"), name_of(*node).c_str(), reason.c_str()), true); + node = nullptr; + } + } + + // models stay within placement distance; tracks in the track workspace have no range cap + if (node && false == (Global.editor_tracks && dynamic_cast(node) != nullptr)) { double const dist = glm::distance(node->location(), glm::dvec3{Global.pCamera.Pos}); if (dist > static_cast(kMaxPlacementDistance)) + { + if (additive) + m_node = previous; return; + } } if (mode == nodebank_panel::MODIFY) { - if (!m_dragging) - return; - - m_node = node; - ui()->set_node(m_node); + if (additive) + m_node = previous; + select_node(node, additive); } else if (mode == nodebank_panel::COPY) { @@ -1601,25 +7763,29 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const if (!src) return; + if (src->starts_with(editor_includes::directive_mark)) + { + // a scenery template rather than a single node + place_include(src->substr(editor_includes::directive_mark.size()), rotation_mode, fixed_rotation_value); + return; + } + std::string name = "editor_"; glm::dvec3 mouseOffset = clamp_mouse_offset_to_max(GfxRenderer->Mouse_Position()); - TAnimModel *cloned = simulation::State.create_model(*src, name, Camera.Pos + mouseOffset); + TAnimModel *cloned = simulation::State.create_model(*src, name, placement_on_ground(Camera.Pos + mouseOffset)); if (!cloned) return; - // record addition for undo - std::string as_text; std::string new_name = "editor_" + cloned->uuid.to_string(); - cloned->m_name = new_name; + apply_rotation_for_new_node(cloned, rotation_mode, fixed_rotation_value); + + // record addition for undo (after rotation, so a redo recreates the same thing) + std::string as_text; cloned->export_as_text(as_text); push_snapshot(cloned, EditorSnapshot::Action::Add, as_text); - if (!m_dragging) - return; - m_node = cloned; - apply_rotation_for_new_node(m_node, rotation_mode, fixed_rotation_value); ui()->set_node(m_node); } }); @@ -1630,16 +7796,96 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const else { if (is_release(Action)) + { mouseHold = false; + finish_track_box(); + point_drag_finish(); + m_handle_drag = {}; + sweep_release(); + if (m_straights.tool_mouse) + finish_straight_gesture(); + if (m_extend.active) + finish_extend(); + if (m_switch.placing) + { + // a press let go with no drag places no switch: the track it took is only selected, the ground with no track there + // selects nothing + auto const &io{ImGui::GetIO()}; + if (glm::length(glm::vec2{io.MousePos.x, io.MousePos.y} - m_switch.pressed_at) <= 10.0f) + { + m_switch.placing = false; + if (m_switch.free) + { + m_switch.free = false; + track_click_select(nullptr); + } + } + else + finish_switch_placement(); + } + if (m_turntable.placing) + turntable_finish_placement(); + if (m_signal.placing || m_signal.moving) + signal_release(); + if (m_switch.slide.active) + switch_slide_finish(); + } m_dragging = false; } } else if (Button == GLFW_MOUSE_BUTTON_RIGHT) { + // Ctrl+RMB: the menu at the cursor, for the model under it or the selection; RMB alone turns the camera + if ((Mods & GLFW_MOD_CONTROL) != 0 && ui()->mode() != nodebank_panel::TRACK) + { + if (is_press(Action)) + { + m_contextpoint = cursor_ground(); + GfxRenderer->Pick_Node_Callback([this](scene::basic_node *node) { + if (!viewport_click()) + return; + auto const selection{selected_nodes()}; + if (node != nullptr && false == node->from_template() && scene::Layers.editable(node) && std::find(selection.begin(), selection.end(), node) == selection.end()) + select_node(node, false); + m_contextopen = true; + }); + } + return; + } + if (ui()->mode() == nodebank_panel::TRACK) + { + if (is_press(Action)) + track_context_press(); + else if (is_release(Action)) + track_context_release(); + } // game-engine style look: hide & grab the cursor while flying, restore it on release Application.set_cursor(is_press(Action) ? GLFW_CURSOR_DISABLED : GLFW_CURSOR_NORMAL); } + else if (Button == GLFW_MOUSE_BUTTON_MIDDLE) + { + if (is_press(Action)) + { + m_ortho_pan = true; + m_ortho_pan_cursor = m_input.mouse.position(); + m_focus_active = false; + Camera.Velocity = {}; + // in the perspective view the ground under the cursor goes along with it: metres of it to a pixel there, as far as it is + m_pan_metres = 0.0; + if (false == Global.EditorOrtho) + { + auto const &io{ImGui::GetIO()}; + auto const distance{glm::length(GfxRenderer->Mouse_Position())}; + if (GfxRenderer->Mouse_Hit() && io.DisplaySize.y > 0.0f && distance > 0.5 && distance < 20000.0) + m_pan_metres = 2.0 * distance * std::tan(glm::radians(Global.FieldOfView / Global.ZoomFactor) * 0.5) / static_cast(io.DisplaySize.y); + else + m_ortho_pan = false; // nothing under the cursor to hold + } + } + else if (is_release(Action)) + ortho_pan_stop(); + } m_input.mouse.button(Button, Action); } @@ -1647,11 +7893,11 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const void editor_mode::render_change_history(){ - ImGui::Begin("Editor History", &m_change_history, ImGuiWindowFlags_AlwaysAutoResize); + ImGui::Begin((std::string(STR_C("Change History")) + "###editorhistory").c_str(), &m_change_history); int maxsize = m_max_history_size; - if (ImGui::InputInt("Max history size", &maxsize)) + if (ImGui::InputInt(STR_C("Max history size"), &maxsize)) { - m_max_history_size = std::max(0, maxsize); + m_max_history_size = std::max(1, maxsize); if ((int)m_history.size() > m_max_history_size && m_max_history_size >= 0) { auto remove_count = (int)m_history.size() - m_max_history_size; @@ -1664,14 +7910,14 @@ void editor_mode::render_change_history(){ } float dist = kMaxPlacementDistance; - if (ImGui::InputFloat("Max placement distance", &dist)) + if (ImGui::InputFloat(STR_C("Max placement distance"), &dist)) { kMaxPlacementDistance = std::max(0.0f, dist); } ImGui::Separator(); - ImGui::Text("History (newest at end): %zu entries", m_history.size()); + ImGui::Text(STR_C("History (newest at end): %zu entries"), m_history.size()); ImGui::BeginChild("history_list", ImVec2(400, 200), true); for (int i = 0; i < (int)m_history.size(); ++i) { @@ -1682,8 +7928,13 @@ void editor_mode::render_change_history(){ s.action == EditorSnapshot::Action::Delete ? "DEL" : s.action == EditorSnapshot::Action::Move ? "MOV" : s.action == EditorSnapshot::Action::Rotate ? "ROT" : - s.action == EditorSnapshot::Action::Scale ? "SCA" : "OTH", - s.node_name.empty() ? "(noname)" : s.node_name.c_str(), + s.action == EditorSnapshot::Action::Scale ? "SCA" : + s.action == EditorSnapshot::Action::TrackEdit ? "TRK" : + s.action == EditorSnapshot::Action::RoadEdit ? "ROAD" : + s.action == EditorSnapshot::Action::Array ? "ARR" : + s.action == EditorSnapshot::Action::Terrain ? "TER" : + s.action == EditorSnapshot::Action::Kilometrage ? "KM" : "OTH", + s.node_name.empty() ? STR_C("(no name)") : s.node_name.c_str(), s.position.x, s.position.y, s.position.z); if (ImGui::Selectable(buf, m_selected_history_idx == i)) @@ -1692,7 +7943,7 @@ void editor_mode::render_change_history(){ ImGui::EndChild(); ImGui::Separator(); - if (ImGui::Button("Clear History")) + if (ImGui::Button(STR_C("Clear History"))) { m_history.clear(); g_redo.clear(); @@ -1701,7 +7952,7 @@ void editor_mode::render_change_history(){ ImGui::SameLine(); ImGui::SameLine(); - if (ImGui::Button("Undo Selected")) + if (ImGui::Button(STR_C("Undo back to the selected"))) { if (m_selected_history_idx >= 0 && m_selected_history_idx < (int)m_history.size()) { @@ -1719,13 +7970,17 @@ void editor_mode::render_change_history(){ void editor_mode::on_event_poll() { + m_selftest.input.deliver(); // game-engine style camera: WSAD/EQ only fly the camera while the right mouse button is held. // when it's released the keyboard is free for gizmo shortcuts, and we flush a zero-movement // command once so the camera doesn't keep coasting on the last velocity it was given. bool const flying = m_input.mouse.button(GLFW_MOUSE_BUTTON_RIGHT) == GLFW_PRESS; if (flying) { - m_input.poll(); + // riding along the track the camera only looks around, the keys drive the ride + if (false == m_ride.active()) + m_input.poll(); + first_step_done(first_step::look); } else if (m_camera_flying) { @@ -1749,3 +8004,82 @@ void editor_mode::set_focus_active(bool isActive) { m_focus_active = isActive; } + +void editor_mode::starter_trainset(std::vector &Trailing) +{ + static std::regex const trainset{R"((^|\n)[ \t]*trainset[ \t])", std::regex::icase}; + for (std::size_t handle = 1; handle <= scene::Layers.size(); ++handle) + { + auto const &layer{scene::Layers.layer(static_cast(handle))}; + if (layer.created) + continue; + std::ifstream input{Global.asCurrentSceneryPath + layer.name, std::ios_base::binary}; + std::string const content{std::istreambuf_iterator(input), std::istreambuf_iterator()}; + if (std::regex_search(content, trainset)) + return; + } + std::error_code error; + if (false == std::filesystem::exists("dynamic/pkp/wmb10_v1/wmb10.mmd", error)) + return; + for (auto const *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || track->eType != tt_Normal || (track->iCategoryFlag & 1) == 0 || track->name().empty() || track->m_paths.empty()) + continue; + auto const length{geometry::bezier{track->m_paths.front()}.plan_length()}; + if (length < 15.0) + continue; + Trailing.push_back("trainset none " + track->name() + " " + to_string(std::min(length, 0.5 * length + 5.0), 2) + " 0"); + Trailing.push_back("node -1 0 wmb10-6457 dynamic pkp/wmb10_v1 wmb10-6457 wmb10 0 headdriver 0 0 enddynamic"); + Trailing.push_back("endtrainset"); + WriteLog("Editor: the scenery has no trainset, a WMB10 is put on " + track->name() + " to drive"); + return; + } +} + +void editor_mode::render_top_tracks_choice(bool const Combo) +{ + static char const *const labels[]{"Whole", "Without ballast", "Rails only"}; + static char const *const tooltips[]{"The tracks as in the 3D view", "The rails and the sleepers, the ground under them shows", "The rails alone, without the sleepers and the timbers of the switches, as on a plan"}; + auto chosen{std::clamp(Global.EditorOrthoTracks, 0, 2)}; + auto const pick = [&](int const Choice) { + Global.EditorOrthoTracks = Choice; + EditorSettings.top_tracks(Choice); + EditorSettings.save(); + }; + if (false == Combo) + { + for (int choice = 0; choice < 3; ++choice) + { + if (ImGui::MenuItem(STR_C(labels[choice]), nullptr, chosen == choice)) + pick(choice); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C(tooltips[choice])); + } + return; + } + ImGui::SetNextItemWidth(130.0f); + if (ImGui::BeginCombo(STR_C("Tracks"), STR_C(labels[chosen]))) + { + for (int choice = 0; choice < 3; ++choice) + { + if (ImGui::Selectable(STR_C(labels[choice]), chosen == choice)) + pick(choice); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C(tooltips[choice])); + } + ImGui::EndCombo(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How the top view draws the tracks")); + if (chosen < 2) + return; + ImGui::SameLine(); + auto colour{ImGui::ColorConvertU32ToFloat4(EditorSettings.top_rails())}; + if (ImGui::ColorEdit3("##toprails", &colour.x, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel)) + { + EditorSettings.top_rails(ImGui::ColorConvertFloat4ToU32(ImVec4(colour.x, colour.y, colour.z, 1.0f))); + EditorSettings.save(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The colour of the rails, to stand out on the imagery and the map")); +} diff --git a/application/editormode.h b/application/editormode.h index 29b1ad690..bcf22592c 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -1,4 +1,4 @@ -/* +/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not @@ -10,22 +10,74 @@ http://mozilla.org/MPL/2.0/. #pragma once #include "application/applicationmode.h" +#include "application/editoruipanels.h" #include "input/editormouseinput.h" #include "input/editorkeyboardinput.h" #include "vehicle/Camera.h" +#include "application/editormodegauge.h" +#include "application/editormoderide.h" +#include "application/editormodeminimap.h" +#include "application/editormodejoints.h" +#include "application/editormodelineside.h" +#include "application/editormodeparallel.h" +#include "application/editormodespeed.h" +#include "application/editormodesrk.h" +#include "application/editormodekm.h" +#include "application/editormodevehicle.h" +#include "application/editortool.h" #include "scene/sceneeditor.h" #include "scene/scenenode.h" #include "editor/editorTerrain.hpp" #include "editor/editorTerrainStreamer.hpp" +#include "editor/editorOrthophoto.hpp" +#include "editor/editorNmt.hpp" +#include "editor/editorGeoMap.hpp" +#include "editor/editorTrack.hpp" +#include "editor/editorTrackTrace.hpp" +#include "editor/editorConnections.hpp" +#include "editor/editorAlignment.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorSwitchStore.hpp" +#include "editor/editorSwitchCurve.hpp" +#include "editor/editorKilometrage.hpp" +#include "editor/editorSpeed.hpp" +#include "editor/editorRoad.hpp" +#include "editor/editorProfile.hpp" +#include "editor/editorGroundFollow.hpp" +#include "editor/editorInfra.hpp" +#include "editor/editorGauge.hpp" +#include "editor/editorClips.hpp" +#include "editor/editorIcons.hpp" +#include "application/scriptedinput.h" +#include "world/Sweep.h" +#include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include +#include +#include +#include -class editor_mode : public application_mode +class TAnimModel; +// a tool of a field of work of the editor, a button in the toolbar and over the 3d view +struct editor_tool_button; +class TTrack; + +class editor_mode : public application_mode, private editor_track::observer, private editor_services { public: // constructors editor_mode(); + ~editor_mode() override; // methods // initializes internal data structures of the mode. returns: true on success, false otherwise bool init() override; @@ -39,20 +91,20 @@ class editor_mode : public application_mode void on_key(int Key, int Scancode, int Action, int Mods) override; void on_cursor_pos(double Horizontal, double Vertical) override; void on_mouse_button(int Button, int Action, int Mods) override; - void on_scroll(double const Xoffset, double const Yoffset) override - { - ; - } + void on_scroll(double const Xoffset, double const Yoffset) override; void on_window_resize(int w, int h) override { ; } void on_event_poll() override; bool is_command_processor() const override; + // takes the last change back; changes made together (e.g. to the models of a selection) are taken back together void undo_last(); static bool focus_active(); static void set_focus_active(bool isActive); static TCamera& get_camera() { return Camera; } + static glm::mat4 projection_matrix(float const Aspect); + void toggle_ortho(); static bool change_history() { return m_change_history; } static void set_change_history(bool enabled) { m_change_history = enabled; } static bool settings_open() { return m_settings_open; } @@ -77,9 +129,22 @@ class editor_mode : public application_mode bool picking; }; + struct stored_profile; struct EditorSnapshot { - enum class Action { Move, Rotate, Scale, Add, Delete, Other }; + enum class Action { Move, Rotate, Scale, Add, Delete, TrackEdit, Other, RoadEdit, Array, Bend, Terrain, Kilometrage }; + // copy of a model an array made + struct array_copy + { + TAnimModel *model{nullptr}; // nullptr while the copy is out of the scene + UID uuid; + // what it takes to make the copy again, filled in when it's taken out of the scene + std::string serialized; + std::string name; + glm::dvec3 position{0.0}; + glm::vec3 rotation{0.0f}; + glm::vec3 scale{1.0f}; + }; Action action{Action::Other}; std::string node_name; // node identifier (basic_node::name()) @@ -90,17 +155,60 @@ class editor_mode : public application_mode glm::vec3 rotation{0.0f, 0.0f, 0.0f}; glm::vec3 scale{1.0f, 1.0f, 1.0f}; UID uuid; // node UUID for reference, used as fallback lookup for deleted/recreated nodes - + scene::layer_handle layer{null_handle}; // scenery layer of the node, so a recreated node returns to it + scene::instance_handle instance{0}; // include of a scenery template which was placed or removed, instead of a node + std::vector instances; // includes placed or removed together + std::vector> directives; // includes changed together, with the directives to go back to + std::vector> sweeps; // models along curves changed, with the definitions to go back to + std::vector sweeps_toggled; // models along curves made or removed: undo flips whether they're there + std::vector> tracks; + std::vector created; + std::vector removed; + editor_road::record roads; // what a change of the roads comes to + std::vector infra; // objects which followed the paths + bool profiles{false}; // the stored grade line designs changed too, these were the ones before + std::vector profile_library; + std::optional> alignments; // the kept horizontal alignments changed too, these were the ones before + std::optional> switch_records; // the kept switches changed too, these were the ones before + std::optional hand_joints; // the joints of a station put by hand changed too, these were the ones before + std::optional kilometrage; // the kilometrage before the change (Action::Kilometrage) + std::vector copies; // models an array added to the one it was made of + bool joined{false}; // undone and redone together with the change before it + std::shared_ptr terrain; // the heightmap terrain from before the change (Action::Terrain) + std::uint64_t serial{next_serial()}; // of each step made, for the revision of the history + static std::uint64_t next_serial() + { + static std::uint64_t counter{0}; + return ++counter; + } }; void push_snapshot(scene::basic_node *node, EditorSnapshot::Action Action = EditorSnapshot::Action::Move, std::string const &Serialized = std::string()); std::vector m_history; // history of changes to nodes, used for undo functionality std::vector g_redo; + int m_track_edits{0}; // methods void update_camera(double const Deltatime); + // the camera onto the track under the cursor, or the nearest one, to ride along it + void ride_enter(); + // the way the camera looks, in the plan + glm::dvec3 camera_look() const; editor_ui *ui() const; void redo_last(); + // a single step of the history, see undo_last() + void undo_one(); + void drop_step(std::size_t const Step); + std::string refused(std::string Text); + void redo_one(); + // the changes of the heightmap terrain since the last step become a step of the history: a stroke of the brush, + // or what a frame did; the next change is recorded from now on + void terrain_history_step(); + // puts the terrain back as the step recorded it, the step left with the state it replaced + void restore_terrain(EditorSnapshot &Snapshot); + // swaps the kilometrage with the one the snapshot keeps + void restore_kilometrage(EditorSnapshot &Snapshot); + bool m_history_busy{false}; // undo or redo under way void handle_brush_mouse_hold(int Action, int Button); void apply_rotation_for_new_node(scene::basic_node *node, int rotation_mode, float fixed_rotation_value); // members @@ -116,18 +224,34 @@ class editor_mode : public application_mode glm::vec3 m_focus_target_angle{0.0f}; // camera pitch/yaw/roll facing the focused object double m_focus_time{0.0}; double m_focus_duration{0.6}; + // the last place and angles of the camera which were numbers: a camera gone to no finite place goes back there + glm::dvec3 m_camera_finite_pos{0.0, 0.0, 0.0}; + glm::vec3 m_camera_finite_angle{0.0f}; + bool m_camera_finite{false}; double fTime50Hz{0.0}; // bufor czasu dla komunikacji z PoKeys scene::basic_editor m_editor; scene::basic_node *m_node{nullptr}; // currently selected scene node + scene::instance_handle m_instance{0}; // currently selected include of a scenery template; these are handled as a whole + include_selection m_include; // parameters of the selected include, changed with the gizmo and in the node properties + bool m_include_gesture{false}; // a change of the selected include is under way, and has its undo snapshot already + std::vector> m_retired; // models replaced after changes of includes, with the frames left until they're destroyed bool m_takesnapshot{true}; // helper, hints whether snapshot of selected node(s) should be taken before modification bool m_dragging = false; - glm::dvec3 oldPos; + glm::dvec3 oldPos; // world position of the last brush placement + bool m_brush_has_last{false}; // false at the start of a brush stroke, so the first placement ignores spacing + bool m_draw_cursor{false}; // the cursor drawn into the picture (View menu), on only while the editor is bool mouseHold{false}; float kMaxPlacementDistance = 200.0f; static bool m_change_history; static bool m_settings_open; + double m_ortho_pitch{0.0}; + bool m_ortho_pan{false}; + glm::dvec2 m_ortho_pan_cursor{0.0}; + double m_pan_metres{0.0}; // of the ground to a pixel, held by the panning in the perspective view + void ortho_pan_to(double const Horizontal, double const Vertical); + void ortho_pan_stop(); // camera fly-mode (right mouse button held); used to flush motion when it's released command_relay m_camera_relay; bool m_camera_flying{false}; @@ -136,58 +260,699 @@ class editor_mode : public application_mode int m_max_history_size{200}; int m_selected_history_idx{-1}; glm::dvec3 clamp_mouse_offset_to_max(const glm::dvec3 &offset); + // the ground under a point the cursor landed on, for things which are to stand on the ground + glm::dvec3 placement_on_ground(glm::dvec3 Location) override; + // the ground under a point, the point itself with none there + glm::dvec3 ground_at(glm::dvec3 Location) const; + // puts every instance of the model the selected node shows on the ground under it + void drop_model_instances(); + void render_object_menu(); + // undo, redo and what can be done with the selection, with their keys + void render_edit_menu(); + // the list of the keyboard shortcuts, opened from the help menu or by F1 + void render_help_menu(); + void render_shortcuts_window(); + bool m_shortcuts_open{false}; + using first_step = editor_first_step; + // the tutorial: a window of lessons, each with a clip or a sketch, the mouse and the keys it teaches and the steps to try + struct tutorial_lesson; + static std::vector const &tutorial_lessons(); + // a lesson is done once all its steps are + bool tutorial_done(tutorial_lesson const &Lesson) const; + void render_first_steps(); + // the steps reached by what the editor is doing now + void note_first_steps(); + // the lesson of the tool in use: the first of its lessons not done yet, or none + char const *tutorial_of_tool(); + // the lesson the tool in use or a button of a panel asks for opened, and the clip of the lesson open loaded + void follow_tutorial(); + void render_tutorial_media(tutorial_lesson const &Lesson, float const Width); + void render_tutorial_goals(tutorial_lesson const &Lesson); + // the button under a lesson, opening the tool it's about or switching the view + void render_tutorial_trial(tutorial_lesson const &Lesson); + // the buttons to the lesson before and after, and a dot for each lesson, green when it's done + void render_tutorial_pages(); + void first_step_done(first_step const Step) override; + void open_kilometrage() override; + bool m_first_steps_open{false}; + std::array(first_step::count)> m_first_steps_done{}; + int m_tutorial_page{0}; + char const *m_tutorial_goto{nullptr}; // the lesson of this title opened by a button of a panel + std::string m_tutorial_followed; // the lesson the tool in use asked for last: it's opened when that changes + double m_tutorial_since{0.0}; + editor_clips::clip m_tutorial_clip; + // deletes what's selected: a road piece or point, a signal, an include of a scenery template, a model, tracks (Del) + void delete_selected(); + void delete_model(TAnimModel *Model, bool const Joined); + + // more models selected at once, in the surroundings: m_node is the one the gizmo is on, the others are in m_selection. + // Shift+LMB adds a model or takes it out; a model of a group stands for the whole group + std::vector m_selection; + std::vector selected_nodes() const; // m_node first + std::vector selection_with_groups() const; // and the other models of their groups + void select_node(scene::basic_node *Node, bool const Additive); + void draw_selection_overlay(); + // the other models of the selection follow m_node moved or turned by the gizmo + void selection_snapshots(EditorSnapshot::Action const Action); + void selection_follow(glm::dvec3 const &Moved, glm::vec3 const &Turned, glm::dvec3 const &Pivot); + // clipboard (Ctrl+C, Ctrl+V): definitions of the models, placed around the cursor as they were around the selected one + struct clipboard_entry + { + std::string definition; + glm::dvec3 offset{0.0}; + glm::vec3 angles{0.0f}; + glm::vec3 scale{1.0f}; + int group{-1}; // models copied with their group are grouped again, each group anew + }; + std::vector m_clipboard; + void copy_selection(); + void paste_clipboard(glm::dvec3 const &Location); + glm::dvec3 cursor_ground(); // the point of the ground under the cursor + // groups (Ctrl+G, Ctrl+Shift+G), written to the scenery as group ... endgroup + void group_selection(); + void ungroup_selection(); + void drop_selection_to_ground(); + // menu at the cursor, Ctrl+RMB + bool m_contextopen{false}; + glm::dvec3 m_contextpoint{0.0}; + void render_context_menu(); // focus camera smoothly on specified node void start_focus(scene::basic_node *node, double duration = 0.6); - // drops the node straight down onto the nearest surface below (terrain or another object) - void snap_to_ground(scene::basic_node *node); + // drops the node straight down onto the nearest surface below (terrain or another object). its group goes along with it, + // unless Alone: then the node goes by itself. Joined: undone together with the change before + void snap_to_ground(scene::basic_node *node, bool const Alone = false, bool const Joined = false); - // editable terrain patches created in the editor + // the heightmap terrain of the scenery (terrain//): chunks, sculpting, painting, water void render_terrain_ui(); - // creates a large terrain as a grid of adjacent chunks (each its own editable patch) - void create_chunked_terrain(); - // manual grid-aligned chunks: add/remove single chunks for fine control - float chunk_grid_size() const { return m_terrain_cells * m_terrain_cellsize; } - void add_grid_chunk(int Cx, int Cz); - void remove_grid_chunk(int Cx, int Cz); - // handles a click in chunk-edit mode (add a neighbour, or Shift = delete the clicked chunk) - void handle_chunk_edit_click(bool DeleteMode); - // commits authored terrain to disk, enables streaming, and exports the scenery (Ctrl+S) - void save_scene_with_terrain(); - // raises/lowers terrain under the cursor while the left mouse button is held in sculpt mode - void handle_terrain_sculpt(double Deltatime); - // returns the terrain patch (if any) whose footprint covers the given world point - editor_terrain *terrain_at(double X, double Z); - // gathers every active terrain patch: manually-created ones plus streamed chunks - std::vector active_terrains(); - // samples the selected model instance's geometry into a new editable terrain patch, then removes it - void capture_terrain(); - std::vector> m_terrains; - // grid-aligned manual chunks, keyed by (cx,cz) on the global chunk grid - std::map, std::unique_ptr> m_grid_chunks; - bool m_terrain_sculpt{false}; // when true, LMB sculpts terrain instead of picking - bool m_chunk_edit{false}; // when true, LMB adds/removes whole chunks - int m_terrain_cells{32}; // grid resolution (quads per side) - int m_terrain_chunks{4}; // chunks per side for a chunked terrain - float m_terrain_cellsize{2.0f}; // metres per quad - float m_terrain_baseheight{0.0f}; // flat starting height - float m_terrain_brush_radius{12.0f}; - float m_terrain_brush_strength{4.0f}; // metres per second while held (one-shot for the buttons) - float m_terrain_simplify_error{0.5f}; // flatness tolerance (m) for mesh simplification - bool m_terrain_auto_optimize{false}; // auto-simplify edited chunks after sculpting settles - double m_terrain_idle{0.0}; // seconds since the last sculpt edit (debounce timer) - char m_terrain_texture[128]{""}; // optional ground texture name + // the terrain as a field of work of its own: the terrain tools and the orthophoto in the tool options window + void render_terrain_tool_options(); + // opens or leaves the terrain; leaving it puts the terrain tools away, so the mouse doesn't stay with them + void terrain_workspace(bool const Open); + // opens the heightmap terrain of the scenery for editing, named after the scenery, if the scenery has none yet. returns: true if it's open + bool ensure_terrain(); + // adds chunks around the camera, Count along a side, at the height of the ground under each grid point where there's any + void add_chunks_around(int const Count); + // adds a chunk of the terrain shaped as the ground under it; where there's no ground, carried on level with the nearest point + // of it, or at the base height. returns: false if there's a chunk already + bool add_chunk_from_ground(heightmap::chunk_key const &Key, float const Spacing, std::uint16_t const Layer = 0); - // streaming terrain that follows the camera (open-world); the editor shares the single - // simulation-level instance so authored terrain also renders in the driver / other modes + // the terrain from the digital terrain model of GUGiK (editormodenmt.cpp) + using nmt_place = ::nmt_place; + struct nmt_state + { + double offset{0.0}; // added to the heights of the model, so they meet the tracks of the scenery + bool fitted{false}; + bool fitting{false}; // waiting for the model under the places of the tracks the offset is worked out from + std::vector fit; + double spread{0.0}; // how much the tracks differ from the model about the offset, m + std::size_t samples{0}; + double band{300.0}; // m from the tracks the chunks made along them reach + bool shape{true}; // the formation and the slopes of the tracks as modifiers of the terrain + bool grow{true}; // while a track is laid, the terrain is made around the cursor where there's none + bool laying{false}; // the tracks committed are being laid: they leave the terrain as it is + bool follow{true}; // a track with its formation edited takes it along, the formation led anew + bool grown{false}; // the chunks waiting were all asked for by growing: the formations aren't made anew after them + bool reshape{false}; // the formations of the tracks laid anew once the chunks waiting are made, as the tracks are put onto the terrain + bool unfitted{false}; // the tracks put onto the terrain are only the ones whose grade line isn't fitted yet + bool redo_hand{false}; // all anew takes the grade lines edited by hand too + std::unordered_set stayed; // the tracks this putting onto the terrain leaves as they are + double grow_time{-10.0}; + double slope{1.5}; + double reach{60.0}; + std::vector pending; // chunks to make once their model is in + // of the chunks waiting, those there already with flat ground, made without the model: the model fills their ground + std::set refill; + std::set given_up; // chunks the growing gave up, next to terrain not from the model: not asked for again + std::size_t made{0}; + std::size_t empty{0}; // chunks not made: the model has no data there + std::size_t foreign{0}; // chunks not made ahead: the terrain beside isn't of the model + std::optional ahead; // how much the terrain made ahead lies over the model + std::set changed; // tracks whose formations are to follow them + std::set gone; // names of the tracks removed, whose formations go with them + double changed_time{0.0}; + bool restoring{false}; // the history is taken back or forward: the terrain comes back with it + std::size_t shaped{0}; + std::string status; + std::string error; + bool common{true}; // the tracks nearly parallel under 5.1 m apart lie on one grade line + static int constexpr grade_line_own{-1}; + static int constexpr grade_line_steep{-2}; + static int constexpr grade_line_off{-3}; // taken off a grade line by hand, stays on its own when the lines are worked out again + static int constexpr grade_line_off_number{-10}; // this and below: taken off the grade line of this number less this + std::map grade_lines; // of each track the number of the grade line it shares, or one of those above + std::set grade_lines_hand; // the tracks put on their grade line by hand: they stay on it when the lines are worked out again + bool grade_lines_loaded{false}; + bool grade_lines_dirty{false}; // the edits of the tracks carried their lines on: stored once, with the next frame + std::unordered_map grade_line_keys; // of the tracks changed, the key each had last, to carry its line on to the next + std::vector> grade_line_replaced; // the first paths of the tracks of a line changed since the last frame: a new track on one takes its line + std::unordered_set on_hump; // the tracks of the humps fitted to the model: no grade line shared levels them + std::size_t grade_lines_changes{0}; + std::string explain; // a track whose run the next sharing of the grade lines tells of in the log, for a selftest + struct surface_place + { + TTrack const *track; + int path; + double share; + int surface; + }; + std::vector surface_places; // what lies on the surface of each group on common timbers + bool camera_check{false}; // chunks were made: the 3d camera may be under them now + std::vector buried; // the tracks just laid, when a part of them is hidden in the ground + double buried_length{0.0}; // m of them hidden + // the tracks of a scenery built at any height put onto the terrain model: the model offset to meet the scenery, then the grade + // line of each line of tracks fitted to the model, the longest first, then the terrain made along them + enum class automatic + { + idle, + fetching, // the model under the tracks + fitting // the grade lines, a few each frame + }; + automatic stage{automatic::idle}; + std::vector probes; // places of the tracks whose model is waited for + std::size_t probes_kept{0}; // the last of the probes, on tracks fitted already: they tell the offset the model had + std::size_t tracks{0}; // rail tracks when the grade lines began, and the paths the grade lines split off since + std::size_t split{0}; + std::vector left; // tracks whose grade line is still to be fitted + std::vector done; // tracks of the lines fitted already: the lines fitted later end on them and don't change them + // the rail tops of the lines fitted already, in squares of the plan: the tracks of a station lie in one plane, a line laid + // near them takes their height for its ground too, the more closely the nearer it is, and a line crossing one of them + // on its level its height on the crossing + struct laid_point + { + glm::dvec3 position{0.0}; + glm::dvec2 direction{0.0, 1.0}; + double grade{0.0}; + double was{0.0}; // the height before the line was fitted + double rails{0.0}; // the height of the rails of the track + TTrack const *track{nullptr}; + }; + std::map, std::vector> laid; + // the points of all the paths as they were laid, for the crossings + std::map, std::vector> paths; + // ends which meet in the plan unlinked, laid apart in height, that the joining of the ends couldn't join as neither of + // them can be changed alone, as of two switches: each with the other one, which a line ending there takes over + std::map, std::tuple> loose; + // the points of the lines over a bridge or a viaduct, the model falling away under them: no formation is laid there + std::map, std::vector> bridged; + // a turntable lies level in its pit, which the model has, at the height of the tracks running up to it: it isn't put onto + // the model, and a line ending on its rim ends there level at its height, turning to the model away from it + struct turntable + { + TTrack *table{nullptr}; + glm::dvec3 centre{0.0}; // at the height of its rails + double rim{0.0}; // m from the centre + std::vector> ends; // of the paths running up to it: track, path, at its end + }; + std::vector turntables; + std::size_t levelled{0}; // turntables moved to the height of their tracks + std::size_t lines{0}; // grade lines fitted and applied + std::size_t refused{0}; // grade lines the checks didn't let apply + std::size_t departures{0}; // grade lines parting from the terrain model by much + // what the last putting of the tracks onto the terrain found, listed in the panel to be looked at: a line the checks + // refused, a line parting from the model by much, a path which didn't take its line + struct finding + { + enum class kind + { + refused, + off, + parted + }; + kind what{kind::refused}; + TTrack *from{nullptr}; // the ends of the line, for its profile + TTrack *to{nullptr}; + double length{0.0}; + glm::dvec3 where{0.0}; // the place to look at + std::string text; + double size{0.0}; // m the line or the path is off by: of one kind the worst told first + }; + std::vector findings; + bool result{false}; // the putting onto the terrain ended: what it did is told in the panel until the next one + bool run{false}; // the tracks are being put onto the terrain, the chunks after the grade lines too: the steps told + std::size_t fetch_most{0}; // the most squares of the model waited for since the loading began, for its progress + // the terrain made under the tracks as they are: the model drawn to them by the difference found at the places along them, + // fading out away from them into the offset of the whole scenery + bool under{false}; + std::vector anchors; // x, z of a place of the tracks, the formation there less the model + std::map, std::vector> anchor_cells; // the anchors in squares of the plan + bool offered{false}; // the terrain was offered to the scenery begun without it + bool prompt{false}; // the offer is shown + bool moving{false}; // the place being picked again + char place[96]{}; // typed: degrees or PUWG 1992 + int shown{-1}; // the frame the terrain panel showed how far the work got + }; + editor_nmt m_nmt; + nmt_state m_nmt_state; + editor_map m_nmt_map; + std::vector nmt_track_places(double const Step) const override; + void nmt_locate() override; + void nmt_fit(); + void nmt_finish_fit(); + // the terrain under the tracks, the tracks left as they are: the model drawn to each of them, its relief kept + void nmt_under_start(); + void nmt_under_anchors(); + // added to the height of the model at the place: the offset of the scenery, drawn to the tracks near them + double nmt_offset_at(double const X, double const Z) const; + std::vector nmt_keys_around() const; + std::vector nmt_keys_along_tracks() const; + // only the chunks there are none of yet: a chunk there is, made from the model or by hand, edited or not, is never made anew. + // Reshape: the formations of the tracks laid anew as the tracks lie now, as when they moved + void nmt_make(std::vector const &Keys, bool const Reshape = false); + enum class nmt_chunk + { + waiting, // for its squares of the model + made, + empty // the model has no data there + }; + // Offset: the heights of the model go up or down by it in the whole chunk, in place of the offsets of the fit + nmt_chunk add_chunk_from_nmt(heightmap::chunk_key const &Key, std::optional const Offset = std::nullopt); + // a chunk there with its ground level all over, as made where there was no ground and no model: none of the shape of the land + bool nmt_flat_chunk(heightmap::chunk_key const &Key) const; + // how much the terrain lies over the model at the points: none where there's too little terrain at them, nor where it + // doesn't follow the model (Foreign), as one made by hand + std::optional nmt_terrain_offset(std::vector const &Points, bool &Foreign) const; + // the same along the edges the chunk shares with the chunks beside it in memory + std::optional nmt_seam_offset(heightmap::chunk_key const &Key, bool &Foreign) const; + // the offset a chunk made from the model where there's no terrain gets: of the terrain made from the model beside it, empty + // (the offset of the scenery) beside terrain made by hand or none + std::optional nmt_chunk_offset(heightmap::chunk_key const &Key) const; + // the terrain beside the formation of the track is the one made from the model; Waiting: its squares of the model aren't in yet + // the tracks changed by hand are told to the terrain: their formations laid anew, of the tracks removed taken away, a + // track laid onto the terrain of the model given its own, once the mouse lets go; in the step of the history of the change + void nmt_track_changed(std::vector const &Tracks); + void nmt_track_gone(TTrack const &Track); + void nmt_follow_tracks(); + // the height the ground will have where the terrain is made ahead of the track laid and isn't there yet + bool nmt_ahead(double const X, double const Z, double &Height) const; + // the same, else the height of the model with the offset of the scenery where its square is in: the ground where there's no + // terrain made yet, as under the base map of the top view + bool nmt_ground(double const X, double const Z, double &Height) const; + // the squares of the model under the rectangle are in, none of them waiting to be asked for again + bool nmt_ready(glm::dvec2 const &Min, glm::dvec2 const &Max); + // Only: the paths of these tracks are shaped anew, the modifiers of those removed taken away; null: all of them. the number + // of the modifiers laid + std::size_t nmt_shape_tracks(std::vector const *Only = nullptr); + void nmt_update(); + // the terrain of the scenery made from the model around the camera within the download area, a chunk at a time while nothing + // else is done with the model and the frames are quick: edited chunks wait in memory to be saved, so not the whole area at once + void nmt_area_terrain(); + void nmt_grow(); + void render_nmt_ui(); + // where the scenery lies: the map to click on, the place typed; true once it's placed + bool render_nmt_place(bool const Moving, bool const Button); + // the work under way: what's left of it and the button to stop it; Compact: one line, for the 3d view + void render_nmt_progress(bool const Compact); + // the formations of the tracks led into the terrain, down or up to it, or taken out of it; one step of the history each + void nmt_pull_terrain(std::vector const &Tracks); + void nmt_restore_terrain(std::vector const &Tracks); + // the terrain of the selected tracks in the panel of the tracks + void render_track_terrain(std::vector const &Tracks); + // all the tracks of the scenery onto the terrain model, or it under them: step 2 of the terrain model (Terrain_panel), and in + // the panel of the tracks + void render_nmt_all_tracks(bool const Terrain_panel); + // what the last putting of the tracks onto the terrain did, and the places it found to be looked at, each to be shown + void render_nmt_result(); + // a line from From to To being put onto the terrain kept to be looked at: the place of it to show and what's wrong there + void nmt_note(nmt_state::finding::kind const What, TTrack *From, TTrack *To, double const Length, glm::dvec3 const &Where, std::string Text, double const Size = 0.0); + // the place found shown in the 3d view with the track there selected; Profile: the profile of its line opened too + void nmt_show(nmt_state::finding const &Finding, bool const Profile); + // the chunks waiting for the terrain model and the tiles of the imagery asked for outlined where they will be, so it's seen + // what's on its way + void draw_nmt_pending() const; + // the download area: a polygon drawn on the map, the boundary of what the orthophoto and the terrain model download in the + // background, none of them asking for anything outside it (application/editormodenmt.cpp) + void area_start(); + // Keep: the area drawn taken, else the one before stays + void area_finish(bool const Keep); + // a press of the left button while drawing: a point added, or the one under the cursor taken to drag, Shift: removed + void area_click(bool const Shift); + void area_update(); + // a point of the area (x, z) where it's drawn: over the map of the top view, on the ground in the 3d view + glm::dvec3 area_point(glm::dvec2 const &Point) const; + void draw_download_area() const; + void render_download_area_ui(editor_orthophoto::statistics const &Stats); + // the download area a square of the side, km, around the camera + void area_square(int const Side); + // the chunk of the terrain (x, z) touches the area, or there's none + bool in_download_area(glm::dvec2 const &Low, glm::dvec2 const &High) const; + // over the 3d view while the terrain panel isn't seen + void render_nmt_banner(); + // the grade lines fitted, the tracks nearly parallel under 5.1 m apart brought onto one, a track going away from them fading back onto its own + void nmt_share_grades(); + void grade_lines_load(); + void grade_lines_store(); + bool on_route_grade_line(TTrack const &Track); + std::vector const &grade_line_beside(); + std::size_t grade_line_follow(std::vector const &Before); + void grade_line_take_off(bool const Off); + // the grade line the route shares, by most of its paths; -1 when it shares none + int route_grade_line(); + // the plain tracks from switch to switch the track is one of, a switch by itself; Alone: the track only + static std::vector grade_line_run(TTrack &Track, bool const Alone); + // the run of the track clicked onto the grade line of the route by hand, or off it if it's on it; a route sharing none makes one with it + void grade_line_pick(TTrack &Track, bool const Alone); + // all the tracks of the grade line, wherever they are, for the view while they're picked + std::vector const &grade_line_members(int const Number); + void draw_grade_line_pick(); + // a piece split off a track lies on the grade line the track does + void grade_line_split(TTrack const &Original, TTrack const &Created); + // a track changed keeps its grade line under the key it has after it; a new one between two tracks of a line, a switch put into one, lies on it + void grade_line_captured(TTrack const &Track); + void grade_lines_committed(std::vector const &Tracks); + void grade_line_renamed(TTrack const &Track, std::string const &Old); + void render_profile_grade_line(); + // the tracks laid since the step of the history hidden in the ground, told over the 3d view with the way to fit the ground to them + void nmt_check_buried(std::size_t const From); + void render_nmt_buried(); + // what to do first, in the middle of the view of a scenery with no tracks nor terrain + void render_empty_scenery_hint(); + // the camera outside the download area: no photos there, told at the bottom of the view with the way to the area + void render_outside_area_hint(); + // the 3d camera under the ground, as after the view from above or the terrain model made under it, lifted over it + void camera_above_ground(); + bool nmt_busy() const; + // the terrain made so far stays, what's waiting is dropped, the grade lines not fitted yet are left + void nmt_stop(); + // a scenery begun from nothing, with no tracks nor terrain, is asked as the first track is laid whether it wants the terrain + void nmt_offer(); + void render_nmt_prompt(); + // the place picked in the terrain window: the terrain model and the orthophoto take it + void nmt_place_scenery(glm::dvec2 const &Point); + void nmt_accept_offer(); + // the whole scenery: tracks, includes and models, moved up or down as one undo step + std::size_t nmt_join_ends(); + // the turntables as they lie, each with the ends of the tracks running up to it on its rim + std::vector nmt_turntables() const; + // each turntable level at the height of the tracks running up to it, its include with it, before the grade lines are fitted: + // at the height of the ones fitted already, else of the terrain model beside its rim; the number of them moved + std::size_t nmt_level_turntables(); + // Unfitted: only the tracks whose grade line isn't fitted yet, the scenery left at its height + void nmt_auto_start(bool const Unfitted = false); + void nmt_auto_step(); + // the grade line of the line of tracks through the track fitted to the terrain model and applied; false if it couldn't be. + // The line runs over the tracks not Fitted, the ones fitted stay as they are and the line meets them. Where the model falls + // away under the line by the abutments the tracks go over on a bridge; Laid: the tracks just laid, the formation fills it and + // they are cut only where they can't follow the line otherwise + bool nmt_fit_line(TTrack &Track, std::function const &Fitted, bool const Laid); + // the tracks laid in one go since the history step From put onto the terrain model as one line, as the tracks go onto the + // terrain: the track ending at End then the one the laying goes on from + bool nmt_fit_laid(std::size_t const From, glm::dvec3 const End); + // the tracks laid one after another on one straight or one arc, cut by the grade lines fitted before, made one again + void nmt_merge_laid(std::unordered_set &Laid); + // the points of the paths of the track about a metre apart, in squares of the plan + static void nmt_sample_paths(TTrack const &Track, std::map, std::vector> &Points); + // the tool of the terrain the left mouse button works + enum class terrain_tool + { + none, // picks the models, as in the surroundings + chunks, // adds a chunk, Shift: removes it + sculpt, // raises the ground, Shift: lowers it + smooth, + level, // leads the ground to the target height, Ctrl: picks the target height under the cursor + paint, // paints the chosen material, Shift: the first material of the palette + spacing, // selects chunks (Ctrl: adds or takes away one), whose point spacing is then converted + water, // outlines a body of water + restore, // takes the touch-ups over the modifiers back + fill // outlines an area filled with a material + }; + terrain_tool m_terrain_tool{terrain_tool::none}; + bool terrain_brush() const + { + return m_terrain_tool == terrain_tool::sculpt || m_terrain_tool == terrain_tool::smooth || m_terrain_tool == terrain_tool::level || m_terrain_tool == terrain_tool::paint || + m_terrain_tool == terrain_tool::restore; + } + // the point of the ground of the terrain under the cursor, found along the ray through the cursor, so it's found also over + // a hole and behind the grass. returns: false if the ray meets no terrain + bool terrain_cursor(glm::dvec3 &World) const; + // the point of the ground under the cursor in this frame, for the points put on the ground (outlines, areas, brushes): along the ray + // through the cursor to the terrain; the depth read back (a frame late, and stopped by the models over the ground) only where + // there's none. false: nothing under the cursor + bool cursor_on_ground(glm::dvec3 &World); + // converts the point spacing of the selected chunks to m_terrain_convert_spacing + void convert_selected_chunks(); + // the chunks selected with the spacing tool taken out of the terrain, in one step of the history + void remove_selected_chunks(); + // takes the height of whatever is under the cursor (terrain, track, model) for the target of the level brush. returns: false if there's nothing + bool pick_terrain_target(); + bool terrain_clicking() const { return m_terrain_tool == terrain_tool::chunks || m_terrain_tool == terrain_tool::spacing || m_terrain_tool == terrain_tool::water || m_terrain_tool == terrain_tool::fill; } + // fills the outlined area with the material of the chosen palette entry, turned by m_paint_rotation + void fill_terrain_area(); + // the brush, the hovered chunk and the outlines of water drawn over the viewport + void draw_terrain_overlay(); + // forgets what's known about the ground, after the terrain changed + void forget_ground(); + // the ground gathered where the terrain changed in the rectangle (x, z) gathered again when asked for, the rest kept + void forget_ground_in(glm::dvec2 const &Min, glm::dvec2 const &Max); + // conversion of the ground of the terrain files of the scenery (terrain directive, .txtf/.btf) to heightmap terrain + struct ground_conversion + { + struct source + { + std::string file; // as the terrain directive names it + std::uint16_t reference{0}; // see scene::terrain_file::reference_of() + bool text{false}; // read from the text file, rather than the binary one + bool good{false}; + bool chosen{true}; + std::string message; + std::size_t first{0}, count{0}; // its triangles + }; + bool open{false}; + std::vector files; + std::vector> triangles; + std::vector materials; // of the triangles: index of the name + std::vector names; // of the materials + std::set chosen; // materials to convert + std::string status; + } m_ground_conversion; + // reads the triangles of the terrain files of the scenery for the conversion + void load_ground_files(); + // the folder of the textures as a browser, in the window of the node bank while the terrain is edited: the textures and the + // materials can be dragged onto the fields which take a material + struct texture_browser + { + struct item + { + std::string name; // as the materials are named: relative to the folder of the textures, without the extension + std::string label; // the file, without the folder + bool material{false}; // there's a .mat file of the name + }; + std::string folder; // relative to the folder of the textures, empty or with a trailing slash + std::vector folders; // under the current one + std::vector items; + bool listed{false}; + char filter[64]{}; + float size{96.f}; // of the images, pixels + std::string selected; + std::map thumbnails; // texture shown for the item of the name, 0: none + int loads{0}; // textures read in the frame, a few at most so the browser doesn't stall the editor + int loadsframe{-1}; + } m_textures; + void render_texture_browser(); + // texture of the image of the item of the browser, 0 while there's none + std::uint64_t texture_thumbnail(texture_browser::item const &Item); + // takes a material dragged from the texture browser onto the item drawn last. returns: true if one was dropped, its name in Name + static bool material_drop(std::string &Name); + // the same, for a text field + static bool material_drop(char *Buffer, std::size_t Size); + // replaces the chosen triangles of the chosen terrain files with chunks of heightmap terrain of their shape, painted with + // their materials; the files lose them on save. returns: summary for the user + std::string convert_ground(); + void render_ground_conversion(); + // handles a click of the chunk, spacing and water tools (Shift: the other way round) + void handle_terrain_click(bool const Shift); + // writes the changes to the files of scenery opened for editing (Ctrl+S) + bool save(); + // places include of specified scenery template at the cursor, in the active layer + void place_include(std::string const &File, int RotationMode, float FixedRotation); + // undo and redo of placing or removing an include: brings removed include back, or removes it + void toggle_include(scene::instance_handle Instance); + // makes specified include the selected one, 0 clears the selection + void select_include(scene::instance_handle Instance); + // writes parameter values of the selected include to its directive, and shows the outcome in the scene + void apply_include(); + // replaces directive of specified include, and the models shown for it + void set_include_directive(scene::instance_handle Instance, std::string const &Directive); + // undo and redo of an include snapshot + void restore_include(EditorSnapshot &Snapshot); + // undo and redo of the includes placed, removed or changed together + void restore_includes(EditorSnapshot &Snapshot); + // gizmo for the selected include, limited to what the parameters of its template can express + void render_include_gizmo(glm::mat4 const &View, glm::mat4 const &Projection, glm::dvec3 const &Camerapos); + // exports the scenery in legacy (text) format, with layers hidden in the editor left out of the picture + void export_scenery(); + // works the brush of the terrain under the cursor while the left mouse button is held + void handle_terrain_brush(double Deltatime); + // the chunk of the terrain (if any) covering the given world point + editor_terrain *terrain_at(double X, double Z); + // the chunks of the terrain held in memory + std::vector active_terrains() const; + // samples the selected model instance's geometry into the chunks of the terrain it covers, then removes it + void capture_terrain(); + bool m_terrain_open{false}; // the terrain is the field of work, chosen in the toolbar + float m_terrain_spacing{2.0f}; // point spacing of the chunks made and of the spacing tool + float m_terrain_baseheight{0.0f}; // height of chunks made where there's no ground + int m_terrain_add_count{4}; // chunks along a side added around the camera + float m_terrain_brush_radius{12.0f}; + float m_terrain_brush_strength{4.0f}; // metres per second while held; for the paint, how fast it covers + // the level brush + float m_terrain_target{0.0f}; // height the ground is led to + int m_terrain_level_mode{0}; // 0: up and down, 1: only raises, 2: only lowers + bool m_terrain_target_from_stroke{false}; // the target is the height where a stroke starts + bool m_terrain_stroke{false}; // a stroke of the brush is under way + bool m_terrain_picking{false}; // the next click picks the target height + int m_terrain_layer{0}; // entry of the palette painted + char m_terrain_material[128]{"grass"}; // material added to the palette + float m_terrain_material_size{0.0f}; // metres its textures repeat at, 0: given by the material + float m_terrain_layer_size{0.0f}; // repeat of the chosen palette entry, while it's dragged + bool m_terrain_layer_size_dragged{false}; + float m_terrain_layer_rotation{0.0f}; // angle of the chosen palette entry, while it's dragged + bool m_terrain_layer_rotation_dragged{false}; + std::vector m_water_points; // outline of a body of water being drawn + float m_water_level{0.0f}; + bool m_water_level_edited{false}; // the level was given by hand, the points clicked don't change it + char m_water_material[128]{""}; + int m_water_selected{-1}; + char m_water_selected_material[128]{""}; // material of the chosen water, while it's edited + int m_water_material_of{-1}; // the water whose material is in the field above + float m_water_selected_size{0.0f}; // metres its texture repeats at, 0: given by the material + std::set m_terrain_selection; // chunks chosen with the spacing tool + float m_terrain_convert_spacing{1.0f}; // point spacing the selected chunks are converted to + bool m_terrain_convert_paint{true}; // chunks converted to 0.5 m get paint samples every 0.5 m too + std::vector m_paint_outline; // of the area filled with a material + float m_paint_feather{0.0f}; // metres the filled material blends in over across the outline, 0: sharp + float m_paint_rotation{0.0f}; // degrees the textures of the filled material are turned by + float m_water_selected_level{0.0f}; // level of the chosen water, while it's edited + bool m_water_level_dragged{false}; + std::string m_terrain_status; + + // the heightmap terrain, shared with the scenery loader so it shows in every mode terrain_streamer &m_streamer{EditorTerrain}; - int m_stream_radius{2}; - bool m_stream_persist{true}; // save edited chunks to disk and load them back + + // geoportal orthophoto layer drawn under the other viewport overlays + void render_orthophoto_ui(); + void render_map_menu(); + bool m_newscenery_asked{false}; + void render_new_scenery_popup(); + bool restart_for_new_scenery(); + bool restart_editor(std::string const &Scenery); + bool m_openscenery_asked{false}; + bool m_opened_at_track{false}; + bool m_turntable_included{false}; + bool turntable_controls(std::vector &Rootstatements); + bool m_nose_included{false}; + bool nose_controls(std::vector &Rootstatements); + void starter_trainset(std::vector &Trailing); + std::optional> m_saved_camera; + char m_openscenery_search[64]{}; + std::vector m_openscenery_list; + std::string m_openscenery_choice; + void render_open_scenery_popup(); + // the settings of the orthophoto, among the base layers in the layers window: asked to be opened there, the frame they were last + // drawn open in + bool m_orthophoto_window{false}; + // the user turned the orthophoto on or off, or the scenery keeps it so: the terrain model made, or the area drawn, leaves it as it + // is then, it turns it on only where nobody chose + bool m_orthophoto_chosen{false}; + // the user turns the orthophoto on or off: kept with the editor, for every scenery + void choose_orthophoto(bool const On); + int m_orthophoto_frame{-10}; + bool orthophoto_settings_open() const; + // view menu: the top view, the lanes of the roads, the structure gauge, the environment + void render_view_menu(); + // time of day, day of the year, visibility, clouds and air temperature, as the scenery is seen in the editor + void render_environment_window(); + bool m_environment_open{false}; + // over the 3d view: the tools of the field of work along its left edge, the modes of the gizmo at its top, the axes of the + // world and the top view in its top right corner + void render_viewport_overlays(); + // the tools of the field of work, in the order of the toolbar + void work_area_tools(std::vector &Buttons); + // the tools of the field of work in the toolbar, as icons with their names + void render_toolbar_tools(); + // what the row of the toolbar holds, written at its left end: the fields of work, the tools + static void render_toolbar_caption(char const *Text); + void render_viewport_gizmo(); + void render_view_axes(); + // the camera looking along an axis of the world (0: x, 1: y, 2: z) from its positive or negative side + void look_along_axis(int const Axis, bool const Positive); + // origin of the scenery in PUWG 1992 the scenery file gives in its //$g line, if it does + bool m_georeference_read{false}; + bool m_georeference{false}; + glm::dvec2 m_georeference_origin{0.0}; // northing, easting + std::string m_georeference_line; + void read_georeference(); + void draw_orthophoto(); + void draw_ortho_compass() const; + // picks up the stored settings and the origin of the current scenery, and the offset of the terrain model the scenery has + void load_orthophoto_settings(); + void save_orthophoto_settings(); + // the settings of the terrain model changed, kept with the editor, and the offset of the model with the scenery's + void keep_nmt_settings(); + editor_orthophoto m_orthophoto; + // the WMS layers of the user's over the orthophoto, the top one first, as the settings of the editor keep them; their tiles are + // kept in memory only + std::vector> m_wms; + // a WMS layer being added: the address typed, what its capabilities tell, read on a thread of its own, the layers ticked + struct wms_adding + { + std::array url{}; + std::array filter{}; + std::future reading; + std::optional info; + std::string service; // the address the capabilities were read of + std::vector ticked; + } m_wms_adding; + // the orthophoto and the WMS layers of the user's at the bottom of the layers window, with their settings + void render_base_layers(); + void render_wms_adding(); + // the WMS layers as the settings have them, laid out by the origin and on the ground of the orthophoto, around the camera + void update_wms_layers(); + // the ground the imagery is fitted onto, the same for the orthophoto and the WMS layers + void ground_sources(editor_orthophoto &Layer); + std::size_t m_ortho_resident{0}; // chunks of the terrain in memory, as the imagery last heard of them + std::size_t m_ortho_waiting{0}; // squares of the terrain model asked for and not in yet, the same + std::string m_orthophoto_scenery; // scenery whose origin is loaded + std::string m_orthophoto_mark; + std::vector m_orthophoto_area_mark; // the lines of the download area as the scenery keeps them + // the download area being drawn on the map: its points in the world (x, z), the one dragged + struct area_drawing + { + bool active{false}; + std::vector points; + int dragged{-1}; + } m_area_drawing; + std::vector m_nmt_prefetched; // the download area the terrain model was given + bool m_area_paused{false}; // the download of the area held by the button; out of the editor it's held anyway + // the terrain made around the camera within the area: the chunks there, nearest first, the next one looked at, when the next one + // may be made, those made (or left: the model has no data there, or the chunk is outside the region) since the scenery opened + struct area_terrain + { + std::vector keys; + std::size_t next{0}; + heightmap::chunk_key centre{0, 0}; + bool listed{false}; + double resume{0.0}; + std::size_t made{0}; + std::size_t square_made{0}; // of them, in the square around the camera now + bool refit{false}; // chunks made since the photos were last laid onto the ground + double waiting{-1.0}; // since when the next chunk waits for its model; -1: it doesn't + std::string held{"-"}; // what held it last, as logged; empty: nothing + double took{0.0}; // s the chunks of the square around the camera took, all and the longest + double took_most{0.0}; + std::set empty; + std::optional run_only; // the selftest turned it on or off for its run, the setting left as it is + } m_area_terrain; + int m_area_square{0}; // km, the side of the square around the camera waiting for its yes in place of the area there is + bool m_outside_area_closed{false}; // the note of the camera outside the area closed; open again once it's back inside + int m_empty_hint_frame{-10}; // the frame the panel of the empty scenery was last drawn in + glm::dvec2 m_orthophoto_origin_edit{0.0}; // origin being typed in (northing, easting); applied when editing ends // hierarchy management void add_to_hierarchy(scene::basic_node *node); void remove_from_hierarchy(scene::basic_node *node); + void erase_model(TAnimModel *model); scene::basic_node* find_in_hierarchy(const std::string &uuid_str); scene::basic_node* find_node_by_any(scene::basic_node *node_ptr, const std::string &uuid_str, const std::string &name); @@ -196,12 +961,2564 @@ class editor_mode : public application_mode void render_change_history(); void render_settings(); + // area fill: scatters models from a package over a polygon outlined in the viewport + void render_area_fill(); + void draw_area_fill_outline() const; + void add_area_fill_point(); + void run_area_fill(); + void undo_last_area_fill(); + std::vector m_fill_points; // outline vertices (world space) in click order + std::vector m_fill_last; // instances created by the most recent fill, for "Undo last fill" + std::vector m_fill_custom; // user-assembled package of node templates + int m_fill_custom_idx{-1}; + model_set_ref m_fill_source; // manual = m_fill_custom, otherwise a user set or node bank group + float m_fill_density{200.0f}; // objects per hectare + float m_fill_min_spacing{2.0f}; // minimal distance between placed objects (m) + bool m_fill_random_rotation{true}; // random yaw; otherwise the Functions panel rotation settings apply + float m_fill_scale_min{1.0f}; + float m_fill_scale_max{1.0f}; + bool m_fill_models_as_ground{true}; // large model instances (terrain tiles) count as ground + std::string m_fill_status; // result of the last fill, shown in the panel + + // array: copies of the selected model set out in a row, after the array modifier of Blender + struct array_settings + { + int fit{0}; // 0: fixed count, 1: as many as the length takes + int count{2}; // the model itself included + float length{10.0f}; // m + bool relative{true}; + glm::vec3 relative_offset{1.0f, 0.0f, 0.0f}; // of the size of the model, along its axes + bool constant{false}; + glm::vec3 constant_offset{1.0f, 0.0f, 0.0f}; // m, along the axes of the model + float turn{0.0f}; // degrees around the vertical axis, each copy against the one before it + bool ground{false}; // the copies are put as high over the ground as the model is + bool operator==(array_settings const &) const = default; + }; + struct array_tool + { + static constexpr int limit = 1000; // models in an array, so a slip of the finger doesn't freeze the editor + static constexpr double minimal_step = 0.001; // m, copies any closer would sit in one another + array_settings settings; + // the array made last, which follows the settings until something else is selected or changed + TAnimModel *base{nullptr}; // model it was made of, nullptr if there's none + std::size_t step{0}; // size of the undo history with the array at its top + array_settings applied; // what the copies were set out with + glm::dvec3 location{0.0}; // of the model then + glm::vec3 angles{0.0f}; + glm::vec3 scale{1.0f}; + // size of the model asked about last + TModel3d const *sized{nullptr}; + glm::vec3 size{0.0f}; + std::string status; // outcome of the last operation, shown in the panel + }; + array_tool m_array; + void render_array(); + // size of the model of specified instance along its axes, the scale of the instance left out + glm::vec3 array_size(TAnimModel const &Base); + // offset of each copy from the one before it, along the axes of the model + glm::dvec3 array_offset(TAnimModel const &Base); + // number of the models in the array, the one it's made of included. Step: length of the offset + int array_count(double const Step) const; + // location and angles of each copy in turn + std::vector> array_placements(TAnimModel &Base); + // true while the array made last follows the settings + bool array_live() const; + void make_array(); + // brings the copies of the array made last to what the settings ask for + void shape_array(); + void update_array(); + void restore_array_snapshot(EditorSnapshot Snapshot, std::vector &Opposite, bool const Undo); + // ImGuizmo-based transform gizmo for the selected node enum class gizmo_operation { translate, rotate, scale }; void render_gizmo(); + // gizmo settings, drawn in the toolset window + void render_gizmo_options(); + // how the top view draws the tracks: as a combo with the colour of the rails, or as items of a menu + void render_top_tracks_choice(bool const Combo); + // the tools of the field of work in the toolbar under the menu + void render_toolbar(); + // an edit mode of the node bank as the field of work, from the toolbar or its key (1-5) + void choose_edit_mode(nodebank_panel::edit_mode const Mode); + // fields of work of the editor, in the row above the toolbar: the models around, the tracks, the roads, the terrain + enum class work_area + { + surroundings, + tracks, + roads, + terrain + }; + work_area current_work_area() const; + void choose_work_area(work_area const Area); + void render_workspaces(); bool m_gizmo_enabled{true}; // master switch for the in-viewport gizmo + bool m_track_gizmo_on{false}; // the gizmo in the tracks: off until Q, W or E, so a track isn't moved by chance + bool gizmo_shown() const; // the switch of the field of work in use bool m_gizmo_using{false}; // tracks an ongoing drag, so a single undo snapshot is taken per drag bool m_gizmo_local{false}; // manipulate in the object's local space instead of world space gizmo_operation m_gizmo_op{gizmo_operation::translate}; // current transform mode (translate/rotate/scale) float m_gizmo_snap{1.0f}; // translation snap step (metres) applied while Ctrl is held + + TTrack *selected_track() const override; + bool track_editing() const override; + std::size_t history_revision() const override; + glm::dvec3 camera_position() const override; + track_hover const &hovered_track() const override; + std::vector const &track_set() const override; + editor_track_tab current_track_tab() const override; + void render_path_ui(); + void draw_track_overlay() const; + editor_track::point_ref track_handle_hit() const; + void select_track(scene::basic_node *Node); + void render_track_gizmo(); + void commit_track_drag(bool const Force); + void cancel_track_tools(); + void push_track_snapshot(std::vector> States, std::vector Created = {}, std::vector Removed = {}) override; + void push_kilometrage_snapshot() override; + void set_current_node(scene::basic_node *Node) override; + alignment::limits const &route_norms() const override; + void clear_track_point() override; + editor_nmt &terrain_model() override; + double terrain_model_offset() const override; + bool terrain_model_fitted() const override; + // false, with the reason, when one of the paths can't be changed, its file not taking the changes back + static bool tracks_editable(std::vector const &Tracks, std::string &Reason); + void trim_history(); + void restore_track_snapshot(EditorSnapshot const &Snapshot, std::vector &Opposite, bool const Undo); + // changes of the kept alignments and switches go into the last step of the history, made just before them + void records_to_history(); + // the paths a drag of the gizmo takes, to tell after it what became of the kept alignments and switches + struct record_watch + { + bool active{false}; + std::vector moving; + std::vector> before; // ends of the first path of each moving track + std::map> on; // the kept alignments and the moving paths on them + std::set whole; // the kept alignments all of whose paths move + } m_record_watch; + void records_watch_begin(); + void records_watch_end(); + editor_track::point_ref m_track_point; + std::vector m_track_drag; + std::vector> m_track_drag_points; + std::vector m_track_joints; // of the neighbours, following the whole track dragged + editor_track::snap_target m_track_snap; + glm::dvec3 m_track_pivot{0.0}; + glm::mat4 m_track_gizmo{1.0f}; + bool m_track_gizmo_using{false}; + struct track_gizmo_drag + { + gizmo_operation operation{gizmo_operation::translate}; + bool control{false}; + double angle{0.0}; + int path{-1}; + bool atend{true}; + std::size_t pieces{1}; + std::vector paths; + editor_track::point_ref point; + glm::dvec3 origin{0.0}; + glm::dvec3 axis{0.0}; + double grabbed{0.0}; + double length{0.0}; + double stretch{0.0}; + std::vector> partners; + glm::dvec3 fixed{0.0}; + std::vector>> held; + std::vector extra; + int ring{-1}; + glm::dmat3 basis{1.0}; + glm::dvec3 pivot{0.0}; + double grade{0.0}; + double roll{0.0}; + double roll0{0.0}; + double pivot_chainage{0.0}; + std::vector chainages; + std::vector lengths; + struct switch_joint + { + TTrack *track{nullptr}; + editor_track::point_ref own; + editor_track::point_ref theirs; + glm::dvec3 point{0.0}; + glm::dvec3 tangent{0.0}; + double roll{0.0}; + bool moved{false}; + std::vector>> cluster; + std::vector>> joints; + }; + std::vector switches; + }; + track_gizmo_drag m_track_gizmo_drag; + gizmo_operation track_gizmo_operation(TTrack const &Track, bool const Pointmode) const; + glm::mat4 track_gizmo_frame(TTrack const &Track, bool const Pointmode, gizmo_operation const Operation) const; + void track_gizmo_hold(); + void track_gizmo_settle(); + void track_gizmo_stretch(TTrack &Track, double const Length); + void track_gizmo_control(TTrack &Track, glm::dvec3 Control); + void track_gizmo_point(TTrack &Track, glm::dvec3 const &Position); + void track_gizmo_switches(TTrack &Track); + void track_gizmo_conform(TTrack &Track) const; + bool track_gizmo_clustered(TTrack const *Track) const; + void track_gizmo_spill(TTrack &Track, std::size_t const Pieces); + void track_gizmo_carry(track_gizmo_drag::switch_joint &Link, glm::dvec3 const &Point, glm::dvec3 const &From, glm::dvec3 const &To, double const Grade); + void track_gizmo_roll_switch(track_gizmo_drag::switch_joint const &Link, double const Roll); + void track_gizmo_take_joints(TTrack &Track); + void track_gizmo_take_points(TTrack &Track); + void track_gizmo_take_partners(TTrack &Track); + void track_gizmo_take_switch_joints(TTrack &Track, bool const Controlmode); + track_gizmo_drag::switch_joint track_gizmo_link(TTrack &Track, editor_track::point_ref const &Own, std::pair const &Connection, std::function const &Movable); + void track_gizmo_take_switches(TTrack &Track); + // the other switch of a double switch and the track between them go with the moved or turned switch as a whole + void track_gizmo_take_double(TTrack &Track); + void track_gizmo_measure_rotation(TTrack &Track, bool const Pointmode); + void track_gizmo_measure(TTrack &Track, bool const Pointmode, gizmo_operation const Operation); + void track_gizmo_begin(TTrack &Track, bool const Pointmode, gizmo_operation const Operation); + void track_gizmo_turn_direction(TTrack &Track, double const Angle); + void track_gizmo_turn_grade(TTrack &Track, double const Angle); + void track_gizmo_turn_cant(TTrack &Track, double const Angle); + void track_gizmo_turn(TTrack &Track, int const Axis, double const Angle); + void track_gizmo_rotated(TTrack &Track); + void track_gizmo_scaled(TTrack &Track); + void track_gizmo_moved_point(TTrack &Track, glm::dvec3 const &Position); + void track_gizmo_length(TTrack &Track, double Length); + void track_gizmo_end(TTrack &Track); + bool m_track_dirty{false}; + bool m_track_drag_on_the_way{false}; // committed, but not as the end of the drag + std::chrono::steady_clock::time_point m_track_last_commit; + editor_track::state m_track_field_before; + // the event to add to the path, typed + TTrack const *m_track_events_for{nullptr}; + std::array m_track_event{}; + int m_track_event_list{0}; + std::string m_track_events_missing; + void render_path_events(TTrack &Track); + std::string m_track_mode_notice; + struct route_design + { + TTrack *from{nullptr}; + TTrack *to{nullptr}; + editor_track::chain chain; + std::string error; + std::string status; + alignment::design design; + alignment::result result; + int vertex{-1}; + int grip{-1}; + bool single{true}; // one curve between its straights, instead of the whole line + bool relaying{false}; // the crossovers of the line were taken out, they go back once it's laid + // crossovers taken out with a line which didn't fit it laid again, tried again as the other lines are laid + struct crossover_out + { + int shape{-1}; + glm::dvec3 press{0.0}, release{0.0}; + std::string name; + std::vector names; // of the switches at the press and at the release + }; + std::vector crossovers_out; + double origin{0.0}; // km of the start, m + int designed{0}; // vertices whose parameters came from the alignment kept in the scenery + int departed{-1}; // alignment kept in the scenery near the fragment, which its paths no longer follow + double departure{0.0}; + // the band of the curvature in the panel: the element under the mouse, the point of it, and what's dragged in it + struct curvature_band + { + int hot{-1}; + double at{-1.0}; + int vertex{-1}; + int part{0}; // 1 the radius, 2 the transition in, 3 the transition out, 4 the transition between two arcs of a compound curve + int arc{0}; // the arc of a compound curve the radius is of, 0 the first; of a transition between arcs the one after it + double value{0.0}; + ImVec2 press{0.0f, 0.0f}; + float metres{1.0f}; // pixels of a metre and of a unit of the curvature, kept as the drag goes + float curvature{1.0f}; + } band; + // the part of a curve whose field the mouse is over in the panel, or which is being edited there, shown in the view + struct curve_focus + { + enum class part + { + whole, + entry, + exit, + arc, // of the radius `arc`, the first one 0 + between // the transition leading into the arc of the radius `arc` + }; + int vertex{-1}; + part what{part::whole}; + int arc{0}; + bool held{false}; // by a field being edited, the mouse over the others doesn't move it + } focus; + // the points clicked when the fragment was laid, kept with its design: the curves keep to them as their transitions and cants + // change, while hold is on + std::vector clicks; + bool hold{true}; + struct click_state + { + double offset{0.0}; // from the line, m + int vertex{-1}; // whose curve it's a point of + bool corner{false}; // a bend of straights clicked, the vertex itself rather than a point of its curve + }; + std::vector click_states; // as the line was at the revision measured + int revision{0}; // of the result, counted as it's computed + int measured{-1}; + // points clicked along the middle of the track seen on the orthophoto, the radii of the curves and their shares fitted to them after each click + struct trace_state + { + bool active{false}; + int radii{0}; // 0: as many as the points need, up to three + std::vector points; + alignment::design before; // taken back by Esc + double rms{0.0}; + double worst{0.0}; + } trace; + }; + void render_route_ui(); + bool render_route_band(); + bool render_route_parameters(); + bool render_route_vertices(); + bool render_route_vertex(int const Index); + void render_route_result(); + void render_route_trace(); + // the camera over the stretch of the line between the chainages, a curve seen whole + void route_show_curve(double const From, double const To); + // the departures of the points clicked from the line and the curves they belong to, measured again when the line changed + void route_measure_clicks(); + // the points clicked along the curve of the vertex, in the plan, the bends of straights left out + std::vector route_clicks_of(int const Vertex) const; + // the radii of the curve of the vertex fitted again to the points clicked along it, its transitions and cants as they are + bool route_hold_clicks(int const Vertex); + // the elements of the part of the curve in focus in the panel, in their order along the line + std::vector route_focused() const; + void route_trace_start(); + void route_trace_fit(); + void route_trace_end(bool const Keep); + int route_trace_hit() const; + glm::dvec3 route_trace_cursor() const; + void route_reset(); + void route_bind_ends(); + bool route_from_curve(TTrack &Track); + bool route_from_line(TTrack &Track); + // the first curve of the design and the last one going on from the curves of the tracks adjoining, where they turn their way: a + // curve cut by a switch bent into it, say. Lays the design + void route_curved_ends(); + alignment::vertex route_vertex_of(editor_track::curve const &Curve) const; + bool route_load(TTrack &Track); + void route_read_stored(TTrack &Track); + void route_take_stored(int const Index); + void record_switch(TTrack &Track, editor_track::switch_template const &Shape); + void record_double(TTrack &First, TTrack &Second, editor_track::switch_template const &Shape); + // the two switches of a double switch and the plain track between them, found from any of the three + struct double_switch + { + TTrack *first{nullptr}; + TTrack *link{nullptr}; + TTrack *second{nullptr}; + }; + std::optional double_of(TTrack const &Track) const; + // a slip of the scenery the track is a part of: its switches, all its tracks, the switches among them, and its ends where it joins + // the tracks around, A and B of its first track through, C and D of the other one, with the way into the slip at each + struct slip_set + { + switch_store::record record; + std::vector switches; + std::vector parts; + std::array ends{}; + std::array into{}; + }; + std::optional slip_of(TTrack const &Track) const; + // the two tracks of the slip through it from end to end, as they cross where it's taken out + static std::array slip_throughs(slip_set const &Slip); + // the slip taken out with its record, nothing of it put in the history yet; with Throughs its two tracks laid crossing in its + // place, given back + std::vector slip_taken_out(slip_set const &Slip, bool const Throughs); + // the record of the crossing of two plain tracks the track is one of + std::optional crossing_record(TTrack const &Track) const; + // the paths of the set in the order editor_track::place_switch gives them + static std::vector double_paths(double_switch const &Set); + // the switch of the template, or the two switches of a double one with the plain track between them, committed and recorded + std::vector create_switch_set(editor_track::switch_template const &Shape, std::vector const &Paths, TTrack const &Style, std::string const &Name); + // with no Style, as the lay tool lays its tracks + std::vector create_switch_set(editor_track::switch_template const &Shape, std::vector const &Paths, TTrack const *Style, std::string const &Name); + void record_slip(std::vector const &Parts, std::string const &Kind, std::string const &Type, double const Radius, double const Angle, std::string const &Base, double const Middle = 0.0); + void render_switch_record(TTrack const &Track) const; + void route_store(); + bool digitize_drawn(std::vector const &Created, bool const Alone = true) override; + bool digitize_chain(editor_track::chain const &Chain, std::string *Reason = nullptr, TTrack **Culprit = nullptr); + int digitize_parts(editor_track::chain const &Chain, std::string *Reason, int &Skipped); + // the lines kept, the paths left out + void digitize_all(int *Kept = nullptr, int *Failed = nullptr); + // what the digitization of the scenery did, or would do + struct digitize_report + { + int lines{0}; + int lines_failed{0}; + int switches{0}; + int known{0}; // kept in the scenery already + int designed{0}; // of a template of the catalogue + int measured{0}; + int slips{0}; + int unnamed{0}; // no record finds them + int odd{0}; + int recorded{0}; + int crossovers{0}; + int crossovers_known{0}; + int crossovers_recorded{0}; + int crossovers_odd{0}; + int found{0}; + int bound{0}; + std::map types; // of the catalogue + std::map shapes; // measured + std::vector notes; + }; + // the switches without a type kept get the one of the catalogue they are of, or the size measured from their shape + void digitize_switches(digitize_report &Report, bool const Write); + // two switches facing each other from two tracks, their diverging tracks joined by a plain one, are kept as a crossover + void digitize_crossovers(digitize_report &Report, bool const Write); + // the lines, the switches, the crossovers and the objects along the tracks at one go; without Write only counts them + std::string digitize_scenery(bool const Write); + void render_route_stored(); + void route_update() + { + m_route.design.norms.checked = true; + m_route.result = alignment::compute(m_route.design); + ++m_route.revision; + } + void route_apply(); + void route_lay(); + bool route_relay_through_switches(editor_track::chain const &Chain, std::vector> &States, std::vector &Created, TTrack *&Last); + void route_recommend(alignment::vertex &Vertex) const; + void draw_route_overlay() const; + void render_route_gizmo(); + glm::dvec3 route_vertex_position(int const Vertex) const; + bool route_active() const; + route_design m_route; + + struct straights_state + { + editor_track::straight_tolerance tolerance; + double minimum_length{50.0}; + std::vector found; + int listed{-1}; + TTrack *current_for{nullptr}; + editor_track::straight current; + std::vector neighbours; + std::vector spacings{3.5, 4.0, 4.5, 4.75, 5.0, 5.5, 6.0}; + char filter[32]{}; + int handle{-1}; + bool dragging{false}; + editor_track::straight drag_line; + std::vector set; + std::vector drag_lines; + bool fitting{false}; + editor_track::curve fit_before; + editor_track::curve fit_after; + bool fit_has_before{false}; + bool fit_has_after{false}; + std::vector> drag_states; + std::size_t drag_step{0}; + glm::dvec3 preview_start{0.0}; + glm::dvec3 preview_end{0.0}; + glm::dvec3 edit_start{0.0}; + glm::dvec3 edit_end{0.0}; + double edit_length{0.0}; + double edit_azimuth{0.0}; + double distance{4.0}; + double curve_radius{0.0}; + bool auto_transitions{true}; + double transition{0.0}; + int tool{0}; + int tool_before{0}; + bool tool_mouse{false}; + std::vector detour; + editor_track::straight detour_line; + glm::dvec3 detour_mouse{0.0}; + bool tool_placed{false}; + double tool_at{0.0}; + glm::dvec3 tool_point{0.0}; + glm::dvec3 tool_handle{0.0}; + editor_track::straight tool_line; + std::string status; + }; + void render_straights_ui(); + void draw_straights_overlay() const; + editor_track::straight const ¤t_straight(); + bool straights_active(); + void render_straight_gizmo(); + void straight_apply(editor_track::straight const &Line, glm::dvec3 const &Start, glm::dvec3 const &End); + void straights_apply(std::vector const &Lines, std::vector> const &Ends); + bool in_straight_set(editor_track::straight const &Line) const; + bool place_straight_tool(); + void apply_straight_tool(); + double straight_tool_radius(editor_track::straight const &Line) const; + void straight_reshape(editor_track::straight const &Line, double const From, double const To, std::function const &Tail, double const Radius); + void straight_refresh() override; + bool start_curve_fit(editor_track::straight const &Line, int const Handle); + void update_curve_fit(glm::dvec3 const &Start, glm::dvec3 const &End); + void add_detour_point(); + void apply_detour(); + std::vector detour_outline() const; + void find_neighbour_straights(); + // listed spacing of a neighbouring straight the line can snap to, if it is close enough + struct parallel_offer + { + bool nearby{false}; + bool snaps{false}; + double spacing{0.0}; + double distance{0.0}; + double angle{0.0}; // deg between the two straights + double correction{0.0}; // m along the line normal to reach the spacing + editor_track::straight const *neighbour{nullptr}; + }; + parallel_offer straight_parallel_offer(editor_track::straight const &Line, glm::dvec3 const &Offset) const; + glm::dvec3 snap_straight_offset(editor_track::straight const &Line, glm::dvec3 const &Offset) const; + glm::dvec3 snap_straight_direction(glm::dvec3 const &Pivot, glm::dvec3 const &Moved) const; + straights_state m_straights; + + struct curve_sample + { + double station{0.0}; + glm::dvec3 position{0.0}; + glm::dvec2 tangent{0.0, 1.0}; + float roll{0.f}; + float radius{0.f}; + }; + // the line leaving an end of a switch off its main straight, taken before the switch moves: its paths up to the end of + // the straight past the curve next to the switch. When the switch moves only the paths up to a joint on that straight + // are laid again, so the curve keeps to the end of the switch and the rest of the network stays where it is + struct switch_branch + { + std::size_t joint{0}; + editor_track::chain chain; + std::size_t straight{0}; // the first path of the straight past the curve + alignment::design design; // as the paths lie + alignment::result result; + // made for the new end of the switch + editor_track::chain part; // the paths laid again + std::vector pieces; + alignment::design laid; // of the whole chain + double factor{1.0}; // of the radius and the transitions of the curve + }; + struct switch_tool + { + std::vector keep_names; // the names the switches laid next take, before the ones of the tool + std::string keep_slip; // the name the slip or the crossing laid next takes, of the one it's laid in place of + bool curved{false}; + // a switch placed where there's no track: started on the ground, or at the free end it goes on from in its direction; the direction + // of its main track taken from the drag once it's long enough, then the drag sideways gives the side of the diverging one + bool free{false}; + editor_track::snap_target free_end; + std::optional free_heading; + // from a free end, dragged on past its end: bent, its diverging track turning the other way than the main one, the same way with + // Tab (one-sided) + bool one_sided{false}; + std::vector frame; + std::vector frame_tracks; + std::vector templates; + bool collected{false}; + int armed{-1}; + int last{0}; // template armed the last time + bool placing{false}; + // where it was pressed on the screen: let go no farther from there, the press places nothing, a click doesn't lay a switch by chance + glm::vec2 pressed_at{0.f}; + double along{0.0}; + double pressed{0.0}; // along a curve: where the press was, the start of the switch drawn from it to the ends of the cant ramps + glm::dvec3 point{0.0}; + glm::dvec3 mouse{0.0}; + editor_track::straight line; + std::string status; + char name[64]{}; + struct drive_family + { + std::string name; + std::array files; + std::array heights{}; + bool preferred{false}; + }; + std::vector drives; + int drives_revision{-1}; // of the include bank the drives were read from + int drive{-1}; + int drive_side{0}; + struct slide_state + { + bool active{false}; + TTrack *track{nullptr}; + glm::vec2 pressed{0.f}; + double grip{0.0}; + double low{0.0}; + double high{0.0}; + double distance{0.0}; + double length{0.0}; + std::vector joints; + // the lines leaving the switch off its straight: the joint they leave at, the path of the switch in the shown ones + struct branch_line + { + editor_track::joint joint; + std::size_t path{0}; + switch_branch branch; + }; + std::vector branches; + // a switch bent into a curve slides along it: the curve its main track and the tracks next to it make, where the switch + // starts on it; low and high the distances it may go back and on + std::vector frame; + double station{0.0}; + }; + slide_state slide; + double slide_typed{0.0}; + int connection{-1}; + int connection_kind{0}; // the kind of connection chosen last, taken again when the connections are chosen + std::string rail_pick{"60E1"}; // the rail whose templates are listed first where the track doesn't tell its rail + int connection_second{-1}; + double connection_radius{0.0}; + double connection_gap{6.0}; + bool connection_together{false}; + char connection_spacings[64]{"4.75;4.75;5.0"}; + double connection_stub{25.0}; + // the connection a switch dragged makes, as where it's let go tells it, in connection then: let go on the other track a + // crossover, across the tracks between them a ladder; by a crossover there already turned the other way a double crossover + // with it, over it a scissors one + bool recognised{false}; + TTrack *partner{nullptr}; // a switch of the crossover there already + }; + switch_tool m_switch; + // what the switch tool places: a switch into a straight or a curve, a slip switch or a crossing at a crossing of two + // straights, or a connection of tracks laid whole + enum class switch_kind + { + single, + slip, + crossing, + connection + }; + switch_kind current_switch_kind() const; + void choose_switch_kind(switch_kind const Kind); + bool switch_kind_offered(switch_kind const Kind) const; + bool plan_connection(connection::request &Request, connection::result &Result) const; + // what the drag of the switch being placed makes, from where the cursor is: sets connection and partner of the tool + void recognise_connection(); + // the double or the scissors crossover of the partner and the crossover dragged, on the lines of their tracks + bool plan_partner_connection(connection::request &Request, connection::result &Result) const; + void insert_partner_connection(); + // the switches and the inserts of the connection planned laid, one step of the history. false if they don't fit + bool lay_planned_connection(connection::request const &Request, connection::result const &Plan, TTrack *Style); + void insert_connection(); + void render_connection_options(); + // the name of a kind of connection of tracks, translated + static char const *connection_name(int const Kind); + // the name of a switch template for the lists: where it comes from and its name without the lengths + static std::string switch_template_label(editor_track::switch_template const &Template); + // the name of a switch template for the user: translated, with the speed on its diverging track + static std::string template_name(editor_track::switch_template const &Template); + // the template of the catalogue a record of the switches was laid of, -1 if none: Lengths compares a and b too, which the + // record of a connection keeps for its spacing; Movable: the nose of the frog, either when not given + int matching_template(switch_store::record const &Record, bool const Lengths, std::optional const Movable = std::nullopt) const; + // the template the switch was laid of, -1 if none: a switch of the scenery of its own shape, say + int switch_template_index(TTrack const &Switch) const; + // why the switch can't take another template here, empty when it can + std::string template_change_blocked(TTrack const &Switch) const; + // the template of the catalogue a slip or a crossing was laid of, of the rail before the others; -1 if none + int slip_template_index(switch_store::record const &Record, std::string const &Rail) const; + // the switch of the template of the index in place: its start and its side kept, the tracks it joins following; a switch of a + // crossover takes the crossover with it, laid again, a slip or a crossing is laid again where its tracks cross. One step of the + // history; the status says how it went + bool change_switch_template(TTrack &Switch, int const Index); + bool change_slip_template(TTrack &Part, int const Index); + // the switch, or the double switch it's a part of, given the shape in place, straight or bent into the curve it lies in; Flip: + // the diverging track to the other side. Notes: for the user + bool apply_switch_template(TTrack &Switch, editor_track::switch_template const &Shape, bool const Flip, std::string &Notes); + // the template to choose: the speeds on the diverging track as chips, the templates of the rail by their skos, all the others + // folded under. Fits: those of the kind wanted; Rail: of the track, empty when it doesn't tell; Popup: inside a combo, with no + // windows of its own. Gives the index picked, -1 while none is + int render_template_picker(char const *Id, std::function const &Fits, std::string const &Rail, int const Chosen, bool const Popup); + // the template of the selected switch, slip or crossing, changed with a pick: in a combo for the inspector, else in full; nothing + // for another track + void render_switch_template(TTrack &Track, bool const Combo); + std::string connection_readout(connection::result const &Plan) const; + editor_track::straight straight_near(glm::dvec3 const &Point, std::vector const &Exclude, double const Reach) const; + editor_track::straight straight_through(glm::dvec3 const &Point, glm::dvec2 const &Direction) const; + void record_connection(connection::kind const Kind, std::vector const &Switches, connection::result const &Plan, editor_track::switch_template const &Shape); + bool switch_room(TTrack &Track, double &Low, double &High, std::string &Reason); + bool switch_vacate(TTrack &Track, glm::dvec3 const &From, glm::dvec3 const &To, double const Shift, editor_track::straight const &Line, editor_track::edit &Edit, std::string &Status); + bool move_switch_paths(TTrack &Track, std::vector const &Paths, std::string &Status); + std::optional take_switch_branch(TTrack const &Track, editor_track::joint const &Joint, std::size_t const Index) const; + // for the path of the switch the line leaves, as it'll lie + bool plan_switch_branch(segment_data const &Path, editor_track::joint const &Joint, switch_branch &Branch) const; + void lay_switch_branch(switch_branch const &Branch, editor_track::edit &Edit); + // of the joints off the main straight of the switch, the neighbours in Skip left out + std::vector switch_branches(TTrack const &Track, std::vector const &Joints, std::vector const &Skip = {}) const; + // for the paths the switch has now; the joints of the branches which can be laid are handled, the others are left out. Gives the notes for the user + std::string plan_switch_branches(TTrack const &Track, std::vector const &Joints, std::vector &Branches, std::vector &Handled) const; + // room on the straight of the whole double switch along the axis of its first switch, and the length of the set + bool double_room(double_switch const &Set, double &Low, double &High, double &Length, std::string &Reason); + bool move_double_paths(double_switch const &Set, std::vector const &Paths, std::string &Status); + bool slide_switch(TTrack &Track, double const Distance); + bool switch_slides(TTrack const &Track) const; + // a slip slid along its first track: the slip and the tracks its crossing track goes on into with their ends free move whole, the + // straights of its first track before it and past it give and take the length. Low and High: how far back and on it may go + struct slip_slide + { + glm::dvec3 shift{0.0}; // along its first track, a metre of it + std::vector movers; + // where it joins the tracks of its first track before it and past it: at its ends A and B, or at the joints of its template + // with the straights out to them going along; those tracks, the end of each there + std::array joints{}; + std::array, 2> ends{}; + double low{0.0}; + double high{0.0}; + }; + bool slip_room(slip_set const &Slip, slip_slide &Slide, std::string &Reason) const; + bool slide_slip(slip_set const &Slip, double const Distance); + // a switch bent into a curve, its main track going on into a plain track at each end: the curve the three make, the two tracks, + // where the switch starts on it; false for any other + bool bent_switch_frame(TTrack const &Track, std::vector &Frame, std::array &Sides, double &Station) const; + // the paths of the switch moved along the curve by the distance, shaped as the curve is there + std::vector bent_switch_paths(TTrack const &Track, std::vector const &Frame, double const Station, double const Distance) const; + bool slide_bent_switch(TTrack &Track, double const Distance); + // the switch bent into a curve given the paths, along the curve of the bent_switch_frame: the tracks next to it laid along it up to + // its new ends, one taken up whole going, the curve past the diverging track following. Notes: for the user + bool lay_bent_switch(TTrack &Track, std::vector const &Frame, std::array const &Sides, std::vector const &Paths, std::string &Notes); + void switch_slide_start(TTrack &Track); + void switch_slide_update(); + void switch_slide_finish(); + void draw_switch_slide() const; + // reads the drives from the include bank once it changes; Wait: for the templates being looked for. true if it read them + bool scan_switch_drives(bool Wait = true); + std::string switch_name_for_new() const; + bool place_switch_drive(TTrack &Switch); + bool flip_switch_drive(TTrack &Switch); + void advance_switch_name(); + void join_last_steps(); + bool render_switch_drive_choice(); + struct turntable_template + { + std::string file; + std::string name; + double length{0.0}; + int angles{0}; + int positions{0}; + int track{0}; + int yaw{0}; + std::vector fixed; + }; + struct turntable_fit + { + editor_track::snap_target end; + double heading{0.0}; + double radius{0.0}; + double length{0.0}; + std::vector pieces; + std::string issue; + bool chosen{true}; + TTrack *replaces{nullptr}; + }; + struct turntable_tool + { + std::vector templates; + int revision{-1}; // of the include bank the templates were read from + int chosen{-1}; + char name[64]{}; + bool placing{false}; + glm::dvec3 centre{0.0}; + double yaw{0.0}; + glm::vec2 pressed{0.f}; + editor_track::snap_target snap; + TTrack *table{nullptr}; + scene::instance_handle include{0}; + int kind{-1}; + double length{0.0}; + double table_yaw{0.0}; + std::vector exits; + float reach{80.f}; + float radius{150.f}; + float stub{25.f}; + float step{0.f}; + std::vector fits; + int hovered{-1}; + double heading{0.0}; + double exit_length{0.0}; + std::string status; + std::string error; + }; + turntable_tool m_turntable; + bool scan_turntables(bool Wait = true); + std::string turntable_name_for_new() const; + bool turntable_read(TTrack *Table); + std::vector turntable_includes(TTrack const &Table); + glm::dvec3 turntable_centre() const; + std::vector turntable_lines() const; + double turntable_snap(double const Heading) const; + void turntable_finish_placement(); + void turntable_place(glm::dvec3 const &Centre, double const Yaw); + bool turntable_fit_end(editor_track::snap_target const &End, turntable_fit &Fit) const; + void turntable_find_fits(); + void turntable_build(std::vector const &Fits); + bool turntable_exit_at(glm::dvec3 const &Ground, double &Heading, double &Length) const; + void turntable_store_exits(); + void render_turntable_ui(); + void draw_turntable_overlay() const; + struct extend_tool + { + bool active{false}; + TTrack *track{nullptr}; + glm::dvec3 point{0.0}; + glm::dvec2 direction{0.0, 1.0}; + double grade{0.0}; + glm::dvec3 mouse{0.0}; + int path{0}; + bool atend{true}; + editor_track::snap_target origin; + editor_track::snap_target snap; + glm::vec2 pressed{0.f}; + std::vector line; + }; + extend_tool m_extend; + // what a point clicked while laying is: a bend of the straights, eased with a large curve, or a point along the middle of a curve + // seen on the photo, the curve ending at the last of these + enum class lay_mode + { + straights, + curve + }; + // a curve traced on the photo as it's laid, how far the points clicked along it are from it + struct lay_trace + { + std::vector points; + std::vector offsets; + double rms{0.0}; + double worst{0.0}; + std::size_t curves{0}; + }; + // the line the points clicked make: its design, the bends among its vertices, the curves traced + struct lay_line_plan + { + alignment::design design; + alignment::result shape; + std::vector corners; + std::vector traces; + // the straights of a fixed direction the next bend slides along: from a free end, out of a curve traced + std::vector> guides; + // where the grade breaks from point to point: the bends kept as such, at the heights clicked; a curve traced, or bends made + // one curve, goes at one grade from end to end + std::vector knots; + }; + // lays new track through the clicked points, with no path needed to start from + struct lay_tool + { + bool active{false}; + std::vector points; + std::vector modes; // of the points, as each was clicked + lay_mode mode{lay_mode::straights}; + int radii{0}; // of a curve traced: 0 as many as the points need, up to three + bool straights_between{true}; // a curve traced may be two with a straight between them + lay_line_plan plan; // of the line shown + editor_track::snap_target start; // free end the track starts from, if any + glm::dvec3 mouse{0.0}; + editor_track::snap_target mouse_snap; + std::vector preview; + std::string preview_error; + double preview_length{0.0}; + // the line worked out whole last, all its fits done: shown while the one of the cursor now still waits for them on the thread, + // so that the curves don't jump from one fit to the next as each comes + struct worked_out + { + std::vector preview; + std::string error; + double length{0.0}; + lay_line_plan plan; + std::optional eased; + alignment::join_result join; + std::vector points; // the ones clicked it was worked out for + }; + std::optional shown; + // the cursor the line is being worked out for, kept till all its fits are done: what it was worked out from + struct settling_cursor + { + glm::dvec3 mouse{0.0}; + editor_track::snap_target snap; + std::vector points; + std::vector modes; + lay_mode mode{lay_mode::straights}; + int edits{0}; + }; + std::optional settling; + bool whole{true}; // false: each fit shown as it comes, as before, for a selftest to compare + double radius{500.0}; + double piece_length{100.0}; + bool copy_selected{false}; + editor_track::path_style style; + bool own_speed{false}; // the speed of the style also where the track goes on from one with its own, the new tracks given it + std::string status; + double status_time{-100.0}; + std::string skew; // what Alt turned the straight to + double escape_time{-100.0}; // when Esc was pressed over points not laid: the second Esc drops them + std::size_t history{0}; // the step of the history the track laid last was begun at + }; + lay_tool m_lay; + alignment::limits laying_norms() const; + glm::dvec3 lay_angle_snap(glm::dvec3 const &Mouse, std::string &Label) const; + // the straight track Alt turns the laid straight to: the nearest one the straight from From to To crosses, or one along From + TTrack const *skew_reference(glm::dvec3 const &From, glm::dvec3 const &To, double const Reach) const; + void lay_after_history(bool const Undo); + void lay_back(); + void lay_escape(); + std::size_t lay_pending() const; // the points clicked and not laid yet + void render_lay_ui(); + void render_lay_status(); + void lay_click(); + void lay_finish(editor_track::snap_target const &End); + void lay_cancel(); + void lay_enter(); + // Tab: the bends of straights or the curve traced, for the points clicked from now on + void lay_switch_mode(); + // the points the same in number as their modes, a point with none a bend of straights + void lay_trim(); + // the track through the points clicked, each the way its mode says; End: the free end it finishes at, the last point then + std::vector lay_pieces(std::vector const &Points, std::vector const &Modes, editor_track::snap_target const &End, double &Length, std::string &Error, + lay_line_plan *Plan = nullptr) const; + // Adjoining: the curve next to a free end on a curve goes on from its curvature, where it turns its way; else from a straight there + bool lay_line(std::vector const &Points, std::vector const &Modes, editor_track::snap_target const &End, lay_line_plan &Plan, std::string &Error, bool const Adjoining = true) const; + // whether the points next to the start of the line, or to its end, AtEnd, a free end joined there, are clicked along a curve + static bool traced_from(std::vector const &Points, std::vector const &Modes, bool const AtEnd); + // the curves of a stretch traced, the ones fitted lately kept for the same points + // none while the stretch the cursor moves along is still being fitted; Meanwhile: the fit done last of the same points but the one + // at the cursor until then + // Exact receives whether the fit is the one of these points, not one shown meanwhile; Going: the curve going on from the curve of the + // free end Base starts at, alignment::fit_going_on + std::optional traced_stretch(alignment::design const &Base, std::vector const &Points, int const Radii, bool const Straights, bool const Meanwhile = true, + bool *Exact = nullptr, bool const Going = false) const; + // the curve through a row of bends clicked close along one, by traced_stretch + alignment::stretch_fit bends_fit() const + { + return [this](alignment::design const &Base, std::vector const &Points) { return traced_stretch(Base, Points, 0, false, false); }; + } + mutable std::vector, alignment::trace_stretch>> m_stretch_cache; + // the stretch the cursor moves along is fitted on a thread, the frames drawn meanwhile with the fit done last + mutable alignment::stretch_fitter m_stretch_fitter; + // a fit the line asked the thread for isn't done yet: the line is one of the fits meanwhile + mutable bool m_fits_waiting{false}; + // how much more the curve at the cursor was turned last to reach it, the first one tried for the next line + mutable double m_turned_last{0.0}; + void render_switch_ui(); + void render_switch_timbers(); + void render_rail_profile_hint(TTrack &Track); + bool start_switch_placement(); + void finish_switch_placement(); + // a switch with no track under it: a press on the ground starts it at the free end of a track within reach, none with no free end near + editor_track::snap_target free_switch_end(glm::dvec3 const &Ground) const; + bool free_switch_offered() const; + void start_free_switch(glm::dvec3 const &Ground); + // the start of the switch, the way its main track goes and the side of its diverging one, as the drag gives them so far + void free_switch_pose(glm::dvec3 &Start, glm::dvec2 &Heading, int &Side, double &Grade) const; + // a switch laid on from a free end, dragged on past its end: bent, its main track turning toward the cursor + struct free_bend + { + double radius{0.0}; // of the main track + int turn{1}; // the way the main track turns, 1 to the left + int side{1}; // of the diverging track + std::vector frame; // the curve the switch is bent into + std::vector paths; + switch_curve::switch_report report; + // a free end the cursor is at, which the main track leads into, the diverging one with Shift + editor_track::snap_target target; + bool diverging{false}; + editor_track::branch_link link; + std::string problem; // why it can't lead into the target + }; + // false where it isn't bent: near the switch, along the straight, or not from a free end + bool free_switch_bend(free_bend &Bend) const; + bool free_switch_bend_now(free_bend &Bend) const; + // laid on from an end of a switch: what the norms say of the change of the curvature from that switch to the tracks of this one + std::vector free_switch_exits(std::vector const &Paths) const; + std::vector free_switch_paths() const; + void insert_free_switch(); + std::vector switch_preview() const; + std::vector switch_preview_now() const; + // where a switch can't go, or doesn't go where it's dragged: what's in the way blinking in the view, each point told what's there, + // why by the cursor; while it's dragged, and a while after it's refused + struct switch_problem + { + std::string text; + std::vector paths; + std::vector> marks; + }; + // what's at the end of the straight: a curve beginning, a switch, the track ending + std::string straight_end_note(editor_track::straight const &Line, bool const Far) const; + std::optional switch_drag_problem() const; + std::optional straight_switch_problem(editor_track::straight const &Line, double const Length, double const Along, int const Direction) const; + void flash_switch_problem(switch_problem Problem); + void flash_switch_problem(std::string const &Text, std::vector Paths, std::vector> Marks = {}); + void draw_switch_problem(switch_problem const &Problem) const; + switch_problem m_switch_flash; + double m_switch_flash_until{-1.0}; + // a preview worked out once a frame for the drawing and the readouts which all show it: the frame and the state of the tool it + // was worked out for + template struct frame_memo + { + int frame{-1}; + std::vector key; + Result result{}; + bool fresh(std::vector const &Key) const { return frame == ImGui::GetFrameCount() && key == Key; } + void keep(std::vector Key, Result const &Value) + { + frame = ImGui::GetFrameCount(); + key = std::move(Key); + result = Value; + } + }; + std::vector switch_memo_key() const; + mutable frame_memo> m_switch_memo; + mutable frame_memo> m_bend_memo; + mutable frame_memo> m_extend_memo; + void insert_switch(editor_track::straight const &Line, double const Along, int const Direction, int const Side); + void switch_placed(std::vector const &Created); + static std::vector sample_chain(editor_track::chain const &Chain); + static curve_sample sample_at(std::vector const &Frame, double const Station); + // the curve a switch goes into as the norms look at it: its headings and its cant along it + std::vector frame_points(std::vector const &Frame) const; + // the way the switch being placed into a curve goes along it and the side its diverging track leaves to, from the drag + void curved_switch_pose(int &Direction, int &Side) const; + // the start of the switch being placed into a curve: where it was pressed, drawn to where the switch meets an end of a cant ramp or + // keeps 6 m off it; What receives which + double curved_switch_start(int const Direction, std::string *What = nullptr) const; + // the switch made of the paths, laid into the curve at the station, as ST-T1-A6 sees it + switch_curve::switch_report curved_switch_report(std::vector const &Paths, std::vector const &Frame, double const Station, int const Direction) const; + static double nearest_station(std::vector const &Frame, glm::dvec3 const &Point); + static std::vector curved_switch_paths(editor_track::switch_template const &Shape, std::vector const &Frame, double const Station, int const Direction, int const Side); + // the path of a switch template laid into the curve: x of the template across the main track to the Side, z along it from the + // Station on, going Direction along the curve; past Bent along it going on straight as the curve heads there. The heights and the + // cant are those of the line where the point is along it + static segment_data frame_path(segment_data const &Local, std::vector const &Frame, double const Station, int const Direction, int const Side, std::optional const &Bent = std::nullopt); + void insert_curved_switch(int const Direction, int const Side); + // a crossover between two tracks running side by side along a curve (editormodeconnectioncurve.cpp) + struct curve_mapping; + // Beyond: the straights past the ends of the curve go with it up to that far, and a straight track that near the curve is taken + // as its part + static bool curve_of(TTrack &Track, editor_track::straight_tolerance const &Tolerance, double const Gauge, std::vector &Frame, std::vector &Tracks, double const Beyond = 0.0); + static void cut_curve(std::vector &Candidates, std::vector const &Frame, glm::dvec3 const &First, glm::dvec3 const &Second, std::vector> &States, std::vector &Created, std::vector &Removed); + void insert_curved_connection(); + struct curved_crossover + { + switch_store::record record; + TTrack *first{nullptr}; + TTrack *second{nullptr}; + TTrack *insert{nullptr}; + }; + // the single crossover the switch is a part of, along a curve or straights + std::optional crossover_of(TTrack const &Switch) const; + bool take_out_crossover(curved_crossover const &Crossover, std::vector> &States, std::vector &Created, std::vector &Removed, TTrack *&First, TTrack *&Second); + bool slide_curved_connection(TTrack &Switch, double const Distance, int const Shape = -1); + // the template a crossover was laid of, -1 if it's not among the templates + int crossover_template(switch_store::record const &Record); + // a crossover laid again from the press on one track to the release by the other, as by the mouse. false if it doesn't fit + // Names: of the switch at the press and of the one at the release, kept when a crossover is laid again + bool lay_crossover(int const Shape, glm::dvec3 const &Press, glm::dvec3 const &Release, double const Reach = 3.0, std::vector const &Names = {}); + // after the grade line of the open route went on its paths: the line on the other side of each crossover of the route + // takes the same change of the heights where it runs beside, and its design with it. returns: how many lines followed + std::size_t follow_crossovers(std::vector const &Before); + bool place_switch_on_straight(editor_track::straight const &Line, editor_track::switch_template const &Shape, TTrack const *Style, double const Along, int const Direction, int const Side, bool const Snap, std::vector> &States, std::vector &Created, std::vector &Removed, std::string const &Name = {}); + struct crossover_plan + { + editor_track::straight target; + editor_track::switch_template shape; + double along{0.0}; + int direction{1}; + int side{1}; + std::vector inserts; // a straight one, or an aligning curve between straights onto a track not parallel + std::vector paths; + connection::result connection; // as it's kept with the two switches + }; + bool plan_crossover(crossover_plan &Plan) const; + struct switch_link + { + editor_track::snap_target target; + editor_track::branch_link link; + double along{0.0}; + int forward{1}; + int side{1}; + double moved{0.0}; + std::vector paths; + std::string reason; + }; + bool plan_switch_link(switch_link &Plan) const; + void insert_linked_switch(switch_link const &Plan); + bool plan_branch_link(editor_track::branch_link &Link, std::string &Reason) const; + void finish_branch_link(editor_track::branch_link const &Link); + std::string link_problem(editor_track::snap_target const &Target, editor_track::branch_link const &Link) const; + bool stretchable(editor_track::snap_target const &Target) const; + std::vector link_tracks(editor_track::snap_target const &Target, editor_track::branch_link const &Link, TTrack const &Style, std::vector> &States, std::vector &Created); + bool cut_straight(editor_track::straight const &Line, double const From, double const To, std::vector> &States, std::vector &Created, std::vector &Removed, TTrack **Style); + // where a slip or a crossing goes for the cursor at Point on the straight Line: the crossing of Line with the rail track + // nearest the cursor, or the double slip there to be replaced. With no track crossing there and Side given (1 to the left, -1 to + // the right of Line), the slip brings the crossing track along at its own angle, turning off to that side ahead + struct slip_plan + { + std::string problem; + std::string note; + bool lone{false}; // no track crosses Line by the cursor + TTrack *replaces{nullptr}; + TTrack *other{nullptr}; // the crossing track, none where the slip brings it along + glm::dvec2 crossing{0.0}; + glm::dvec2 first{0.0, 1.0}; + glm::dvec2 direction{0.0, 1.0}; + double angle{0.0}; + double alongfirst{0.0}; + double half{0.0}; + // where the slip brings its crossing track along: from the crossing to the joints of its template, past the frogs of the diamond, + // the straights of both tracks laid out that far; the ends of the straights there, in the order of the points + double reach{0.0}; + std::array ends{}; + editor_track::slip_curve curve; + std::array points{}; + }; + bool plan_double_slip(editor_track::straight const &Line, glm::dvec3 const &Point, editor_track::switch_template const &Shape, slip_plan &Plan, int const Side = 0) const; + // a slip is made for its skos: where the tracks cross at another one, the refusal, which tells the template made for theirs; empty + // where it fits, and for a crossing + std::string slip_skew(editor_track::switch_template const &Shape, double const Angle) const; + // the cursor where it points at the straight, at the height of the straight there + glm::dvec3 cursor_on_straight(editor_track::straight const &Line) const; + bool insert_double_slip(editor_track::straight const &Line, glm::dvec3 const &Point, editor_track::switch_template const &Shape, int const Side = 0); + // the side a slip dragged out on a straight with no track crossing it brings its crossing track to: the one through the quarter of + // the cursor + int lone_slip_side() const; + bool replace_double_slip(TTrack &Part, editor_track::switch_template const &Shape); + // Bend: what a path of the slip laid out as on straights turns into where it's bent into a curve + std::vector build_double_slip(glm::dvec3 const &PointA, glm::dvec3 const &PointB, glm::dvec3 const &PointC, glm::dvec3 const &PointD, glm::dvec2 const &Crossing, double const Height, glm::dvec2 const &First, glm::dvec2 const &Second, double const Angle, editor_track::slip_curve const &Curve, TTrack &Style, std::string const &Type = "Rkpd", + std::function const &Bend = {}); + // a slip switch bent into a curve of a side track (ST-T1-A6 11.4 pkt 4b): laid out on the tangent to the curve at its crossing, where + // it was pressed, and bent onto the curve as a switch laid into it is, its crossing track coming along with its ends free. Direction + // and Side as of a switch dragged into a curve: the crossing track goes ahead to that side, through the quarter of the cursor, and the + // slip curve of a single slip lies on that side + struct curved_slip + { + std::string problem; + std::string snapped; // what the ends of the slip were drawn to + double middle{0.0}; // the station of the crossing along the curve + double half{0.0}; // from the crossing to the ends of the slip + double reach{0.0}; // from the crossing to the joints of the template, the straights of both tracks laid out that far + int direction{1}; + double angle{0.0}; + editor_track::slip_curve curve; + // as the slip is laid out on the tangent, before it's bent: its crossing, its tracks going Direction along the curve, its ends + glm::dvec2 crossing{0.0}; + glm::dvec2 first{0.0, 1.0}; + glm::dvec2 second{0.0, 1.0}; + std::array points{}; + }; + bool plan_curved_slip(editor_track::switch_template const &Shape, int const Direction, int const Side, curved_slip &Plan) const; + // the path of the slip laid out on the tangent, bent onto the curve + segment_data bent_slip_path(curved_slip const &Plan, segment_data const &Path) const; + // the two tracks through the slip and its slip curves, each from end to end, bent: the first track, the slip curve leaving it at its + // start, the second track, the other slip curve of a double slip + std::vector curved_slip_lines(curved_slip const &Plan, std::string const &Type) const; + // the straights of both tracks from the ends of the slip out to the joints of the template, bent + std::vector curved_slip_reaches(curved_slip const &Plan) const; + switch_curve::slip_report curved_slip_report(curved_slip const &Plan, std::string const &Type) const; + // the radii of the slip and its cant, as the view and the status tell them + static std::vector slip_report_lines(switch_curve::slip_report const &Report); + void insert_curved_slip(int const Direction, int const Side); + bool start_extend(editor_track::snap_target const &End); + void finish_extend(); + std::vector extend_pieces() const; + // the same for the track shown while it's dragged: its grade line fitted on the thread of the fitter, the frame not waiting for it + std::vector extend_preview() const; + // the free end of the path as the start of a new track; false if it isn't free or has no direction + static bool free_end(TTrack &Track, int const Path, bool const Atend, extend_tool &Tool); + // the free end new pieces are added at: the selected point if it's one, else the end, else the start + bool chosen_free_end(extend_tool &Tool); + // adds a straight (Side 0) or a curve to the left (1) or the right (-1) at the free end of the selected track + void extend_add(int const Side); + void render_extend_ui(); + using track_layout = editor_track::layout; + // the shape dragged from a free end, as the mode of laying has it: a straight in the one of the straights, an arc and a straight in + // the one of a curve + track_layout m_track_layout{track_layout::straight}; + double m_join_radius{0.0}; + int m_join_variant{0}; + TTrack const *m_join_track{nullptr}; + editor_track::point_ref m_join_point; + mutable alignment::join_result m_join_last; + // the layout laid on from the end of From with the transition curves of the norms; none where it doesn't fit + std::optional eased_layout(TTrack const *From, glm::dvec3 const &Point, glm::dvec2 const &Direction, glm::dvec3 const &Target, double const Radius) const; + mutable std::optional m_eased_last; + mutable std::optional>> m_eased_cache; + bool track_wheel(double const Offset); + // a touchpad sends fractions of a notch: a choice moves a step for each whole notch gathered, and only one in a gesture when + // Gesture; a pause, another key or the other way starts over + struct wheel_state + { + double rest{0.0}; + double time{-10.0}; + int keys{0}; + bool spent{false}; + }; + wheel_state m_wheel; + int wheel_step(double const Offset, bool const Gesture); + std::string track_shaping(bool const Joined) const; + double design_speed(TTrack const *From, TTrack const *To) const; + // the track whose speed the design takes, none where it's the one set for the laying + TTrack const *speed_track(TTrack const *From, TTrack const *To) const; + // the tracks the laying under way goes on from and to + std::pair laying_ends() const; + std::string design_speed_of(TTrack const *From, TTrack const *To) const; + // what ST-T1-A6 says of the sudden changes of the cant deficiency right behind a switch the pieces laid come out of at Start (From), + // or go into at End (To): of the end of its curve and the first sudden change of the pieces (9.11, tables 9.15, 9.16) + std::vector switch_exit_warnings(TTrack const *From, glm::dvec3 const &Start, TTrack const *To, glm::dvec3 const &End, std::vector const &Pieces) const; + void give_own_speed(std::vector const &Created) const; + std::vector join_pieces(TTrack const *From, editor_track::point_ref const &Frompoint, glm::dvec3 const &Start, glm::dvec2 const &Direction, editor_track::snap_target const &End, double &Length, + std::string &Error) const; + double m_extend_length{25.0}; + double m_extend_radius{300.0}; + bool extend_snap(editor_track::snap_target &Target) const; + void update_build_tools(); + void draw_build_overlay() const; + // the joint before the blades of the switch being placed or the one selected and the tips of its blades + void draw_blade_tips() const; + // modes of the track editor, one at a time: path is the plain selection + using track_tab = editor_track_tab; + struct track_mode + { + char const *label; + char const *key; + track_tab tab; + char const *tooltip; + editor_icons::icon picture; + int family; // 0 builds the track, 1 equips it, 2 checks it + }; + static std::array const &track_modes(); + bool track_plan_tab() const { return m_track_tab == track_tab::straights || m_track_tab == track_tab::route; } + // a tool of the station: they share its schematic + bool srk_tab() const { return m_track_tab == track_tab::station || m_track_tab == track_tab::station_signals || m_track_tab == track_tab::line_block; } + track_tab plan_tab_for(TTrack const *Track) const; + // the objects along the track: a tab for each tool + int m_lineside_tab{0}; + void render_lineside_ui(); + void arm_switch(); + // the window of the switch templates: the catalogue and the own ones, made of straights, arcs and transition curves + struct switch_designer + { + bool open{false}; + bool loaded{false}; + std::vector catalogue; + std::vector own; + bool from_catalogue{true}; + int selected{-1}; + bool dirty{false}; + bool stretched{true}; + double quick_radius{300.0}; + double quick_ratio{9.0}; + double quick_a{0.0}; + double quick_b{0.0}; + int fit_kind{3}; // of switch_design::tangent_fit + double quick_first{0.0}; // the radius of the first arc of an arc, a straight and an arc, 0: the R + bool picking{false}; // the switch clicked off the view, the orthophoto under it + std::vector clicks; + bool on_view{true}; // the template shown in the view where its first points were clicked + switch_design::design measured; // what the points clicked so far make + bool measured_ready{false}; + std::string measured_text; + int pointed{-1}; // the value under the mouse, its dimension shown on the drawing + int pointed_test{-1}; + double blade_length{5.0}; + double blade_gap{0.15}; + std::string status; + }; + switch_designer m_switch_designer; + void switch_designs_load(); + // the list of the switch tool built again with the own templates, keeping the armed one or arming the one whose label starts with Arm + void switch_templates_refresh(std::string const &Arm = {}); + void render_switch_designer(); + void switch_designer_click(glm::dvec3 const &Point); + void switch_designer_measure(); + void switch_designer_finish(); + void draw_switch_designer_clicks() const; + void draw_cursor_ring(glm::dvec3 const &Point) const; + static std::string grade_line_key(TTrack const &Track); + static std::string grade_line_key(std::string const &Name, TTrack const &Track); + static void move_path_heights(segment_data &Path, double const First, double const Second, std::function const &After = {}); + bool m_track_window_open{false}; + // the inspector is pinned to the right edge of the screen, the profile strip to the bottom one, both resized from the inner edge + void render_track_inspector(); + // the track tools in the tool options window, and the selected path in the inspector + void render_track_tool_options(); + void render_track_selection(); + void show_track_tab(track_tab const Wanted) override; + bool track_analysis_tab() const { return m_track_tab == track_tab::profile || m_track_tab == track_tab::speed || m_track_tab == track_tab::joints || m_track_tab == track_tab::infra; } + bool track_shortcut(int const Key); + bool track_busy() const; // something going on in the mode, which Esc drops before it leaves the mode + std::string track_mode_name() const; + void render_turnout_ui(); + struct track_name_edit + { + TTrack const *track{nullptr}; + std::string synced; + char text[128]{}; + editor_track::name_uses uses; + std::string status; + }; + track_name_edit m_track_name; + void render_track_name(TTrack &Track); + void render_straight_ui(); + track_tab m_track_tab{track_tab::path}; + void delete_selected_track(); + // the switch thrown over to its other path in the editor, its blades going over as in the simulation; the scenery keeps no state of it + void throw_switch(TTrack &Switch); + // the blades of the switches thrown in the editor moved on by the time of the frame: the time of the simulation stands still in it + void move_thrown_switches(); + std::vector m_thrown_switches; + std::string designs_trimmed(std::vector const &Removed); + void start_straight_gesture(int const Tool); + void finish_straight_gesture(); + void toggle_straight_set(TTrack &Track); + struct key_hint + { + char const *key; + std::string action; + char const *raw{nullptr}; // the key before it's translated, its gesture drawn from it + }; + std::vector track_key_hints(bool const All) const; + void render_track_guide(); + std::string track_readout() const; + void draw_track_hints(); + // a scenery with no tracks yet: in the middle of the view, how the first one is laid + void draw_empty_scenery_hint(); + // path under the cursor, outlined before a click so it's known which one the click takes + track_hover m_hover; + track_hover track_under_cursor(TTrack const *Only = nullptr, float const Pixels = 0.0f) const; + track_hover split_spot() const; + void update_track_hover(); + void draw_track_lines() const; + // what the colours of the tracks in the view tell + enum class track_colouring { plain, radius, speed, grade }; + track_colouring m_track_colouring{track_colouring::plain}; + void draw_track_legend() const; + // the radii and lengths of the curves and the names and types of the switches written by them, from above, as on a plan + bool m_track_labels{true}; + void draw_track_labels() const; + void draw_track_hover() const; + struct track_intent + { + enum class kind { none, gizmo, select, point, box, straight_set, straight_break, detour, straight_tool, straight_handle, route_vertex, route_grip, switch_at, switch_free, lay, lay_end, sweep, turntable_place, turntable_exit, turntable_fit, spread, extend_end, signal_place, signal_move, signal_read, switch_slide, pick_style, grade_line_pick, fouling, measure, route_trace, kilometrage, srk_boundary, srk_joint }; + kind what{kind::none}; + TTrack *track{nullptr}; + int path{0}; + editor_track::point_ref point; + int index{-1}; + glm::dvec3 position{0.0}; + editor_track::snap_target snap; + std::string action; + }; + track_intent m_intent; + // the measure between two points (M): on the ground, at a free end or on the axis of the track under the cursor + struct tape_state + { + bool active{false}; + std::vector points; + glm::dvec3 mouse{0.0}; + }; + tape_state m_tape; + void tape_update(); + std::string tape_readout() const; + void draw_tape() const; + track_intent track_intent_at(int const Mods); + bool track_gesture_on() const; + void update_track_intent(); + void track_press(track_intent const &Intent); + void turntable_press(track_intent const &Intent); + track_intent turntable_intent(glm::dvec3 const &Ground, bool const Shift); + void draw_track_intent() const; + editor_track::snap_target snap_free_end(glm::dvec3 const &Near, glm::vec2 const &Screen, TTrack const *Self, int const Category, std::vector const &Exclude) const; + void draw_free_ends(TTrack const *Self, int const Category, std::vector const &Exclude) const; + // the free ends of the rail tracks around the camera, looked for again after an edit or once the camera leaves the place + struct free_end_cache + { + int edits{-1}; + glm::dvec3 centre{0.0}; + double reach{0.0}; + std::vector points; + }; + mutable free_end_cache m_free_end_cache; + std::vector const &free_end_points(glm::dvec3 const &Centre, double const Reach) const; + struct point_drag + { + bool active{false}; + bool moved{false}; + glm::vec2 from{0.f}; + double height{0.0}; + std::size_t step{0}; + }; + point_drag m_point_drag; + struct handle_drag + { + bool active{false}; + bool moved{false}; + glm::vec2 from{0.f}; + double height{0.0}; + glm::dvec3 offset{0.0}; + glm::dvec3 position{0.0}; + }; + handle_drag m_handle_drag; + void handle_drag_start(glm::dvec3 const &Anchor); + // Ground: the handle goes onto the ground, at the height of the ballast of the track, unless Shift is held + bool handle_drag_step(glm::dvec3 &Position, TTrack const *Ground = nullptr); + void point_drag_start(editor_track::point_ref const &Point); + void point_drag_update(); + void point_drag_finish(); + bool route_hit(int &Vertex, int &Grip) const; + int straight_handle_hit(); + bool switch_reach(glm::dvec3 const &Ground, glm::dvec3 &Point); + glm::dvec3 cursor_ground() const; + glm::dvec3 cursor_level(double const Height) const; + glm::dvec3 cursor_terrain(double const Height); + double bed_height(glm::dvec3 const &Point, glm::dvec2 const &Direction, TTrack const *Style) const; + double nearby_ground(glm::dvec3 const &Point) const; + static std::pair trackbed(TTrack const *Style); + std::vector bed_heights(std::vector const &Points, std::vector const &Directions, TTrack const *Style) const; + void follow_ground(std::vector &Pieces, double const Height0, double const Grade0, double const Height1, double const Grade1, TTrack const *Style) const; + ground_follow::grading laying_grading(TTrack const *Style) const; + // the grade lines of the tracks shown while they're laid are fitted on a thread of their own, not to hold up the frames + mutable ground_follow::fitter m_fitter; + mutable bool m_follow_preview{false}; + glm::dvec3 lay_bed(glm::dvec3 const &Point); + std::optional m_cursor_override; + bool sweep_grabs(glm::dvec3 const &Point); + // menu of the path a click of the right mouse button lands on + struct track_context + { + track_hover target; + std::chrono::steady_clock::time_point pressed; + glm::vec3 angle{0.f}; + glm::vec2 mouse{0.f}; + bool armed{false}; + bool pending{false}; + }; + track_context m_track_context; + void track_context_press(); + void track_context_release(); + void render_track_context(); + void split_track_at(TTrack &Track, glm::dvec3 const &Point); + void focus_track(TTrack &Track, int const Path, glm::dvec3 const &Point) override; + // the camera flies over Duration seconds to the place Distance back from the target along Look, looking along it + void fly_to(glm::dvec3 const &Target, glm::dvec3 const &Look, double const Distance, double const Duration = 0.6) override; + // paths found by their names + struct track_search + { + char text[64]{}; + std::string searched; + std::vector found; + std::size_t total{0}; + bool focus{false}; + }; + track_search m_track_search; + void render_track_search(); + // paths selected together: Shift+LMB adds or takes one out, Shift+drag adds those in the box + std::vector m_track_set; + struct track_box + { + bool active{false}; + bool replace{false}; // the tracks in the box become the selection, else they join it + glm::vec2 from{0.f}; + glm::vec2 to{0.f}; + TTrack *hovered{nullptr}; + }; + track_box m_track_box; + glm::mat4 m_track_set_gizmo{1.0f}; + bool m_track_set_using{false}; + glm::dvec3 m_track_set_pivot{0.0}; + std::vector>> m_track_set_joints; + bool in_track_set(TTrack const *Track) const; + // the track is selected: alone or in the set + bool track_selected(TTrack const *Track) const; + // a click in the view: the track under the cursor becomes the selection, or nothing + void track_click_select(TTrack *Hovered); + bool track_set_begin(bool const Rotate); + void track_set_turn(double const Angle); + void track_set_move(glm::dvec3 const &Offset); + void track_set_end(); + glm::dvec3 track_set_centre() const; + void track_set_toggle(TTrack &Track); + void track_set_prune(); + void start_track_box(bool const Replace = false); + void finish_track_box(); + void draw_track_set() const; + void render_track_set_ui(); + void render_track_set_gizmo(); + void track_set_delete(); + struct track_spread + { + int stop{0}; + bool same_rails{false}; + bool same_bed{false}; + bool same_speed{false}; + float reach{0.f}; + TTrack const *from{nullptr}; + int signature{-1}; + std::vector preview; + double length{0.0}; + }; + mutable track_spread m_spread; + std::vector track_spread_from(TTrack &Start) const; + std::vector const &track_spread_preview(TTrack &Start) const; + void track_spread_apply(TTrack &Start); + void track_set_grow(); + void render_track_spread_ui(); + void draw_track_spread() const; + // the properties of the selected tracks in the inspector, one sheet for one track and for many; see editormodetrackprops.cpp + // the set when there's one, the selected track otherwise + std::vector selected_tracks(); + void select_tracks(std::vector const &Tracks); + // changes each track which can be changed, in one step of the undo; false from Change: the track stays as it was + std::size_t tracks_apply(std::vector const &Tracks, std::function const &Change, bool const Rebuild, char const *What); + // the model of the timbers, with the fastenings where it has them, set on all the switches and crossings of the scenery, in one + // step of the undo; empty: the one of eu07.ini. returns: the tracks changed + std::size_t set_switch_timbers(std::string const &Model); + int track_property_index(std::string const &Key) const; + std::size_t track_property_apply(int const Property, std::vector const &Tracks, std::string const &Text); + void track_field_finish(); + void track_field_settle(); + void track_textures_scan(); + // a texture in use, offered first in the picker + struct texture_use + { + material_handle material{null_handle}; // null: its image is read by the name + std::string name; + int count{0}; // shown on its tile, 0: nothing + std::string note; // what's said of it above the tiles + }; + // what the picker of a texture offers besides every texture of the folder + struct texture_offer + { + char const *title; // the heading of the ones in use + std::function()> used; // gathered when the picker opens + char const *none; // the entry for no texture, nullptr: there's none + char const *none_name; // the name that entry gives + }; + // every texture and material under the folder of the textures, read on the first use of the picker + void textures_index(); + // the picker of a texture, in an open combo. returns: true when one is chosen, its name in Chosen + bool texture_picker(texture_offer const &Offer, std::string const &Current, bool const Mixed, std::string &Chosen); + // the same, of a texture of the rails (Kind 0) or of the trackbed (1) + bool track_texture_picker(int const Kind, std::string const &Current, bool const Mixed, std::string &Chosen); + // image of the texture of the name, 0 while there's none + std::uint64_t texture_image(std::vector const &Used, std::string const &Name); + std::uint64_t track_texture_image(int const Kind, std::string const &Name); + // a field of a texture: its image and its name, a click opens the picker, a material of the texture browser can be dropped on it. + // returns: true when another one was chosen, in Value + bool texture_field(char const *Label, float const Width, std::string &Value, texture_offer const &Offer); + // the same, for a name kept in a buffer + bool texture_field(char const *Label, float const Width, char *Buffer, std::size_t const Size, texture_offer const &Offer); + // the textures of the roads and junctions of the scenery + std::vector road_textures_used() const; + // the textures of the palette and of the water of the terrain; None: the entry for no texture of its own, nullptr: there's none + texture_offer terrain_texture_offer(char const *None); + void render_track_properties(std::vector const &Tracks); + void render_track_set_header(std::vector const &Tracks); + void render_track_select_tools(std::vector const &Tracks); + void render_track_style(std::vector const &Tracks); + void copy_track_style(TTrack const &Track); + std::size_t paste_track_style(std::vector const &Tracks); + // which groups of the properties are pasted or put on the tracks by a preset, in the order of the groups of editormodetrackprops.cpp + using track_groups = std::array; + // the values of the properties of the chosen groups put on the tracks, in one step of the undo. returns: the number of the + // tracks changed, none when no value is of the chosen groups + std::optional apply_track_values(std::vector> const &Values, track_groups const &Groups, std::vector const &Tracks, char const *What); + // presets of the properties of the tracks (editorTrackPresets), made from a track and put on the selected ones + void render_track_presets(std::vector const &Tracks); + void render_track_presets_menu(); + std::size_t apply_track_preset(int const Id, std::vector const &Tracks); + std::vector similar_tracks(int const Property, std::vector const &Tracks) const; + // values of the properties over the selected tracks, each with the number of the tracks having it + struct track_values + { + std::size_t signature{0}; + int generation{0}; + int generation_seen{-1}; + std::size_t history{0}; + int frame{-100}; + std::vector>> values; + std::vector applies; + std::size_t unsaved{0}; // of the tracks, changed since the file was written + }; + track_values m_track_values; + // how the last value given in the sheet went: on how many tracks, and why not on the others + struct track_outcome + { + int property{-1}; + std::string text; + bool refused{false}; // some tracks couldn't take it + std::size_t signature{0}; // of the tracks it was given to + std::size_t history{0}; + double time{0.0}; + }; + track_outcome m_track_outcome; + // the lines under the rows of the sheet + struct track_note + { + enum class kind + { + typing, + done, + refused + }; + int property{-1}; + std::string text; + kind type{kind::done}; + }; + std::vector m_track_notes; + // the field being typed in, with the tracks it was started on + struct track_field + { + int property{-1}; + std::vector tracks; + std::array text{}; + std::string initial; + int frame{0}; + }; + track_field m_track_field; + std::array, 2> m_track_textures; // of the rails, of the trackbed + std::vector m_texture_used; // the ones in use the open picker offers + std::array m_texture_filter{}; + struct texture_index_entry + { + std::string name; // as the materials are named: relative to the folder of the textures, without the extension + std::string lowered; + bool material{false}; // there's a .mat file of the name + }; + std::vector m_texture_index; // sorted by the name + bool m_texture_indexed{false}; + std::string m_texture_hovered; // the tile under the mouse in the picker, shown large above them + // properties taken from a track, to be set on the selected ones + struct track_style + { + std::string from; + std::vector> values; + // ticked at first by their groups: speed, environment, overhead line, track circuits, rails, trackbed, its shape, sleepers, ride and + // sound, frogs, sleeper placement + track_groups groups{false, false, false, false, true, true, true, true, false, true, true}; + std::map ticks; // changed by hand, by the keys of the properties + bool picking{false}; // the next click on a track in the view takes its properties + bool reveal{false}; // its section of the inspector opens, a track having been taken + }; + track_style m_track_style; + // a property of the track taken which the selected ones have otherwise + struct track_style_line + { + int property{-1}; + std::string now; // as the selected tracks have it, or how many values they have + std::string taken; // as the track taken has it + std::size_t differ{0}; // of the selected tracks, the ones it changes + }; + std::vector track_style_lines(std::vector const &Tracks); + bool track_style_takes(std::string const &Key) const; + struct track_presets_panel + { + int selected{0}; // id of the preset chosen in the inspector + int nameid{0}; // the preset whose name is in the field + char name[128]{}; + }; + track_presets_panel m_track_presets; + std::vector> m_track_similar; + TTrack const *m_track_list_hover{nullptr}; // in the list of the selected tracks + int m_track_list_hover_frame{-1}; + using template_item = ::template_item; + using standing_template = ::standing_template; + // includes of the templates whose file names the test accepts, with the location in p2..p4 and the rotation in p5 + std::vector standing_templates(std::function const &Accept) const override; + struct switch_drive + { + standing_template standing; + int family{-1}; + int index{0}; + }; + std::optional find_switch_drive(TTrack const &Switch, bool Wait = true); + // the drives standing in the scenery by the switch each is set to, read from the files once a frame for all the switches + std::map const &switch_drives_standing(bool Wait = true); + struct drives_standing + { + std::map by_switch; + int frame{-1}; + int revision{-1}; // of the drives scanned + std::size_t instances{0}; + }; + std::optional m_drives_standing; // emptied when an include changes + std::string missing_drive_variant(int const Family, bool const Rightswitch, bool const Driveright) const; + bool replace_switch_drive(TTrack &Switch, int Family, bool Flip); + void apply_switch_drive_choice(TTrack &Switch); + void switch_drive_captured(TTrack const &Track); + void switch_drives_committed(std::vector const &Tracks); + // the drives of the switches deleted go with them, in the step of the undo history the deletion made last + void drives_deleted(std::vector const &Switches); + // the drives of all the switches of the scenery set at the tips of their blades, the ones the earlier versions of the editor set at the + // joint before them too: once, as the scenery is opened, with no step of the undo history; how many moved + std::size_t drives_to_blade_tips(); + bool m_drives_checked{false}; + scene::layer_handle output_layer(std::string const &Part) override; + // places them in the active layer or the given one, as one step of the undo. returns: how many were placed + std::size_t place_templates(std::vector const &Items, std::string &Error, scene::layer_handle Layer = scene::layer_handle{}) override; + // moves them, as one step of the undo + std::size_t move_templates(std::vector> const &Moves) override; + // takes them out, as one step of the undo + std::size_t remove_templates(std::vector const &Instances) override; + bool standing_signals(std::vector &Signals, bool const Wait) override; + std::size_t signal_batch(signal_changes const &Changes, std::vector> States, std::vector Created, std::string &Error) override; + std::string signal_templates_missing(std::vector const &Orders) override; + bool signal_heads(std::vector &Heads, bool const Wait) override; + std::string signal_mount(std::string const &Kind, std::string const &File) override; + std::size_t signal_reattach(std::vector const &Instances) override; + void select_signal(scene::instance_handle const Instance) override; + void render_signal_templates(std::vector const &Kinds) override; + + struct signal_template + { + std::string file; + std::string name; + std::string description; + std::string kind; + std::string mount; + std::string lamps; + std::string lean; + std::string read; + int parameters{0}; + bool plate{false}; + bool linked{false}; + std::vector speeds; + int aspects{0}; // of a block signal, 3 or 4 + int arms{0}; // of a semaphore, 1 or 2, from its description + // m, of the zero of its model over the rail heads, from its description: where it stands by default + double height{0.0}; + // m, how deep its model reaches under its zero, from its description: none, it isn't put on the ground + std::optional depth; + // the aspects its description lists, by name (Sr1, Od2...) with the event giving each; empty for a template not described so + std::vector> aspect_events; + // of a warning disc: its event for each speed class of the signal after it, stop, vmax, 100, 60, 40 + std::vector> repeats; + }; + // an indicator to put on a signal, a template described as one + struct indicator_template + { + std::string file; + std::string name; + std::string description; + std::string sign; + std::string place; // "head": under the lights of the signal, one under another; "foot": by its foot, the place in its model + std::vector> events; + }; + struct signal_spot + { + TTrack *track{nullptr}; + int path{0}; + glm::dvec3 axis{0.0}; + glm::dvec2 travel{0.0, 1.0}; + int side{1}; + int list{2}; + double offset{0.0}; + glm::dvec3 position{0.0}; + double yaw{0.0}; + // the path and its list that read the signal: the track it stands by, or past the frog of a switch the track joined to the end + // of its path, which only the trains of that path run on + TTrack *reader{nullptr}; + int reader_list{2}; + }; + struct signal_standing + { + standing_template include; + int kind{-1}; + std::string name; + std::string read; + TTrack *track{nullptr}; + int list{0}; + // every path and list having the read, the first of them in track and list + std::vector> reads; + // the indicators put on it: named after it, at its foot, the highest first + std::vector indicators; + }; + struct signal_tool + { + std::vector templates; + std::vector indicators; + int revision{-1}; + int kind{0}; + std::array chosen{-1, -1, -1, -1, -1, -1, -1, -1}; + bool armed{false}; // a click by a track places the chosen template + char filter[64]{}; + char name[64]{"A"}; + char plate[64]{}; + std::array plate_index{}; // the speed index of the drawn plate, "4" or "12" for 1/2 + bool plate_m{false}; // the drawn plate gets the "m" of a signal giving shunting signals too + char linked[64]{"none"}; + float height{0.0f}; + bool placing{false}; + signal_spot press; + signal_spot press_raw; // where the press was, before it went to a round distance to the switch ahead + glm::vec2 pressed{0.f}; + int facing{0}; + std::vector standing; + std::size_t standing_history{static_cast(-1)}; + double standing_time{-1.0}; + int hover{-1}; + scene::instance_handle selected{0}; + bool moving{false}; + glm::dvec2 grab{0.0}; + signal_spot home; + bool home_valid{false}; + signal_spot moved; + bool moved_valid{false}; + // a click on a track gives the read of the signal selected to it + bool picking_read{false}; + // the entry of the selected signal into the gauge of the paths around it, measured again as the history or the selection changes + struct + { + scene::instance_handle instance{0}; + std::size_t history{static_cast(-1)}; + glm::dvec3 location{0.0}; // of the signal, which follows a dragged track without a new step of the history + gauge_tool::gauge_hit hit; + } gauge; + // the signal the gizmo has taken: as it stood then, the frame of its models, the size of the history before the step of the + // gizmo and the directives of its indicators + struct + { + scene::instance_handle instance{0}; + signal_standing from; + glm::dmat3 frame{1.0}; + std::size_t history{0}; + std::vector> directives; + } gizmo; + std::string status; + }; + signal_tool m_signal; + // the way from the spot of a signal along its track to the switch the trains it faces come to first + track_trace::danger signal_danger(signal_spot const &Spot) const; + // the spot moved along its track to a round distance to the switch ahead, 50 m, 100 m..., when it's that near one; Alt leaves it + void signal_snap(signal_spot &Spot, signal_template const &Template) const; + // of the selected signal: the spot it stands at and the way to the switch ahead of it, kept until it or the history changes + struct signal_metre + { + scene::instance_handle instance{0}; + std::size_t history{static_cast(-1)}; + glm::dvec3 location{0.0}; + double yaw{0.0}; + bool valid{false}; + signal_spot spot; + track_trace::danger danger; + }; + mutable signal_metre m_signal_metre; + signal_metre const &signal_metre_of(signal_standing const &Standing) const; + bool signal_scan(bool Wait = true); + signal_template const *signal_current() const; + signal_template const *signal_armed() const; + signal_template const *signal_template_of(std::string const &File) const; + // the template it is placed by: the one of its file if that is of its kind, else the one chosen for its kind. returns: nullptr if none + signal_template const *signal_template_for(signal_order const &Order) const; + bool signal_spot_at(TTrack &Track, int const Path, glm::dvec3 const &Point, glm::dvec3 const &Cursor, int const Facing, int const Side, signal_template const &Template, signal_spot &Spot) const; + void signal_refresh(bool const Force = false); + // the signals standing, read by the tracks as they are now, the templates as found so far + std::vector signal_standing_now() const; + int signal_hit() const; + void signal_press(track_intent const &Intent); + void signal_release(); + bool signal_place(signal_spot const &Spot, signal_template const &Template); + void signal_move_update(); + // Moved: the signal moved from its track, the nearest track takes it if that's nearer by more than a little + bool signal_standing_spot(signal_standing const &Standing, signal_spot &Spot, bool const Moved = false) const; + bool signal_drop_at(signal_standing const &Standing, TTrack &Track, int const Path, glm::dvec3 const &Point, int const Side, signal_spot &Spot) const; + bool signal_move_to(signal_standing const &Standing, signal_spot const &Spot, char const *Read, char const *Unread); + indicator_template const *indicator_template_of(std::string const &File) const; + // the indicator put on the signal, named after it: under its lights below the ones there, or at its foot. returns: false if it can't be + bool signal_indicator_add(signal_standing const &Standing, indicator_template const &Indicator); + bool signal_indicator_remove(scene::instance_handle const Indicator); + // the indicators under the lights of the signal at Upper and Lower in its list, the highest first, swapped: each takes the place of the other + bool signal_indicators_swap(signal_standing const &Standing, std::size_t const Upper, std::size_t const Lower); + // the signal set the distance from the axis of its track in the plan and its height, raised over where it stands by default (over the rail heads, on a gantry), unless none + bool signal_set_across(signal_standing const &Standing, std::optional const Offset, std::optional const Height); + // the distance from the axis and the height over where it stands by default From has, carried to To, a spot of the same signal + // along its track: a signal set across or raised by hand keeps it as it is dragged or snapped + void signal_carry(signal_spot const &From, signal_spot &To, signal_template const &Template) const; + // the height of the zero of the model of a signal at Position by the track of the axis at Axis, as it stands by default: as far over + // the rail heads as its description gives, lower only where its bottom would hang over the ground; a gantry as high over the rails + // as chosen + double signal_default_height(signal_template const &Template, glm::dvec3 const &Axis, glm::dvec3 const &Position) const; + // how much higher the default height of To is than of From at Position by the track of the axis at Axis: what a signal given the + // template To in place of From goes up by, to stand as raised as it was + double signal_default_change(signal_template const &From, signal_template const &To, glm::dvec3 const &Axis, glm::dvec3 const &Position) const; + // the indicators of the signal moved after it to the place and the frame it has now, at the same place by it as they were, the + // directives they had going to Directives + void signal_indicators_follow(signal_standing const &Standing, glm::dmat3 const &Before, std::vector> &Directives); + bool render_signal_indicators(signal_standing const &Found); + // the indicators put on the signal named Name standing at Location, as the scenery has them now, the highest first: the list of + // the tool is kept up only while the tool is open + std::vector signal_indicators_of(std::string const &Name, glm::dvec3 const &Location) const; + // the indicators of the signal named Before at Location named After it, the directives they had going to Directives once each + void signal_indicators_renamed(std::string const &Before, std::string const &After, glm::dvec3 const &Location, std::vector> &Directives); + // the directives of more includes taken back by the step: one of a single include is made one of them + void history_add_directives(EditorSnapshot &Step, std::vector> const &Directives); + // the signal of the selected include taken by the gizmo: its indicators go with it, and once it's let go it is moved as a drag of + // the signal tool moves it, read by the path it stands by then, out of the gauge, as one step of the history + void signal_gizmo_begin(); + void signal_gizmo_step(); + void signal_gizmo_end(); + // the height of the lowest lamp of the signal in the world, from the geometry of its lamps; 0 when it has none + double signal_lowest_lamp(scene::instance_handle const Instance) const; + // the deepest entry of the models of the signal into the gauge of the paths around it + gauge_tool::gauge_hit signal_gauge(scene::instance_handle const Instance); + // the signal just placed or moved, at Local in its file, taken across away from the axis of each path whose gauge it enters, a few + // times at most, its directive changed with it. returns: the way it went, metres, and in Hit the entry it still makes + double signal_off_gauge(scene::instance_handle const Instance, std::string const &File, std::vector &Values, glm::dvec3 Local, gauge_tool::gauge_hit &Hit); + // a sentence more to the status about it, none when the signal kept out of the gauge where it was put + void signal_gauge_note(std::string &Status, double const Shift, gauge_tool::gauge_hit const &Hit, bool const Gantry) const; + bool signal_flip(scene::instance_handle const Instance); + bool signal_turn(scene::instance_handle const Instance); + bool signal_swap(scene::instance_handle const Instance, std::string const &File); + // the signal set to the aspect in the editor, as its event sets it in the game: only how it looks, nothing saved + bool signal_show_aspect(scene::instance_handle const Instance, std::string const &Aspect, std::string const &Event); + signal_standing const *signal_standing_of(scene::instance_handle const Instance) const; + bool signal_delete(scene::instance_handle const Instance); + void signal_detach_events(std::string const &Read, std::vector> &States); + // a track split in two: the reads of the signals placed since the scenery was opened, not bound yet, go to the piece by the signal + void signal_split(TTrack &Original, TTrack &Created); + // the list of a path the trains the signal faces read it from, as they run by the point of the path nearest to it + int signal_read_list(signal_standing const &Standing, TTrack const &Track, int const Path) const; + // the read of the signal in exactly these lists of these paths, as one step taken back by Ctrl+Z + bool signal_read_set(signal_standing const &Standing, std::vector> const &Reads); + // a click on a track while picking the path that reads the selected signal: its read goes there, or one more there with Add, + // or off it with Add when it's there already + bool signal_read_pick(TTrack &Track, int const Path, bool const Add); + std::string signal_read_label(TTrack const &Track, int const Path, bool const Add) const; + void signal_renamed(std::string const &Before, std::string const &After, EditorSnapshot &Snapshot); + // the plate a signal of this name gets when none is picked: one drawn by python/local/signal_plate.py with the given style + // ("look=toned", with "&index=12" and "&m=1" when it has them), or none for a name it can't carry + static std::string signal_plate(std::string const &Name, std::string const &Style); + // true for a plate signal_plate() gives, of any name and look + static bool signal_plate_drawn(std::string_view Plate); + static bool signal_plate_blank(std::string const &Name, std::string const &Plate); + static std::string signal_plate_text(std::string const &Name); + // what a drawn plate is drawn with but its name, kept through a rename; for one not drawn the look set in the editor + static std::string signal_plate_style(std::string const &Plate); + void signal_select(scene::instance_handle const Instance); + std::string signal_next_name(std::string const &Name) const; + void render_signal_ui(); + void render_signal_palette(); + void render_signal_selected(); + // the paths reading the signal, each turned the other way or removed, a path picked or the one the editor gives. returns: true when they changed + bool render_signal_reads(signal_standing const &Found); + // of the signal selected: its template and another one for it, the aspects it can be set to; true when it got another one + bool render_signal_template(signal_standing const &Found, signal_template const &Item); + // the list of the templates the signal can take instead, Across those of another mount too: the file picked, empty for none + std::string signal_swap_combo(signal_template const &Item, bool const Across) const; + void render_signal_aspects(signal_standing const &Found, signal_template const &Item); + void draw_signal_overlay() const; + std::string signal_intent_label(signal_template const &Template, signal_spot const &Spot) const; + std::string signal_variant(signal_template const &Template, signal_spot const &Spot) const; + // what a deleted track carried and no other one took, its read events and track circuits, for a track laid in its place + struct orphan_record + { + TTrack *track{nullptr}; // retired; the record waits while it stays so + std::vector> events; // the name, the list it was on + std::vector circuits; + // the tracks given the circuits: while one stays the circuits don't wait, once a step other than an undo removes one they + // are its own + std::vector given; + bool fresh{false}; // made by the step being taken + }; + std::vector m_orphans; + std::string m_orphan_note; // shown by the cursor after the step which made it + void orphans_register(std::vector const &Removed, std::vector const &Kept); + // Created: made by the step, their circuits the ones of the tracks they were made from; Changed: the others it changed + void orphans_take_over(std::vector const &Created, std::vector const &Changed); + + // a model laid along the track: bent to follow it, or repeated along it + struct sweep_tool + { + bool open{false}; + bool expand{false}; + char model[256]{}; + char skin[128]{"none"}; + char search[64]{}; + std::vector models; + bool scanned{false}; + int revision{-1}; // of the include bank the templates were taken from + // parameters of a template laid along the track, with their names + std::string parameters_for; + std::vector> parameters; + std::vector parameter_labels; + std::vector parameter_placement; // filled in with zeros: the template is placed in its own space + std::vector> parameter_choices; // variants of the textures a parameter is a part of the name of + int length_mode{2}; // 0: one copy as long as the original, 1: the length given, 2: the whole stretch of the line + double length{200.0}; + sweep_node::state settings; + int axis{0}; // 0: the longer one of the model, 1: z, 2: x + double model_length{0.0}; + std::string measured; // model the length is of + // the curve: the axis of the track + TTrack *curve_for{nullptr}; + std::size_t curve_history{0}; + struct piece + { + TTrack *track{nullptr}; + int path{0}; + bool forward{true}; + }; + std::vector curve_pieces; + std::vector curve; + double curve_length{0.0}; + std::vector outline; // of the curve, for the preview + std::vector stations; + // marking the stretch in the view: press where it starts, the distance from the track sets the offset, drag to the end + bool marking{false}; + bool dragging{false}; + double anchor{0.0}; // station the drag started at + sweep_node *edited{nullptr}; + std::string status; + }; + sweep_tool m_sweep; + // paths the models along curves were laid on, so they follow the changes of the paths + struct sweep_link + { + sweep_node *sweep{nullptr}; + std::size_t piece{0}; + TTrack *track{nullptr}; + int path{0}; + bool reversed{false}; + }; + std::vector m_sweep_links; + void sweep_curve(); + void sweep_outline(); + bool sweep_extend(bool const Atend, glm::dvec3 const &Cursor); + double sweep_station(glm::dvec3 const &Point, double &Lateral) const; + void sweep_scan_models(); + void sweep_measure(); + sweep_node::state sweep_definition() const; + void sweep_create(); + void sweep_apply(); + void sweep_delete(sweep_node &Sweep); + void sweep_edit(sweep_node &Sweep); + std::vector sweeps_near(TTrack const &Track) const; + bool sweep_press(); + void sweep_drag(); + void sweep_release(); + // the same at a point of the world: Anywhere takes the press however far from the track it is + bool sweep_press_at(glm::dvec3 const &Point, bool const Anywhere); + void sweep_drag_at(glm::dvec3 const &Point); + void render_sweep_ui(); + void draw_sweep_overlay() const; + void restore_sweeps(EditorSnapshot &Snapshot); + void sweeps_captured(TTrack const &Track); + void sweeps_committed(std::vector const &Tracks); + void sweeps_split(TTrack &Original, TTrack &Created); + + struct bend_source + { + TAnimModel *model{nullptr}; + scene::instance_handle instance{0}; + std::string file; + std::string skin{"none"}; + std::vector parameters; + glm::dmat4 transform{1.0}; + glm::dvec3 scale{1.0}; + scene::layer_handle layer{null_handle}; + }; + struct bend_tool + { + int axis{0}; + bool turned{false}; + int along_anchor{1}; + int side_anchor{0}; + int height_anchor{0}; + glm::dvec3 point{0.0}; + bool picking{false}; + void const *tracks_for{nullptr}; + glm::dvec3 tracks_at{0.0}; + std::vector> tracks; + int track{0}; + sweep_node *edited{nullptr}; + std::string signature; + bool marker_valid{false}; + glm::dvec3 marker{0.0}; + std::string status; + int dragging{0}; // 1: the cross along and aside, 2: up, 3: only along, 4: the start of the model, 5: its end + sweep_node::state drag_state; + std::shared_ptr drag_line; // the line as it was when the drag began + double drag_first{0.0}; // m along it, where the model began and ended then + double drag_last{0.0}; + glm::dvec3 drag_anchor{0.0}; + double drag_station{0.0}; + std::string drag_label; + sweep_node *hover{nullptr}; + bool over_marker{false}; + int over_end{0}; // the handle under the cursor: 1 at the start of the model, 2 at its end + std::string label; + std::string details; + }; + bend_tool m_bend; + bool bend_drag_start(int const Mods); + void bend_drag_update(); + sweep_node *sweep_under(glm::dvec3 const &Point) const; + bool bend_click(); + bool bend_shortcut(); + bool bend_source_of_selection(bend_source &Source) const; + void bend_find_tracks(glm::dvec3 const &Point, void const *Key); + bool bend_definition(bend_source const &Source, TTrack &Track, sweep_node::state &State, std::vector &Tracks); + void bend_selection(); + void bend_edit(sweep_node::state const &State); + void bend_reanchor(sweep_node::state &State, int const Side, int const Height, glm::dvec3 const &Point) const; + double bend_fixed(sweep_node const &Sweep, glm::dvec3 const &Point) const; + void bend_stretch(sweep_node const &Sweep, double const Fixed, double const Length, glm::dvec3 const &Point, sweep_node::state &State) const; + // the model laid along another track: it stays where it stands, with its length + void bend_retrack(sweep_node const &Sweep, TTrack const &Track, sweep_node::state &State) const; + // the handles at the ends of the model, at the height and the side of its reference point + std::array bend_ends(sweep_node const &Sweep) const; + // a drag of the model begun: 1 the cross along and aside, 2 up, 3 only along, 4 the start, 5 the end + void bend_drag_begin(int const Kind); + // the end of the model taken to the point, the line lengthened through the tracks joined there; the length it has then + double bend_end_to(bool const Atend, glm::dvec3 const &Point, sweep_node::state &State) const; + std::string bend_selftest(std::string const &Command, std::istringstream &Words); + void sweep_relink(sweep_node const &Sweep); + void bend_pick(glm::dvec3 const &Point); + glm::dvec3 bend_marker(sweep_node const &Sweep) const; + void restore_bend(EditorSnapshot &Snapshot, bool const Undo); + void render_bend(); + void draw_bend_overlay() const; + + // script of editor actions given in the EU07_EDITOR_SELFTEST file, run a step at a time, for testing without a person + struct selftest + { + bool loaded{false}; + std::vector lines; + std::size_t next{0}; + int wait{0}; + bool quitting{false}; + scripted_input input; + std::string badge; // the mouse or the keys drawn over the view, for the clips of the tutorial + glm::vec2 badge_at{0.0f}; // its bottom left corner, in the pixels of the window + }; + selftest m_selftest; + using selftest_result = editor_selftest_result; + selftest_result selftest_scene(std::string const &command, std::istringstream &words); + selftest_result selftest_sleepers(std::string const &command, std::istringstream &words); + selftest_result selftest_sweep(std::string const &command, std::istringstream &words); + selftest_result selftest_track(std::string const &command, std::istringstream &words); + selftest_result selftest_switch(std::string const &command, std::istringstream &words); + selftest_result selftest_rails(std::string const &command, std::istringstream &words); + selftest_result selftest_join(std::string const &command, std::istringstream &words); + selftest_result selftest_signal(std::string const &command, std::istringstream &words); + selftest_result selftest_terrain(std::string const &command, std::istringstream &words); + selftest_result selftest_props(std::string const &command, std::istringstream &words); + selftest_result selftest_monkey(std::string const &command, std::istringstream &words); + selftest_result selftest_dispatch(std::string const &command, std::istringstream &words); + void selftest_step(); + // a value typed during a gesture, taken instead of the one the cursor gives + std::string m_typed; + // what the typed value sets in the gesture under way, nullptr when the gesture takes none + char const *typed_meaning() const; + std::vector typed_values() const; + bool typed_key(int const Key); + glm::dvec3 typed_lay(glm::dvec3 const &Mouse) const; + void typed_turn(); + bool m_route_tab{true}; + + // vertical profile (grade line) along a route + struct profile_state + { + bool open{false}; + TTrack *from{nullptr}; + TTrack *to{nullptr}; + TTrack *picked_from{nullptr}; + TTrack *picked_to{nullptr}; + double run_length{std::numeric_limits::infinity()}; // the whole line through the track clicked + std::vector followed; // the selection the route was last taken from + editor_track::route route; + std::vector samples; + std::vector created; // the paths the last apply split off the route + std::vector terrain; // NaN where there's no terrain + std::vector model; // the ground of the terrain model (NMT) as measured; NaN where it's not known + bool model_waiting{false}; // squares of the model under the route still to come + double model_polled{0.0}; + // what the joined ends take their height and grade from, when it's a switch: shown on the plot + std::string start_inherits, end_inherits; + // depth of the formation under the grade line, the rail top, of the track of each sample: the formation, not the rails, + // lies on the ground + std::vector beds; + profile::line line; + profile::context context; + std::vector issues; + double origin{0.0}; // chainage of the start of the route + double departure{0.0}; // largest difference between the grade line and the track + profile::ground_fit fit; + // the heightmap terrain led to the grade line by a modifier: formation under the track, slopes down or up to the ground + struct earthworks + { + bool from_ballast{true}; + double depth{0.7}; // m, formation below the top of the rail + double half_width{3.5}; // m, from the axis of the route to the edge of the formation + double slope{1.5}; // horizontal run of the slopes per metre of height + double reach{60.0}; // m, from the edge of the formation, where the slopes end even if they don't get to the ground + double rounding{1.5}; // m, over which the slopes bend into the formation and into the ground + bool generate{true}; + // chunks of terrain made under the route by the last shaping + std::vector> generated; + // the modifier of the terrain made by the last shaping + std::string modifier; + } earthworks; + double view_from{0.0}; + double view_to{100.0}; + double view_centre{0.0}; + float exaggeration{20.0f}; + bool show_terrain{true}; + bool show_model{true}; + bool show_track{true}; + bool show_plan{true}; + bool whole_grade_line{true}; // applied, the tracks sharing the grade line of the route go with it + profile::line line_read; // the line before it was edited + bool fitting{false}; // the line comes from the fit to the terrain model: any error of it refuses it + std::vector beside; // those of them lying by it, for the route and the state of the tracks below + std::tuple beside_of{nullptr, 0, 0, 0}; + bool picking{false}; // a click on a track in the view puts it on the grade line of the route or takes it off + std::vector members; // of the grade line picked, wherever they are + std::tuple members_of{-1, 0, 0}; + int selected{-1}; + int dragging{-1}; + // where the point was grabbed: the mouse there, the point against the mouse; the point moves once the mouse does + ImVec2 drag_press{0.0f, 0.0f}; + glm::dvec2 drag_grab{0.0}; + bool drag_moved{false}; + int curve_grip{-1}; + bool panning{false}; + bool changed{false}; + double hover{-1.0}; + // under the cursor in the strip + int hover_point{-1}; + int hover_grip{-1}; + bool hover_line{false}; + int shown{-2}; // point in the side panel + bool show_remarks{false}; + float strip_top{-1.0f}; // the top of the strip over the 3d view, -1 while it isn't shown + int edits{-1}; // of the tracks, when the route was last read + std::string status; + std::string error; + }; + profile_state m_profile; + // grade lines designed in the editor, kept in the scenery files as "//$p" comment lines + struct stored_profile + { + scene::layer_handle layer{null_handle}; + double length{0.0}; + glm::dvec3 start{0.0}, end{0.0}, middle{0.0}; // of the route, world space + double origin{0.0}; + profile::line line; + double departure{-1.0}; // of the track from the design when it was kept; -1 as kept by an older editor + }; + std::vector m_profiles; + bool m_profiles_loaded{false}; + void profile_library_load(); + void profile_library_mark(std::vector Layers); + // the last step takes the kept grade lines back to the library given, as they were before it changed them + void profiles_to_history(std::vector Library); + // the kept grade lines back to the library given, the step changing them given up before it went to the history + void profiles_restore(std::vector Library); + // the tracks whose grade line was fitted, by name, with the shape they had then, kept as "//$t" comment lines: a track + // changed since, by hand or taken back, isn't fitted any more + struct fitted_mark + { + scene::layer_handle layer{null_handle}; + std::uint64_t shape{0}; + bool hand{false}; + }; + std::map, fitted_mark> m_fitted; // by the name and the shape: scenery files have names used twice + bool m_fitted_loaded{false}; + void fitted_load(); + void fitted_set(std::vector const &Tracks, bool const Hand = false); + bool grade_fitted(TTrack const &Track); + bool grade_hand(TTrack const &Track); // its grade line was edited with the profile tool, and it wasn't changed since + bool nmt_stays(TTrack const &Track); // this putting of the tracks onto the terrain leaves it as it is + static std::uint64_t fitted_shape(TTrack const &Track); + int profile_find(bool &Reversed) const; + bool profile_restore(); + bool profile_restore_parts(); + // the route a kept design was laid over, as it runs now; none when its paths moved or are gone + std::optional profile_stored_route(stored_profile const &Entry, TTrack **From = nullptr, TTrack **To = nullptr) const; + // the kept designs over the tracks moved, as by the grade lines shared, laid anew onto them where they part from them; returns how + // many were, how many couldn't be without an error and are left as they were + std::pair profile_refit_stored(std::unordered_set const &Moved); + void profile_store(); + void profile_forget(); + void profile_open_stored(std::size_t const Index); + void profile_edited(); + // the radii of its neighbours were for the breaks of the grade it made, they follow the limits after it + void profile_remove_point(int const Index); + void render_profile_body(); + void render_profile_strip(); + void render_profile_header(); + void render_profile_empty(); + void render_profile_toolbar(); + void render_profile_points(); + void render_profile_source(); + bool render_profile_parameters(); + void render_profile_issues(); + void profile_open(TTrack *From, TTrack *To); + void profile_open_run(TTrack &Track); + void profile_take(editor_track::route Route, TTrack *From, TTrack *To); + void profile_open_selection(std::vector const &Tracks); + void profile_follow_selection(); + void profile_resample(); + // the ground of the terrain model under the route, as it was measured before any earthworks + void profile_sample_model(); + void profile_recognize(); + void profile_fit_ground(); + // depth of the foot of the ballast under the rail top, and its distance from the axis + static std::pair profile_ballast(TTrack const &Track); + // false for a track with no trackbed of its own, as the switches of the older sceneries whose bed is an include + static bool profile_own_bed(TTrack const &Track); + void profile_shape_ground(); + std::pair profile_generate_ground(std::vector> const &Beds, double const Reach); + void profile_restore_ground(); + void render_profile_earthworks(); + void profile_check(); + // Terrain: the heightmap terrain follows the tracks changed. Bridges: stretches of the route over a bridge or a viaduct, the + // paths over them cut off at their ends and set to the bridge environment + void profile_apply(bool const Terrain = false, std::vector const &Bridges = {}, double const Fewest = 0.0); + // the terrain under the tracks changed by the last Edits steps of the history which changed tracks + void profile_follow_terrain(std::size_t const Edits); + void profile_fit_view(); + // the camera to the part of the route the plot shows; the plot to the part of the route the camera shows, its zoom kept + void profile_frame_view(); + void profile_to_camera(); + void profile_after_undo(); + void profile_follow_edits(); + struct profile_view; + void render_profile_canvas(float const Height); + void profile_fit_exaggeration(profile_view const &View); + void profile_navigate(profile_view const &View, bool const Hovered); + bool profile_canvas_edit(profile_view const &View, bool const Hovered); + void draw_profile_canvas(profile_view const &View, ImDrawList &Draw) const; + void profile_canvas_tooltip() const; + void render_profile_point(); + void draw_profile_overlay() const; + + // infrastructure along the track: objects bound to the paths follow their changes. bindings are kept in the + // scenery files as "//$b" comment lines + struct infra_candidate + { + infra::binding binding; + double offset{0.0}; // sideways from the axis + std::string reason; + bool chosen{false}; + bool bound{false}; + TTrack *reader{nullptr}; + std::string event; // of that path + std::string cell; + bool loose{false}; + TTrack *nearer{nullptr}; + glm::dvec3 nearer_foot{0.0}; + bool unread{false}; + }; + struct infra_window + { + bool open{false}; + int scope{1}; // 0: the selected path, 1: the line through it, 2: the route of the vertical profile + float reach{1500.0f}; + float corridor{8.0f}; + bool follow{true}; + bool show{true}; + std::vector rules{infra::default_rules()}; + std::vector tracks; // of the scope + std::vector candidates; + int filter{0}; + int read{0}; + int overruled{0}; + int unread{0}; + int elsewhere{0}; + int hovered{-1}; + std::string status; + std::string error; + }; + infra_window m_infra; + std::vector m_bindings; + std::vector> m_bindings_unresolved; // lines kept as they are + bool m_bindings_loaded{false}; + std::vector m_infra_buffer; // states of the objects before the change in progress + std::vector> m_drive_buffer; + bool m_infra_suspended{false}; + // the point objects which go with a path: the signals and the warning discs it reads, the SHP resonators, and the controls of the + // block sections, the signs and the posts by the path nearest to them + struct point_object + { + scene::instance_handle include{0}; + glm::dvec3 location{0.0}; + TTrack *reader{nullptr}; + TTrack *nearest{nullptr}; // of one no path reads + infra::category group{infra::category::other}; + }; + std::vector m_point_objects; + std::size_t m_point_objects_revision{static_cast(-1)}; + std::size_t m_point_objects_count{0}; + void infra_adopt(TTrack &Track); + int infra_bound_count() const; // by the infra tool, not the ones a change of their track took along + std::set> m_infra_carried; // the objects their tracks moved since the tool cleared it + std::string infra_carried_note(); // a line of the status telling how many, empty for none; clears them + void infra_load(); + void infra_store(); + void infra_forget(scene::basic_node const *Node); + std::vector infra_scope() const; + void infra_recognize(); + void infra_bind_chosen(); + void infra_unbind(std::vector Indices); + infra::binding *infra_find(infra::binding const &Binding); + infra::object_state infra_state_of(infra::binding const &Binding) const; + void infra_restore_state(infra::object_state const &State); + void infra_buffer(infra::binding const &Binding, bool const Refresh); + // editor_track::observer + void track_captured(TTrack const &Track) override; + void tracks_committed(std::vector const &Tracks) override; + void track_retired(TTrack &Track) override; + void track_split(TTrack &Original, TTrack &Created, segment_data const &First) override; + void track_renamed(TTrack const &Track, std::string const &Old) override; + void infra_move(infra::binding &Binding); + void infra_attach(EditorSnapshot &Snapshot); + void render_infra_body(); + + gauge_tool m_gauge{*this, *this, *this, *this}; + speed_tool m_speed{*this, *this, *this, *this}; + joints_tool m_joints{*this, *this, *this, *this}; + vehicle_tool m_vehicle{*this, *this}; + hekto_tool m_hekto{*this, *this, *this, *this, *this, *this}; + fouling_tool m_fouling{*this, *this, *this, *this, *this}; + parallel_tool m_parallel{*this, *this, *this, *this}; + srk_tool m_srk{*this, *this, *this, *this, *this, *this}; + km_tool m_km{*this, *this, *this, *this}; + track_ride m_ride; + minimap_tool m_minimap{*this, *this, m_ride}; + std::vector m_tools{&m_gauge, &m_speed, &m_joints, &m_vehicle, &m_hekto, &m_fouling, &m_parallel, &m_srk, &m_km, &m_ride, &m_minimap}; + + void infra_rebase(); + void render_infra_search(); + void render_infra_candidates(); + void render_infra_bound(); + void draw_infra_overlay() const; + + bool m_route_dragging{false}; + alignment::design m_route_drag_from; + float m_track_snap_radius{1.0f}; + bool m_track_align_tangent{true}; + bool m_track_drag_connected{true}; + + // roads: a menu and a window of their own, independent from the edit modes of the toolset + // what a click of the build tool would make + struct road_plan + { + std::vector pieces; // axes of the pieces, in the order they're laid + editor_road::loose_end snap; // loose end of a road or arm of a junction the road is led to + editor_road::branch start; // junction made, or given another arm, for a road led out of the side of a road or out of a junction + bool hasstart{false}; + editor_road::branch end; // the same for a road led into the side of a road or into a junction + bool hasend{false}; + std::string error; // why there's nothing to make + }; + struct road_tool + { + bool window{false}; // the road window is open, the left mouse button belongs to its tools + bool lanes{true}; // lanes of the roads are drawn as trajectories + int tool{0}; // 0: select, 1: build, 2: place + road_node *selected{nullptr}; + junction_node *junction{nullptr}; // selected junction + roadpoint_node *marker{nullptr}; // selected level crossing or traffic point + std::vector points; // selected points where the pieces meet or end + road_node::state settings; // layout shown in the window: of the selected piece, or of the pieces about to be built + bool whole{true}; // layout changes go to every piece of the road the selected one belongs to + bool varied{false}; // the selected piece is shown with lanes of its own for its end + bool chain{false}; // the point to build from is set + glm::dvec3 point{0.0}; // where the next piece starts + glm::dvec2 direction{0.0, 1.0}; // the way it has to leave that point + bool hasdirection{false}; + bool reversed{false}; // the pieces are laid from their ends, to carry on a road from its start + double grade{0.0}; // slope the next piece has to start with, to carry on what it's attached to + bool hasgrade{false}; + // the road being built leaves the side of a road, or a junction between its roads. the point to build from is the centre + // of the junction, which gets made, or gets another arm, along with the first piece + road_node *branchroad{nullptr}; + double branchat{0.0}; // value of the curve parameter of the axis of that road + junction_node *branchjunction{nullptr}; + float offset{0.1f}; // height above the ground the roads are built at + bool follow{true}; // built roads are led over the ground between the clicked points + float crossingspeed{30.f}; // speed limit on the junctions being made + float heightstep{0.1f}; // how much the selected points are raised or lowered at a time + // Alt+LMB on a point dragged up or down: the heights of the selected points changed by the drag, applied when let go + bool lifting{false}; + float lift_mouse{0.0f}; // where on the screen the drag began, pixels down + double lift_scale{0.0}; // metres for a pixel at the point picked + std::vector lift_from; // the heights of the selected points when the drag began + bool ring{false}; // the build tool makes roundabouts + float ringradius{15.f}; // of the middle of the road going around + std::string island{"none"}; // what the middle of a roundabout is covered with + float bankgrade{1.5f}; // metres a bank led to the ground runs for each metre it drops + // level crossings and traffic points + int placekind{0}; // what the place tool puts down: 0: level crossing, 1: spawn point, 2: removal point, 3: pedestrian crossing + roadpoint_node::state placing[4]; // what the next point of each kind is going to be like + float stopmargin{5.f}; // distance from the outermost track of a new crossing to the places the vehicles stop at + roadpoint_node::state target; // the point a click of the place tool would make at the moment + bool hastarget{false}; + glm::dvec3 targetdirection{0.0}; // the way the traffic goes there + std::string targetnote; // what's worth knowing about that point, or why there's none + glm::dvec3 aimed{0.0}; // where the cursor was when the target was worked out, and for what kind of point + int aimedkind{-1}; + char vehicles[4096]{}; // vehicles to add to the set of a spawn point, written the way they're put in a scenery + road_plan plan; // what a click would make at the moment, worked out once a frame for display + glm::dvec3 hover{0.0}; // point of a road or a junction under the cursor a road can be led out of + bool hashover{false}; + glm::dvec3 mouse{0.0}; + std::string status; + }; + void render_road_tool_options(); + // the change of the road tool + void road_choose_tool(int const Tool); + void render_road_selection(); + bool render_road_layout(road_node::state &State); + bool render_road_material(char const *Label, std::string &Value); + void render_junction_layout(junction_node &Junction); + void junction_apply(junction_node &Junction, junction_node::state const &State); + // leads the banks of the corners of a junction to the ground beside it + void junction_bank_to_ground(junction_node &Junction); + // how far from specified point, and how far down, a slope of the grade set for the banks gets to the ground. + // Outwards: the way the slope leads, seen from above + std::pair bank_reach(glm::dvec3 const &Edge, glm::dvec3 const &Outwards); + void draw_road_overlay() const; + void update_road_tool(); + void road_click(); + // the point where pieces meet or end nearest to the cursor on the screen, within a few pixels; it's found under the + // terrain too, where the click on the ground doesn't get near it + bool road_joint_on_screen(glm::dvec3 &Joint) const; + // Alt+LMB: the drag of the heights of the selected points begun on a point, and finished + bool road_lift_start(); + void road_lift_finish(); + double road_lift_offset() const; + void road_select(road_node *Road); + void junction_select(junction_node *Junction); + void road_apply(); + bool road_delete(); + bool road_split(); + void road_cancel(); + // sets the width of the road at the selected points, or the height of each of them + void road_point_width(float const Width); + void road_point_heights(std::vector const &Heights); + bool road_points_apply(std::vector> const &Changes, std::vector> const &Junctions); + // takes the selected points out of their roads + bool road_points_delete(); + // puts a roundabout around specified point + void road_roundabout(glm::dvec3 const &Ground); + // leads the banks of the selected piece, or of the whole road, to the ground beside it + void road_bank_to_ground(); + // level crossings and traffic points + void roadpoint_select(roadpoint_node *Point); + // works out the point a click of the place tool would make. Fresh: even if the cursor is where it was the last time + void roadpoint_aim(bool const Fresh); + void roadpoint_place(); + void roadpoint_apply(roadpoint_node &Point, roadpoint_node::state const &State); + // Point: the point the controls are for, nullptr for the one about to be made + bool render_roadpoint_layout(roadpoint_node::state &State, roadpoint_node const *Point); + // Fresh: the ground which wasn't looked up yet is gathered on the spot, instead of a bit of it each frame + road_plan road_preview(bool const Fresh); + // Firstgrade, Lastgrade: slopes the road has to start and end with, nullptr for none + void road_profile(std::vector &Pieces, double const *Firstgrade, double const *Lastgrade, bool const Fresh); + // height of the ground under each of the points, with the roads not taken for the ground. a point with nothing under it keeps its height + // Found: set for the points which have the ground under them + std::vector ground_heights(std::vector const &Points, bool const Fresh, std::vector *Found = nullptr) const; + void push_road_snapshot(editor_road::record Record); + void restore_road_snapshot(EditorSnapshot const &Snapshot, std::vector &Opposite, bool const Undo); + road_tool m_roadtool; }; diff --git a/application/editormodeconnection.cpp b/application/editormodeconnection.cpp new file mode 100644 index 000000000..275e5754e --- /dev/null +++ b/application/editormodeconnection.cpp @@ -0,0 +1,615 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editoruilayer.h" +#include "application/editormodeshared.h" +#include "editor/editorFormat.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorSwitchStore.hpp" +#include "editor/editorGeometry.hpp" +#include "application/editormodetrackshared.h" + +#include "scene/scene.h" +#include "simulation/simulation.h" +#include "world/Track.h" +#include "utilities/translation.h" + +#include "imgui/imgui.h" +#include +#include +#include + +namespace +{ + +using geometry::cross; +using geometry::plan_distance; +using geometry::plan_of; + +std::vector spacings_of(char const *Text) +{ + std::string text{Text}; + for (auto &letter : text) + if (letter == ';') + letter = ' '; + else if (letter == ',') + letter = '.'; + std::istringstream words{text}; + std::vector result; + double value{0.0}; + while (words >> value) + result.push_back(value); + return result; +} + +bool usable_in_connection(editor_track::switch_template const &Template) +{ + return false == Template.double_slip && false == Template.twofold(); +} + +// m: a switch let go this near the other track is dragged onto it, at least this far from its own track +double constexpr kOntoTrack{1.5}; +double constexpr kOffTrack{2.5}; +// m: the furthest the switches of two crossovers meeting on one track are apart for a double crossover +double constexpr kDoubleGap{50.0}; + +// whether the main track of the switch runs along the line +bool on_line(TTrack const &Switch, connection::line const &Line) +{ + auto const &main{Switch.m_paths.front()}; + return std::abs(Line.lateral(main.points[segment_data::point::start])) < 0.05 && std::abs(Line.lateral(main.points[segment_data::point::end])) < 0.05; +} + +// the line along the main track of the switch, reaching far past both of its ends +connection::line line_through(TTrack const &Switch) +{ + double constexpr reach{2000.0}; + auto const &main{Switch.m_paths.front()}; + auto const start{main.points[segment_data::point::start]}; + auto const end{main.points[segment_data::point::end]}; + connection::line result; + result.direction = glm::normalize(plan_of(end - start)); + result.grade = (end.y - start.y) / std::max(1e-9, glm::length(plan_of(end - start))); + result.start = start - glm::dvec3{result.direction.x, result.grade, result.direction.y} * reach; + result.length = 2.0 * reach; + return result; +} + +} // namespace + +char const *editor_mode::connection_name(int const Kind) +{ + switch (static_cast(Kind)) + { + case connection::kind::double_crossover: return STR_C("Double crossover"); + case connection::kind::scissors: return STR_C("Scissors crossover"); + case connection::kind::ladder: return STR_C("Switch ladder"); + default: return STR_C("Crossover"); + } +} + +editor_track::straight editor_mode::straight_near(glm::dvec3 const &Point, std::vector const &Exclude, double const Reach) const +{ + TTrack *found{nullptr}; + auto best{Reach}; + for (auto *section : simulation::Region->sections(Point, static_cast(std::max(40.0, Reach)))) + for (auto const &cell : section->m_cells) + for (auto *track : cell.m_paths) + { + if (track->eType != tt_Normal || track->m_editorremoved || track->m_paths.empty() || std::find(Exclude.begin(), Exclude.end(), track) != Exclude.end() || false == editor_track::is_straight(*track, m_straights.tolerance)) + continue; + auto const &path{track->m_paths.front()}; + auto const a{plan_of(path.points[segment_data::point::start])}; + auto const segment{plan_of(path.points[segment_data::point::end]) - a}; + auto const t{std::clamp(glm::dot(plan_of(Point) - a, segment) / std::max(1e-9, glm::dot(segment, segment)), 0.0, 1.0)}; + auto const distance{glm::distance(plan_of(Point), a + segment * t)}; + if (distance < best) + { + best = distance; + found = track; + } + } + return found != nullptr ? editor_track::find_straight(*found, m_straights.tolerance) : editor_track::straight{}; +} + +editor_track::straight editor_mode::straight_through(glm::dvec3 const &Point, glm::dvec2 const &Direction) const +{ + for (auto *section : simulation::Region->sections(Point, 40.f)) + for (auto const &cell : section->m_cells) + for (auto *track : cell.m_paths) + { + if (track->eType != tt_Normal || track->m_editorremoved || track->m_paths.empty() || false == editor_track::is_straight(*track, m_straights.tolerance)) + continue; + auto const &path{track->m_paths.front()}; + auto const a{plan_of(path.points[segment_data::point::start])}; + auto const segment{plan_of(path.points[segment_data::point::end]) - a}; + auto const length{glm::length(segment)}; + if (length < 1e-6 || std::abs(cross(segment / length, Direction)) > 1e-3 || std::abs(cross(segment / length, plan_of(Point) - a)) > 0.02) + continue; + auto const t{glm::dot(plan_of(Point) - a, segment) / (length * length)}; + if (t >= -1e-6 && t <= 1.0 + 1e-6) + return editor_track::find_straight(*track, m_straights.tolerance); + } + return {}; +} + +bool editor_mode::plan_connection(connection::request &Request, connection::result &Result) const +{ + auto const &tool{m_switch}; + Result = {}; + if (false == tool.placing || tool.curved || tool.connection < 0 || tool.armed < 0 || tool.armed >= static_cast(tool.templates.size()) || tool.line.tracks.empty()) + return false; + auto const &line{tool.line}; + Request = {}; + Request.type = static_cast(tool.connection); + Request.from = connection::of(line); + Request.first = tool.templates[tool.armed]; + auto const second{tool.connection_second >= 0 && tool.connection_second < static_cast(tool.templates.size()) ? tool.connection_second : tool.armed}; + Request.second = tool.templates[second]; + Request.radius = tool.connection_radius; + Request.gap = tool.connection_gap; + Request.together = tool.connection_together; + Request.stub = tool.connection_stub; + Request.spacings = spacings_of(tool.connection_spacings); + Request.along = tool.along; + glm::dvec2 const offset{plan_of(tool.mouse - tool.point)}; + Request.forward = glm::dot(offset, line.direction) >= 0.0 ? 1 : -1; + glm::dvec2 const travel{line.direction * static_cast(Request.forward)}; + Request.side = cross(travel, offset) >= 0.0 ? 1 : -1; + std::vector const exclude(line.tracks.begin(), line.tracks.end()); + auto const other{straight_near(tool.mouse, exclude, 8.0)}; + if (false == other.tracks.empty()) + { + auto const target{connection::of(other)}; + if (Request.type != connection::kind::ladder) + { + Request.to.push_back(target); + Request.target = target.along(tool.mouse); + } + else if (std::abs(cross(target.direction, line.direction)) < 1e-3) + { + auto const side{cross(travel, plan_of(target.point(target.along(tool.point)) - tool.point)) > 0.0 ? 1.0 : -1.0}; + auto const lateral = [&](glm::dvec3 const &Point) { return side * cross(travel, plan_of(Point - tool.point)); }; + auto const outermost{lateral(target.point(target.along(tool.point)))}; + std::map> fan; + auto const better = [](double const One, double const Two) { return (One < 0.0) != (Two < 0.0) ? One >= 0.0 : std::abs(One) < std::abs(Two); }; + auto const centre{(tool.point + tool.mouse) * 0.5}; + for (auto *section : simulation::Region->sections(centre, static_cast(glm::length(offset) * 0.5 + 200.0))) + for (auto const &cell : section->m_cells) + for (auto *track : cell.m_paths) + { + if (track->eType != tt_Normal || track->m_editorremoved || track->m_paths.empty() || std::find(exclude.begin(), exclude.end(), track) != exclude.end() || false == editor_track::is_straight(*track, m_straights.tolerance)) + continue; + auto const &path{track->m_paths.front()}; + auto const a{path.points[segment_data::point::start]}; + auto const b{path.points[segment_data::point::end]}; + auto const direction{plan_of(b - a)}; + if (glm::length(direction) < 1e-6 || std::abs(cross(glm::normalize(direction), line.direction)) > 1e-3) + continue; + auto const distance{lateral(a)}; + auto const along1{glm::dot(travel, plan_of(a - tool.point))}; + auto const along2{glm::dot(travel, plan_of(b - tool.point))}; + if (distance < 1.0 || distance > outermost + 0.05 || std::max(along1, along2) <= 0.0) + continue; + auto const nearer{std::min(along1, along2)}; + auto &entry{fan[std::lround(distance * 20.0)]}; + if (entry.second == nullptr || better(nearer, entry.first)) + entry = {nearer, track}; + } + for (auto const &entry : fan) + Request.to.push_back(connection::of(editor_track::find_straight(*entry.second.second, m_straights.tolerance))); + } + } + Result = connection::plan(Request); + return Result.valid; +} + +void editor_mode::recognise_connection() +{ + auto &tool{m_switch}; + // a connection chosen by a script stays as it was chosen + if (false == tool.recognised && tool.connection >= 0) + return; + tool.connection = -1; + tool.recognised = false; + tool.partner = nullptr; + if (false == tool.placing || tool.free || tool.armed < 0 || tool.armed >= static_cast(tool.templates.size()) || tool.templates[tool.armed].double_slip || tool.templates[tool.armed].twofold()) + return; + auto const mark = [&](connection::kind const Kind) { + tool.connection = static_cast(Kind); + tool.recognised = true; + }; + // let go at a free end, the switch joins it + auto const own{tool.curved ? std::vector(tool.frame_tracks.begin(), tool.frame_tracks.end()) : std::vector(tool.line.tracks.begin(), tool.line.tracks.end())}; + if (editor_track::find_free_end(nullptr, ::track_mode::kRailCategory, tool.mouse, ::track_mode::kLaySnapRadius, own).track != nullptr) + return; + if (tool.curved) + { + // along a curve a crossover only, let go on the track running beside it + if (tool.frame.size() < 2 || plan_distance(sample_at(tool.frame, nearest_station(tool.frame, tool.mouse)).position, tool.mouse) < kOffTrack) + return; + for (auto *section : simulation::Region->sections(tool.mouse, 40.f)) + for (auto const &cell : section->m_cells) + for (auto *track : cell.m_paths) + if (track->eType == tt_Normal && false == track->m_editorremoved && false == track->m_paths.empty() && std::find(tool.frame_tracks.begin(), tool.frame_tracks.end(), track) == tool.frame_tracks.end() && + plan_distance(editor_track::point_at(*track, editor_track::nearest_parameter(*track, tool.mouse)), tool.mouse) < kOntoTrack) + { + mark(connection::kind::crossover); + return; + } + return; + } + if (tool.line.tracks.empty()) + return; + auto const line{connection::of(tool.line)}; + if (std::abs(line.lateral(tool.mouse)) < kOffTrack) + return; + std::vector const exclude(tool.line.tracks.begin(), tool.line.tracks.end()); + auto const other{straight_near(tool.mouse, exclude, kOntoTrack)}; + if (other.tracks.empty()) + return; + auto const otherline{connection::of(other)}; + mark(connection::kind::crossover); + // a crossover between the two tracks turned the other way: behind the press, or past it on the other track, a double crossover + // with it; over it a scissors one + auto const forward{glm::dot(plan_of(tool.mouse - tool.point), line.direction) >= 0.0 ? 1.0 : -1.0}; + auto const press{line.along(tool.point)}; + auto nearest{kDoubleGap}; + for (auto *section : simulation::Region->sections(tool.point, 200.f)) + for (auto const &cell : section->m_cells) + for (auto *track : cell.m_paths) + { + if (track->eType != tt_Switch || track->m_editorremoved || track->m_paths.size() < 2 || false == on_line(*track, line)) + continue; + auto const crossover{crossover_of(*track)}; + if (false == crossover.has_value()) + continue; + auto const *opposite{crossover->first == track ? crossover->second : crossover->first}; + if (false == on_line(*opposite, otherline)) + continue; + auto const &main{track->m_paths.front()}; + auto const way{glm::dot(plan_of(main.points[segment_data::point::end] - main.points[segment_data::point::start]), line.direction) >= 0.0 ? 1.0 : -1.0}; + if (way == forward) + continue; + // along this track in the way the crossover there runs from it to the other one: its switch here starts at 0, the one on + // the other track at Span; the one dragged, turned the other way, crosses it from 0 to twice that + auto const span{way * (line.along(opposite->m_paths.front().points[segment_data::point::start]) - line.along(main.points[segment_data::point::start]))}; + auto const at{way * (press - line.along(main.points[segment_data::point::start]))}; + if (span <= 0.0) + continue; + double gap; + bool together{false}; + if (at < 0.0) + { + gap = -at; + together = true; + } + else if (at > 2.0 * span) + gap = at - 2.0 * span; + else + gap = 0.0; + if (gap >= nearest) + continue; + nearest = gap; + tool.partner = track; + tool.connection = static_cast(at >= 0.0 && at <= 2.0 * span ? connection::kind::scissors : connection::kind::double_crossover); + tool.connection_together = together; + tool.connection_gap = gap; + } + if (tool.partner != nullptr) + return; + // across tracks running parallel between the two, a ladder onto all of them + if (std::abs(cross(other.direction, tool.line.direction)) < 1e-3) + { + tool.connection = static_cast(connection::kind::ladder); + connection::request request; + connection::result plan; + plan_connection(request, plan); + if (request.to.size() < 2) + tool.connection = static_cast(connection::kind::crossover); + } +} + +bool editor_mode::plan_partner_connection(connection::request &Request, connection::result &Result) const +{ + auto const &tool{m_switch}; + Result = {}; + auto const crossover{tool.partner != nullptr ? crossover_of(*tool.partner) : std::nullopt}; + if (false == crossover.has_value() || tool.connection < 0) + return false; + auto *opposite{crossover->first == tool.partner ? crossover->second : crossover->first}; + auto const shape{editor_track::template_of_switch(tool.partner)}; + if (false == shape.has_value()) + return false; + // on lines through the crossover there, the double or the scissors one starting with it + Request = {}; + Request.type = static_cast(tool.connection); + Request.from = line_through(*tool.partner); + Request.to = {line_through(*opposite)}; + Request.along = Request.from.along(tool.partner->m_paths.front().points[segment_data::point::start]); + Request.forward = 1; + Request.target = Request.to.front().along(opposite->m_paths.front().points[segment_data::point::start]); + Request.first = *shape; + Request.second = *shape; + Request.radius = tool.connection_radius; + Request.gap = tool.connection_gap; + Request.together = tool.connection_together; + Result = connection::plan(Request); + return Result.valid; +} + +void editor_mode::insert_partner_connection() +{ + auto &tool{m_switch}; + tool.placing = false; + connection::request request; + connection::result plan; + auto const fail = [&](std::string const &Reason) { + tool.status = Reason; + ui()->set_status(Reason, true); + flash_switch_problem(Reason, {}, {{tool.partner->location(), ""}}); + }; + if (false == plan_partner_connection(request, plan)) + return fail(plan.error.empty() ? std::string{STR_C("The connection doesn't fit with the crossover there")} : plan.error); + auto const crossover{crossover_of(*tool.partner)}; + auto *here{tool.partner}; + auto *opposite{crossover->first == here ? crossover->second : crossover->first}; + auto const armed{tool.armed}; + auto const shape{crossover_template(crossover->record)}; + tool.armed = armed; + if (shape < 0) + return fail(STR_C("The template the crossover was laid of isn't among the templates")); + auto const press{here->m_paths.front().points[segment_data::point::start]}; + auto const heading{plan_of(here->m_paths.front().points[segment_data::point::end] - press)}; + auto const release{opposite->m_paths.front().points[segment_data::point::start]}; + std::vector const names{here->name(), opposite->name()}; + // the crossover there taken out, then laid again with the other one, one step of the history + profile_library_load(); + auto library{m_profiles}; + std::vector> states; + std::vector created; + std::vector removed; + TTrack *first{nullptr}; + TTrack *second{nullptr}; + if (false == take_out_crossover(*crossover, states, created, removed, first, second)) + return fail(STR_C("The crossover there can't be taken out")); + auto *nearplain{crossover->first == here ? first : second}; + auto *farplain{crossover->first == here ? second : first}; + switch_store::follow(); + push_track_snapshot(std::move(states), std::move(created), std::move(removed)); + records_to_history(); + if (crossover->record.lifted()) + profiles_to_history(std::move(library)); + auto const from{editor_track::find_straight(*nearplain, m_straights.tolerance)}; + auto const to{editor_track::find_straight(*farplain, m_straights.tolerance)}; + if (from.tracks.empty() || to.tracks.empty()) + { + undo_last(); + return fail(STR_C("The tracks of the crossover there aren't straights")); + } + request.from = connection::of(from); + request.to = {connection::of(to)}; + request.along = request.from.along(press); + request.forward = glm::dot(request.from.direction, heading) >= 0.0 ? 1 : -1; + request.target = request.to.front().along(release); + request.first = tool.templates[shape]; + request.second = tool.templates[shape]; + plan = connection::plan(request); + tool.keep_names = names; + auto const laid{plan.valid && lay_planned_connection(request, plan, from.tracks.front())}; + tool.keep_names.clear(); + if (false == laid) + { + auto const reason{plan.valid ? tool.status : plan.error}; + undo_last(); + return fail(reason); + } + join_last_steps(); +} + +std::string editor_mode::connection_readout(connection::result const &Plan) const +{ + if (false == Plan.valid) + return Plan.error; + auto text{format(STR_C("%s: %d switches, spacing %.2f m"), connection_name(m_switch.connection), static_cast(Plan.switches.size()), Plan.spacing)}; + if (false == Plan.straights.empty()) + { + text += STR_C(", straight inserts"); + for (auto const length : Plan.straights) + text += format(" %.2f", length); + text += " m"; + } + if (Plan.points > 0.0) + text += format(STR_C(", mathematical points %.2f m apart"), Plan.points); + if (Plan.radius > 0.0) + text += format(STR_C(", aligning curve R %.0f m"), Plan.radius); + if (Plan.crossing && Plan.angle > 1e-6) + text += format(STR_C(", crossing 1:%.2f"), 1.0 / std::tan(Plan.angle)); + if (false == Plan.fan.empty()) + { + text += STR_C(", tracks at"); + for (auto const offset : Plan.fan) + text += format(" %.2f", offset); + text += " m"; + } + if (false == Plan.warning.empty()) + text += "\n" + Plan.warning; + return text; +} + +void editor_mode::insert_connection() +{ + auto &tool{m_switch}; + connection::request request; + connection::result plan; + auto const planned{plan_connection(request, plan)}; + // the switches as they'd go, blinking where they don't fit + auto const preview{planned ? std::vector{} : switch_preview()}; + tool.placing = false; + if (false == planned) + { + tool.status = plan.error.empty() ? std::string{STR_C("Drag onto the other track")} : plan.error; + ui()->set_status(tool.status, true); + flash_switch_problem(tool.status, preview, {{tool.mouse, ""}}); + return; + } + lay_planned_connection(request, plan, tool.line.tracks.front()); +} + +bool editor_mode::lay_planned_connection(connection::request const &Request, connection::result const &Plan, TTrack *Style) +{ + auto &tool{m_switch}; + auto const &request{Request}; + auto const &plan{Plan}; + std::vector> states; + std::vector created; + std::vector removed; + auto *style{Style}; + auto const fail = [&](std::string const &Reason) { + for (auto *track : created) + editor_track::retire(*track); + for (auto entry{states.rbegin()}; entry != states.rend(); ++entry) + { + editor_track::apply(*entry->first, entry->second); + editor_track::commit({entry->first}); + } + for (auto *track : removed) + { + editor_track::revive(*track); + editor_track::commit({track}); + } + if (auto before{switch_store::take_changes()}) + switch_store::restore(std::move(*before)); + if (auto before{alignment_store::take_changes()}) + alignment_store::restore(std::move(*before)); + straight_refresh(); + tool.status = Reason; + ui()->set_status(Reason, true); + }; + std::vector switches; + for (auto const &entry : plan.switches) + { + auto const &shape{entry.second ? request.second : request.first}; + auto const name{switch_name_for_new()}; + auto const before{created.size()}; + auto const start{entry.paths[0].points[segment_data::point::start]}; + auto const end{entry.paths[0].points[segment_data::point::end]}; + if (entry.line >= 0) + { + auto const &target{entry.line == 0 ? request.from : request.to[entry.line - 1]}; + auto const found{straight_through((start + end) * 0.5, target.direction)}; + if (found.tracks.empty()) + { + fail(STR_C("A switch of the connection goes where its track isn't a plain straight")); + return false; + } + auto const forward{glm::dot(found.direction, plan_of(end - start)) > 0.0 ? 1 : -1}; + if (false == place_switch_on_straight(found, shape, nullptr, found.along(start), forward, entry.side, false, states, created, removed, name)) + { + fail(tool.status); + return false; + } + } + else + { + auto const made{create_switch_set(shape, entry.paths, *style, name)}; + if (made.empty()) + { + fail(tool.status); + return false; + } + created.insert(created.end(), made.begin(), made.end()); + } + auto const made{std::find_if(created.begin() + static_cast(before), created.end(), [](TTrack const *Track) { return Track != nullptr && Track->eType == tt_Switch; })}; + // in the plan: the height is the track's there, which needn't keep to one grade as the line of the plan does + if (made == created.end() || plan_distance((*made)->m_paths.front().points[segment_data::point::start], start) > 0.01) + { + fail(STR_C("A switch of the connection doesn't fit where it was planned, its straight is too short")); + return false; + } + switches.push_back(*made); + advance_switch_name(); + } + // the inserts meet the switches at the heights they were put at + std::vector ends; + for (auto const *track : switches) + for (auto const &path : track->m_paths) + for (auto const index : {segment_data::point::start, segment_data::point::end}) + ends.push_back(path.points[index]); + std::vector inserts; + for (auto insert : plan.inserts) + { + for (auto const index : {segment_data::point::start, segment_data::point::end}) + for (auto const &end : ends) + if (plan_distance(insert.points[index], end) < 0.05) + { + insert.points[index].y = end.y; + break; + } + if (auto *track{editor_track::create_path(*style, insert)}) + inserts.push_back(track); + } + editor_track::commit(inserts); + digitize_drawn(inserts); + created.insert(created.end(), inserts.begin(), inserts.end()); + if (plan.crossing) + { + auto const first{glm::normalize(plan_of(plan.ends[1] - plan.ends[0]))}; + auto second{glm::normalize(plan_of(plan.ends[3] - plan.ends[2]))}; + if (glm::dot(first, second) < 0.0) + second = -second; + auto const parts{build_double_slip(plan.ends[0], plan.ends[1], plan.ends[2], plan.ends[3], plan_of(plan.centre), plan.centre.y, first, second, plan.angle, editor_track::slip_curve{}, *style, "Skrz")}; + editor_track::commit(parts); + created.insert(created.end(), parts.begin(), parts.end()); + } + record_connection(request.type, switches, plan, request.first); + push_track_snapshot(std::move(states), std::move(created), std::move(removed)); + straight_refresh(); + first_step_done(first_step::turnout); + m_track_point = {}; + m_node = switches.front(); + ui()->set_node(m_node); + std::string names; + for (auto *track : switches) + { + if (place_switch_drive(*track)) + join_last_steps(); + names += (names.empty() ? "" : ", ") + track->name(); + } + tool.status = format(STR_C("%s laid, switches %s"), connection_name(static_cast(request.type)), names.c_str()) + "\n" + connection_readout(plan); + ui()->set_status(tool.status, false); + return true; +} + +void editor_mode::render_connection_options() +{ + auto &tool{m_switch}; + // of the connections a switch dragged onto the track beside makes + if (false == begin_fields("##connectionoptions")) + return; + auto const label = [&](int const Index) { return Index < 0 || Index >= static_cast(tool.templates.size()) ? std::string{STR_C("The same as the first one")} : switch_template_label(tool.templates[Index]); }; + field_row("Other switches of a connection##connectionsecond"); + if (ImGui::BeginCombo("##connectionsecond", label(tool.connection_second).c_str())) + { + if (ImGui::Selectable(STR_C("The same as the first one"), tool.connection_second < 0)) + tool.connection_second = -1; + for (int i = 0; i < static_cast(tool.templates.size()); ++i) + if (usable_in_connection(tool.templates[i]) && ImGui::Selectable((switch_template_label(tool.templates[i]) + "##connectionsecond" + std::to_string(i)).c_str(), tool.connection_second == i)) + tool.connection_second = i; + ImGui::EndCombo(); + } + item_tooltip("Template of the switches on the other track and along a ladder, when a switch is dragged onto the track beside; the first switch is the one chosen on the list above"); + field_row("Aligning curve R, m##connectionradius"); + ImGui::InputDouble("##connectionradius", &tool.connection_radius, 10.0, 100.0, "%.0f"); + tool.connection_radius = std::clamp(tool.connection_radius, 0.0, 10000.0); + item_tooltip("Of the curve between switches of different angles or on tracks that aren't parallel, and at the end of a ladder; 0: the radius of the sharper switch"); + ImGui::EndTable(); +} diff --git a/application/editormodeconnectioncurve.cpp b/application/editormodeconnectioncurve.cpp new file mode 100644 index 000000000..15e8f8c67 --- /dev/null +++ b/application/editormodeconnectioncurve.cpp @@ -0,0 +1,1124 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +// a crossover between two tracks running side by side along a curve: planned as between straights in the frame of the curve +// (along it, across it) and laid onto the curve, the switches, the insert and the other track on the plane the cant tilts the +// inner track to. The outer track goes up to that plane over the crossover, with ramps on both sides + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editoruilayer.h" +#include "application/editormodeshared.h" +#include "application/editormodetrackshared.h" +#include "editor/editorFormat.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorSwitchStore.hpp" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" +#include "world/Track.h" + +#include + +using geometry::bezier; +using geometry::plan_distance; +using geometry::plan_of; + +namespace +{ + +// of the ramps the outer track goes up to the crossover and down from it by, a share of the change of grade which needs a +// vertical curve: the ramps break the grade line without one +double constexpr kRampShare{0.9}; +double constexpr kOtherReach{10.0}; // m, from the release to the other track +double constexpr kStraightReach{track_mode::kCrossoverStraights}; + +// the first curved track a straight track leads to along its straight, either way, within the reach +TTrack *curve_ahead(TTrack &Track, editor_track::straight_tolerance const &Tolerance, double const Reach) +{ + TTrack *found{nullptr}; + auto nearest{Reach}; + for (auto const throughend : {true, false}) + { + TTrack const *previous{&Track}; + TTrack *current{throughend ? Track.trNext : Track.trPrev}; + double distance{0.0}; + for (int count = 0; current != nullptr && count < 1000 && distance < nearest; ++count) + { + if (current->eType != tt_Normal || current->m_editorremoved || current->m_paths.empty()) + break; + if (false == editor_track::is_straight(*current, Tolerance)) + { + found = current; + nearest = distance; + break; + } + auto const &path{current->m_paths.front()}; + distance += plan_distance(path.points[segment_data::point::start], path.points[segment_data::point::end]); + auto *next{current->trPrev == previous ? current->trNext : current->trPrev}; + previous = current; + current = next; + } + } + return found; +} + +// the lift of the outer track along its line: from First at the chainage From to Second at To in a straight line, down to none over +// the ramps beyond them +struct outer_lift +{ + double from, to; + double first, second; + double ramp; + + double at(double const Chainage) const + { + if (Chainage <= from - ramp || Chainage >= to + ramp) + return 0.0; + if (Chainage < from) + return first * (Chainage - (from - ramp)) / ramp; + if (Chainage > to) + return second * ((to + ramp) - Chainage) / ramp; + return to - from > 1e-6 ? first + (second - first) * (Chainage - from) / (to - from) : first; + } + double grade(double const Chainage) const + { + if (Chainage > from - ramp && Chainage < from) + return first / ramp; + if (Chainage > to && Chainage < to + ramp) + return -second / ramp; + if (Chainage >= from && Chainage <= to && to - from > 1e-6) + return (second - first) / (to - from); + return 0.0; + } + std::vector breaks(double const Length) const + { + std::vector found; + for (auto const chainage : {from - ramp, from, to, to + ramp}) + if (chainage > 0.5 && chainage < Length - 0.5) + found.push_back(chainage); + return found; + } +}; + +} // namespace + +// the plan of a connection between straights laid onto the curve: its x across the curve, minus to the left, its z the station +struct editor_mode::curve_mapping +{ + std::vector const &frame; + + glm::dvec3 point(glm::dvec3 const &Local) const + { + auto const sample{sample_at(frame, Local.z)}; + glm::dvec2 const left{-sample.tangent.y, sample.tangent.x}; + auto const lateral{-Local.x}; + auto const planar{plan_of(sample.position) + left * lateral}; + return {planar.x, sample.position.y + Local.y - lateral * std::tan(glm::radians(static_cast(sample.roll))), planar.y}; + } + glm::dvec2 tangent(glm::dvec3 const &Local, glm::dvec2 const &Direction) const + { + auto const sample{sample_at(frame, Local.z)}; + glm::dvec2 const left{-sample.tangent.y, sample.tangent.x}; + return glm::normalize(sample.tangent * Direction.y - left * Direction.x); + } + float roll(glm::dvec3 const &Local) const { return sample_at(frame, Local.z).roll; } + // the height of the tilted plane at the point of the plan + double height(glm::dvec2 const &Planar) const + { + auto const sample{sample_at(frame, nearest_station(frame, {Planar.x, 0.0, Planar.y}))}; + auto const lateral{glm::dot(Planar - plan_of(sample.position), glm::dvec2{-sample.tangent.y, sample.tangent.x})}; + return sample.position.y - lateral * std::tan(glm::radians(static_cast(sample.roll))); + } + + segment_data path(segment_data const &Local) const + { + auto const &start{Local.points[segment_data::point::start]}; + auto const &end{Local.points[segment_data::point::end]}; + auto const &control1{Local.points[segment_data::point::control1]}; + auto const &control2{Local.points[segment_data::point::control2]}; + glm::dvec2 const chord{end.x - start.x, end.z - start.z}; + auto const localstart{glm::normalize(control1 != glm::dvec3{} ? plan_of(control1) : chord)}; + auto const localend{glm::normalize(control2 != glm::dvec3{} ? -plan_of(control2) : chord)}; + auto const p0{point(start)}; + auto const p3{point(end)}; + auto const t0{tangent(start, localstart)}; + auto const t3{tangent(end, localend)}; + auto const handle{plan_distance(p0, p3) / 3.0}; + segment_data result; + result.points[segment_data::point::start] = p0; + result.points[segment_data::point::end] = p3; + result.points[segment_data::point::control1] = {t0.x * handle, (p3.y - p0.y) / 3.0, t0.y * handle}; + result.points[segment_data::point::control2] = {-t3.x * handle, -(p3.y - p0.y) / 3.0, -t3.y * handle}; + // the heights of the inner points on the tilted plane + auto const h1{height(plan_of(bezier{result}.point(1.0 / 3.0)))}; + auto const h2{height(plan_of(bezier{result}.point(2.0 / 3.0)))}; + auto const y1{3.0 * h1 - 1.5 * h2 - 5.0 / 6.0 * p0.y + p3.y / 3.0}; + auto const y2{3.0 * h2 - 1.5 * h1 + p0.y / 3.0 - 5.0 / 6.0 * p3.y}; + result.points[segment_data::point::control1].y = y1 - p0.y; + result.points[segment_data::point::control2].y = y2 - p3.y; + // the cant of a path is told along it: a path running against the stations of the curve has it the other way round + result.rolls = {roll(start) * (localstart.y >= 0.0 ? 1.f : -1.f), roll(end) * (localend.y >= 0.0 ? 1.f : -1.f)}; + result.radius = Local.radius; + bezier const curve{result}; + auto const begin{plan_of(curve.first(0.0))}; + auto const finish{plan_of(curve.first(1.0))}; + auto const turn{glm::length(begin) > 1e-9 && glm::length(finish) > 1e-9 ? geometry::signed_angle(begin, finish) : 0.0}; + if (std::abs(turn) > 1e-6) + result.radius = static_cast(curve.plan_length() / turn); + else + result.radius = 0.f; + for (auto const &piece : Local.pieces) + result.pieces.push_back(path(piece)); + return result; + } +}; + +// the curve the track is a part of, as a frame of samples, and its tracks +bool editor_mode::curve_of(TTrack &Track, editor_track::straight_tolerance const &Tolerance, double const Gauge, std::vector &Frame, std::vector &Tracks, double const Beyond) +{ + auto *base{&Track}; + if (Beyond > 0.0 && Track.eType == tt_Normal && editor_track::is_straight(Track, Tolerance)) + base = curve_ahead(Track, Tolerance, Beyond); + if (base == nullptr) + return false; + editor_track::curve curve; + editor_track::chain chain; + std::string error; + if (false == editor_track::find_curve(*base, Tolerance, Gauge, curve) || false == editor_track::find_chain(curve.from, curve.to, chain, error, true)) + return false; + for (auto const &part : editor_track::chain_parts(chain)) + if (std::find(part.tracks.begin(), part.tracks.end(), base) != part.tracks.end()) + { + chain = part; + break; + } + if (Beyond > 0.0) + { + // the straights past both ends, as far as the reach, taken along the curve: the one before it from its far end + auto const taken = [&](editor_track::straight_run const &Run) { + std::size_t count{0}; + for (double reached{0.0}; count < Run.tracks.size() && reached < Beyond; ++count) + { + auto const &path{Run.tracks[count]->m_paths.front()}; + reached += plan_distance(path.points[segment_data::point::start], path.points[segment_data::point::end]); + } + return count; + }; + auto const before{editor_track::straight_beyond(chain, false, Tolerance)}; + auto const after{editor_track::straight_beyond(chain, true, Tolerance)}; + editor_track::chain extended; + for (auto i{taken(before)}; i-- > 0;) + { + extended.tracks.push_back(before.tracks[i]); + extended.forward.push_back(false == before.outward[i]); + } + extended.tracks.insert(extended.tracks.end(), chain.tracks.begin(), chain.tracks.end()); + extended.forward.insert(extended.forward.end(), chain.forward.begin(), chain.forward.end()); + for (std::size_t i = 0, count = taken(after); i < count; ++i) + { + extended.tracks.push_back(after.tracks[i]); + extended.forward.push_back(after.outward[i]); + } + chain = std::move(extended); + } + if (std::find(chain.tracks.begin(), chain.tracks.end(), &Track) == chain.tracks.end()) + return false; + Frame = sample_chain(chain); + Tracks = chain.tracks; + return Frame.size() >= 2; +} + +// the paths of the curve between the points cut off at both, right at the points, and taken out, the switch to go in their place +void editor_mode::cut_curve(std::vector &Candidates, std::vector const &Frame, glm::dvec3 const &First, glm::dvec3 const &Second, std::vector> &States, std::vector &Created, std::vector &Removed) +{ + auto const one{nearest_station(Frame, First)}; + auto const two{nearest_station(Frame, Second)}; + auto const From{std::min(one, two)}; + auto const To{std::max(one, two)}; + for (auto const &point : {First, Second}) + { + for (auto *candidate : std::vector(Candidates)) + { + if (candidate->m_editorremoved || candidate->eType != tt_Normal) + continue; + auto const t{editor_track::nearest_parameter(*candidate, point)}; + if (plan_distance(editor_track::point_at(*candidate, t), point) > 0.05) + continue; + if (t > 0.002 && t < 0.998) + { + if (std::find(Created.begin(), Created.end(), candidate) == Created.end() && std::none_of(States.begin(), States.end(), [&](auto const &Entry) { return Entry.first == candidate; })) + States.emplace_back(candidate, editor_track::capture(*candidate)); + if (auto *second{editor_track::split_path(*candidate, t)}) + { + Created.push_back(second); + Candidates.push_back(second); + } + } + break; + } + } + for (auto *candidate : Candidates) + { + if (candidate->m_editorremoved) + continue; + auto const where{nearest_station(Frame, editor_track::point_at(*candidate, 0.5))}; + if (where > From + 0.01 && where < To - 0.01) + { + editor_track::retire(*candidate); + // a piece split off in this step goes as if it had never been made: kept among the ones made and the ones taken out + // too, an undo would retire it and then bring it back + if (auto const made{std::find(Created.begin(), Created.end(), candidate)}; made != Created.end()) + Created.erase(made); + else + Removed.push_back(candidate); + } + } +} + +void editor_mode::insert_curved_connection() +{ + auto &tool{m_switch}; + tool.placing = false; + auto const fail = [&](std::string const &Reason) { + tool.status = Reason; + ui()->set_status(Reason, true); + flash_switch_problem(Reason, {}, {{tool.point, ""}}); + }; + if (tool.connection != static_cast(connection::kind::crossover)) + return fail(STR("Along a curve only a crossover can be laid")); + // the curve pressed on with the straights past its ends: from a transition the crossover goes on onto the straight + auto pressedframe{tool.frame}; + auto pressedtracks{tool.frame_tracks}; + auto *pressed{tool.frame_tracks.front()}; + { + auto nearest{std::numeric_limits::max()}; + for (auto *track : tool.frame_tracks) + if (false == track->m_editorremoved) + if (auto const distance{plan_distance(editor_track::point_at(*track, editor_track::nearest_parameter(*track, tool.point)), tool.point)}; distance < nearest) + { + nearest = distance; + pressed = track; + } + std::vector frame; + std::vector tracks; + if (curve_of(*pressed, m_straights.tolerance, m_route.design.norms.gauge, frame, tracks, kStraightReach)) + { + pressedframe = std::move(frame); + pressedtracks = std::move(tracks); + } + } + // the other track: one beside this curve near the release, running along with it + TTrack *other{nullptr}; + auto best{kOtherReach}; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || track->eType != tt_Normal || track->m_paths.empty() || std::find(pressedtracks.begin(), pressedtracks.end(), track) != pressedtracks.end()) + continue; + auto const distance{plan_distance(editor_track::point_at(*track, editor_track::nearest_parameter(*track, tool.mouse)), tool.mouse)}; + if (distance < best) + { + best = distance; + other = track; + } + } + if (other == nullptr) + return fail(STR("Drag onto the other track")); + std::vector otherframe; + std::vector othertracks; + if (false == curve_of(*other, m_straights.tolerance, m_route.design.norms.gauge, otherframe, othertracks, kStraightReach)) + return fail(STR("The other track isn't a curve running along this one")); + // the inner track is the frame: the plane of its cant carries the crossover, the outer track goes up onto it + auto innerframe{pressedframe}; + auto innertracks{pressedtracks}; + auto station{nearest_station(innerframe, tool.point)}; + auto const at{sample_at(innerframe, station)}; + auto const across{sample_at(otherframe, nearest_station(otherframe, at.position))}; + glm::dvec2 const left{-at.tangent.y, at.tangent.x}; + auto offset{glm::dot(plan_of(across.position) - plan_of(at.position), left)}; + auto lift{at.position.y - offset * std::tan(glm::radians(static_cast(at.roll))) - across.position.y}; + bool swapped{false}; + if (lift < -0.005) + { + // the plane falls towards the other track: that one is the inner one + std::swap(innerframe, otherframe); + std::swap(innertracks, othertracks); + station = nearest_station(innerframe, at.position); + auto const inner{sample_at(innerframe, station)}; + glm::dvec2 const innerleft{-inner.tangent.y, inner.tangent.x}; + offset = glm::dot(plan_of(at.position) - plan_of(inner.position), innerleft); + lift = inner.position.y - offset * std::tan(glm::radians(static_cast(inner.roll))) - at.position.y; + swapped = true; + } + WriteLog(format("Editor: curved crossover - at station %.1f, inner roll %.3f deg, other roll %.3f deg, offset %.3f m, lift %.3f m%s", station, at.roll, across.roll, offset, lift, swapped ? ", the other track is the inner one" : ""), logtype::generic); + if (std::abs(offset) < 3.0 || std::abs(offset) > 30.0) + return fail(format(STR_C("The tracks are %.2f m apart, too close or too far for a crossover"), std::abs(offset))); + + // the crossover planned as between two straights, in the frame of the inner curve + auto const total{innerframe.back().station}; + connection::request request; + request.type = connection::kind::crossover; + request.from.start = {0.0, 0.0, 0.0}; + request.from.direction = {0.0, 1.0}; + request.from.length = total; + connection::line to; + to.start = {-offset, 0.0, 0.0}; + to.direction = {0.0, 1.0}; + to.length = total; + request.to.push_back(to); + request.first = tool.templates[tool.armed]; + auto const second{tool.connection_second >= 0 && tool.connection_second < static_cast(tool.templates.size()) ? tool.connection_second : tool.armed}; + request.second = tool.templates[second]; + request.radius = tool.connection_radius; + auto const release{nearest_station(innerframe, tool.mouse)}; + auto const press{swapped ? nearest_station(innerframe, tool.point) : station}; + request.forward = release >= press ? 1 : -1; + // the plan starts on the track pressed on + if (swapped) + { + request.from.start = {-offset, 0.0, 0.0}; + request.to.front().start = {0.0, 0.0, 0.0}; + } + request.along = press; + request.target = release; + // the side of the travel along the starting track the other one lies on + auto const across_plan{request.to.front().start.x - request.from.start.x}; + request.side = -request.forward * across_plan >= 0.0 ? 1 : -1; + auto plan{connection::plan(request)}; + if (false == plan.valid) + { + // the other side, if the side was taken the wrong way round + request.side = -request.side; + plan = connection::plan(request); + } + if (false == plan.valid) + return fail(plan.error.empty() ? std::string{STR("The crossover doesn't fit on the curve")} : plan.error); + + curve_mapping const mapping{innerframe}; + std::vector> states; + std::vector created; + std::vector removed; + auto *style{pressed}; + // the kept grade lines before the outer track went up, the design of which goes up with it + std::optional> library; + auto const undo_all = [&]() { + for (auto *track : created) + editor_track::retire(*track); + for (auto entry{states.rbegin()}; entry != states.rend(); ++entry) + { + editor_track::apply(*entry->first, entry->second); + editor_track::commit({entry->first}); + } + for (auto *track : removed) + { + editor_track::revive(*track); + editor_track::commit({track}); + } + if (library.has_value()) + profiles_restore(std::move(*library)); + straight_refresh(); + }; + + // the outer track up onto the plane of the inner one over the crossover, with ramps on both sides + auto const outerline{swapped ? 0 : 1}; + double low{std::numeric_limits::max()}, high{std::numeric_limits::lowest()}; + for (auto const &entry : plan.switches) + for (auto const &path : entry.paths) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + { + low = std::min(low, path.points[end].z); + high = std::max(high, path.points[end].z); + } + auto *outertrack{swapped ? pressed : other}; + for (auto const &entry : plan.switches) + WriteLog(format("Editor: curved crossover - planned switch on %d: %.3f %.3f -> %.3f %.3f; extent %.3f..%.3f", entry.line, entry.paths.front().points[segment_data::point::start].x, entry.paths.front().points[segment_data::point::start].z, entry.paths.front().points[segment_data::point::end].x, entry.paths.front().points[segment_data::point::end].z, low, high), logtype::generic); + glm::dvec3 flatfrom{0.0}, flatto{0.0}; + outer_lift raise{0.0, 0.0, 0.0, 0.0, 0.0}; + { + auto route{editor_track::run_route(*outertrack, 3000.0)}; + auto const samples{editor_track::sample_route(route, 1.0)}; + if (samples.size() < 2) + return fail(STR("The outer track can't be followed")); + // the chainage of the point projected onto the line between the samples + auto const chainage_of = [&](glm::dvec3 const &Point) { + double best{std::numeric_limits::max()}; + double chainage{0.0}; + for (std::size_t i = 0; i + 1 < samples.size(); ++i) + { + auto const a{plan_of(samples[i].position)}; + auto const run{plan_of(samples[i + 1].position) - a}; + auto const t{std::clamp(glm::dot(plan_of(Point) - a, run) / std::max(1e-12, glm::dot(run, run)), 0.0, 1.0)}; + if (auto const distance{glm::length(plan_of(Point) - (a + run * t))}; distance < best) + { + best = distance; + chainage = samples[i].chainage + (samples[i + 1].chainage - samples[i].chainage) * t; + } + } + return chainage; + }; + // the outer track lies at -offset in the frame of the inner one, whichever of them was pressed on + auto const outerx{-offset}; + auto c1{chainage_of(mapping.point({outerx, 0.0, low}))}; + auto c2{chainage_of(mapping.point({outerx, 0.0, high}))}; + // the top of the ramps where the switch on the outer track ends: no short paths left between the two + if (c1 > c2) + std::swap(c1, c2); + // the switch on the outer track lies on the plane of the inner one at both its ends: the grade lines of the two tracks needn't run + // alike, so the lift goes along in a straight line through what the two ends need + auto ca{c1}, cb{c2}; + auto la{lift}, lb{lift}; + for (auto const &entry : plan.switches) + if (entry.line == outerline) + { + auto const path{mapping.path(entry.paths.front())}; + auto const &a{path.points[segment_data::point::start]}; + auto const &b{path.points[segment_data::point::end]}; + ca = chainage_of(a); + cb = chainage_of(b); + la = a.y - editor_track::sampled_elevation(samples, ca); + lb = b.y - editor_track::sampled_elevation(samples, cb); + break; + } + auto const rise{std::abs(cb - ca) > 1.0 ? (lb - la) / (cb - ca) : 0.0}; + raise = {c1, c2, la + rise * (c1 - ca), la + rise * (c2 - ca), 0.0}; + if (std::max(std::abs(raise.first), std::abs(raise.second)) > 0.002) + { + raise.ramp = std::max(std::abs(raise.first), std::abs(raise.second)) / (std::max(0.5, kRampShare * m_profile.line.norms.curve_threshold) / 1000.0); + flatfrom = editor_track::sampled_position(samples, c1); + flatto = editor_track::sampled_position(samples, c2); + auto const breaks{raise.breaks(route.length)}; + // the design of the outer track before, kept or read from the track, to go up with it + auto *first{route.spans.front().track}; + auto *last{route.spans.back().track}; + profile_library_load(); + library = m_profiles; + profile_take(route, first, last); + auto const before{m_profile.line}; + std::vector> raisestates; + std::vector raisecreated; + editor_track::apply_profile( + route, [&](double const Chainage) { return editor_track::sampled_elevation(samples, Chainage) + raise.at(Chainage); }, + [&](double const Chainage) { return editor_track::sampled_grade(samples, Chainage) + raise.grade(Chainage); }, breaks, raisestates, raisecreated); + states.insert(states.end(), raisestates.begin(), raisestates.end()); + created.insert(created.end(), raisecreated.begin(), raisecreated.end()); + // the raised grade line kept as the design of the outer track, in place of the one it had: its points gone up with it + // and the corners of the ramps, straight between them as the ramps are + if (false == route.spans.empty()) + { + profile_take(route, route.spans.front().track, route.spans.back().track); + std::vector points; + for (auto point : before.points) + { + point.elevation += raise.at(point.chainage); + points.push_back(point); + } + for (auto const chainage : breaks) + { + profile::pvi corner; + corner.chainage = chainage; + corner.elevation = profile::elevation(before, chainage) + raise.at(chainage); + corner.automatic = false; + points.push_back(corner); + } + std::sort(points.begin(), points.end(), [](auto const &Left, auto const &Right) { return Left.chainage < Right.chainage; }); + std::vector line; + for (auto const &point : points) + { + if (false == line.empty() && point.chainage - line.back().chainage < 0.5) + { + // the corner of a ramp before a point of the design at the same place + if (false == point.automatic && point.radius == 0.0) + line.back() = point; + continue; + } + line.push_back(point); + } + if (line.size() >= 2) + { + m_profile.line = before; + m_profile.line.points = std::move(line); + m_profile.selected = -1; + profile_check(); + profile_store(); + } + } + WriteLog(format("Editor: curved crossover - the outer track %s raised by %.3f .. %.3f m from %.1f to %.1f m of its line, ramps %.1f m", outertrack->name().c_str(), raise.first, raise.second, c1, c2, raise.ramp), logtype::generic); + } + } + // the outer curve again, as it lies now + std::vector outerframe; + std::vector outertracks; + { + auto const probe{mapping.point({-offset, 0.0, 0.5 * (low + high)})}; + TTrack *closest{nullptr}; + auto nearest{1.0}; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || track->eType != tt_Normal || track->m_paths.empty()) + continue; + auto const distance{plan_distance(editor_track::point_at(*track, editor_track::nearest_parameter(*track, probe)), probe)}; + if (distance < nearest) + { + nearest = distance; + closest = track; + } + } + if (closest == nullptr || false == curve_of(*closest, m_straights.tolerance, m_route.design.norms.gauge, outerframe, outertracks, kStraightReach)) + { + undo_all(); + return fail(STR("The outer track can't be followed after it went up")); + } + } + // the inner curve again: the outer track may be split where the ramps end + if (false == swapped) + innertracks = pressedtracks; + + std::vector switches; + for (auto const &entry : plan.switches) + { + auto const &shape{entry.second ? request.second : request.first}; + std::vector paths; + for (auto const &local : entry.paths) + paths.push_back(mapping.path(local)); + auto const onouter{entry.line == outerline}; + auto &frame{onouter ? outerframe : innerframe}; + auto &candidates{onouter ? outertracks : innertracks}; + // the other track runs along at the distance the crossover was planned for, else its switch would miss it + for (auto const end : {segment_data::point::start, segment_data::point::end}) + { + auto const &point{paths.front().points[end]}; + if (auto const off{plan_distance(sample_at(frame, nearest_station(frame, point)).position, point)}; off > 0.1) + { + WriteLog(format("Editor: curved crossover - the switch on %s misses it by %.3f m at %.3f %.3f, station %.1f of %.1f", onouter ? "the outer track" : "the inner track", off, point.x, point.z, nearest_station(frame, point), frame.empty() ? 0.0 : frame.back().station), + logtype::generic); + undo_all(); + return fail(STR("The other track doesn't run along at the same distance there")); + } + } + cut_curve(candidates, frame, paths.front().points[segment_data::point::start], paths.front().points[segment_data::point::end], states, created, removed); + // the ends of the main track of the switch onto the ends of the paths cut off, which the curve put a little apart + auto const snap = [&](glm::dvec3 const &Point) { + glm::dvec3 found{Point}; + auto nearest{0.1}; + for (auto *candidate : candidates) + { + if (candidate->m_editorremoved || candidate->m_paths.empty()) + continue; + for (auto const which : {segment_data::point::start, segment_data::point::end}) + if (auto const distance{glm::distance(candidate->m_paths.front().points[which], Point)}; distance < nearest) + { + nearest = distance; + found = candidate->m_paths.front().points[which]; + } + } + return found; + }; + auto const begin{paths.front().points[segment_data::point::start]}; + auto const finish{paths.front().points[segment_data::point::end]}; + auto const start{snap(begin)}; + auto const end{snap(finish)}; + for (auto &path : paths) + { + if (glm::distance(path.points[segment_data::point::start], begin) < 1e-6) + { + path.points[segment_data::point::start] = start; + if (false == path.pieces.empty()) + path.pieces.front().points[segment_data::point::start] = start; + } + } + paths.front().points[segment_data::point::end] = end; + if (false == paths.front().pieces.empty()) + paths.front().pieces.back().points[segment_data::point::end] = end; + auto const made{create_switch_set(shape, paths, *style, switch_name_for_new())}; + if (made.empty()) + { + undo_all(); + return fail(tool.status.empty() ? std::string{STR("A switch of the crossover couldn't be made")} : tool.status); + } + created.insert(created.end(), made.begin(), made.end()); + for (auto *track : made) + if (track->eType == tt_Switch) + switches.push_back(track); + advance_switch_name(); + } + std::vector inserts; + for (auto const &insert : plan.inserts) + if (auto *track{editor_track::create_path(*style, mapping.path(insert))}) + inserts.push_back(track); + editor_track::commit(inserts); + digitize_drawn(inserts); + created.insert(created.end(), inserts.begin(), inserts.end()); + if (switches.empty()) + { + undo_all(); + return fail(STR("The crossover couldn't be laid")); + } + record_connection(request.type, switches, plan, request.first); + // the lift kept with the crossover, so it can be taken back when the crossover moves or goes + if (raise.ramp > 0.0) + for (auto entry : switch_store::connections(*switches.front())) + if (entry.kind == "connection" && entry.name == switches.front()->name()) + { + entry.lift = raise.first; + entry.lift_end = raise.second; + entry.lift_from = flatfrom; + entry.lift_to = flatto; + entry.ramp = raise.ramp; + switch_store::put(entry, entry.layer); + } + push_track_snapshot(std::move(states), std::move(created), std::move(removed)); + // the design of the outer track goes back down with it + if (library.has_value()) + profiles_to_history(std::move(*library)); + straight_refresh(); + first_step_done(first_step::turnout); + m_node = switches.front(); + ui()->set_node(m_node); + std::string names; + for (auto *track : switches) + { + if (place_switch_drive(*track)) + join_last_steps(); + names += (names.empty() ? "" : ", ") + track->name(); + } + tool.status = format(STR_C("Crossover laid along the curve, switches %s, the tracks %.2f m apart"), names.c_str(), std::abs(offset)); + if (raise.ramp > 0.0) + tool.status += format(STR_C("\nThe outer track went up %.3f m onto the plane of the cant of the inner one, with ramps of %.1f per mille"), std::max(std::abs(raise.first), std::abs(raise.second)), std::max(0.5, kRampShare * m_profile.line.norms.curve_threshold)); + tool.status += "\n" + connection_readout(plan); + ui()->set_status(tool.status, false); +} + +// the crossover laid along a curve the switch is a part of: its record, its two switches and the insert between them +std::optional editor_mode::crossover_of(TTrack const &Switch) const +{ + if (Switch.eType != tt_Switch || Switch.m_editorremoved) + return std::nullopt; + for (auto const &entry : switch_store::connections(Switch)) + { + if (entry.kind != "connection" || entry.type != connection::word(connection::kind::crossover) || entry.parts.size() != 2) + continue; + curved_crossover result; + result.record = entry; + result.first = simulation::Paths.find(entry.parts[0]); + result.second = simulation::Paths.find(entry.parts[1]); + if (result.first == nullptr || result.second == nullptr || result.first->m_editorremoved || result.second->m_editorremoved || result.first->m_paths.size() < 2 || result.second->m_paths.size() < 2) + continue; + auto const &end{result.first->m_paths[1].points[segment_data::point::end]}; + auto const &other{result.second->m_paths[1].points[segment_data::point::end]}; + for (auto const &[track, point] : editor_track::connected_points(*result.first, end)) + { + if (track == nullptr || track->m_editorremoved || track->eType != tt_Normal || track->m_paths.size() != 1) + continue; + auto const &path{track->m_paths.front()}; + if (plan_distance(path.points[segment_data::point::start], other) < 0.05 || plan_distance(path.points[segment_data::point::end], other) < 0.05) + result.insert = track; + } + if (result.insert != nullptr) + return result; + } + return std::nullopt; +} + +// the crossover taken out: the main tracks of its switches plain paths again, of the same shape, the insert gone, the outer track +// down by the lift it went up by. Gives the plain paths in place of the first and the second switch +bool editor_mode::take_out_crossover(curved_crossover const &Crossover, std::vector> &States, std::vector &Created, std::vector &Removed, TTrack *&First, TTrack *&Second) +{ + TTrack const *style{nullptr}; + for (auto const &[track, point] : editor_track::connected_points(*Crossover.first, Crossover.first->m_paths.front().points[segment_data::point::start])) + if (track != nullptr && track->eType == tt_Normal && false == track->m_editorremoved) + style = track; + if (style == nullptr) + style = Crossover.insert; + std::vector plains; + for (auto *track : {Crossover.first, Crossover.second}) + { + auto *plain{editor_track::create_path(*style, track->m_paths.front())}; + if (plain == nullptr) + return false; + plains.push_back(plain); + Created.push_back(plain); + } + for (auto *track : {Crossover.first, Crossover.second, Crossover.insert}) + { + editor_track::retire(*track); + Removed.push_back(track); + } + editor_track::commit(plains); + switch_store::forget(Crossover.first->name()); + switch_store::forget(Crossover.second->name()); + First = plains[0]; + Second = plains[1]; + auto const &record{Crossover.record}; + if (false == record.lifted() || record.ramp <= 0.0) + return true; + // the outer track is the one the level stretch of the lift lies on + TTrack *outer{nullptr}; + for (auto *plain : plains) + if (plan_distance(editor_track::point_at(*plain, editor_track::nearest_parameter(*plain, record.lift_from)), record.lift_from) < 1.0 || + plan_distance(editor_track::point_at(*plain, editor_track::nearest_parameter(*plain, record.lift_to)), record.lift_to) < 1.0) + outer = plain; + if (outer == nullptr) + return true; + auto route{editor_track::run_route(*outer, 3000.0)}; + auto const samples{editor_track::sample_route(route, 1.0)}; + if (samples.size() < 2) + return true; + auto const chainage_of = [&](glm::dvec3 const &Point) { + double best{std::numeric_limits::max()}; + double chainage{0.0}; + for (std::size_t i = 0; i + 1 < samples.size(); ++i) + { + auto const a{plan_of(samples[i].position)}; + auto const run{plan_of(samples[i + 1].position) - a}; + auto const t{std::clamp(glm::dot(plan_of(Point) - a, run) / std::max(1e-12, glm::dot(run, run)), 0.0, 1.0)}; + if (auto const distance{glm::length(plan_of(Point) - (a + run * t))}; distance < best) + { + best = distance; + chainage = samples[i].chainage + (samples[i + 1].chainage - samples[i].chainage) * t; + } + } + return chainage; + }; + outer_lift lowered{chainage_of(record.lift_from), chainage_of(record.lift_to), record.lift, record.lift_end, record.ramp}; + if (lowered.from > lowered.to) + { + std::swap(lowered.from, lowered.to); + std::swap(lowered.first, lowered.second); + } + auto const breaks{lowered.breaks(route.length)}; + profile_take(route, route.spans.front().track, route.spans.back().track); + auto const before{m_profile.line}; + editor_track::apply_profile( + route, [&](double const Chainage) { return editor_track::sampled_elevation(samples, Chainage) - lowered.at(Chainage); }, + [&](double const Chainage) { return editor_track::sampled_grade(samples, Chainage) - lowered.grade(Chainage); }, breaks, States, Created); + // the design of the outer track down with it, the corners of the ramps left out where the line runs on straight through them + profile_take(route, route.spans.front().track, route.spans.back().track); + std::vector points; + for (auto point : before.points) + { + point.elevation -= lowered.at(point.chainage); + points.push_back(point); + } + for (std::size_t k = 1; k + 1 < points.size();) + { + auto const in{(points[k].elevation - points[k - 1].elevation) / std::max(1e-6, points[k].chainage - points[k - 1].chainage)}; + auto const out{(points[k + 1].elevation - points[k].elevation) / std::max(1e-6, points[k + 1].chainage - points[k].chainage)}; + if (std::abs(out - in) < 1e-7) + points.erase(points.begin() + static_cast(k)); + else + ++k; + } + if (points.size() >= 2) + { + m_profile.line = before; + m_profile.line.points = std::move(points); + m_profile.selected = -1; + profile_check(); + profile_store(); + } + WriteLog(format("Editor: curved crossover - the outer track %s down by %.3f .. %.3f m again", outer->name().c_str(), record.lift, record.lift_end), logtype::generic); + return true; +} + +// the crossover along a curve moved along it by the distance, from its first switch towards the second: taken out and laid again, +// of the template Shape when it's given +bool editor_mode::slide_curved_connection(TTrack &Switch, double const Distance, int const Shape) +{ + auto const crossover{crossover_of(Switch)}; + if (false == crossover.has_value()) + return false; + auto &tool{m_switch}; + auto const shape{Shape >= 0 ? Shape : crossover_template(crossover->record)}; + if (shape < 0) + { + tool.status = STR_C("The template the crossover was laid of isn't among the templates"); + ui()->set_status(tool.status, true); + return false; + } + std::vector const names{crossover->first->name(), crossover->second->name()}; + auto const firststart{crossover->first->m_paths.front().points[segment_data::point::start]}; + auto const firstend{crossover->first->m_paths.front().points[segment_data::point::end]}; + auto const secondstart{crossover->second->m_paths.front().points[segment_data::point::start]}; + std::vector> states; + std::vector created; + std::vector removed; + TTrack *first{nullptr}; + TTrack *second{nullptr}; + // the design of the outer track comes down with the lift taken back, an undo puts both back + profile_library_load(); + auto library{m_profiles}; + if (false == take_out_crossover(*crossover, states, created, removed, first, second)) + return false; + // the new places of the press and of the release, along the two curves, or the two straights + std::vector firstframe, secondframe; + std::vector firsttracks, secondtracks; + glm::dvec3 press, release; + if (curve_of(*first, m_straights.tolerance, m_route.design.norms.gauge, firstframe, firsttracks, kStraightReach) && curve_of(*second, m_straights.tolerance, m_route.design.norms.gauge, secondframe, secondtracks, kStraightReach)) + { + auto const towards{nearest_station(firstframe, firstend) >= nearest_station(firstframe, firststart) ? 1.0 : -1.0}; + press = sample_at(firstframe, nearest_station(firstframe, firststart) + towards * Distance).position; + auto const ahead{nearest_station(secondframe, secondstart) >= nearest_station(secondframe, firststart) ? 1.0 : -1.0}; + release = sample_at(secondframe, nearest_station(secondframe, secondstart) + ahead * Distance).position; + } + else + { + auto direction{plan_of(firstend - firststart)}; + direction = glm::length(direction) > 1e-9 ? glm::normalize(direction) : glm::dvec2{0.0, 1.0}; + press = firststart + glm::dvec3{direction.x, 0.0, direction.y} * Distance; + release = secondstart + glm::dvec3{direction.x, 0.0, direction.y} * Distance; + firsttracks = {first}; + } + switch_store::follow(); + push_track_snapshot(std::move(states), std::move(created), std::move(removed)); + records_to_history(); + if (crossover->record.lifted()) + profiles_to_history(std::move(library)); + // laid again + if (false == lay_crossover(shape, press, release, 3.0, names)) + { + auto const reason{tool.status}; + undo_last(); + tool.status = reason.empty() ? std::string{STR_C("The crossover doesn't fit there")} : reason; + ui()->set_status(tool.status, true); + return false; + } + join_last_steps(); + tool.status = (Shape >= 0 ? format(STR_C("Crossover laid again of %s"), template_name(tool.templates[shape]).c_str()) : format(STR_C("Crossover moved %.2f m"), Distance)) + "\n" + tool.status; + ui()->set_status(tool.status, false); + return true; +} + +std::size_t editor_mode::follow_crossovers(std::vector const &Before) +{ + auto &state{m_profile}; + auto const changedroute{state.route}; + auto *changedfrom{state.from}; + auto *changedto{state.to}; + auto const after{state.samples}; + auto const changedline{state.line}; + if (Before.size() < 2 || after.size() < 2) + return 0; + double constexpr follow{25.0}; + double constexpr leave{50.0}; + // how much the route went up at the point beside it, and how far the point is from it + auto const change_at = [&](glm::dvec3 const &Point, double &Distance, double &Chainage) { + Distance = std::numeric_limits::max(); + Chainage = 0.0; + for (std::size_t i = 0; i + 1 < after.size(); ++i) + { + auto const a{plan_of(after[i].position)}; + auto const run{plan_of(after[i + 1].position) - a}; + auto const t{std::clamp(glm::dot(plan_of(Point) - a, run) / std::max(1e-12, glm::dot(run, run)), 0.0, 1.0)}; + if (auto const distance{glm::length(plan_of(Point) - (a + run * t))}; distance < Distance) + { + Distance = distance; + Chainage = after[i].chainage + (after[i + 1].chainage - after[i].chainage) * t; + } + } + auto const weight{std::clamp((leave - Distance) / (leave - follow), 0.0, 1.0)}; + return weight * (editor_track::sampled_elevation(after, Chainage) - editor_track::sampled_elevation(Before, Chainage)); + }; + std::vector done; + std::size_t followed{0}; + for (auto const &span : changedroute.spans) + { + if (span.track == nullptr || span.track->eType != tt_Switch) + continue; + auto const crossover{crossover_of(*span.track)}; + if (false == crossover.has_value()) + continue; + auto *other{crossover->first == span.track ? crossover->second : crossover->first}; + // on the same grade line it goes with the route anyway, grade_line_follow sees to it; what a fit to the terrain leaves as it is stays + if ((m_profile.whole_grade_line && false == m_profile.fitting && on_route_grade_line(*other)) || (m_profile.fitting && m_nmt_state.stayed.contains(other))) + continue; + if (std::any_of(changedroute.spans.begin(), changedroute.spans.end(), [&](auto const &Span) { return Span.track == other; }) || std::find(done.begin(), done.end(), other) != done.end()) + continue; + done.push_back(other); + auto route{editor_track::run_route(*other, 3000.0)}; + auto const samples{editor_track::sample_route(route, 1.0)}; + if (samples.size() < 2) + continue; + // the change of each point of the other line + std::vector changes(samples.size(), 0.0); + std::vector distances(samples.size(), 0.0); + bool any{false}; + for (std::size_t i = 0; i < samples.size(); ++i) + { + double chainage; + changes[i] = change_at(samples[i].position, distances[i], chainage); + any = any || std::abs(changes[i]) > 0.001; + } + if (false == any) + continue; + auto const change = [&](double const Chainage) { + auto const at{std::clamp(Chainage, samples.front().chainage, samples.back().chainage)}; + auto const next{std::lower_bound(samples.begin(), samples.end(), at, [](auto const &Sample, double const Value) { return Sample.chainage < Value; })}; + if (next == samples.begin()) + return changes.front(); + if (next == samples.end()) + return changes.back(); + auto const i{static_cast(std::distance(samples.begin(), next))}; + auto const f{(at - samples[i - 1].chainage) / std::max(1e-9, samples[i].chainage - samples[i - 1].chainage)}; + return changes[i - 1] + (changes[i] - changes[i - 1]) * f; + }; + // where the grade line of the route breaks, the other line breaks too + std::vector breaks; + for (auto const &point : changedline.points) + { + auto const at{editor_track::sampled_position(after, point.chainage)}; + double best{std::numeric_limits::max()}; + double chainage{0.0}; + for (auto const &sample : samples) + if (auto const distance{plan_distance(sample.position, at)}; distance < best) + { + best = distance; + chainage = sample.chainage; + } + if (best < follow && chainage > 0.5 && chainage < route.length - 0.5) + breaks.push_back(chainage); + } + // and where it starts and stops running beside the route + for (std::size_t i = 1; i < samples.size(); ++i) + for (auto const bound : {follow, leave}) + if ((distances[i - 1] < bound) != (distances[i] < bound) && samples[i].chainage > 0.5 && samples[i].chainage < route.length - 0.5) + breaks.push_back(samples[i].chainage); + std::sort(breaks.begin(), breaks.end()); + breaks.erase(std::unique(breaks.begin(), breaks.end(), [](double const A, double const B) { return std::abs(A - B) < 1.0; }), breaks.end()); + profile_take(route, route.spans.front().track, route.spans.back().track); + auto const designed{m_profile.line}; + std::vector> states; + std::vector created; + editor_track::apply_profile( + route, [&](double const Chainage) { return editor_track::sampled_elevation(samples, Chainage) + change(Chainage); }, + [&](double const Chainage) { return editor_track::sampled_grade(samples, Chainage) + (change(Chainage + 0.5) - change(Chainage - 0.5)); }, breaks, states, created); + profile_library_load(); + auto library{m_profiles}; + push_track_snapshot(std::move(states), std::move(created)); + m_history.back().profiles = true; + m_history.back().profile_library = std::move(library); + join_last_steps(); + // its design changed by as much + profile_take(route, route.spans.front().track, route.spans.back().track); + std::vector points; + for (auto point : designed.points) + { + point.elevation += change(point.chainage); + points.push_back(point); + } + for (auto const chainage : breaks) + { + profile::pvi point; + point.chainage = chainage; + point.elevation = profile::elevation(designed, chainage) + change(chainage); + points.push_back(point); + } + std::sort(points.begin(), points.end(), [](auto const &Left, auto const &Right) { return Left.chainage < Right.chainage; }); + std::vector line; + for (auto const &point : points) + if (line.empty() || point.chainage - line.back().chainage >= 0.5) + line.push_back(point); + if (line.size() >= 2) + { + m_profile.line = designed; + m_profile.line.points = std::move(line); + m_profile.selected = -1; + profile_check(); + profile_store(); + } + ++followed; + WriteLog(format("Editor: vertical profile - the track %s across the crossover %s followed the change", other->name().c_str(), crossover->first->name().c_str()), logtype::generic); + } + if (followed > 0) + { + // the route the user works on open again + profile_take(changedroute, changedfrom, changedto); + } + return followed; +} + +int editor_mode::crossover_template(switch_store::record const &Record) +{ + auto &tool{m_switch}; + show_track_tab(track_tab::turnout); + arm_switch(); + if (auto const found{matching_template(Record, false)}; found >= 0) + return found; + // switches of no template of the catalogue, as the digitized ones of the old sceneries: the first one is the template + if (Record.source != "measured" || Record.parts.empty()) + return -1; + auto own{editor_track::template_of_switch(simulation::Paths.find(Record.parts.front()))}; + if (false == own.has_value()) + return -1; + tool.templates.push_back(std::move(*own)); + return static_cast(tool.templates.size()) - 1; +} + +bool editor_mode::lay_crossover(int const Shape, glm::dvec3 const &Press, glm::dvec3 const &Release, double const Reach, std::vector const &Names) +{ + auto &tool{m_switch}; + tool.keep_names = Names; + struct forget_names + { + std::vector &names; + ~forget_names() { names.clear(); } + } const forget{tool.keep_names}; + // the plain path the press falls on + TTrack *closest{nullptr}; + auto nearest{Reach}; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || track->eType != tt_Normal || track->m_paths.empty()) + continue; + if (auto const distance{plan_distance(editor_track::point_at(*track, editor_track::nearest_parameter(*track, Press)), Press)}; distance < nearest) + { + nearest = distance; + closest = track; + } + } + if (closest == nullptr || Shape < 0) + return false; + show_track_tab(track_tab::turnout); + arm_switch(); + tool.armed = Shape; + tool.connection = static_cast(connection::kind::crossover); + tool.connection_second = -1; + m_node = closest; + ui()->set_node(m_node); + // the press onto the path, where the line went sideways + auto const press{editor_track::point_at(*closest, editor_track::nearest_parameter(*closest, Press))}; + m_cursor_override = press; + auto const started{start_switch_placement()}; + m_cursor_override.reset(); + if (false == started) + return false; + tool.mouse = {Release.x, tool.point.y, Release.z}; + auto const steps{m_history.size()}; + if (tool.curved) + insert_curved_connection(); + else + insert_connection(); + if (m_history.size() == steps) + return false; + // both switches joined to their tracks at the start and at the end of the main track, else the line under them moved + // and it's taken back + for (auto *track : std::vector{m_node != nullptr ? dynamic_cast(m_node) : nullptr}) + if (auto const crossover{track != nullptr ? crossover_of(*track) : std::nullopt}) + for (auto *part : {crossover->first, crossover->second}) + for (auto const which : {segment_data::point::start, segment_data::point::end}) + { + auto const joined{editor_track::connected_points(*part, part->m_paths.front().points[which])}; + if (std::none_of(joined.begin(), joined.end(), [&](auto const &Entry) { return Entry.first != part && Entry.first != nullptr && false == Entry.first->m_editorremoved; })) + { + undo_last(); + tool.status = STR_C("The crossover wouldn't join the tracks there"); + return false; + } + } + return true; +} diff --git a/application/editormodedigitize.cpp b/application/editormodedigitize.cpp new file mode 100644 index 000000000..75e76f817 --- /dev/null +++ b/application/editormodedigitize.cpp @@ -0,0 +1,424 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.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 digitization of a scenery made without the editor: its lines kept with their designs, its switches with their types out of +// the catalogue, its crossovers as connections and the objects along the tracks bound to them, at one go + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editormodeshared.h" +#include "application/editoruilayer.h" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorConnections.hpp" +#include "editor/editorFormat.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorSwitchStore.hpp" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" +#include "world/Track.h" +#include +#include +#include +#include + +namespace +{ + +using geometry::bezier; +using geometry::plan_of; +using geometry::signed_angle; + +// how far the size of a switch may be from the template to be of it: the length of the main and the diverging track, the angle +double constexpr kMainTolerance{0.10}; +double constexpr kBranchTolerance{0.15}; +double constexpr kAngleTolerance{0.0025}; +// a plain track this short between the ends of two switches is a part of a slip +double constexpr kSlipLink{6.0}; +// the longest insert of a crossover +double constexpr kInsertLongest{150.0}; +// the tracks a crossover joins lie this far apart +double constexpr kSpacingLeast{2.5}; +double constexpr kSpacingMost{15.0}; +// radii of the diverging track the switches are made with; a measured one this close to one of them is taken for it +double constexpr kNominalRadii[]{150.0, 190.0, 205.0, 230.0, 265.0, 300.0, 500.0, 760.0, 1200.0}; +double constexpr kNominalNear{0.04}; + +double nominal_radius(double const Radius) +{ + for (auto const nominal : kNominalRadii) + if (std::abs(Radius - nominal) <= kNominalNear * nominal) + return nominal; + return std::round(Radius); +} + +std::vector parts_of(segment_data const &Path) +{ + std::vector parts; + if (Path.pieces.empty()) + parts.push_back(&Path); + else + for (auto const &piece : Path.pieces) + parts.push_back(&piece); + return parts; +} + +double path_length(segment_data const &Path) +{ + double length{0.0}; + for (auto const *part : parts_of(Path)) + length += bezier{*part}.plan_length(); + return length; +} + +glm::dvec2 heading(segment_data const &Path, bool const End) +{ + auto const parts{parts_of(Path)}; + bezier const curve{End ? *parts.back() : *parts.front()}; + auto const direction{plan_of(curve.first(End ? 1.0 : 0.0))}; + if (glm::length(direction) > 1e-9) + return glm::normalize(direction); + auto const chord{plan_of(Path.points[segment_data::point::end] - Path.points[segment_data::point::start])}; + return glm::length(chord) > 1e-9 ? glm::normalize(chord) : glm::dvec2{0.0, 1.0}; +} + +// in the plan, + to the left, at the middle of the longest part of the path +double curvature(segment_data const &Path) +{ + segment_data const *longest{nullptr}; + double length{-1.0}; + for (auto const *part : parts_of(Path)) + if (auto const l{bezier{*part}.plan_length()}; l > length) + { + length = l; + longest = part; + } + if (longest == nullptr || false == geometry::has_controls(*longest)) + return 0.0; + bezier const curve{*longest}; + auto const first{plan_of(curve.first(0.5))}; + auto const second{plan_of(curve.second(0.5))}; + auto const speed{glm::length(first)}; + return speed > 1e-9 ? (first.x * second.y - first.y * second.x) / (speed * speed * speed) : 0.0; +} + +struct switch_size +{ + double main{0.0}; + double branch{0.0}; + double angle{0.0}; // between the ends of the two tracks + double radius{0.0}; // of the diverging track of the straight switch the switch is made of +}; + +switch_size size_of(segment_data const &Main, segment_data const &Branch) +{ + switch_size size; + size.main = path_length(Main); + size.branch = path_length(Branch); + size.angle = std::abs(signed_angle(heading(Main, true), heading(Branch, true))); + auto const bend{std::abs(curvature(Branch) - curvature(Main))}; + size.radius = bend > 1e-6 ? 1.0 / bend : 0.0; + return size; +} + +// the template of the catalogue the size is of: the rail of the track and a movable nose decide between the same shapes +int matching(std::vector const &Templates, std::vector> const &Sizes, switch_size const &Size, std::string const &Rail, bool const Movable) +{ + int best{-1}; + auto score{std::numeric_limits::max()}; + for (auto const &[index, size] : Sizes) + { + auto const &shape{Templates[index]}; + auto const main{std::abs(size.main - Size.main)}; + auto const branch{std::abs(size.branch - Size.branch)}; + auto const angle{std::abs(size.angle - Size.angle)}; + if (main > kMainTolerance || branch > kBranchTolerance || angle > kAngleTolerance) + continue; + auto value{main / kMainTolerance + branch / kBranchTolerance + angle / kAngleTolerance}; + if (false == Rail.empty() && shape.rail != Rail) + value += 10.0; + if (shape.movable != Movable) + value += 5.0; + if (value < score) + { + score = value; + best = index; + } + } + return best; +} + +bool usable_switch(TTrack const *Track) +{ + return Track != nullptr && false == Track->m_editorremoved && Track->eType == tt_Switch && Track->m_paths.size() == 2; +} + +bool named(TTrack const &Track) +{ + return false == Track.name().empty() && Track.name() != "none"; +} + +glm::dvec3 far_end(segment_data const &Path, editor_track::point_kind const Kind) +{ + return Path.points[Kind == editor_track::point_kind::start ? segment_data::point::end : segment_data::point::start]; +} + +// the end of the path meets an end of another switch, right there or over a short plain track: the paths of a slip do +bool towards_switch(TTrack const &Track, glm::dvec3 const &Point) +{ + for (auto const &[other, point] : editor_track::connected_points(Track, Point)) + { + if (other == nullptr || other == &Track || other->m_editorremoved) + continue; + if (other->eType == tt_Switch && point.kind == editor_track::point_kind::end) + return true; + if (other->eType != tt_Normal || other->m_paths.size() != 1 || path_length(other->m_paths.front()) > kSlipLink) + continue; + for (auto const &[next, nextpoint] : editor_track::connected_points(*other, far_end(other->m_paths.front(), point.kind))) + if (next != nullptr && next != other && next != &Track && next->eType == tt_Switch && nextpoint.kind == editor_track::point_kind::end) + return true; + } + return false; +} + +bool slip_part(TTrack const &Switch) +{ + return towards_switch(Switch, Switch.m_paths[0].points[segment_data::point::end]) && towards_switch(Switch, Switch.m_paths[1].points[segment_data::point::end]); +} + +} // namespace + +void editor_mode::digitize_switches(digitize_report &Report, bool const Write) +{ + auto const templates{editor_track::standard_switch_templates()}; + std::vector> sizes; + for (int i = 0; i < static_cast(templates.size()); ++i) + { + auto const &shape{templates[i]}; + if (shape.source == nullptr && false == shape.double_slip && false == shape.twofold()) + sizes.emplace_back(i, size_of(shape.local[0], shape.local[1])); + } + for (auto *track : simulation::Paths.sequence()) + { + if (false == usable_switch(track)) + continue; + ++Report.switches; + if (switch_store::named(*track).has_value()) + { + ++Report.known; + continue; + } + if (slip_part(*track)) + { + ++Report.slips; + continue; + } + auto const &main{track->m_paths[0]}; + auto const &branch{track->m_paths[1]}; + if (geometry::plan_distance(main.points[segment_data::point::start], branch.points[segment_data::point::start]) > geometry::same_point) + { + ++Report.odd; + Report.notes.push_back(track->name() + ": " + STR("the tracks of the switch don't start at the same point")); + continue; + } + auto const size{size_of(main, branch)}; + auto const movable{track->SwitchExtension != nullptr && track->SwitchExtension->m_movablenose}; + auto const found{matching(templates, sizes, size, editor_track::rail_of(track), movable)}; + editor_track::switch_template shape; + if (found >= 0) + { + shape = templates[found]; + ++Report.designed; + ++Report.types[shape.label.substr(0, shape.label.find(" "))]; + } + else + { + shape.source = track; + shape.radius = nominal_radius(size.radius); + shape.ratio = size.angle > 1e-6 ? 1.0 / std::tan(size.angle) : 0.0; + ++Report.measured; + ++Report.shapes[format("L %.2f / %.2f 1:%.2f R %.0f", size.main, size.branch, shape.ratio, shape.radius)]; + } + if (false == named(*track)) + { + // the record finds the switch by its name; the names of the scenery stay as they are + ++Report.unnamed; + continue; + } + if (Write && found >= 0) + record_switch(*track, shape); + else if (Write) + { + switch_store::record entry; + entry.kind = "switch"; + entry.name = track->name(); + entry.parts = {entry.name}; + entry.radius = shape.radius; + entry.ratio = shape.ratio; + entry.source = "measured"; + auto const rail{editor_track::rail_of(track)}; + entry.rail = rail.empty() ? std::string{"-"} : rail; + switch_store::place(entry, *track); + switch_store::classify(entry, *track); + switch_store::put(entry, alignment_store::layer_of(*track)); + } + ++Report.recorded; + } +} + +void editor_mode::digitize_crossovers(digitize_report &Report, bool const Write) +{ + std::set> seen; + for (auto *first : simulation::Paths.sequence()) + { + if (false == usable_switch(first) || slip_part(*first)) + continue; + auto const &branch{first->m_paths[1]}; + auto const end{branch.points[segment_data::point::end]}; + // the insert: plain tracks from the end of the diverging track up to the end of the diverging track of another switch + std::vector insert; + TTrack *second{nullptr}; + auto *from{static_cast(first)}; + auto point{end}; + double length{0.0}; + bool direct{false}; + while (second == nullptr && length <= kInsertLongest) + { + TTrack *next{nullptr}; + editor_track::point_ref at; + for (auto const &[other, ref] : editor_track::connected_points(*from, point)) + { + if (other == nullptr || other == from || other->m_editorremoved || std::find(insert.begin(), insert.end(), other) != insert.end()) + continue; + if (usable_switch(other) && other != first && ref.path == 1 && ref.kind == editor_track::point_kind::end) + { + second = other; + direct = insert.empty(); + break; + } + if (other->eType == tt_Normal && other->m_paths.size() == 1) + { + next = other; + at = ref; + } + } + if (second != nullptr || next == nullptr) + break; + insert.push_back(next); + length += path_length(next->m_paths.front()); + point = far_end(next->m_paths.front(), at.kind); + from = next; + } + if (second == nullptr || slip_part(*second)) + continue; + if (seen.count({second, first}) > 0) + continue; + seen.insert({first, second}); + // the two switches face each other from two tracks side by side + auto const along{heading(first->m_paths[0], false)}; + auto const back{heading(second->m_paths[0], false)}; + if (glm::dot(along, back) > -0.9) + continue; + auto const spacing{std::abs(geometry::cross(along, plan_of(second->m_paths[0].points[segment_data::point::start] - first->m_paths[0].points[segment_data::point::start])))}; + if (spacing < kSpacingLeast || spacing > kSpacingMost) + continue; + ++Report.crossovers; + auto const name = [](TTrack const *Track) { return name_of(*Track); }; + auto const note = [&](std::string const &Why) { Report.notes.push_back(name(first) + " + " + name(second) + ": " + Why); }; + if (false == switch_store::connections(*first).empty()) + { + ++Report.crossovers_known; + continue; + } + if (direct || insert.size() != 1) + { + ++Report.crossovers_odd; + note(direct ? STR("the diverging tracks meet without an insert between them") : format(STR_C("the insert is made of %zu paths"), insert.size())); + continue; + } + auto const one{switch_store::named(*first)}; + auto const other{switch_store::named(*second)}; + if (Write && (false == one.has_value() || false == other.has_value())) + { + ++Report.crossovers_odd; + note(STR("a switch of it has no type kept")); + continue; + } + if (one.has_value() && other.has_value() && (std::abs(one->radius - other->radius) > kNominalNear * one->radius || std::abs(one->ratio - other->ratio) > kNominalNear * one->ratio)) + { + ++Report.crossovers_odd; + note(format(STR_C("the switches differ: %s and %s"), switch_store::label(*one).c_str(), switch_store::label(*other).c_str())); + continue; + } + if (Write) + { + auto entry{*one}; + entry.kind = "connection"; + entry.name = first->name(); + entry.parts = {first->name(), second->name()}; + entry.number = "-"; + switch_store::place(entry, *first); + switch_store::classify(entry, *first); + entry.type = connection::word(connection::kind::crossover); + entry.a = spacing; + entry.b = length; + switch_store::put(entry, alignment_store::layer_of(*first)); + WriteLog(format("Editor: digitizing - crossover %s + %s kept, %s, spacing %.2f m, insert %.2f m", first->name().c_str(), second->name().c_str(), switch_store::label(entry).c_str(), spacing, length), logtype::generic); + } + ++Report.crossovers_recorded; + } +} + +std::string editor_mode::digitize_scenery(bool const Write) +{ + digitize_report report; + if (Write) + digitize_all(&report.lines, &report.lines_failed); + digitize_switches(report, Write); + digitize_crossovers(report, Write); + if (Write) + { + switch_store::settle(); + auto const scope{m_infra.scope}; + m_infra.scope = 3; + infra_recognize(); + report.found = static_cast(m_infra.candidates.size()); + auto const before{infra_bound_count()}; + infra_bind_chosen(); + report.bound = infra_bound_count() - before; + m_infra.scope = scope; + } + auto text{format(STR_C("Switches: %d, kept already %d, of the catalogue %d, measured %d, parts of slips %d, odd %d"), report.switches, report.known, report.designed, report.measured, report.slips, report.odd)}; + if (report.unnamed > 0) + text += format(STR_C(", without a name, left out %d"), report.unnamed); + text += "\n" + format(STR_C("Crossovers: %d, kept already %d, recorded %d, left out %d"), report.crossovers, report.crossovers_known, report.crossovers_recorded, report.crossovers_odd); + if (Write) + { + text = format(STR_C("Lines digitized: %d, paths left out: %d"), report.lines, report.lines_failed) + "\n" + text; + text += "\n" + format(STR_C("Objects by the tracks: %d found, %d bound"), report.found, report.bound); + } + WriteLog("Editor: digitizing the scenery\n" + text, logtype::generic); + std::vector> types; + for (auto const &[label, count] : report.types) + types.emplace_back(count, label); + std::sort(types.rbegin(), types.rend()); + for (auto const &[count, label] : types) + WriteLog(format("Editor: digitizing - %4d x %s", count, label.c_str()), logtype::generic); + std::vector> shapes; + for (auto const &[label, count] : report.shapes) + shapes.emplace_back(count, label); + std::sort(shapes.rbegin(), shapes.rend()); + for (std::size_t i = 0; i < std::min(shapes.size(), 20); ++i) + WriteLog(format("Editor: digitizing - measured %4d x %s", shapes[i].first, shapes[i].second.c_str()), logtype::generic); + for (std::size_t i = 0; i < std::min(report.notes.size(), 30); ++i) + WriteLog("Editor: digitizing - " + report.notes[i], logtype::generic); + if (Write) + ui()->set_status(text, report.odd + report.crossovers_odd + report.lines_failed > 0); + return text; +} diff --git a/application/editormodegauge.cpp b/application/editormodegauge.cpp new file mode 100644 index 000000000..7e11b9615 --- /dev/null +++ b/application/editormodegauge.cpp @@ -0,0 +1,942 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormodegauge.h" +#include "editor/editorTrack.hpp" +#include "application/editoruilayer.h" +#include "editor/editorFormat.hpp" +#include "editor/editorGauge.hpp" +#include "editor/editorGeometry.hpp" +#include "model/AnimModel.h" +#include "model/Model3d.h" +#include "rendering/editoroverlay.h" +#include "rendering/renderer.h" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "world/Sweep.h" +#include "world/Track.h" +#include "imgui/imgui.h" +#include "utilities/translation.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using geometry::plan_of; + +namespace +{ + +char const *const gauge_file{"editor_structure_gauges.txt"}; +// past this distance of the camera from the origin of the overlay it's rebuilt, to keep its float precision +double const gauge_origin_range{2000.0}; +// length of the line shown each way from the selected path, and around a hit +double const gauge_reach{500.0}; +double const gauge_spot_reach{60.0}; +// time spent on the scan of the whole map in a frame +auto const gauge_slice{std::chrono::milliseconds(8)}; +// distance of the camera from the place of a hit, along the track +double const gauge_view_distance{4.0}; + +// sampled line of the tracks with the widening of the gauge along it +struct gauge_line +{ + gauge::profile const *profile{nullptr}; + editor_track::route route; + std::vector samples; + std::vector sections; +}; + +// half of the carriageway of a road at the sample, it narrows linearly to the width at the end +double carriageway(editor_track::route_span const &Span, double const Chainage) +{ + auto const &track{*Span.track}; + auto const end{track.fTrackWidth2 > 0.f ? track.fTrackWidth2 : track.fTrackWidth}; + auto t{Span.to > Span.from ? std::clamp((Chainage - Span.from) / (Span.to - Span.from), 0.0, 1.0) : 0.0}; + if (false == Span.forward) + t = 1.0 - t; + return 0.5 * std::abs(track.fTrackWidth + (end - track.fTrackWidth) * t); +} + +gauge_line make_line(editor_track::route &Route, gauge::profile const &Profile) +{ + gauge_line line; + line.profile = &Profile; + line.samples = editor_track::sample_route(Route, 1.0); + line.route = Route; + bool const road{Profile.kind == gauge::kind::road}; + std::vector chainage, curvature, cant; + for (auto &sample : line.samples) + { + if (false == road) + sample.position.y += gauge::rail_height; + chainage.push_back(sample.chainage); + curvature.push_back(sample.curvature); + cant.push_back(sample.cant); + } + line.sections = gauge::sections(Profile.kind, chainage, curvature, cant); + if (road) + for (std::size_t i = 0; i < line.samples.size(); ++i) + line.sections[i].base = carriageway(line.route.spans[line.samples[i].span], line.samples[i].chainage); + return line; +} + +// outline checked along the path, none on the pavements, which are the roads with the pavement texture +gauge::profile const *outline_of(gauge::choice const &Choice, TTrack const &Track) +{ + auto const *profile{Choice.of(Track.iCategoryFlag)}; + if (profile == nullptr || profile->outline.size() < 2) + return nullptr; + if (profile == Choice.road) + { + auto name{editor_track::material_name(Track.m_material1)}; + std::transform(name.begin(), name.end(), name.begin(), [](unsigned char const C) { return static_cast(std::tolower(C)); }); + if (name.find("chodnik") != std::string::npos) + return nullptr; + } + return profile; +} + +// the line along the route from the path with the outline of its kind, none without the outline or the length +std::optional track_line(gauge::choice const &Choice, TTrack const &Track, editor_track::route &Route) +{ + auto const *profile{outline_of(Choice, Track)}; + if (profile == nullptr) + return std::nullopt; + auto line{make_line(Route, *profile)}; + if (line.samples.size() < 2) + return std::nullopt; + return line; +} + +// lines through all paths of the scenery, each path in one of them at least +std::vector scenery_lines(gauge::choice const &Choice) +{ + std::vector lines; + std::unordered_set visited; + auto const seen{[&](editor_track::route_span const &Span) { return visited.count(Span.track) > 0; }}; + auto const checked{[&](TTrack const *Track) { return Track != nullptr && editor_track::is_supported(*Track) && outline_of(Choice, *Track) != nullptr; }}; + for (auto *track : simulation::Paths.sequence()) + { + if (false == checked(track) || visited.count(track) > 0) + continue; + auto route{editor_track::run_route(*track, 1e7)}; + // the line may run on over the paths already covered, one of them is enough for the widening ahead of a curve + auto &spans{route.spans}; + while (spans.size() > 2 && seen(spans[0]) && seen(spans[1])) + spans.erase(spans.begin()); + while (spans.size() > 2 && seen(spans[spans.size() - 1]) && seen(spans[spans.size() - 2])) + spans.pop_back(); + for (auto const &span : spans) + visited.insert(span.track); + lines.push_back(make_line(route, *outline_of(Choice, *track))); + } + // diverging paths of the switches + for (auto *track : simulation::Paths.sequence()) + if (checked(track) && track->eType == tt_Switch) + { + editor_track::route route; + route.spans.push_back({track, 1, true}); + lines.push_back(make_line(route, *outline_of(Choice, *track))); + } + return lines; +} + +// samples of the lines, found by the position in the plan +class corridor +{ +public: + explicit corridor(std::vector const &Lines) : m_lines{Lines} + { + for (std::uint32_t line = 0; line < Lines.size(); ++line) + for (std::uint32_t i = 0; i < Lines[line].samples.size(); ++i) + { + // with the room for the widening in the sharpest curves on the largest cant + m_margin = std::max(m_margin, gauge::widest(*Lines[line].profile) + Lines[line].sections[i].base + 1.2); + auto const point{plan_of(Lines[line].samples[i].position)}; + m_cells[key(point, cell)].push_back({line, i}); + m_regions.insert(key(point, region)); + } + } + + static glm::dvec2 normal(editor_track::route_sample const &Sample) + { + return {-Sample.direction.y, Sample.direction.x}; + } + + // whether the sphere may reach the gauge of a line sampled in the cells around it + bool close(glm::dvec3 const &Center, double const Radius) const + { + auto const center{plan_of(Center)}; + auto const reach{Radius + m_margin}; + auto const from{index(center - reach, cell)}; + auto const to{index(center + reach, cell)}; + for (auto x = from.x; x <= to.x; ++x) + for (auto y = from.y; y <= to.y; ++y) + if (m_cells.count(key(x, y)) > 0) + return true; + return false; + } + + // whether the sphere may reach the gauge, roughly + bool nearby(glm::dvec3 const &Center, double const Radius) const + { + auto const center{plan_of(Center)}; + auto const reach{Radius + m_margin + region}; + auto const from{index(center - reach, region)}; + auto const to{index(center + reach, region)}; + for (auto x = from.x; x <= to.x; ++x) + for (auto y = from.y; y <= to.y; ++y) + if (m_regions.count(key(x, y)) > 0) + return true; + return false; + } + + struct hit + { + double depth{0.0}; // not positive outside of the gauge + editor_track::route_span const *span{nullptr}; // of the line the point enters + glm::dvec2 direction{0.0}; // of the line there, in the plan + }; + // deepest intrusion of the point into the gauge of the lines nearby + hit intrusion(glm::dvec3 const &Point) const + { + auto const point{plan_of(Point)}; + auto const center{index(point, cell)}; + // nearest sample of every line around + std::vector> nearest; + for (auto x = center.x - 1; x <= center.x + 1; ++x) + for (auto y = center.y - 1; y <= center.y + 1; ++y) + { + auto const found{m_cells.find(key(x, y))}; + if (found == m_cells.end()) + continue; + for (auto const &candidate : found->second) + { + auto const distance{glm::length2(plan_of(sample(candidate).position) - point)}; + if (distance > m_margin * m_margin) + continue; + auto const same{std::find_if(nearest.begin(), nearest.end(), [&](auto const &Other) { return Other.first.line == candidate.line; })}; + if (same == nearest.end()) + nearest.push_back({candidate, distance}); + else if (distance < same->second) + *same = {candidate, distance}; + } + } + hit deepest; + for (auto const &[found, distance] : nearest) + { + auto const &line{m_lines[found.line]}; + auto const &sample{line.samples[found.index]}; + auto const offset{point - plan_of(sample.position)}; + auto const along{glm::dot(offset, sample.direction)}; + if ((found.index == 0 && along < -0.6) || (found.index + 1 == line.samples.size() && along > 0.6)) + continue; + gauge::ring(*line.profile, line.sections[found.index], m_ring); + auto const depth{gauge::intrusion(m_ring, {glm::dot(offset, normal(sample)), Point.y - (sample.position.y + sample.grade * along)})}; + if (depth > deepest.depth) + deepest = {depth, &line.route.spans[sample.span], sample.direction}; + } + return deepest; + } + +private: + static constexpr double cell{8.0}; + static constexpr double region{64.0}; + + struct entry + { + std::uint32_t line; + std::uint32_t index; + }; + + static glm::i64vec2 index(glm::dvec2 const &Point, double const Size) + { + return {static_cast(std::floor(Point.x / Size)), static_cast(std::floor(Point.y / Size))}; + } + static std::uint64_t key(std::int64_t const X, std::int64_t const Y) + { + return (static_cast(X) << 32) ^ static_cast(Y); + } + static std::uint64_t key(glm::dvec2 const &Point, double const Size) + { + auto const cell{index(Point, Size)}; + return key(cell.x, cell.y); + } + editor_track::route_sample const &sample(entry const &Entry) const + { + return m_lines[Entry.line].samples[Entry.index]; + } + + std::vector const &m_lines; + double m_margin{0.0}; + mutable std::vector m_ring; // reused by the checks + std::unordered_map> m_cells; + std::unordered_set m_regions; +}; + +glm::dmat4 placement(TAnimModel const &Instance) +{ + auto const angles{Instance.Angles()}; + auto matrix{glm::translate(glm::dmat4(1.0), Instance.location())}; + matrix = glm::rotate(matrix, glm::radians(static_cast(angles.y)), glm::dvec3(0.0, 1.0, 0.0)); + matrix = glm::rotate(matrix, glm::radians(static_cast(angles.x)), glm::dvec3(1.0, 0.0, 0.0)); + matrix = glm::rotate(matrix, glm::radians(static_cast(angles.z)), glm::dvec3(0.0, 0.0, 1.0)); + return glm::scale(matrix, glm::dvec3(Instance.Scale())); +} + +// calls the visitor with the world corners of the visible triangles of the submodel, its siblings and children +template void visit_triangles(TSubModel *Submodel, glm::dmat4 const &Matrix, Visitor const &Visit) +{ + for (auto *submodel = Submodel; submodel != nullptr; submodel = submodel->NextGet()) + { + if (submodel->iVisible == 0) + continue; + auto matrix{Matrix}; + if ((submodel->iFlags & 0xC000) && submodel->GetMatrix() != nullptr) + matrix *= glm::dmat4(glm::make_mat4(submodel->GetMatrix()->readArray())); + if (submodel->eType == GL_TRIANGLES && submodel->m_geometry.handle != null_handle) + { + auto const &vertices{GfxRenderer->Vertices(submodel->m_geometry.handle)}; + auto const &indices{GfxRenderer->Indices(submodel->m_geometry.handle)}; + auto const corner{[&](std::size_t const Index) { return glm::dvec3(matrix * glm::dvec4(glm::dvec3(vertices[Index].position), 1.0)); }}; + auto const count{indices.empty() ? vertices.size() : indices.size()}; + for (std::size_t i = 0; i + 2 < count; i += 3) + { + if (indices.empty()) + Visit(corner(i), corner(i + 1), corner(i + 2)); + else + Visit(corner(indices[i]), corner(indices[i + 1]), corner(indices[i + 2])); + } + } + visit_triangles(submodel->ChildGet(), matrix, Visit); + } +} + +// the triangle enters the gauge when any point of a grid spread over it does; the deepest such point goes to the hit +void scan_triangle(corridor const &Space, glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C, gauge_tool::gauge_hit &Hit) +{ + auto const middle{(A + B + C) / 3.0}; + if (false == Space.close(middle, std::max({glm::distance(middle, A), glm::distance(middle, B), glm::distance(middle, C)}))) + return; + auto const edge{std::max({glm::distance(A, B), glm::distance(B, C), glm::distance(C, A)})}; + auto const steps{std::clamp(static_cast(std::ceil(edge / 0.5)), 1, 24)}; + for (int u = 0; u <= steps; ++u) + for (int v = 0; u + v <= steps; ++v) + { + auto const point{A + (B - A) * (static_cast(u) / steps) + (C - A) * (static_cast(v) / steps)}; + auto const found{Space.intrusion(point)}; + if (found.depth <= 0.0) + continue; + if (found.depth > Hit.depth) + { + Hit.depth = found.depth; + Hit.point = point; + Hit.track = found.span->track; // NOSONAR + Hit.path = found.span->path; + Hit.direction = found.direction; + } + return; + } +} + +// the deepest place of the model in the gauge, added to the hits when it enters it +void scan_model(corridor const &Space, TAnimModel &Instance, std::vector &Hits) +{ + if (false == Instance.visible() || Instance.Model() == nullptr || Instance.Model()->GetSMRoot() == nullptr) + return; + if (false == Space.nearby(Instance.location(), Instance.radius())) + return; + gauge_tool::gauge_hit hit{Instance.name(), Instance.location()}; + visit_triangles(Instance.Model()->GetSMRoot(), placement(Instance), [&](glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C) { scan_triangle(Space, A, B, C, hit); }); + if (hit.depth > 0.0) + Hits.push_back(std::move(hit)); +} + +// the same for the copies of a model laid along a curve +void scan_sweep(corridor const &Space, sweep_node &Sweep, std::vector &Hits) +{ + if (Sweep.m_editorremoved || false == Space.nearby(Sweep.location(), Sweep.radius())) + return; + gauge_tool::gauge_hit hit{Sweep.name(), Sweep.location()}; + for (auto const &shape : Sweep.create_shapes()) + { + auto const &vertices{shape.data().vertices}; + for (std::size_t i = 0; i + 2 < vertices.size(); i += 3) + scan_triangle(Space, vertices[i].position, vertices[i + 1].position, vertices[i + 2].position, hit); + } + if (hit.depth > 0.0) + Hits.push_back(std::move(hit)); +} + +void sort_hits(std::vector &Hits) +{ + std::sort(Hits.begin(), Hits.end(), [](auto const &Left, auto const &Right) { return Left.depth > Right.depth; }); +} + +// the models entering the gauge, the deepest first +void scan_models(corridor const &Space, std::vector &Hits) +{ + for (auto *instance : simulation::Instances.sequence()) + if (instance != nullptr) + scan_model(Space, *instance, Hits); + for (auto *sweep : simulation::Sweeps.sequence()) + if (sweep != nullptr) + scan_sweep(Space, *sweep, Hits); + sort_hits(Hits); +} + +// translucent tunnel of the gauge along the line, with the rings every 10 m and the lines along its corners +void build_tunnel(gauge_line const &Line, std::vector &Surface, std::vector &Edges) +{ + std::vector places; + auto const ring{[&](std::size_t const Index) { + gauge::ring(*Line.profile, Line.sections[Index], places); + auto const &sample{Line.samples[Index]}; + auto const normal{corridor::normal(sample)}; + std::vector points; + for (auto const &place : places) + points.push_back(sample.position + glm::dvec3(normal.x * place.lateral, place.height, normal.y * place.lateral)); + return points; + }}; + std::vector previous; + double lastring{-1e9}; + for (std::size_t i = 0; i < Line.samples.size(); i += 2) + { + auto const current{ring(i)}; + if (false == previous.empty()) + for (std::size_t j = 1; j < current.size(); ++j) + { + Surface.insert(Surface.end(), {previous[j - 1], previous[j], current[j], previous[j - 1], current[j], current[j - 1]}); + Edges.insert(Edges.end(), {previous[j], current[j]}); + } + if (Line.samples[i].chainage - lastring >= 10.0 || i + 2 >= Line.samples.size()) + { + lastring = Line.samples[i].chainage; + for (std::size_t j = 1; j < current.size(); ++j) + Edges.insert(Edges.end(), {current[j - 1], current[j]}); + } + previous = current; + } +} + +// table of the points of the outline with the inserting and removing of the points, whether it changed +bool edit_points(std::vector &Points) +{ + bool edited{false}; + bool inserted{false}; + int remove{-1}; + ImGui::Columns(3, "gaugeoutline", false); + ImGui::SetColumnWidth(0, 110.0f); + ImGui::SetColumnWidth(1, 110.0f); + ImGui::TextDisabled(STR_C("Half-width")); + ImGui::NextColumn(); + ImGui::TextDisabled(STR_C("Height")); + ImGui::NextColumn(); + ImGui::NextColumn(); + for (int i = 0; i < static_cast(Points.size()); ++i) + { + ImGui::PushID(i); + auto &point{Points[i]}; + ImGui::SetNextItemWidth(-1.0f); + ImGui::InputDouble("##width", &point.half_width, 0.0, 0.0, "%.3f"); + edited |= ImGui::IsItemDeactivatedAfterEdit(); + ImGui::NextColumn(); + ImGui::SetNextItemWidth(-1.0f); + ImGui::InputDouble("##height", &point.height, 0.0, 0.0, "%.3f"); + edited |= ImGui::IsItemDeactivatedAfterEdit(); + ImGui::NextColumn(); + if (ImGui::SmallButton("+")) + { + auto const &next{Points[std::min(i + 1, Points.size() - 1)]}; + Points.insert(Points.begin() + i + 1, {0.5 * (point.half_width + next.half_width), 0.5 * (point.height + next.height)}); + inserted = edited = true; + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Insert a point after this one")); + ImGui::SameLine(); + if (Points.size() > 2 && ImGui::SmallButton("x")) + remove = i; + ImGui::NextColumn(); + ImGui::PopID(); + if (inserted) + break; + } + ImGui::Columns(1); + if (remove >= 0) + { + Points.erase(Points.begin() + remove); + edited = true; + } + return edited; +} + +// the railway outline drawn across the track at the size of the panel, so the name in the list has a shape +void gauge_sketch(gauge::profile const &Profile) +{ + auto const width{ImGui::GetContentRegionAvail().x}; + auto const height{std::round(ImGui::GetFontSize() * 9.0f)}; + auto const low{ImGui::GetCursorScreenPos()}; + ImGui::Dummy(ImVec2(width, height)); + if (Profile.outline.size() < 2) + return; + double top{0.0}; + double half{0.0}; + for (auto const &point : Profile.outline) + { + top = std::max(top, point.height); + half = std::max(half, point.half_width); + } + if (top <= 0.0 || half <= 0.0) + return; + auto const pad{ImGui::GetFontSize() * 1.2f}; + auto const scale{static_cast(std::min((height - pad * 2.0f) / top, (width - pad * 2.0f) / (half * 2.0)))}; + ImVec2 const base{std::round(low.x + width * 0.5f), std::round(low.y + height - pad)}; + auto const at = [&](double const X, double const Y) { return ImVec2(base.x + static_cast(X) * scale, base.y - static_cast(Y) * scale); }; + auto *draw{ImGui::GetWindowDrawList()}; + draw->AddRectFilled(low, ImVec2(low.x + width, low.y + height), ImGui::GetColorU32(ImGuiCol_FrameBg), 4.0f); + // ballast, a sleeper and the two rails + ImVec2 const ballast[]{at(-2.1, -0.6), at(2.1, -0.6), at(1.55, -0.2), at(-1.55, -0.2)}; + draw->AddConvexPolyFilled(ballast, 4, IM_COL32(110, 100, 90, 255)); + draw->AddRectFilled(at(-1.3, -0.2), at(1.3, -0.13), IM_COL32(150, 150, 150, 255)); + for (double const side : {-0.7175, 0.7175}) + draw->AddRectFilled(at(side - 0.04, -0.13), at(side + 0.04, 0.0), IM_COL32(210, 210, 215, 255)); + // the outline, the right half from the bottom up and its mirror back down + std::vector points; + for (auto const &point : Profile.outline) + points.push_back(at(point.half_width, point.height)); + for (auto point{Profile.outline.rbegin()}; point != Profile.outline.rend(); ++point) + points.push_back(at(-point->half_width, point->height)); + auto const accent{IM_COL32(120, 200, 255, 255)}; + auto const flags{draw->Flags}; + draw->Flags &= ~ImDrawListFlags_AntiAliasedFill; + draw->AddConcavePolyFilled(points.data(), static_cast(points.size()), IM_COL32(120, 200, 255, 40)); + draw->Flags = flags; + draw->AddPolyline(points.data(), static_cast(points.size()), accent, ImDrawFlags_Closed, 2.0f); + // the height over the top and the widest half at its height + auto const widest{std::max_element(Profile.outline.begin(), Profile.outline.end(), [](auto const &A, auto const &B) { return A.half_width < B.half_width; })}; + auto const tall{format("%.2f m", top)}; + auto const size{ImGui::CalcTextSize(tall.c_str())}; + draw->AddText(ImVec2(std::round(base.x - size.x * 0.5f), std::round(at(0.0, top).y - size.y - 2.0f)), accent, tall.c_str()); + auto const wide{format("%.2f m", widest->half_width * 2.0)}; + auto const y{at(0.0, widest->height).y}; + draw->AddLine(ImVec2(at(-widest->half_width, 0.0).x, y), ImVec2(at(widest->half_width, 0.0).x, y), IM_COL32(255, 220, 120, 160), 1.0f); + auto const wsize{ImGui::CalcTextSize(wide.c_str())}; + draw->AddText(ImVec2(std::round(base.x - wsize.x * 0.5f), std::round(y - wsize.y - 1.0f)), IM_COL32(255, 220, 120, 255), wide.c_str()); +} + +} // namespace + +struct gauge_scan +{ + std::optional railway; + std::optional road; + std::vector lines; + std::optional space; // of the lines + std::size_t next{0}; // instance to check + float progress{0.f}; + std::chrono::steady_clock::time_point started; +}; + +void gauge_tool::gauge_load() +{ + if (m_gauge.profiles.empty()) + m_gauge.profiles = gauge::load_profiles(gauge_file); + // the chosen railway and road outlines, the first ones of the kind when there's none + auto const fits{[&](int const Index, bool const Road) { + return Index >= 0 && Index < static_cast(m_gauge.profiles.size()) && (m_gauge.profiles[Index].kind == gauge::kind::road) == Road; + }}; + for (auto [index, road] : {std::pair{&m_gauge.profile, false}, std::pair{&m_gauge.road, true}}) + if (false == fits(*index, road)) + { + *index = -1; + for (int i = 0; i < static_cast(m_gauge.profiles.size()) && *index < 0; ++i) + if (fits(i, road)) + *index = i; + } +} + +gauge::choice gauge_tool::gauge_choice() const +{ + auto const pick{[&](int const Index) { return Index >= 0 ? &m_gauge.profiles[Index] : nullptr; }}; + return {pick(m_gauge.profile), pick(m_gauge.road)}; +} + +std::vector const &gauge_tool::gauge_hits() const +{ + return m_gauge.map.scanned ? m_gauge.map.hits : m_gauge.line.hits; +} + +gauge_tool::gauge_hit gauge_tool::gauge_models(std::vector const &Models) +{ + gauge_load(); + auto const choice{gauge_choice()}; + gauge_hit deepest; + // a line along each path which may reach the models + std::vector lines; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved) + continue; + auto const close{std::any_of(Models.begin(), Models.end(), [&](TAnimModel const *Model) { + return Model != nullptr && geometry::plan_distance(Model->location(), track->location()) <= static_cast(Model->radius() + track->radius()) + 6.0; + })}; + if (false == close || false == editor_track::is_supported(*track) || outline_of(choice, *track) == nullptr) + continue; + for (int path = 0; path < static_cast(track->m_paths.size()); ++path) + { + editor_track::route route; + route.spans.push_back({track, path, true}); + if (auto line{track_line(choice, *track, route)}) + lines.push_back(std::move(*line)); + } + } + if (lines.empty()) + return deepest; + corridor const space{lines}; + std::vector hits; + for (auto *model : Models) + if (model != nullptr) + scan_model(space, *model, hits); + sort_hits(hits); + return hits.empty() ? deepest : hits.front(); +} + +void gauge_tool::update() +{ + if (m_gauge.scan) + step_gauge_map(); + if (false == m_gauge.open) + { + if (false == EditorOverlay.batches.empty()) + EditorOverlay.clear(); + m_gauge.published = false; + return; + } + auto *track{m_gauge.enabled ? m_selection.selected_track() : nullptr}; + // the geometry is rescanned once the edit ends + if (ImGui::IsMouseDown(0) || m_design.track_editing()) + m_gauge.pending = true; + else if (track == nullptr) + { + if (m_gauge.track != nullptr) + { + m_gauge.line = {}; + m_gauge.track = nullptr; + m_gauge.published = false; + } + } + else if (track != m_gauge.track || m_history.history_revision() != m_gauge.history || m_gauge.pending) + { + m_gauge.track = track; + m_gauge.history = m_history.history_revision(); + m_gauge.pending = false; + scan_gauge(*track); + m_gauge.published = false; + } + if (false == m_gauge.published || glm::distance(m_view.camera_position(), EditorOverlay.origin) > gauge_origin_range) + gauge_publish(); +} + +void gauge_tool::scan_gauge(TTrack &Track) +{ + gauge_load(); + m_gauge.line = {}; + auto route{editor_track::run_route(Track, gauge_reach)}; + auto line{track_line(gauge_choice(), Track, route)}; + if (false == line.has_value()) + return; + std::vector const lines{std::move(*line)}; + corridor const space{lines}; + build_tunnel(lines.front(), m_gauge.line.surface, m_gauge.line.edges); + scan_models(space, m_gauge.line.hits); + if (false == m_gauge.map.scanned) + m_gauge.current = -1; +} + +void gauge_tool::scan_gauge_map() +{ + gauge_load(); + auto scan{std::make_shared()}; + scan->started = std::chrono::steady_clock::now(); + auto const chosen{gauge_choice()}; + // copies, the outlines may be edited while it runs + scan->railway = chosen.railway != nullptr ? std::optional{*chosen.railway} : std::nullopt; + scan->road = chosen.road != nullptr ? std::optional{*chosen.road} : std::nullopt; + scan->lines = scenery_lines({scan->railway ? &*scan->railway : nullptr, scan->road ? &*scan->road : nullptr}); + scan->space.emplace(scan->lines); + m_gauge.map = {}; + m_gauge.map.scanned = true; + m_gauge.map.history = m_history.history_revision(); + auto const name{[](gauge::profile const *Profile) { return Profile != nullptr ? Profile->name : std::string{"-"}; }}; + m_gauge.map.profile = name(chosen.railway) + ", " + name(chosen.road); + m_gauge.current = -1; + m_gauge.published = false; + m_gauge.scan = std::move(scan); +} + +void gauge_tool::step_gauge_map() +{ + auto &scan{*m_gauge.scan}; + auto const &instances{simulation::Instances.sequence()}; + auto const &sweeps{simulation::Sweeps.sequence()}; + auto const total{instances.size() + sweeps.size()}; + auto const until{std::chrono::steady_clock::now() + gauge_slice}; + while (scan.next < total && std::chrono::steady_clock::now() < until) + { + auto const next{scan.next++}; + if (next < instances.size()) + { + if (auto *instance{instances[next]}) + scan_model(*scan.space, *instance, m_gauge.map.hits); + } + else if (auto *sweep{sweeps[next - instances.size()]}) + scan_sweep(*scan.space, *sweep, m_gauge.map.hits); + } + scan.progress = total == 0 ? 1.f : static_cast(scan.next) / total; + if (scan.next >= total) + finish_gauge_map(); +} + +void gauge_tool::finish_gauge_map() +{ + auto const scan{std::move(m_gauge.scan)}; + auto &hits{m_gauge.map.hits}; + // the hit the camera went to stays chosen + auto const chosen{m_gauge.current >= 0 && m_gauge.current < static_cast(hits.size()) ? std::optional{hits[m_gauge.current].point} : std::nullopt}; + sort_hits(hits); + if (chosen) + m_gauge.current = static_cast(std::find_if(hits.begin(), hits.end(), [&](auto const &Hit) { return Hit.point == *chosen; }) - hits.begin()); + WriteLog("Structure gauge (" + m_gauge.map.profile + "): " + std::to_string(hits.size()) + " models enter it along " + std::to_string(scan->lines.size()) + " lines, scanned in " + + std::to_string(std::chrono::duration_cast(std::chrono::steady_clock::now() - scan->started).count()) + " ms"); + if (false == chosen.has_value() && false == hits.empty()) + gauge_focus(0); +} + +void gauge_tool::gauge_publish() +{ + m_gauge.published = true; + EditorOverlay.clear(); + EditorOverlay.origin = m_view.camera_position(); + auto const batch{[](glm::vec4 const &Color, unsigned int const Type, std::vector const &Points) { + gfx::editor_overlay::batch result{Color, Type}; + result.points.reserve(Points.size()); + for (auto const &point : Points) + result.points.emplace_back(point - EditorOverlay.origin); + return result; + }}; + std::vector marker; + auto const &hits{gauge_hits()}; + if (m_gauge.current >= 0 && m_gauge.current < static_cast(hits.size())) + { + auto const point{hits[m_gauge.current].point}; + marker = {point - glm::dvec3(0.0, 3.0, 0.0), point + glm::dvec3(0.0, 3.0, 0.0), point - glm::dvec3(1.0, 0.0, 0.0), point + glm::dvec3(1.0, 0.0, 0.0), + point - glm::dvec3(0.0, 0.0, 1.0), point + glm::dvec3(0.0, 0.0, 1.0)}; + } + EditorOverlay.batches = {batch({0.2f, 0.9f, 0.3f, 0.12f}, GL_TRIANGLES, m_gauge.line.surface), + batch({0.2f, 1.0f, 0.3f, 0.5f}, GL_LINES, m_gauge.line.edges), + batch({1.0f, 0.9f, 0.1f, 1.0f}, GL_LINES, marker), + batch({0.2f, 0.9f, 0.3f, 0.12f}, GL_TRIANGLES, m_gauge.spot.surface), + batch({0.2f, 1.0f, 0.3f, 0.5f}, GL_LINES, m_gauge.spot.edges)}; +} + +void gauge_tool::gauge_focus(int const Index) +{ + auto const &hits{gauge_hits()}; + if (hits.empty()) + return; + m_gauge.current = (Index % static_cast(hits.size()) + static_cast(hits.size())) % static_cast(hits.size()); + m_gauge.published = false; + gauge_spot(hits[m_gauge.current]); + auto const &hit{hits[m_gauge.current]}; + // along the track, tangent to the gauge at the height of the place, from the end nearer to the camera + glm::dvec3 look{hit.direction.x, 0.0, hit.direction.y}; + look = glm::length(look) > 1e-6 ? glm::normalize(look) : glm::dvec3(0.0, 0.0, 1.0); + if (glm::dot(m_view.camera_position() - hit.point, look) > 0.0) + look = -look; + m_view.fly_to(hit.point, look, gauge_view_distance); +} + +void gauge_tool::gauge_spot(gauge_hit const &Hit) +{ + m_gauge.spot = {}; + auto const &paths{simulation::Paths.sequence()}; + // the hit outlives the scan, the path may be gone since + if (Hit.track == nullptr || std::find(paths.begin(), paths.end(), Hit.track) == paths.end()) + return; + auto *track{const_cast(Hit.track)}; + editor_track::route route; + if (Hit.path == 0) + route = editor_track::run_route(*track, gauge_spot_reach); + else + route.spans.push_back({track, Hit.path, true}); + if (auto const line{track_line(gauge_choice(), *track, route)}) + build_tunnel(*line, m_gauge.spot.surface, m_gauge.spot.edges); +} + +void gauge_tool::render_windows() +{ + if (false == m_gauge.open) + return; + ImGui::SetNextWindowSize(ImVec2(380.0f, 420.0f), ImGuiCond_FirstUseEver); + if (false == ImGui::Begin((std::string(STR_C("Structure gauge")) + "###structuregauge").c_str(), &m_gauge.open)) + { + ImGui::End(); + return; + } + if (ImGui::Checkbox(STR_C("Show along the selected path"), &m_gauge.enabled)) + m_gauge.pending = true; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Translucent tunnel of the gauge 500 m each way along the line of the selected path.\nWidened in the curves under 250 m and tilted on the cant, from 20 m (inner side)\nand 26 m (outer side) ahead of the curve, as in the PKP PLK standard, volume II.")); + gauge_load(); + bool changed{render_gauge_choice("Railway", m_gauge.profile, false)}; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("GPL: unified structure gauge, widened only in the curves under 250 m.\nG1, G2, GA, GB, GC: limit (GSZ) and nominal (NSZ) installation gauges, widened by 3750/R in all curves.")); + if (m_gauge.profile >= 0) + gauge_sketch(m_gauge.profiles[m_gauge.profile]); + changed |= render_gauge_choice("Road", m_gauge.road, true); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Clearance over the roads, from 0.5 m beyond the edges of the carriageway")); + + if (m_gauge.scan) + { + auto const label{format(STR_C("Scanning the scenery %.0f%%, %zu found"), m_gauge.scan->progress * 100.f, m_gauge.map.hits.size())}; + ImGui::ProgressBar(m_gauge.scan->progress, ImVec2(-70.0f, 0.0f), label.c_str()); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Cancel"))) + finish_gauge_map(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Stops the scan and keeps the models found so far")); + } + else if (ImGui::Button(STR_C("Find the violations in the whole scenery"))) + scan_gauge_map(); + else if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Checks the models along all tracks of the scenery against the chosen gauge\nand lists them, the deepest first.\nRuns in the background, the list fills up as it goes")); + if (m_gauge.map.scanned && false == static_cast(m_gauge.scan)) + { + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Clear"))) + { + m_gauge.map = {}; + m_gauge.current = -1; + m_gauge.published = false; + } + else if (m_gauge.map.history != m_history.history_revision()) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), STR_C("The scenery changed since the scan (%s)"), m_gauge.map.profile.c_str()); + } + render_gauge_hits(); + changed |= render_gauge_outline(m_gauge.profile); + changed |= render_gauge_outline(m_gauge.road); + if (changed) + m_gauge.pending = true; + ImGui::End(); +} + +void gauge_tool::render_gauge_hits() +{ + auto const &hits{gauge_hits()}; + if (false == m_gauge.map.scanned && (false == m_gauge.enabled || m_gauge.track == nullptr)) + return; + if (hits.empty()) + { + ImGui::TextDisabled("%s", m_gauge.map.scanned ? STR_C("No model in the scenery enters the gauge") : STR_C("The gauge is clear along this line")); + return; + } + ImGui::TextColored(ImVec4(1.0f, 0.35f, 0.3f, 1.0f), STR_C("%zu models enter the gauge%s"), hits.size(), m_gauge.map.scanned ? STR_C(" in the whole scenery") : ""); + if (ImGui::ArrowButton("##gaugeprevious", ImGuiDir_Left)) + gauge_focus(m_gauge.current - 1); + ImGui::SameLine(); + if (ImGui::ArrowButton("##gaugenext", ImGuiDir_Right)) + gauge_focus(m_gauge.current + 1); + ImGui::SameLine(); + ImGui::Text("%d / %zu", m_gauge.current + 1, hits.size()); + ImGui::BeginChild("gaugehits", ImVec2(0.0f, std::min(160.0f, ImGui::GetTextLineHeightWithSpacing() * hits.size() + 8.0f)), true); + ImGuiListClipper clipper; + clipper.Begin(static_cast(hits.size())); + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; ++i) + { + auto const &hit{hits[i]}; + auto const label{(hit.model.empty() ? STR("(no name)") : hit.model) + " " + std::to_string(static_cast(std::lround(hit.depth * 100.0))) + " cm##" + std::to_string(i)}; + if (ImGui::Selectable(label.c_str(), m_gauge.current == i)) + gauge_focus(i); + } + ImGui::EndChild(); +} + +bool gauge_tool::render_gauge_choice(char const *Label, int &Index, bool const Road) +{ + bool changed{false}; + ImGui::PushID(Label); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(STR_C(Label)); + ImGui::SameLine(std::round(ImGui::GetCursorStartPos().x + std::max(ImGui::CalcTextSize(STR_C("Railway")).x, ImGui::CalcTextSize(STR_C("Road")).x) + ImGui::GetStyle().ItemSpacing.x)); + ImGui::SetNextItemWidth(-FLT_MIN); + if (ImGui::BeginCombo("##profile", Index >= 0 ? m_gauge.profiles[Index].name.c_str() : STR_C("(none)"))) + { + for (int i = 0; i < static_cast(m_gauge.profiles.size()); ++i) + if ((m_gauge.profiles[i].kind == gauge::kind::road) == Road && ImGui::Selectable(m_gauge.profiles[i].name.c_str(), i == Index)) + { + changed = i != Index; + Index = i; + } + ImGui::EndCombo(); + } + ImGui::PopID(); + return changed; +} + +bool gauge_tool::render_gauge_outline(int const Index) +{ + if (Index < 0) + return false; + auto &profile{m_gauge.profiles[Index]}; + if (false == ImGui::TreeNode(&profile, STR_C("Outline of %s (right half)"), profile.name.c_str())) + return false; + ImGui::TextDisabled(profile.kind == gauge::kind::road ? STR_C("Metres from the edge of the carriageway and above the road, bottom up.") + : STR_C("PKP PLK standard, volume II; below 1170 mm the limit installation gauge.\nMetres from the track axis and above the rail top, bottom up.")); + bool edited{edit_points(profile.outline)}; + if (ImGui::SmallButton(STR_C("Restore the starting outlines"))) + { + m_gauge.profiles = gauge::default_profiles(); + gauge_load(); + edited = true; + } + if (edited) + gauge::save_profiles(gauge_file, m_gauge.profiles); + ImGui::TreePop(); + return edited; +} + +editor_selftest_result gauge_tool::selftest(std::string const &Command, std::istringstream &Words) +{ + if (Command == "gauge") + { + std::string name; + Words >> name; + if (auto *track{simulation::Paths.find(name)}) + { + scan_gauge(*track); + WriteLog(format("SELFTEST gauge %s: %d hits", name.c_str(), static_cast(m_gauge.line.hits.size()))); + for (auto const &hit : m_gauge.line.hits) + WriteLog(format("SELFTEST gauge hit %s depth %.3f at %.2f %.2f %.2f", hit.model.c_str(), hit.depth, hit.point.x, hit.point.y, hit.point.z)); + } + else + WriteLog("SELFTEST gauge " + name + ": no such track"); + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} diff --git a/application/editormodegauge.h b/application/editormodegauge.h new file mode 100644 index 000000000..b37a85c0d --- /dev/null +++ b/application/editormodegauge.h @@ -0,0 +1,96 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "application/editortool.h" +#include "editor/editorGauge.hpp" + +#include +#include +#include + +class TAnimModel; + +class gauge_tool final : public editor_tool +{ + public: + // model entering the structure gauge, at its deepest place + struct gauge_hit + { + std::string model; + glm::dvec3 point{0.0}; + double depth{0.0}; // m + TTrack const *track{nullptr}; // nearest one, may be gone by now + int path{0}; + glm::dvec2 direction{0.0, 1.0}; // of the track there, in the plan + }; + gauge_tool(editor_selection &Selection, editor_view &View, editor_history &History, editor_track_design &Design) : m_selection{Selection}, m_view{View}, m_history{History}, m_design{Design} {} + void update() override; + void render_windows() override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + bool is_open() const { return m_gauge.open; } + // the deepest entry of the models into the outlines of the paths around them, of the outline chosen in the window; a hit of + // depth 0 when they keep out of them all + gauge_hit gauge_models(std::vector const &Models); + void toggle() { m_gauge.open = !m_gauge.open; } + + private: + editor_selection &m_selection; + editor_view &m_view; + editor_history &m_history; + editor_track_design &m_design; + // structure gauge along the line of the selected path, shown in the 3d view + struct gauge_state + { + bool open{false}; // window + bool enabled{true}; // tunnel along the selected path + std::vector profiles; + int profile{0}; // railway + int road{-1}; + TTrack const *track{nullptr}; // scanned + std::size_t history{0}; + bool pending{false}; // rescan once the edit ends + struct + { + std::vector surface; // triangles of the tunnel + std::vector edges; // lines + std::vector hits; + } line; // along the selected path + struct + { + bool scanned{false}; + std::size_t history{0}; + std::string profile; + std::vector hits; + } map; // whole scenery + struct + { + std::vector surface; + std::vector edges; + } spot; // tunnel around the hit the camera went to + int current{-1}; // hit the camera went to + bool published{false}; // overlay up to date + std::shared_ptr scan; // of the whole scenery, done in slices over the frames + } m_gauge; + void gauge_load(); + // the chosen railway and road outlines + gauge::choice gauge_choice() const; + std::vector const &gauge_hits() const; + void scan_gauge(TTrack &Track); + void scan_gauge_map(); + void step_gauge_map(); + void finish_gauge_map(); + void gauge_publish(); + void gauge_focus(int Index); + void gauge_spot(gauge_hit const &Hit); + void render_gauge_hits(); + bool render_gauge_choice(char const *Label, int &Index, bool Road); + bool render_gauge_outline(int Index); +}; diff --git a/application/editormodegradeline.cpp b/application/editormodegradeline.cpp new file mode 100644 index 000000000..8f2dd51ee --- /dev/null +++ b/application/editormodegradeline.cpp @@ -0,0 +1,739 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.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 grade lines the tracks nearly parallel share: kept in the scenery, followed when the profile tool changes a route of them, a route +// taken off them and back, tracks clicked onto the line of the route and off it by hand + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editorprojection.h" +#include "application/editormodeshared.h" +#include "editor/editorFormat.hpp" +#include "editor/editorGeometry.hpp" +#include "simulation/simulation.h" +#include "utilities/translation.h" +#include "world/Track.h" + +#include "imgui/imgui.h" +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +std::string const kGradeLineMark{"//$w"}; +} // namespace + +// the ends of the path up or down by these, what's between them in proportion; After is given the path and each of its pieces then +void editor_mode::move_path_heights(segment_data &Path, double const First, double const Second, std::function const &After) +{ + auto const origin{Path.points[segment_data::point::start]}; + auto const chord{geometry::plan_of(Path.points[segment_data::point::end] - origin)}; + auto const square{std::max(1e-9, glm::dot(chord, chord))}; + auto const by = [&](glm::dvec3 const &Point) { return glm::mix(First, Second, std::clamp(glm::dot(geometry::plan_of(Point - origin), chord) / square, 0.0, 1.0)); }; + auto const lay = [&](segment_data &Part) { + auto &points{Part.points}; + auto const start{points[segment_data::point::start]}; + auto const end{points[segment_data::point::end]}; + if (points[segment_data::point::control1] != glm::dvec3{} || points[segment_data::point::control2] != glm::dvec3{}) + { + points[segment_data::point::control1].y += by(start + points[segment_data::point::control1]) - by(start); + points[segment_data::point::control2].y += by(end + points[segment_data::point::control2]) - by(end); + } + points[segment_data::point::start].y += by(start); + points[segment_data::point::end].y += by(end); + if (After) + After(Part); + }; + for (auto &piece : Path.pieces) + lay(piece); + lay(Path); +} + +// a track on a grade line is told by its name and where it starts in the plan: scenery files have names used twice, and the height of a +// track on the line changes with it +std::string editor_mode::grade_line_key(TTrack const &Track) +{ + return grade_line_key(Track.name(), Track); +} + +std::string editor_mode::grade_line_key(std::string const &Name, TTrack const &Track) +{ + if (Track.m_paths.empty()) + return Name; + auto const &start{Track.m_paths.front().points[segment_data::point::start]}; + return format("%s@%lld,%lld", Name.c_str(), static_cast(std::llround(start.x)), static_cast(std::llround(start.z))); +} + +// the grade lines shared go to the scenery files as "//$w" comment lines, by those keys +void editor_mode::grade_lines_load() +{ + auto &state{m_nmt_state}; + if (state.grade_lines_loaded) + return; + state.grade_lines_loaded = true; + for (auto const layer : scene::Layers.marked_layers(kGradeLineMark)) + for (auto const &text : scene::Layers.marked(layer, kGradeLineMark)) + { + std::istringstream line{text}; + std::string keyword, name, hand; + int number{0}; + line >> keyword >> name >> number; + if (keyword == "gradeline" && false == line.fail()) + { + state.grade_lines[name] = number; + if (line >> hand && hand == "hand") + state.grade_lines_hand.insert(name); + } + } +} + +void editor_mode::grade_lines_store() +{ + if (scene::Layers.empty()) + return; + std::map> lines; + for (auto const layer : scene::Layers.marked_layers(kGradeLineMark)) + lines[layer]; + for (auto const *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved) + continue; + auto const key{grade_line_key(*track)}; + auto const found{m_nmt_state.grade_lines.find(key)}; + if (found == m_nmt_state.grade_lines.end() || found->second == nmt_state::grade_line_own || found->second == nmt_state::grade_line_steep) + continue; + auto const hand{found->second >= 0 && m_nmt_state.grade_lines_hand.contains(key)}; + auto layer{scene::Layers.resolve(track->layer())}; + if (false == scene::Layers.valid(layer) || false == scene::Layers.accepts(layer)) + layer = scene::Layers.active(); + auto &those{lines[layer]}; + if (those.empty()) + those.emplace_back("# the tracks sharing a grade line, each with the number of it; the simulation skips these lines"); + those.push_back(format("gradeline %s %d%s", key.c_str(), found->second, hand ? " hand" : "")); + } + for (auto &[layer, those] : lines) + if (scene::Layers.valid(layer)) + scene::Layers.mark(layer, kGradeLineMark, std::move(those)); +} + +bool editor_mode::on_route_grade_line(TTrack const &Track) +{ + grade_lines_load(); + auto const &lines{m_nmt_state.grade_lines}; + auto const found{lines.find(grade_line_key(Track))}; + if (found == lines.end() || found->second < 0) + return false; + return std::any_of(m_profile.route.spans.begin(), m_profile.route.spans.end(), [&](auto const &Span) { + auto const own{lines.find(grade_line_key(*Span.track))}; + return own != lines.end() && own->second == found->second; + }); +} + +std::vector const &editor_mode::grade_line_beside() +{ + double constexpr kBeside{200.0}; // m from the route, the width of a station; farther it has nothing to do with this one + auto &state{m_profile}; + std::tuple const of{state.route.spans.empty() ? nullptr : state.route.spans.front().track, state.route.spans.size(), static_cast(m_track_edits), m_nmt_state.grade_lines_changes}; + if (of == state.beside_of) + return state.beside; + state.beside_of = of; + state.beside.clear(); + grade_lines_load(); + std::unordered_set numbers; + std::unordered_set route; + for (auto const &span : state.route.spans) + { + route.insert(span.track); + if (auto const found{m_nmt_state.grade_lines.find(grade_line_key(*span.track))}; found != m_nmt_state.grade_lines.end() && found->second >= 0) + numbers.insert(found->second); + } + if (numbers.empty() || state.samples.size() < 2) + return state.beside; + auto const lying_by = [&](glm::dvec3 const &Point) { + for (auto const &sample : state.samples) + if (glm::length(glm::dvec2{sample.position.x - Point.x, sample.position.z - Point.z}) < kBeside) + return true; + return false; + }; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || route.contains(track) || track->m_paths.empty()) + continue; + auto const found{m_nmt_state.grade_lines.find(grade_line_key(*track))}; + if (found != m_nmt_state.grade_lines.end() && numbers.contains(found->second) && (lying_by(track->m_paths.front().points[segment_data::point::start]) || lying_by(track->m_paths.front().points[segment_data::point::end]))) + state.beside.push_back(track); + } + // and whatever lies on common timbers with them, on a grade line or not: those stay on one surface + std::unordered_set taken{route}; + taken.insert(state.beside.begin(), state.beside.end()); + std::unordered_set surfaces; + for (auto const &place : m_nmt_state.surface_places) + if (taken.contains(place.track)) + surfaces.insert(place.surface); + for (auto const &place : m_nmt_state.surface_places) + if (surfaces.contains(place.surface) && taken.insert(place.track).second && false == place.track->m_editorremoved) + state.beside.push_back(const_cast(place.track)); + return state.beside; +} + +// the tracks beside the route on the grade line it shares go up and down with it, by what it changed by abreast of them, however far +// across the station: a surface on common timbers stays one. Past the ends of the route the change fades from kFollow to kLeave beyond +// them; a track joined to them from off the grade line takes the change at that end only +std::size_t editor_mode::grade_line_follow(std::vector const &Before) +{ + double constexpr kFollow{0.0}; // m + double constexpr kLeave{50.0}; // m + auto &state{m_profile}; + auto const after{state.samples}; + if (false == state.whole_grade_line || Before.size() < 2 || after.size() < 2) + return 0; + auto const beside{grade_line_beside()}; + if (beside.empty()) + return 0; + auto const change_at = [&](glm::dvec3 const &Point) { + auto closest{std::numeric_limits::max()}; + auto chainage{0.0}; + auto past{0.0}; + for (std::size_t i = 0; i + 1 < after.size(); ++i) + { + auto const a{geometry::plan_of(after[i].position)}; + auto const run{geometry::plan_of(after[i + 1].position) - a}; + auto const along{glm::dot(geometry::plan_of(Point) - a, run) / std::max(1e-12, glm::dot(run, run))}; + auto const t{std::clamp(along, 0.0, 1.0)}; + if (auto const distance{glm::length(geometry::plan_of(Point) - (a + run * t))}; distance < closest) + { + closest = distance; + chainage = after[i].chainage + (after[i + 1].chainage - after[i].chainage) * t; + // how far along the way of the route it lies past its first or its last point + past = (i == 0 && along < 0.0) || (i + 2 == after.size() && along > 1.0) ? std::abs(along - t) * glm::length(run) : 0.0; + } + } + return std::clamp((kLeave - past) / (kLeave - kFollow), 0.0, 1.0) * (editor_track::sampled_elevation(after, chainage) - editor_track::sampled_elevation(Before, chainage)); + }; + auto const key_of = [](glm::dvec3 const &Point) { return std::pair{static_cast(std::round(Point.x * 20.0)), static_cast(std::round(Point.z * 20.0))}; }; + // the ends of the route itself lie where they should already, those of the switches on it with them + std::set> route_ends; + std::unordered_set route; + for (auto const &span : state.route.spans) + { + route.insert(span.track); + for (auto const &path : span.track->m_paths) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + route_ends.insert(key_of(path.points[end])); + } + std::map, double> moves; + auto any{false}; + for (auto const *track : beside) + for (auto const &path : track->m_paths) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + if (auto const key{key_of(path.points[end])}; false == route_ends.contains(key) && false == moves.contains(key)) + { + auto const move{change_at(path.points[end])}; + moves[key] = move; + any = any || std::abs(move) >= 0.001; + } + if (false == any) + return 0; + // the tracks going on from them off the grade line take the change in over a length, however short each of them is + double constexpr kRampIn{60.0}; // m, 0.3 m in over it is 5 per mille + std::unordered_set const members(beside.begin(), beside.end()); + struct joined + { + std::pair to; + double length; + }; + std::map, std::vector> ways; + for (auto const *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && false == route.contains(track) && false == members.contains(track)) + for (auto const &path : track->m_paths) + { + auto const a{key_of(path.points[segment_data::point::start])}; + auto const b{key_of(path.points[segment_data::point::end])}; + auto const length{glm::length(geometry::plan_of(path.points[segment_data::point::end] - path.points[segment_data::point::start]))}; + ways[a].push_back({b, length}); + ways[b].push_back({a, length}); + } + struct ramp + { + double from; // the change where it begins + double gone; // m from there + }; + std::map, ramp> ramps; + std::vector> waiting; + for (auto const &[key, move] : moves) + { + ramps[key] = {move, 0.0}; + waiting.push_back(key); + } + auto const height_of = [](ramp const &Ramp) { return Ramp.from * std::max(0.0, 1.0 - Ramp.gone / kRampIn); }; + while (false == waiting.empty()) + { + auto const here{waiting.back()}; + waiting.pop_back(); + auto const ramp_here{ramps.at(here)}; + auto const found{ways.find(here)}; + if (found == ways.end()) + continue; + for (auto const &way : found->second) + { + if (route_ends.contains(way.to) || moves.contains(way.to) || ramp_here.gone + way.length >= kRampIn) + continue; + ramp const further{ramp_here.from, ramp_here.gone + way.length}; + if (auto const known{ramps.find(way.to)}; known == ramps.end() || std::abs(height_of(further)) > std::abs(height_of(known->second))) + { + ramps[way.to] = further; + waiting.push_back(way.to); + } + } + } + for (auto const &[key, ramped] : ramps) + moves[key] = height_of(ramped); + auto const move_of = [&](glm::dvec3 const &Point) { + auto const found{moves.find(key_of(Point))}; + return found != moves.end() ? found->second : 0.0; + }; + editor_track::edit edit; + std::vector moved; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || route.contains(track)) + continue; + auto const touched{std::any_of(track->m_paths.begin(), track->m_paths.end(), [&](auto const &Path) { return moves.contains(key_of(Path.points[segment_data::point::start])) || moves.contains(key_of(Path.points[segment_data::point::end])); })}; + if (false == touched) + continue; + edit.capture(*track); + moved.push_back(track); + for (auto &path : track->m_paths) + move_path_heights(path, move_of(path.points[segment_data::point::start]), move_of(path.points[segment_data::point::end])); + } + if (moved.empty()) + return 0; + editor_track::commit(moved); + push_track_snapshot(std::move(edit.states), {}); + join_last_steps(); + fitted_set(moved, true); + return moved.size(); +} + +void editor_mode::grade_line_take_off(bool const Off) +{ + auto &lines{m_nmt_state.grade_lines}; + std::size_t changed{0}; + grade_lines_load(); + for (auto const &span : m_profile.route.spans) + { + auto const found{lines.find(grade_line_key(*span.track))}; + if (found == lines.end()) + continue; + auto &line{found->second}; + if (Off && line >= 0) + { + line = nmt_state::grade_line_off_number - line; + m_nmt_state.grade_lines_hand.erase(found->first); + } + else if (false == Off && line <= nmt_state::grade_line_off_number) + line = nmt_state::grade_line_off_number - line; + else if (false == Off && line == nmt_state::grade_line_off) + line = nmt_state::grade_line_own; + else + continue; + ++changed; + } + ++m_nmt_state.grade_lines_changes; + grade_lines_store(); + m_profile.status = format(Off ? STR_P("%zu track taken off the common grade line, it goes on its own now", "%zu tracks taken off the common grade line, they go on their own now", changed) : STR_P("%zu track back on the common grade line", "%zu tracks back on the common grade line", changed), changed); +} + +int editor_mode::route_grade_line() +{ + grade_lines_load(); + std::map lengths; + for (auto const &span : m_profile.route.spans) + if (auto const found{m_nmt_state.grade_lines.find(grade_line_key(*span.track))}; found != m_nmt_state.grade_lines.end() && found->second >= 0) + lengths[found->second] += span.track->Length(); + auto best{-1}; + auto longest{-1.0}; + for (auto const &[number, length] : lengths) + if (length > longest) + { + best = number; + longest = length; + } + return best; +} + +std::vector editor_mode::grade_line_run(TTrack &Track, bool const Alone) +{ + std::vector run{&Track}; + if (Alone || Track.eType != tt_Normal) + return run; + std::unordered_set seen{&Track}; + for (auto const forward : {true, false}) + { + TTrack const *previous{&Track}; + auto *current{forward ? Track.trNext : Track.trPrev}; + while (current != nullptr && current->eType == tt_Normal && false == current->m_editorremoved && seen.insert(current).second) + { + run.push_back(current); + auto *next{current->trPrev == previous ? current->trNext : current->trPrev}; + previous = current; + current = next; + } + } + return run; +} + +// put on by hand, or taken off, the tracks stay so when the lines are worked out again: a map of fiction has no terrain model to tell +// them by +void editor_mode::grade_line_pick(TTrack &Track, bool const Alone) +{ + auto &state{m_profile}; + auto &lines{m_nmt_state.grade_lines}; + auto &hand{m_nmt_state.grade_lines_hand}; + grade_lines_load(); + std::unordered_set route; + for (auto const &span : state.route.spans) + route.insert(span.track); + if (route.contains(&Track)) + { + state.status = STR("This is the route itself: the button above takes it off the common grade line"); + return; + } + auto const line_of = [&](TTrack const &Of) { + auto const found{lines.find(grade_line_key(Of))}; + return found != lines.end() ? found->second : nmt_state::grade_line_own; + }; + auto number{route_grade_line()}; + auto const run{grade_line_run(Track, Alone)}; + std::size_t changed{0}; + if (number >= 0 && line_of(Track) == number) + { + for (auto const *track : run) + if (line_of(*track) == number && false == route.contains(track)) + { + auto const key{grade_line_key(*track)}; + lines[key] = nmt_state::grade_line_off_number - number; + hand.erase(key); + ++changed; + } + state.status = format(STR_P("%zu track taken off the common grade line of the route", "%zu tracks taken off the common grade line of the route", changed), changed); + } + else + { + auto const made{number < 0}; + if (made) + { + // a new one, by a number no other line has, nor one a track taken off keeps + number = 0; + for (auto const &[key, line] : lines) + number = std::max(number, line >= 0 ? line + 1 : line <= nmt_state::grade_line_off_number ? nmt_state::grade_line_off_number - line + 1 : 0); + for (auto const *track : route) + { + auto const key{grade_line_key(*track)}; + lines[key] = number; + hand.insert(key); + } + } + for (auto const *track : run) + if (false == route.contains(track)) + { + auto const key{grade_line_key(*track)}; + lines[key] = number; + hand.insert(key); + ++changed; + } + state.status = format(made ? STR_P("A common grade line made of the route and %zu track", "A common grade line made of the route and %zu tracks", changed) + : STR_P("%zu track put on the common grade line of the route", "%zu tracks put on the common grade line of the route", changed), + changed); + } + ++m_nmt_state.grade_lines_changes; + grade_lines_store(); +} + +void editor_mode::grade_line_split(TTrack const &Original, TTrack const &Created) +{ + grade_lines_load(); + auto &lines{m_nmt_state.grade_lines}; + auto const found{lines.find(grade_line_key(Original))}; + if (found == lines.end() || Created.m_paths.empty()) + return; + auto const line{found->second}; + auto const hand{m_nmt_state.grade_lines_hand.contains(found->first)}; + auto const key{grade_line_key(Created)}; + lines[key] = line; + if (hand) + m_nmt_state.grade_lines_hand.insert(key); + ++m_nmt_state.grade_lines_changes; + m_nmt_state.grade_lines_dirty = true; +} + +void editor_mode::grade_line_captured(TTrack const &Track) +{ + if (scene::Layers.empty()) + return; + grade_lines_load(); + auto const key{grade_line_key(Track)}; + m_nmt_state.grade_line_keys.try_emplace(&Track, key); + if (false == Track.m_paths.empty() && m_nmt_state.grade_lines.contains(key)) + m_nmt_state.grade_line_replaced.emplace_back(key, Track.m_paths.front()); +} + +// what the track had under its key before goes on under the one it has now; the key it had stays too, for an undo bringing it back. A +// track never changed before is new: one lying where a track of a line lay before the change takes its line, so the pieces of it laid +// anew and a switch put into it; one between two tracks of a line at the ends of its first path lies on it, put on by hand if both of +// them are, so the link of a crossover between two switches of it +void editor_mode::grade_lines_committed(std::vector const &Tracks) +{ + auto &state{m_nmt_state}; + if (false == state.grade_lines_loaded) + return; + auto &lines{state.grade_lines}; + auto &hand{state.grade_lines_hand}; + auto changed{false}; + auto const carry = [&](std::string const &From, std::string const &To) { + auto const found{lines.find(From)}; + if (From == To || found == lines.end() || lines.contains(To)) + return; + auto const line{found->second}; + auto const byhand{hand.contains(From)}; + lines[To] = line; + if (byhand) + hand.insert(To); + changed = true; + }; + std::vector fresh; + for (auto *track : Tracks) + { + if (track == nullptr || track->m_editorremoved || track->m_paths.empty()) + continue; + auto const key{grade_line_key(*track)}; + auto const known{state.grade_line_keys.find(track)}; + if (known == state.grade_line_keys.end()) + { + if (false == lines.contains(key)) + fresh.push_back(track); + continue; + } + carry(known->second, key); + known->second = key; + } + auto const lying_on = [&](TTrack const &Track) -> std::string const * { + double constexpr kOn{0.3}; // m off the path it lay on + geometry::bezier const mine{Track.m_paths.front()}; + auto const middle{mine.point(0.5)}; + auto const way{geometry::plan_of(mine.point(0.55) - mine.point(0.45))}; + if (glm::length(way) < 1e-9) + return nullptr; + for (auto const &[key, path] : state.grade_line_replaced) + { + geometry::bezier const theirs{path}; + auto const reach{theirs.plan_length()}; + if (geometry::plan_distance(middle, theirs.point(0.5)) > 0.5 * reach + kOn) + continue; + int constexpr kSteps{64}; + for (int k = 0; k < kSteps; ++k) + { + auto const a{theirs.point(static_cast(k) / kSteps)}; + auto const b{theirs.point(static_cast(k + 1) / kSteps)}; + auto const run{geometry::plan_of(b - a)}; + auto const square{glm::dot(run, run)}; + if (square < 1e-12) + continue; + auto const t{std::clamp(glm::dot(geometry::plan_of(middle - a), run) / square, 0.0, 1.0)}; + if (glm::length(geometry::plan_of(middle - a) - run * t) < kOn && std::abs(glm::dot(glm::normalize(run), glm::normalize(way))) > 0.98) + return &key; + } + } + return nullptr; + }; + for (auto *&track : fresh) + if (auto const *was{lying_on(*track)}; was != nullptr && lines.contains(*was)) + { + auto const line{lines.at(*was)}; + auto const byhand{hand.contains(*was)}; + auto const key{grade_line_key(*track)}; + lines[key] = line; + if (byhand) + hand.insert(key); + state.grade_line_keys.try_emplace(track, key); + track = nullptr; + changed = true; + } + auto const lines_at = [&](TTrack const &Track, glm::dvec3 const &Point) { + std::map found; + for (auto const &[other, end] : editor_track::connected_points(Track, Point)) + if (other != &Track && false == other->m_editorremoved) + if (auto const entry{lines.find(grade_line_key(*other))}; entry != lines.end() && entry->second >= 0) + found[entry->second] = found[entry->second] || hand.contains(entry->first); + return found; + }; + // the switches first, the link between two of them after + for (int pass = 0; pass < 3; ++pass) + { + auto any{false}; + for (auto *&track : fresh) + { + if (track == nullptr) + continue; + auto const &path{track->m_paths.front()}; + auto const start{lines_at(*track, path.points[segment_data::point::start])}; + auto const end{lines_at(*track, path.points[segment_data::point::end])}; + auto number{-1}; + auto byhand{false}; + for (auto const &[line, lefthand] : start) + if (auto const other{end.find(line)}; other != end.end()) + { + // two lines at both ends tell nothing + number = number < 0 ? line : -2; + byhand = lefthand && other->second; + } + if (number < 0) + continue; + auto const key{grade_line_key(*track)}; + lines[key] = number; + if (byhand) + hand.insert(key); + state.grade_line_keys.try_emplace(track, key); + track = nullptr; + any = changed = true; + } + if (false == any) + break; + } + if (changed) + { + ++state.grade_lines_changes; + state.grade_lines_dirty = true; + } +} + +void editor_mode::grade_line_renamed(TTrack const &Track, std::string const &Old) +{ + if (Old.empty() || scene::Layers.empty()) + return; + grade_lines_load(); + auto &state{m_nmt_state}; + auto const from{grade_line_key(Old, Track)}; + auto const to{grade_line_key(Track)}; + auto const found{state.grade_lines.find(from)}; + if (found != state.grade_lines.end() && false == state.grade_lines.contains(to)) + { + auto const line{found->second}; + auto const byhand{state.grade_lines_hand.contains(from)}; + state.grade_lines[to] = line; + if (byhand) + state.grade_lines_hand.insert(to); + ++state.grade_lines_changes; + state.grade_lines_dirty = true; + } + if (auto const known{state.grade_line_keys.find(&Track)}; known != state.grade_line_keys.end()) + known->second = to; +} + +std::vector const &editor_mode::grade_line_members(int const Number) +{ + auto &state{m_profile}; + std::tuple const of{Number, m_nmt_state.grade_lines_changes, static_cast(m_track_edits)}; + if (of == state.members_of) + return state.members; + state.members_of = of; + state.members.clear(); + if (Number < 0) + return state.members; + grade_lines_load(); + for (auto const *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved) + if (auto const found{m_nmt_state.grade_lines.find(grade_line_key(*track))}; found != m_nmt_state.grade_lines.end() && found->second == Number) + state.members.push_back(track); + return state.members; +} + +// while they're picked: the tracks of the grade line of the route wherever they are, the run under the mouse in the colour of what a +// click does with it +void editor_mode::draw_grade_line_pick() +{ + auto const &state{m_profile}; + if (false == state.open || false == state.picking || state.route.spans.empty()) + return; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const draw = [&](TTrack const &Track, ImU32 const Colour, float const Width) { + for (auto const &path : Track.m_paths) + { + geometry::bezier const curve{path}; + auto const count{std::clamp(static_cast(curve.plan_length() / 3.0), 2, 64)}; + auto previous{curve.point(0.0)}; + for (int k = 1; k <= count; ++k) + { + auto const next{curve.point(static_cast(k) / count)}; + projection.line(drawlist, previous, next, Colour, Width); + previous = next; + } + } + }; + auto const number{route_grade_line()}; + for (auto const *track : grade_line_members(number)) + draw(*track, IM_COL32(70, 170, 255, 220), 3.0f); + if (m_intent.what != track_intent::kind::grade_line_pick || m_intent.track == nullptr) + return; + auto const found{m_nmt_state.grade_lines.find(grade_line_key(*m_intent.track))}; + auto const leaving{number >= 0 && found != m_nmt_state.grade_lines.end() && found->second == number}; + for (auto const *track : grade_line_run(*m_intent.track, m_intent.index == 1)) + draw(*track, leaving ? IM_COL32(255, 90, 70, 235) : IM_COL32(90, 230, 110, 235), 5.0f); +} + +void editor_mode::render_profile_grade_line() +{ + auto &state{m_profile}; + grade_lines_load(); + auto const &lines{m_nmt_state.grade_lines}; + std::size_t shared{0}, off{0}; + for (auto const &span : state.route.spans) + if (auto const found{lines.find(grade_line_key(*span.track))}; found != lines.end()) + { + shared += found->second >= 0 ? 1 : 0; + off += found->second == nmt_state::grade_line_off || found->second <= nmt_state::grade_line_off_number ? 1 : 0; + } + auto const number{route_grade_line()}; + if (shared > 0) + ImGui::TextUnformatted(format(STR_C("Common grade line %d, %zu tracks on it"), number + 1, grade_line_members(number).size()).c_str()); + else + ImGui::TextDisabled("%s", STR_C("The route shares no grade line with other tracks")); + if (state.picking) + { + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.85f, 0.55f, 0.1f, 1.0f)); + if (ImGui::Button(STR_C("Click the tracks in the view, Esc: done"), ImVec2(-FLT_MIN, 0.0f))) + state.picking = false; + ImGui::PopStyleColor(); + } + else if (ImGui::Button(shared > 0 ? STR_C("Put tracks on it or take them off...") : STR_C("Make a common grade line..."), ImVec2(-FLT_MIN, 0.0f))) + state.picking = true; + item_tooltip("Then click the tracks in the view: a click puts the stretch from switch to switch on the common grade line of the route, on a blue one takes it off; Shift+click the track only.\nWhat's set by hand stays when the lines are worked out again from the terrain model; there needn't be one"); + if (shared > 0) + { + auto const beside{grade_line_beside().size()}; + ImGui::Checkbox(STR_C("Move the whole common grade line"), &state.whole_grade_line); + item_tooltip("Applied, the tracks and switches lying on one grade line with this route go up and down with it, the ones on common timbers staying on one surface.\nUnticked, only the route changes"); + ImGui::TextDisabled(STR_P("%zu track beside goes with the route (blue in the view)", "%zu tracks beside go with the route (blue in the view)", beside), beside); + if (ImGui::SmallButton(STR_C("Take off the common grade line"))) + grade_line_take_off(true); + item_tooltip("This route gets a grade line of its own: the tracks beside no longer go with it, and it doesn't go with them, also when the lines are worked out again"); + } + if (off > 0) + { + if (ImGui::SmallButton(STR_C("Back on the common grade line"))) + grade_line_take_off(false); + item_tooltip("The route lies on the common grade line again. Its height doesn't change by this; if it's off the tracks beside, fit it to them with the grade line or by working out the lines anew"); + } +} diff --git a/application/editormodeinfra.cpp b/application/editormodeinfra.cpp new file mode 100644 index 000000000..d5212f56a --- /dev/null +++ b/application/editormodeinfra.cpp @@ -0,0 +1,1969 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editorprojection.h" +#include "application/editormodeshared.h" +#include "editor/editorFormat.hpp" +#include "editor/editorGeometry.hpp" + +#include "editor/editorIncludeInfo.hpp" +#include "model/AnimModel.h" +#include "model/Model3d.h" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/utilities.h" +#include "world/Event.h" +#include "world/EvLaunch.h" +#include "world/MemCell.h" +#include "world/Track.h" +#include "world/Traction.h" + +#include "imgui/imgui.h" +#include "utilities/translation.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using geometry::bezier; +using geometry::plan_distance; +using geometry::plan_of; + +std::string const kBindingMark{"//$b"}; +// the templates of the signalling which go with a path without a signal template of their own: the SHP resonator, read by its +// event, and the control of a block section, by the path nearest to it +std::string const kResonatorFile{"rezonator.inc"}; +std::string const kControlFile{"sbl_odstep.inc"}; +double constexpr kAdoptReach{12.0}; // m, of a point object from the axis of its path +double constexpr kBoundReach{30.0}; // m, of a point object bound by hand, as far as a changed path looks for it + +template +bool contains(std::vector const &Items, Type_ const &Item) +{ + return std::find(Items.begin(), Items.end(), Item) != Items.end(); +} + +ImU32 colour(infra::category const Category, int const Alpha = 255) +{ + switch (Category) + { + case infra::category::signal: return IM_COL32(255, 80, 80, Alpha); + case infra::category::sign: return IM_COL32(255, 220, 60, Alpha); + case infra::category::pole: return IM_COL32(160, 160, 255, Alpha); + case infra::category::catenary: return IM_COL32(80, 200, 255, Alpha); + case infra::category::logic: return IM_COL32(220, 120, 255, Alpha); + case infra::category::other: return IM_COL32(200, 200, 200, Alpha); + case infra::category::equipment: return IM_COL32(255, 150, 60, Alpha); + case infra::category::environment: return IM_COL32(110, 190, 110, Alpha); + } + return IM_COL32(200, 200, 200, Alpha); +} + +// nodes still present in the scene; the editor deletes models outright +class live_nodes +{ + public: + void refresh() + { + std::array const sizes{simulation::Instances.sequence().size(), simulation::Traction.sequence().size(), simulation::Memory.sequence().size(), simulation::Events.launchers().size()}; + if (sizes == m_sizes && m_valid) + return; + m_sizes = sizes; + m_valid = true; + m_nodes.clear(); + for (auto *node : simulation::Instances.sequence()) + m_nodes.insert(node); + for (auto *node : simulation::Traction.sequence()) + m_nodes.insert(node); + for (auto *node : simulation::Memory.sequence()) + m_nodes.insert(node); + for (auto *node : simulation::Events.launchers()) + m_nodes.insert(node); + } + bool alive(scene::basic_node const *Node) const + { + return Node != nullptr && m_nodes.count(Node) > 0; + } + void forget(scene::basic_node const *Node) + { + m_nodes.erase(Node); + m_valid = false; + } + + private: + std::unordered_set m_nodes; + std::array m_sizes{}; + bool m_valid{false}; +}; +live_nodes Live; + +bool alive(infra::binding const &Binding) +{ + if (Binding.type == infra::kind::include) + { + if (false == scene::Layers.tracked(Binding.include)) + return false; + auto const &included{scene::Layers.instance(Binding.include)}; + return false == included.removed && false == included.dead; + } + return Live.alive(Binding.node); +} + +// placement parameters of an include +struct include_place +{ + std::string file; + std::vector values; + std::array position{-1, -1, -1}; // indices of the values + int yaw{-1}; + glm::dvec3 offset{0.0}; + std::string description; // name and category of the template + std::string category; // of the description of the template +}; + +bool include_place_of(scene::instance_handle const Instance, include_place &Place) +{ + if (false == scene::Layers.tracked(Instance)) + return false; + auto const &included{scene::Layers.instance(Instance)}; + if (included.removed || included.dead || included.file == nullptr) + return false; + // with a rotation or a scale in effect the parameters don't translate to a location in a single way + if (included.context.rotation != glm::vec3{0.f} || included.context.scale != glm::vec3{1.f}) + return false; + if (false == editor_includes::parse_directive(scene::Layers.directive(Instance), Place.file, Place.values)) + return false; + static std::map descriptions; + auto found{descriptions.find(*included.file)}; + if (found == descriptions.end()) + { + include_info info; + std::string error; + editor_includes::load(*included.file, info, error); + editor_includes::suggest(*included.file, info); + found = descriptions.emplace(*included.file, std::move(info)).first; + } + auto const &info{found->second}; + auto const index = [&](char const *Role) { + auto const result{editor_includes::parameter_with_role(info, Role) - 1}; + double value; + return (result >= 0 && result < static_cast(Place.values.size()) && numeric(Place.values[result], value)) ? result : -1; + }; + Place.position = {index("pos.x"), index("pos.y"), index("pos.z")}; + Place.yaw = index("rot.y"); + Place.offset = included.context.offset; + Place.description = info.name + ' ' + info.category; + Place.category = info.category; + return Place.position[0] >= 0 && Place.position[1] >= 0 && Place.position[2] >= 0; +} + +glm::dvec3 include_location(include_place const &Place) +{ + glm::dvec3 result{Place.offset}; + for (int axis = 0; axis < 3; ++axis) + { + double value{0.0}; + numeric(Place.values[Place.position[axis]], value); + result[axis] += value; + } + return result; +} + +// points which define the object, and its rotation around the vertical axis if it has one +bool object_points(infra::binding const &Binding, std::vector &Points, std::optional &Yaw) +{ + Points.clear(); + Yaw.reset(); + switch (Binding.type) + { + case infra::kind::model: + { + auto const *model{static_cast(Binding.node)}; + Points.push_back(model->location()); + Yaw = model->Angles().y; + return true; + } + case infra::kind::include: + { + include_place place; + if (false == include_place_of(Binding.include, place)) + return false; + Points.push_back(include_location(place)); + if (place.yaw >= 0) + { + double value{0.0}; + numeric(place.values[place.yaw], value); + Yaw = value; + } + return true; + } + case infra::kind::traction: + { + auto const *traction{static_cast(Binding.node)}; + Points = {traction->pPoint1, traction->pPoint2, traction->pPoint3, traction->pPoint4}; + return true; + } + case infra::kind::memcell: + case infra::kind::launcher: Points.push_back(Binding.node->location()); return true; + } + return false; +} + +std::string object_key(infra::binding const &Binding) +{ + std::string result; + switch (Binding.type) + { + case infra::kind::model: + { + auto const *model{static_cast(Binding.node)}; + result = model->Model() != nullptr ? model->Model()->NameGet() : std::string{}; + break; + } + case infra::kind::include: result = *scene::Layers.instance(Binding.include).file; break; + case infra::kind::traction: break; + case infra::kind::memcell: + case infra::kind::launcher: result = Binding.node->name(); break; + } + if (result.empty() || result.find_first_of(" \t\r\n") != std::string::npos) + result = "-"; + return result; +} + +std::string object_label(infra::binding const &Binding) +{ + switch (Binding.type) + { + case infra::kind::model: + { + auto const *model{static_cast(Binding.node)}; + auto name{model->Model() != nullptr ? model->Model()->NameGet() : std::string{}}; + if (false == model->name().empty() && model->name() != "none") + name = model->name() + " (" + name + ')'; + return name; + } + case infra::kind::include: return *scene::Layers.instance(Binding.include).file; + case infra::kind::traction: return Binding.node->name().empty() || Binding.node->name() == "none" ? std::string{"traction"} : Binding.node->name(); + case infra::kind::memcell: return "memcell " + Binding.node->name(); + case infra::kind::launcher: return "eventlauncher " + Binding.node->name(); + } + return {}; +} + +void move_model(TAnimModel *Model, glm::dvec3 const &Location, glm::vec3 const &Angles) +{ + if (glm::distance(Model->location(), Location) > 1e-6) + { + simulation::Region->erase(Model); + Model->location(Location); + simulation::Region->insert(Model); + } + Model->Angles(Angles); +} + +void move_traction(TTraction *Traction, std::array const &Points) +{ + if (Traction->pPoint1 == Points[0] && Traction->pPoint2 == Points[1] && Traction->pPoint3 == Points[2] && Traction->pPoint4 == Points[3]) + return; + // the height of the lowest dropper stays the same + auto const minheight{(Traction->pPoint3.y - Traction->pPoint1.y + Traction->pPoint4.y - Traction->pPoint2.y) * 0.5 - Traction->fHeightDifference}; + simulation::Region->erase_and_unregister(Traction); + Traction->pPoint1 = Points[0]; + Traction->pPoint2 = Points[1]; + Traction->pPoint3 = Points[2]; + Traction->pPoint4 = Points[3]; + Traction->fHeightDifference = (Points[2].y - Points[0].y + Points[3].y - Points[1].y) * 0.5 - minheight; + Traction->Init(); + Traction->location(glm::mix(Points[1], Points[0], 0.5)); + Traction->m_area.radius = -1.f; + simulation::Region->insert_and_register(Traction); + GfxRenderer->Erase(Traction->m_geometry); + Traction->m_geometry = gfx::geometry_handle{}; + auto §ion{simulation::Region->section(Traction->location())}; + if (section.m_geometrycreated) + Traction->create_geometry(section.m_geometrybank); + Traction->mark_dirty(); +} + +void move_memcell(TMemCell *Memcell, glm::dvec3 const &Location) +{ + if (glm::distance(Memcell->location(), Location) <= 1e-6) + return; + simulation::Region->erase(Memcell); + Memcell->location(Location); + simulation::Region->insert(Memcell); +} + +void move_launcher(TEventLauncher *Launcher, glm::dvec3 const &Location) +{ + if (glm::distance(Launcher->location(), Location) <= 1e-6) + return; + // global and radio launchers aren't a part of the region + auto const placed{false == Launcher->IsGlobal() && false == Launcher->IsRadioActivated()}; + if (placed) + simulation::Region->erase(Launcher); + Launcher->location(Location); + if (placed) + simulation::Region->insert(Launcher); + Launcher->mark_dirty(); +} + +// bounding circle of the paths of a track, in the plan +struct track_area +{ + TTrack *track{nullptr}; + glm::dvec3 centre{0.0}; + double radius{0.0}; +}; + +track_area area_of(TTrack &Track) +{ + track_area result; + result.track = &Track; + std::vector points; + for (auto const &path : Track.m_paths) + { + auto const &start{path.points[segment_data::point::start]}; + auto const &end{path.points[segment_data::point::end]}; + points.insert(points.end(), {start, end, start + path.points[segment_data::point::control1], end + path.points[segment_data::point::control2]}); + } + if (points.empty()) + return result; + for (auto const &point : points) + result.centre += point / static_cast(points.size()); + for (auto const &point : points) + result.radius = std::max(result.radius, plan_distance(point, result.centre)); + return result; +} + +// the point lies sideways of the path, not beyond one of its ends +bool beside(infra::station const &Station, glm::dvec3 const &Point, bool const Interior) +{ + if (Interior) + return true; + auto const axis{infra::frame_at(Station)}; + return std::abs(glm::dot(plan_of(Point - axis.point), axis.forward)) <= 0.5; +} + +// nearest point of the tracks, sideways from the axis within the corridor +template +bool nearest_beside(Areas_ const &Areas, glm::dvec3 const &Point, double const Corridor, infra::station &Station) +{ + auto best{-1.0}; + for (auto const &entry : Areas) + { + track_area const &area = entry; + if (plan_distance(Point, area.centre) > area.radius + Corridor) + continue; + infra::station station; + bool interior; + auto const distance{infra::project(*area.track, Point, station, interior)}; + if (distance <= Corridor && (best < 0.0 || distance < best) && beside(station, Point, interior)) + { + best = distance; + Station = station; + } + } + return best >= 0.0; +} + +// paths of the whole scenery by cells of the plan, for the lookups reaching up to kReach from the axis +class track_index +{ + public: + static constexpr double kReach{55.0}; + void add(TTrack &Track) + { + auto const index{m_areas.size()}; + m_areas.push_back(area_of(Track)); + std::set cells; + for (auto const &path : Track.m_paths) + for (auto const &point : infra::outline(path, kCell * 0.5)) + for (auto x = key(point.x - kReach - kCell * 0.25); x <= key(point.x + kReach + kCell * 0.25); ++x) + for (auto z = key(point.z - kReach - kCell * 0.25); z <= key(point.z + kReach + kCell * 0.25); ++z) + cells.insert({x, z}); + for (auto const &cell : cells) + m_cells[cell].push_back(index); + } + bool nearest(glm::dvec3 const &Point, double const Corridor, infra::station &Station) const + { + auto const cell{m_cells.find({key(Point.x), key(Point.z)})}; + if (cell == m_cells.end()) + return false; + std::vector> areas; + for (auto const index : cell->second) + areas.emplace_back(m_areas[index]); + return nearest_beside(areas, Point, std::min(Corridor, kReach), Station); + } + bool empty() const + { + return m_areas.empty(); + } + + private: + static constexpr double kCell{64.0}; + using cell_key = std::pair; + static long long key(double const Value) + { + return static_cast(std::floor(Value / kCell)); + } + std::vector m_areas; + std::map> m_cells; +}; + +struct cell_reader +{ + TTrack *track{nullptr}; + std::string event; + std::string cell; + bool loose{false}; +}; + +class event_links +{ + public: + event_links() + { + std::unordered_map named; + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && false == track->name().empty() && track->name() != "none") + named.emplace(track->name(), track); + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved) + continue; + for (auto const *sequence : {&track->m_events0, &track->m_events1, &track->m_events2, &track->m_events0all, &track->m_events1all, &track->m_events2all}) + for (auto const &entry : *sequence) + read(track, entry.second != nullptr ? entry.second : simulation::Events.FindEvent(entry.first), entry.first.empty()); + } + static std::set const kinds{"event0", "event1", "event2", "eventall0", "eventall1", "eventall2"}; + std::unordered_set models(simulation::Instances.sequence().begin(), simulation::Instances.sequence().end()); + std::unordered_set cells(simulation::Memory.sequence().begin(), simulation::Memory.sequence().end()); + for (auto *event : simulation::Events.sequence()) + { + if (event == nullptr) + continue; + auto const &name{event->name()}; + auto const colon{name.rfind(':')}; + if (colon != std::string::npos && colon > 0 && kinds.count(name.substr(colon + 1)) > 0) + { + auto const track{named.find(name.substr(0, colon))}; + if (track != named.end()) + read(track->second, event, true); + } + auto const *multi{dynamic_cast(event)}; + if (multi == nullptr) + continue; + std::vector shown; + std::vector set; + for (auto *child : multi->children()) + { + auto const setter{dynamic_cast(child) != nullptr || dynamic_cast(child) != nullptr}; + for (auto *target : child->target_nodes()) // NOSONAR + { + if (models.count(target) > 0 && false == contains(shown, static_cast(target))) + shown.push_back(target); + else if (setter && cells.count(target) > 0 && false == contains(set, static_cast(target))) + set.push_back(static_cast(target)); + } + } + if (shown.size() > 4 || set.size() > 4) + continue; + for (auto const *model : shown) + for (auto *cell : set) + if (plan_distance(model->location(), cell->location()) <= kCellReach && false == contains(m_cells[model], cell)) + m_cells[model].push_back(cell); + } + for (auto *cell : simulation::Memory.sequence()) + { + if (cell == nullptr) + continue; + if (cell->m_instance != 0) + m_included[cell->m_instance].push_back(cell); + if (false == cell->name().empty() && cell->name() != "none") + m_named.emplace_back(cell->name(), cell); + } + std::sort(m_named.begin(), m_named.end(), [](auto const &A, auto const &B) { return A.first < B.first; }); + } + std::vector cells_of(infra::binding const &Binding) const + { + std::vector result; + switch (Binding.type) + { + case infra::kind::memcell: result.push_back(static_cast(Binding.node)); break; + case infra::kind::include: + { + auto const found{m_included.find(Binding.include)}; + if (found != m_included.end()) + result = found->second; + break; + } + case infra::kind::model: + { + auto const found{m_cells.find(Binding.node)}; + if (found != m_cells.end()) + result = found->second; + auto const &name{Binding.node->name()}; + if (result.empty() && name.size() >= 3 && name != "none") + for (auto entry{std::lower_bound(m_named.begin(), m_named.end(), name, [](auto const &Entry, std::string const &Name) { return Entry.first < Name; })}; + entry != m_named.end() && entry->first.compare(0, name.size(), name) == 0; ++entry) + if (plan_distance(entry->second->location(), Binding.node->location()) <= kCellReach) + result.push_back(entry->second); + break; + } + default: break; + } + return result; + } + std::vector readers_of(std::vector const &Cells) const + { + std::vector result; + for (auto const *cell : Cells) + { + auto const found{m_readers.find(cell)}; + if (found == m_readers.end()) + continue; + for (auto const &reader : found->second) + if (std::none_of(result.begin(), result.end(), [&](cell_reader const &Reader) { return Reader.track == reader.track; })) + result.push_back(reader); + } + return result; + } + + private: + static constexpr double kCellReach{60.0}; + void read(TTrack *Track, basic_event *Event, bool const Loose) + { + std::vector pending{Event}; + std::unordered_set seen; + while (false == pending.empty()) + { + auto *event{pending.back()}; + pending.pop_back(); + if (event == nullptr || false == seen.insert(event).second) + continue; + if (auto const *multi{dynamic_cast(event)}) + { + auto const children{multi->children()}; + pending.insert(pending.end(), children.begin(), children.end()); + continue; + } + if (dynamic_cast(event) == nullptr) + continue; + auto const targets{event->target_nodes()}; + if (targets.empty()) + continue; + auto &list{m_readers[targets.front()]}; + if (std::none_of(list.begin(), list.end(), [&](cell_reader const &Reader) { return Reader.track == Track; })) + list.push_back({Track, Event->name(), targets.front()->name(), Loose}); + } + } + std::unordered_map> m_readers; + std::unordered_map> m_cells; + std::unordered_map> m_included; + std::vector> m_named; +}; + +// lookup of points by a grid of 1 m cells in the plan +template +class point_grid +{ + public: + void add(glm::dvec3 const &Point, Type_ Item) + { + m_cells[key(Point)].emplace_back(Point, Item); + } + template + std::optional find(glm::dvec3 const &Point, double const Tolerance, Match_ const &Match) const + { + auto const centre{key(Point)}; + for (auto x = centre.first - 1; x <= centre.first + 1; ++x) + for (auto z = centre.second - 1; z <= centre.second + 1; ++z) + { + auto const cell{m_cells.find({x, z})}; + if (cell == m_cells.end()) + continue; + for (auto const &entry : cell->second) + if (glm::distance(entry.first, Point) <= Tolerance && Match(entry.second)) + return entry.second; + } + return std::nullopt; + } + + private: + using cell_key = std::pair; + static cell_key key(glm::dvec3 const &Point) + { + return {static_cast(std::floor(Point.x)), static_cast(std::floor(Point.z))}; + } + std::map>> m_cells; +}; + +double turn_of(infra::binding const &Binding, double const Yaw) +{ + auto const axis{infra::frame_at(Binding.anchors.front().at)}; + return clamp_circular(Yaw - infra::heading(axis.forward)); +} + +// the objects which the stored bindings can name, by their locations +struct bindable_objects +{ + point_grid paths; + point_grid models; + point_grid traction; + point_grid logic; + point_grid includes; + + bindable_objects() + { + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved) + for (auto const &path : track->m_paths) + paths.add(path.points[segment_data::point::start], track); + for (auto *model : simulation::Instances.sequence()) + if (model != nullptr && false == model->from_template() && model->Model() != nullptr) + models.add(model->location(), model); + for (auto *piece : simulation::Traction.sequence()) + if (piece != nullptr && false == piece->from_template()) + traction.add(piece->pPoint1, piece); + for (auto *memcell : simulation::Memory.sequence()) + if (memcell != nullptr && false == memcell->from_template()) + logic.add(memcell->location(), memcell); + for (auto *launcher : simulation::Events.launchers()) + if (launcher != nullptr && false == launcher->from_template()) + logic.add(launcher->location(), launcher); + for (scene::instance_handle handle = 1; handle <= scene::Layers.instance_count(); ++handle) + { + include_place place; + if (include_place_of(handle, place)) + includes.add(include_location(place), handle); + } + } +}; + +// format of the lines, coordinates in the space of the file: +// { } +// the object is the model, the include (position from its parameters), the traction piece (its first point), the memory +// cell or the event launcher found at the location; the anchors name the paths by their ends +std::optional read_binding(std::string const &Text, scene::layer_context const &Context, bindable_objects const &Objects) +{ + double const tolerance{0.05}; + std::istringstream line{Text}; + std::string kindname; + std::string key; + int group{0}; + int turns{0}; + int count{0}; + glm::dvec3 location; + line >> kindname >> group >> location.x >> location.y >> location.z >> key >> turns >> count; + if (line.fail() || count < 1 || count > 4) + return std::nullopt; + location = Context.to_world(location); + infra::binding binding; + binding.group = static_cast(std::clamp(group, 0, static_cast(infra::category::environment))); + binding.turns = (turns != 0); + auto found{false}; + if (kindname == infra::name(infra::kind::model)) + { + binding.type = infra::kind::model; + auto const model{Objects.models.find(location, tolerance, [&](TAnimModel *Model) { return Model->Model()->NameGet() == key; })}; + if ((found = model.has_value())) + binding.node = *model; + } + else if (kindname == infra::name(infra::kind::include)) + { + binding.type = infra::kind::include; + auto const handle{Objects.includes.find(location, tolerance, [&](scene::instance_handle Handle) { return *scene::Layers.instance(Handle).file == key; })}; + if ((found = handle.has_value())) + binding.include = *handle; + } + else if (kindname == infra::name(infra::kind::traction)) + { + binding.type = infra::kind::traction; + auto const piece{Objects.traction.find(location, tolerance, [](TTraction *) { return true; })}; + if ((found = piece.has_value())) + binding.node = *piece; + } + else if (kindname == infra::name(infra::kind::memcell) || kindname == infra::name(infra::kind::launcher)) + { + binding.type = (kindname == infra::name(infra::kind::memcell) ? infra::kind::memcell : infra::kind::launcher); + auto const node{Objects.logic.find(location, tolerance, [&](scene::basic_node *Node) { + auto const ismemcell{dynamic_cast(Node) != nullptr}; + return ismemcell == (binding.type == infra::kind::memcell) && (key == "-" || Node->name() == key); + })}; + if ((found = node.has_value())) + binding.node = *node; + } + std::vector points; + std::optional yaw; + if (false == found || false == object_points(binding, points, yaw)) + return std::nullopt; + for (int i = 0; i < count && found; ++i) + { + int path{0}; + glm::dvec3 start; + glm::dvec3 end; + line >> path >> start.x >> start.y >> start.z >> end.x >> end.y >> end.z; + start = Context.to_world(start); + end = Context.to_world(end); + auto const track{Objects.paths.find(start, tolerance, [&](TTrack *Track) { + return path >= 0 && path < static_cast(Track->m_paths.size()) && + glm::distance(Track->m_paths[path].points[segment_data::point::start], start) <= tolerance && + glm::distance(Track->m_paths[path].points[segment_data::point::end], end) <= tolerance; + })}; + if (line.fail() || false == track.has_value()) + { + found = false; + break; + } + auto const &point{points[std::min(i, points.size() - 1)]}; + binding.anchors.push_back(infra::make_anchor(*track, path, point)); + } + if (false == found || binding.anchors.size() != points.size()) + return std::nullopt; + binding.turns = binding.turns && yaw.has_value(); + if (binding.turns) + binding.yaw = turn_of(binding, *yaw); + binding.label = object_label(binding); + return binding; +} + +} // namespace + +void editor_mode::infra_load() +{ + if (m_bindings_loaded || scene::Layers.empty()) + return; + m_bindings_loaded = true; + auto const marked{scene::Layers.marked_layers(kBindingMark)}; + if (marked.empty()) + return; + + bindable_objects const objects; + auto resolved{0}; + for (auto const layer : marked) + { + auto const &context{scene::Layers.layer(layer).context_insert()}; + for (auto const &text : scene::Layers.marked(layer, kBindingMark)) + { + if (text.empty() || text.front() == '#') + continue; + auto binding{read_binding(text, context, objects)}; + if (false == binding.has_value()) + { + m_bindings_unresolved.emplace_back(layer, text); + continue; + } + m_bindings.push_back(std::move(*binding)); + ++resolved; + } + } + WriteLog("Editor: " + std::to_string(resolved) + " object(s) bound to the paths read from the scenery" + + (m_bindings_unresolved.empty() ? std::string{} : ", " + std::to_string(m_bindings_unresolved.size()) + " binding(s) whose objects or paths weren't found are kept as they are"), + logtype::generic); +} + +void editor_mode::infra_forget(scene::basic_node const *Node) +{ + Live.forget(Node); + auto const held = [Node](infra::binding const &Binding) { return Binding.type != infra::kind::include && Binding.node == Node; }; + m_bindings.erase(std::remove_if(m_bindings.begin(), m_bindings.end(), held), m_bindings.end()); + m_infra_buffer.erase(std::remove_if(m_infra_buffer.begin(), m_infra_buffer.end(), [&](infra::object_state const &State) { return held(State.saved); }), m_infra_buffer.end()); + for (auto &candidate : m_infra.candidates) + if (held(candidate.binding)) + candidate.binding.node = nullptr; +} + +void editor_mode::infra_store() +{ + if (false == m_bindings_loaded || scene::Layers.empty()) + return; + Live.refresh(); + m_bindings.erase(std::remove_if(m_bindings.begin(), m_bindings.end(), [](infra::binding const &Binding) { return false == alive(Binding); }), m_bindings.end()); + + std::map> lines; + for (auto const layer : scene::Layers.marked_layers(kBindingMark)) + lines[layer]; + for (auto const &entry : m_bindings_unresolved) + lines[entry.first].push_back(entry.second); + for (auto const &binding : m_bindings) + { + std::vector points; + std::optional yaw; + if (binding.adopted || binding.anchors.empty() || false == object_points(binding, points, yaw)) + continue; + auto layer{scene::Layers.resolve(binding.anchors.front().at.track->layer())}; + if (false == scene::Layers.valid(layer) || false == scene::Layers.accepts(layer)) + layer = scene::Layers.active(); + if (false == scene::Layers.valid(layer)) + layer = 1; + auto const &context{scene::Layers.layer(layer).context_insert()}; + auto const local = [&](glm::dvec3 const &Point) { + auto const point{context.to_local(Point)}; + return format("%.4f %.4f %.4f", point.x, point.y, point.z); + }; + auto text{std::string{infra::name(binding.type)} + ' ' + std::to_string(static_cast(binding.group)) + ' ' + local(points.front()) + ' ' + object_key(binding) + ' ' + + (binding.turns ? "1 " : "0 ") + std::to_string(binding.anchors.size())}; + for (auto const &anchor : binding.anchors) + { + auto const &path{anchor.at.track->m_paths[anchor.at.path]}; + text += ' ' + std::to_string(anchor.at.path) + ' ' + local(path.points[segment_data::point::start]) + ' ' + local(path.points[segment_data::point::end]); + } + lines[layer].push_back(std::move(text)); + } + for (auto &entry : lines) + { + if (false == entry.second.empty()) + entry.second.insert(entry.second.begin(), "# objects bound to the paths in the track editor, they follow changes of the track; the simulation skips these lines"); + scene::Layers.mark(entry.first, kBindingMark, std::move(entry.second)); + } +} + +std::vector editor_mode::infra_scope() const +{ + std::vector result; + auto const add = [&](TTrack *Track) { + if (Track != nullptr && false == Track->m_editorremoved && editor_track::is_supported(*Track) && false == contains(result, Track)) + result.push_back(Track); + }; + auto *selected{selected_track()}; + switch (m_infra.scope) + { + case 0: add(selected); break; + case 1: + if (selected != nullptr) + for (auto const &span : editor_track::run_route(*selected, m_infra.reach).spans) + add(span.track); + break; + case 2: + for (auto const &span : m_profile.route.spans) + add(span.track); + break; + case 3: + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && editor_track::is_supported(*track)) + result.push_back(track); + break; + default: break; + } + return result; +} + +infra::binding *editor_mode::infra_find(infra::binding const &Binding) +{ + for (auto &binding : m_bindings) + if (binding.same(Binding)) + return &binding; + return nullptr; +} + +std::string editor_mode::infra_carried_note() +{ + auto const count{m_infra_carried.size()}; + m_infra_carried.clear(); + return count > 0 ? format(STR_P("\n%zu object by the tracks moved sideways with them", "\n%zu objects by the tracks moved sideways with them", count), count) : std::string{}; +} + +int editor_mode::infra_bound_count() const +{ + return static_cast(std::count_if(m_bindings.begin(), m_bindings.end(), [](infra::binding const &Binding) { return false == Binding.adopted; })); +} + +void editor_mode::infra_recognize() +{ + auto &state{m_infra}; + infra_load(); + state.candidates.clear(); + state.hovered = -1; + state.error.clear(); + state.status.clear(); + state.tracks = infra_scope(); + if (state.tracks.empty()) + { + state.error = (state.scope == 2 ? STR_C("Open the vertical profile of a route first") : state.scope == 3 ? STR_C("The scenery has no paths the editor can handle") : STR_C("Select a path first")); + return; + } + state.read = 0; + state.overruled = 0; + state.unread = 0; + state.elsewhere = 0; + track_index index; + std::unordered_set names; + std::unordered_set const scope(state.tracks.begin(), state.tracks.end()); + for (auto *track : state.tracks) + { + index.add(*track); + if (false == track->name().empty() && track->name() != "none") + names.insert(track->name()); + } + Live.refresh(); + event_links const links; + std::unordered_map> threads; + auto const thread_of = [&](TTrack *Reader) -> std::vector const & { + auto found{threads.find(Reader)}; + if (found != threads.end()) + return found->second; + std::vector areas; + for (auto const &span : editor_track::run_route(*Reader, 250.0).spans) + if (scope.count(span.track) > 0 && std::none_of(areas.begin(), areas.end(), [&](track_area const &Area) { return Area.track == span.track; })) + areas.push_back(area_of(*span.track)); + return threads.emplace(Reader, std::move(areas)).first->second; + }; + + auto const corridor{static_cast(state.corridor)}; + auto const add = [&](infra::binding Binding, std::string const &Reason, double const Reach) { + std::vector points; + std::optional yaw; + if (false == object_points(Binding, points, yaw)) + return; + infra_candidate candidate; + auto const cells{points.size() == 1 ? links.cells_of(Binding) : std::vector{}}; + auto const readers{links.readers_of(cells)}; + infra::station geometric; + auto const nearby{index.nearest(points.front(), Reach, geometric)}; + if (false == readers.empty()) + { + auto best{-1.0}; + infra::station station; + for (auto const &reader : readers) + { + infra::station at; + auto const &thread{thread_of(reader.track)}; + if (false == nearest_beside(thread, points.front(), std::max(Reach, 25.0), at)) + continue; + auto const distance{plan_distance(infra::frame_at(at).point, points.front())}; + if (best < 0.0 || distance < best) + { + best = distance; + station = at; + candidate.reader = reader.track; + candidate.event = reader.event; + candidate.cell = reader.cell; + candidate.loose = reader.loose; + } + } + if (candidate.reader == nullptr) + { + state.elsewhere += nearby ? 1 : 0; + return; + } + auto const &thread{thread_of(candidate.reader)}; + if (nearby && geometric.track != station.track && std::none_of(thread.begin(), thread.end(), [&](track_area const &Area) { return Area.track == geometric.track; })) + { + candidate.nearer = geometric.track; + candidate.nearer_foot = infra::frame_at(geometric).point; + } + Binding.anchors.push_back(infra::make_anchor(station, points.front())); + if (Binding.group == infra::category::other && Binding.type != infra::kind::memcell) + Binding.group = infra::category::signal; + } + else + { + for (auto const &point : points) + { + infra::station station; + if (false == index.nearest(point, Reach, station)) + return; + Binding.anchors.push_back(infra::make_anchor(station, point)); + } + candidate.unread = (false == cells.empty() && Binding.type != infra::kind::memcell && Binding.group == infra::category::signal); + } + if (std::abs(Binding.anchors.front().height) > 40.0) + return; + Binding.turns = yaw.has_value() && Binding.type != infra::kind::traction; + if (Binding.turns) + Binding.yaw = turn_of(Binding, *yaw); + Binding.label = object_label(Binding); + candidate.offset = Binding.anchors.front().offset; + candidate.reason = Reason; + auto const *existing{infra_find(Binding)}; + candidate.bound = (existing != nullptr && false == existing->adopted); + candidate.chosen = (false == candidate.bound && Binding.group != infra::category::other && Binding.group != infra::category::environment); + candidate.binding = std::move(Binding); + state.read += candidate.reader != nullptr ? 1 : 0; + state.overruled += candidate.nearer != nullptr ? 1 : 0; + state.unread += candidate.unread ? 1 : 0; + state.candidates.push_back(std::move(candidate)); + }; + + for (auto *model : simulation::Instances.sequence()) + { + // models of the includes follow along with their include + if (model == nullptr || model->from_template() || model->Model() == nullptr) + continue; + infra::binding binding; + binding.type = infra::kind::model; + binding.node = model; + binding.group = infra::classify(model->Model()->NameGet() + ' ' + model->name(), state.rules); + add(binding, binding.group == infra::category::other ? STR("nearby, no rule matches the file name") : STR("the file name matches a rule"), corridor); + } + for (scene::instance_handle handle = 1; handle <= scene::Layers.instance_count(); ++handle) + { + include_place place; + if (false == include_place_of(handle, place)) + continue; + infra::binding binding; + binding.type = infra::kind::include; + binding.include = handle; + // the kind the description of the template names, else by the rules + if (auto const named{infra::category_named(place.category)}) + { + binding.group = *named; + add(binding, STR("the description of the template says what it is"), corridor); + continue; + } + binding.group = infra::classify(place.file + ' ' + place.description, state.rules); + add(binding, binding.group == infra::category::other ? STR("nearby, no rule matches the template or its description") : STR("the template or its description matches a rule"), corridor); + } + for (auto *piece : simulation::Traction.sequence()) + { + if (piece == nullptr || piece->from_template()) + continue; + infra::binding binding; + binding.type = infra::kind::traction; + binding.node = piece; + binding.group = infra::category::catenary; + add(binding, STR("wire over the track"), corridor); + } + for (auto *memcell : simulation::Memory.sequence()) + { + if (memcell == nullptr || memcell->from_template()) + continue; + infra::binding binding; + binding.type = infra::kind::memcell; + binding.node = memcell; + binding.group = infra::category::logic; + auto const named{false == memcell->asTrackName.empty() && names.count(memcell->asTrackName) > 0}; + add(binding, named ? format(STR_C("names the path %s"), memcell->asTrackName.c_str()) : STR("nearby"), named ? std::max(corridor, 50.0) : corridor); + } + for (auto *launcher : simulation::Events.launchers()) + { + if (launcher == nullptr || launcher->from_template()) + continue; + infra::binding binding; + binding.type = infra::kind::launcher; + binding.node = launcher; + binding.group = infra::category::logic; + add(binding, STR("nearby"), corridor); + } + std::stable_sort(state.candidates.begin(), state.candidates.end(), [](infra_candidate const &A, infra_candidate const &B) { return A.binding.group < B.binding.group; }); + state.status = format(STR_C("%d object(s) found along %d path(s)"), static_cast(state.candidates.size()), static_cast(state.tracks.size())); + if (state.elsewhere > 0) + state.status += format(STR_C("; %d left out: they stand by the scope, but the paths which read them are elsewhere"), state.elsewhere); +} + +void editor_mode::infra_bind_chosen() +{ + auto &state{m_infra}; + auto count{0}; + Live.refresh(); + for (auto &candidate : state.candidates) + { + if (false == candidate.chosen || candidate.bound || false == alive(candidate.binding)) + continue; + if (auto *existing{infra_find(candidate.binding)}) + *existing = candidate.binding; + else + m_bindings.push_back(candidate.binding); + candidate.bound = true; + candidate.chosen = false; + ++count; + } + state.status = format(STR_C("%d object(s) bound, they follow the changes of the track. The bindings are kept in the scenery files on save"), count); +} + +void editor_mode::infra_unbind(std::vector Indices) +{ + std::sort(Indices.begin(), Indices.end()); + Indices.erase(std::unique(Indices.begin(), Indices.end()), Indices.end()); + for (auto index{Indices.rbegin()}; index != Indices.rend(); ++index) + { + if (*index >= m_bindings.size()) + continue; + for (auto &candidate : m_infra.candidates) + if (candidate.binding.same(m_bindings[*index])) + candidate.bound = false; + m_bindings.erase(m_bindings.begin() + *index); + } +} + +infra::object_state editor_mode::infra_state_of(infra::binding const &Binding) const +{ + infra::object_state result; + result.saved = Binding; + switch (Binding.type) + { + case infra::kind::model: + { + auto const *model{static_cast(Binding.node)}; + result.location = model->location(); + result.angles = model->Angles(); + break; + } + case infra::kind::include: result.directive = scene::Layers.directive(Binding.include); break; + case infra::kind::traction: + { + auto const *traction{static_cast(Binding.node)}; + result.points = {traction->pPoint1, traction->pPoint2, traction->pPoint3, traction->pPoint4}; + break; + } + case infra::kind::memcell: + case infra::kind::launcher: result.location = Binding.node->location(); break; + } + return result; +} + +void editor_mode::infra_restore_state(infra::object_state const &State) +{ + Live.refresh(); + if (false == alive(State.saved)) + return; + if (auto *binding{infra_find(State.saved)}) + *binding = State.saved; + switch (State.saved.type) + { + case infra::kind::model: move_model(static_cast(State.saved.node), State.location, State.angles); break; + case infra::kind::include: + if (false == State.directive.empty() && State.directive != scene::Layers.directive(State.saved.include)) + set_include_directive(State.saved.include, State.directive); + break; + case infra::kind::traction: move_traction(static_cast(State.saved.node), State.points); break; + case infra::kind::memcell: move_memcell(static_cast(State.saved.node), State.location); break; + case infra::kind::launcher: move_launcher(static_cast(State.saved.node), State.location); break; + } +} + +void editor_mode::infra_buffer(infra::binding const &Binding, bool const Refresh) +{ + for (auto &entry : m_infra_buffer) + { + if (false == entry.saved.same(Binding)) + continue; + if (Refresh && false == entry.moved) + entry = infra_state_of(Binding); + return; + } + if (false == Refresh && false == m_history.empty() && m_history.back().action == EditorSnapshot::Action::TrackEdit) + { + // a drag keeps a single undo step, which holds the state from before the drag already + for (auto const &entry : m_history.back().infra) + if (entry.saved.same(Binding)) + return; + } + m_infra_buffer.push_back(infra_state_of(Binding)); +} + +void editor_mode::infra_adopt(TTrack &Track) +{ + auto const revision{history_revision()}; + if (revision != m_point_objects_revision || scene::Layers.instance_count() != m_point_objects_count) + { + m_point_objects_revision = revision; + m_point_objects_count = scene::Layers.instance_count(); + m_point_objects.clear(); + std::unordered_map readers; + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved) + for (int list = 0; list < 6; ++list) + for (auto const &event : editor_track::events(*track, list)) + if (false == event.first.empty()) + readers.emplace(ToLower(event.first), track); + static auto const rules{infra::default_rules()}; + // an indicator goes with its signal: by the path reading the signal named by its first parameter, not by the path nearest + // to it, which can be another one + std::unordered_map signal_reads; + std::vector> marks; + for (scene::instance_handle handle = 1; handle <= scene::Layers.instance_count(); ++handle) + { + include_place place; + if (false == include_place_of(handle, place) || place.values.empty() || false == scene::Layers.removable(handle)) + continue; + point_object object; + object.include = handle; + object.location = include_location(place); + auto const file{ToLower(place.file)}; + if (indicator_template_of(place.file) != nullptr) + { + object.group = infra::category::sign; + marks.emplace_back(std::move(object), ToLower(place.values.front())); + continue; + } + auto const *signal{signal_template_of(place.file)}; + std::string read; + if (signal != nullptr) + { + object.group = infra::category::signal; + read = signal->read.empty() ? std::string{} : editor_includes::substitute(signal->read, place.values); + signal_reads[ToLower(place.values.front())] = read; + } + else if (file == kResonatorFile) + { + object.group = infra::category::equipment; + read = place.values.front() + "_shp"; + } + else if (file == kControlFile) + object.group = infra::category::logic; + else + { + auto const named{infra::category_named(place.category)}; + object.group = named.has_value() ? *named : infra::classify(place.file + ' ' + place.description, rules); + if (object.group != infra::category::signal && object.group != infra::category::sign) + continue; + } + if (false == read.empty()) + if (auto const reader{readers.find(ToLower(read))}; reader != readers.end()) + object.reader = reader->second; + m_point_objects.push_back(std::move(object)); + } + // one whose signal no path reads is left where it is + for (auto &[object, name] : marks) + if (auto const read{signal_reads.find(name)}; read != signal_reads.end() && false == read->second.empty()) + if (auto const reader{readers.find(ToLower(read->second))}; reader != readers.end()) + { + object.reader = reader->second; + m_point_objects.push_back(std::move(object)); + } + // the path nearest to each one no path reads, the objects by cells of the plan + auto constexpr cell{200.0}; + auto const key = [&](double const Value) { return static_cast(std::floor(Value / cell)); }; + std::map, std::vector> cells; + for (std::size_t i = 0; i < m_point_objects.size(); ++i) + if (m_point_objects[i].reader == nullptr) + cells[{key(m_point_objects[i].location.x), key(m_point_objects[i].location.z)}].push_back(i); + std::vector nearest(m_point_objects.size(), kAdoptReach); + for (auto *track : simulation::Paths.sequence()) + { + if (cells.empty() || track == nullptr || track->m_editorremoved || false == editor_track::is_supported(*track)) + continue; + auto const area{area_of(*track)}; + auto const reach{area.radius + kAdoptReach}; + for (auto x = key(area.centre.x - reach); x <= key(area.centre.x + reach); ++x) + for (auto z = key(area.centre.z - reach); z <= key(area.centre.z + reach); ++z) + { + auto const found{cells.find({x, z})}; + if (found == cells.end()) + continue; + for (auto const i : found->second) + { + auto &object{m_point_objects[i]}; + if (plan_distance(object.location, area.centre) > area.radius + nearest[i]) + continue; + infra::station station; + bool interior; + auto const distance{infra::project(*track, object.location, station, interior)}; + if (distance < nearest[i] && beside(station, object.location, interior)) + { + nearest[i] = distance; + object.nearest = track; + } + } + } + } + } + auto const area{area_of(Track)}; + for (auto const &object : m_point_objects) + { + if (plan_distance(object.location, area.centre) > area.radius + kAdoptReach) + continue; + infra::binding binding; + binding.type = infra::kind::include; + binding.include = object.include; + if (infra_find(binding) != nullptr) + continue; + // of the line of the track: read by it or by a path of its run, else nearest to it; not one of the track alongside + if (object.reader != nullptr && object.reader != &Track) + { + auto const spans{editor_track::run_route(*object.reader, 250.0).spans}; + if (std::none_of(spans.begin(), spans.end(), [&](auto const &Span) { return Span.track == &Track; })) + continue; + } + if (object.reader == nullptr && object.nearest != &Track) + continue; + infra::station station; + bool interior; + if (infra::project(Track, object.location, station, interior) > kAdoptReach || false == beside(station, object.location, interior)) + continue; + std::vector points; + std::optional yaw; + if (false == object_points(binding, points, yaw) || points.empty()) + continue; + binding.group = object.group; + binding.anchors.push_back(infra::make_anchor(station, points.front())); + binding.turns = yaw.has_value() && object.group != infra::category::logic; + if (binding.turns) + binding.yaw = turn_of(binding, *yaw); + binding.label = object_label(binding); + binding.adopted = true; + binding.measured = points.front(); + m_bindings.push_back(std::move(binding)); + } +} + +void editor_mode::track_captured(TTrack const &Track) +{ + sweeps_captured(Track); + switch_drive_captured(Track); + grade_line_captured(Track); + if (m_infra_suspended || false == m_infra.follow) + return; + infra_load(); + // the signals and the like of the track follow it, staying where they stand along it + infra_adopt(const_cast(Track)); + if (m_bindings.empty()) + return; + Live.refresh(); + std::vector gone; + for (std::size_t index = 0; index < m_bindings.size(); ++index) + { + auto &binding{m_bindings[index]}; + if (std::none_of(binding.anchors.begin(), binding.anchors.end(), [&](infra::anchor const &Anchor) { return Anchor.at.track == &Track; }) || false == alive(binding)) + continue; + // an object moved by hand since it was bound is measured again, as long as the path is the way it was measured. one of a single + // point moved away from the track, off its side, doesn't follow it any more: measured along it, it would be taken back to its end + std::vector points; + std::optional yaw; + auto away{false}; + if (object_points(binding, points, yaw) && points.size() == binding.anchors.size()) + { + for (std::size_t i = 0; i < points.size() && false == away; ++i) + { + auto &anchor{binding.anchors[i]}; + if (anchor.at.track != &Track || anchor.at.path >= static_cast(Track.m_paths.size())) + continue; + auto const &path{Track.m_paths[anchor.at.path]}; + if (glm::distance(path.points[segment_data::point::start], anchor.start) > 1e-4 || glm::distance(path.points[segment_data::point::end], anchor.end) > 1e-4) + continue; + auto placed{anchor}; + if (glm::distance(infra::place(placed), points[i]) <= 0.01) + continue; + infra::station station; + bool interior{false}; + auto const reach{binding.adopted ? kAdoptReach : kBoundReach}; + if (points.size() == 1 && (infra::project(const_cast(Track), points[i], station, interior) > reach || false == beside(station, points[i], interior))) + away = true; + else + anchor = infra::make_anchor(anchor.at.track, anchor.at.path, points[i]); + } + if (false == away && binding.turns && yaw.has_value() && binding.anchors.front().at.track == &Track) + binding.yaw = turn_of(binding, *yaw); + } + if (away) + { + WriteLog("Editor: " + binding.label + " moved away from track " + Track.name() + ", it doesn't follow it any more"); + gone.push_back(index); + continue; + } + if (binding.adopted && false == points.empty()) + binding.measured = points.front(); + infra_buffer(binding, true); + } + infra_unbind(std::move(gone)); +} + +void editor_mode::tracks_committed(std::vector const &Tracks) +{ + nmt_track_changed(Tracks); + m_joints.tracks_committed(Tracks); + sweeps_committed(Tracks); + switch_drives_committed(Tracks); + grade_lines_committed(Tracks); + if (m_infra_suspended || false == m_infra.follow) + return; + infra_load(); + if (m_bindings.empty()) + return; + Live.refresh(); + std::vector areas; + for (auto *track : Tracks) + if (false == track->m_editorremoved) + areas.push_back(area_of(*track)); + // paths which took over may have been committed before the old ones were retired + std::optional> everywhere; + auto const take_over = [&](glm::dvec3 const &Foot, infra::station &Station) { + if (nearest_beside(areas, Foot, 30.0, Station)) + return true; + if (false == everywhere.has_value()) + { + everywhere.emplace(); + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && editor_track::is_supported(*track)) + everywhere->push_back(area_of(*track)); + } + // only a path running where the old one did, not the one alongside + return nearest_beside(*everywhere, Foot, 1.0, Station); + }; + std::vector dropped; + for (auto &binding : m_bindings) + { + auto const affected{std::any_of(binding.anchors.begin(), binding.anchors.end(), [&](infra::anchor const &Anchor) { + return Anchor.at.track != nullptr && (Anchor.at.track->m_editorremoved || contains(Tracks, Anchor.at.track)); + })}; + if (false == affected || false == alive(binding)) + continue; + std::vector standing; + std::optional facing; + if (binding.adopted && (false == object_points(binding, standing, facing) || standing.empty() || glm::distance(standing.front(), binding.measured) > 0.01)) + { + // moved by another tool while its track was being changed: it stays where that put it, bound again with the next change + dropped.push_back(binding.include); + continue; + } + auto moved{binding}; + auto lost{false}; + for (auto &anchor : moved.anchors) + { + auto *track{anchor.at.track}; + if (false == track->m_editorremoved && false == contains(Tracks, track)) + continue; + // the object goes square to the new axis from the point of the old one, so a shift of the track carries it + // sideways rather than along; its own path goes first, then the ones which took over + infra::station station; + auto found{false}; + if (false == track->m_editorremoved && anchor.at.path < static_cast(track->m_paths.size())) + { + double s; + bool interior; + auto const distance{infra::project(track->m_paths[anchor.at.path], anchor.foot, s, interior)}; + station = {track, anchor.at.path, s}; + found = (distance <= 30.0 && beside(station, anchor.foot, interior)); + } + if (false == found && false == take_over(anchor.foot, station)) + { + lost = true; + break; + } + auto const offset{anchor.offset}; + auto const height{anchor.height}; + // a path taking the object over may run the other way: the object stays on its side, turned as it was + auto const before{plan_of(anchor.end - anchor.start)}; + anchor = infra::make_anchor(station, anchor.foot); + auto const reversed{glm::length(before) > 1e-6 && glm::dot(before, infra::frame_at(anchor.at).forward) < 0.0}; + anchor.offset = reversed ? -offset : offset; + anchor.height = height; + if (reversed && &anchor == &moved.anchors.front()) + moved.yaw = clamp_circular(moved.yaw + 180.0); + } + if (lost) + { + if (binding.adopted) + dropped.push_back(binding.include); + else + binding.lost = true; + continue; + } + if (binding.adopted) + { + // where nothing moved, the directive stays as it is written + auto const there{infra::place(moved.anchors.front())}; + auto const turned{facing.has_value() && moved.turns ? std::abs(clamp_circular(infra::heading(infra::frame_at(moved.anchors.front().at).forward) + moved.yaw - *facing + 180.0) - 180.0) : 0.0}; + if (glm::distance(there, standing.front()) < 0.005 && turned < 0.01) + { + moved.lost = false; + binding = std::move(moved); + continue; + } + } + infra_buffer(binding, false); + moved.lost = false; + binding = std::move(moved); + infra_move(binding); + m_infra_carried.emplace(binding.node, binding.include); + if (binding.adopted) + { + std::vector points; + std::optional yaw; + if (object_points(binding, points, yaw) && false == points.empty()) + binding.measured = points.front(); + } + for (auto &entry : m_infra_buffer) + if (entry.saved.same(binding)) + entry.moved = true; + } + if (false == dropped.empty()) + m_bindings.erase(std::remove_if(m_bindings.begin(), m_bindings.end(), [&](infra::binding const &Binding) { return Binding.adopted && contains(dropped, Binding.include); }), m_bindings.end()); +} + +void editor_mode::track_retired(TTrack &Track) +{ + nmt_track_gone(Track); + tracks_committed({}); +} + +void editor_mode::track_renamed(TTrack const &Track, std::string const &Old) +{ + grade_line_renamed(Track, Old); +} + +void editor_mode::track_split(TTrack &Original, TTrack &Created, segment_data const &First) +{ + sweeps_split(Original, Created); + grade_line_split(Original, Created); + signal_split(Original, Created); + if (m_infra_suspended || Created.m_paths.empty()) + return; + auto const length{infra::plan_length(First)}; + auto const &second{Created.m_paths.front()}; + for (auto &binding : m_bindings) + for (auto &anchor : binding.anchors) + { + if (anchor.at.track != &Original || anchor.at.path != 0) + continue; + if (anchor.at.s > length) + { + anchor.at.track = &Created; + anchor.at.s -= length; + anchor.start = second.points[segment_data::point::start]; + anchor.end = second.points[segment_data::point::end]; + anchor.length = infra::plan_length(second); + } + else + { + anchor.end = First.points[segment_data::point::end]; + anchor.length = length; + } + } +} + +void editor_mode::infra_move(infra::binding &Binding) +{ + if (Binding.anchors.empty()) + return; + auto const location{infra::place(Binding.anchors.front())}; + auto const facing = [&]() { return clamp_circular(infra::heading(infra::frame_at(Binding.anchors.front().at).forward) + Binding.yaw); }; + switch (Binding.type) + { + case infra::kind::model: + { + auto *model{static_cast(Binding.node)}; + auto angles{model->Angles()}; + if (Binding.turns) + angles.y = static_cast(facing()); + move_model(model, location, angles); + break; + } + case infra::kind::include: + { + include_place place; + if (false == include_place_of(Binding.include, place)) + return; + for (int axis = 0; axis < 3; ++axis) + place.values[place.position[axis]] = editor_includes::number(location[axis] - place.offset[axis]); + if (Binding.turns && place.yaw >= 0) + place.values[place.yaw] = editor_includes::number(facing()); + auto const directive{editor_includes::compose_directive(place.file, place.values)}; + if (directive != scene::Layers.directive(Binding.include)) + set_include_directive(Binding.include, directive); + break; + } + case infra::kind::traction: + { + if (Binding.anchors.size() != 4) + return; + std::array points; + for (std::size_t i = 0; i < 4; ++i) + points[i] = infra::place(Binding.anchors[i]); + move_traction(static_cast(Binding.node), points); + break; + } + case infra::kind::memcell: move_memcell(static_cast(Binding.node), location); break; + case infra::kind::launcher: move_launcher(static_cast(Binding.node), location); break; + } +} + +void editor_mode::infra_attach(EditorSnapshot &Snapshot) +{ + auto const involved = [&](infra::object_state const &State) { + if (State.moved) + return true; + // one the editor bound for the change which didn't move: its own changes, if any, are taken back by the tool which made them + if (State.saved.adopted) + return false; + for (auto const &anchor : State.saved.anchors) + { + if (contains(Snapshot.created, anchor.at.track) || contains(Snapshot.removed, anchor.at.track)) + return true; + for (auto const &entry : Snapshot.tracks) + if (entry.first == anchor.at.track) + return true; + } + return false; + }; + for (auto &entry : m_infra_buffer) + if (involved(entry)) + Snapshot.infra.push_back(std::move(entry)); + m_infra_buffer.clear(); +} + +void editor_mode::render_infra_body() +{ + auto &state{m_infra}; + infra_load(); + Live.refresh(); + + auto follow{state.follow}; + if (ImGui::Checkbox(STR_C("Bound objects follow the changes of the track"), &follow)) + { + state.follow = follow; + if (follow) + infra_rebase(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Bound objects keep their chainage along the path, the offset from its axis and the height above the rail top;\n" + "models and includes turn with the path and stay upright. The move is a part of the undo step of the change.")); + ImGui::SameLine(); + ImGui::Checkbox(STR_C("Show in 3D"), &state.show); + ImGui::Text(STR_C("Objects bound in the scenery: %d"), infra_bound_count()); + if (false == m_bindings_unresolved.empty()) + { + ImGui::SameLine(); + ImGui::TextColored(ImVec4(1.f, 0.8f, 0.3f, 1.f), STR_C("(%d stored binding(s) not found, kept as they are)"), static_cast(m_bindings_unresolved.size())); + } + + ImGui::Separator(); + render_infra_search(); + render_infra_candidates(); + render_infra_bound(); + if (false == state.error.empty()) + ImGui::TextColored(ImVec4(1.f, 0.4f, 0.35f, 1.f), "%s", state.error.c_str()); + else if (false == state.status.empty()) + ImGui::TextWrapped("%s", state.status.c_str()); +} + +// what changed while the bindings did not follow the track becomes their new starting point +void editor_mode::infra_rebase() +{ + for (auto &binding : m_bindings) + { + std::vector points; + std::optional yaw; + if (false == alive(binding) || false == object_points(binding, points, yaw) || points.size() != binding.anchors.size()) + continue; + for (std::size_t i = 0; i < points.size(); ++i) + { + auto &anchor{binding.anchors[i]}; + if (anchor.at.track == nullptr || anchor.at.track->m_editorremoved || anchor.at.path >= static_cast(anchor.at.track->m_paths.size())) + { + binding.lost = true; + continue; + } + anchor = infra::make_anchor(anchor.at.track, anchor.at.path, points[i]); + } + if (binding.turns && yaw.has_value()) + binding.yaw = turn_of(binding, *yaw); + } +} + +void editor_mode::render_infra_search() +{ + auto &state{m_infra}; + char const *const scopes[] = {STR_C("Selected path"), STR_C("Line through the selected path"), STR_C("Route of the vertical profile"), STR_C("Whole scenery")}; + ImGui::SetNextItemWidth(260.f); + ImGui::Combo(STR_C("Look along"), &state.scope, scopes, IM_ARRAYSIZE(scopes)); + if (ImGui::TreeNode(STR_C("More settings"))) + { + if (state.scope == 1) + { + ImGui::SetNextItemWidth(120.f); + ImGui::InputFloat(STR_C("Reach each way, m"), &state.reach, 100.f, 500.f, "%.0f"); + state.reach = std::clamp(state.reach, 10.f, 20000.f); + } + ImGui::SetNextItemWidth(120.f); + ImGui::InputFloat(STR_C("Corridor each side of the axis, m"), &state.corridor, 0.5f, 2.f, "%.1f"); + state.corridor = std::clamp(state.corridor, 0.5f, 50.f); + if (ImGui::TreeNode(STR_C("Rules for names of the files"))) + { + ImGui::TextDisabled("%s", STR_C("Parts of the names, separated by spaces; the first rule which matches decides")); + for (std::size_t i = 0; i < state.rules.size(); ++i) + { + auto &rule{state.rules[i]}; + char buffer[512]; + std::snprintf(buffer, sizeof(buffer), "%s", rule.keywords.c_str()); + ImGui::SetNextItemWidth(360.f); + if (ImGui::InputText((std::string{STR_C(infra::name(rule.group))} + "##rule" + std::to_string(i)).c_str(), buffer, sizeof(buffer))) + rule.keywords = buffer; + } + if (ImGui::SmallButton(STR_C("Default rules"))) + state.rules = infra::default_rules(); + ImGui::TextDisabled("%s", STR_C("Includes are matched by the template name and its //$e description, models by the file and node name;\n" + "traction is always the catenary, memory cells and event launchers the logic")); + ImGui::TreePop(); + } + ImGui::TreePop(); + } + if (ImGui::Button(STR_C("Find objects"))) + infra_recognize(); + +} + +void editor_mode::render_infra_candidates() +{ + auto &state{m_infra}; + auto &candidates{state.candidates}; + ImVec4 const readcolour{0.45f, 0.85f, 1.f, 1.f}; + ImVec4 const warncolour{1.f, 0.75f, 0.3f, 1.f}; + auto const shown = [&](infra_candidate const &Candidate) { + switch (state.filter) + { + case 1: return Candidate.reader != nullptr; + case 2: return Candidate.nearer != nullptr; + case 3: return Candidate.unread; + default: return true; + } + }; + auto const choose = [&](std::optional const Group, bool const Chosen) { + for (auto &candidate : candidates) + if ((false == Group.has_value() || candidate.binding.group == *Group) && shown(candidate)) + candidate.chosen = Chosen && false == candidate.bound; + }; + state.hovered = -1; + if (candidates.empty()) + return; + int chosen{0}; + for (auto const &candidate : candidates) + chosen += candidate.chosen ? 1 : 0; + ImGui::SameLine(); + if (ImGui::Button(format(STR_C("Bind the chosen (%d)"), chosen).c_str())) + infra_bind_chosen(); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("All"))) + choose({}, true); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("None"))) + choose({}, false); + + if (state.read > 0 || state.unread > 0) + { + std::string const labels[]{format("%s (%d)", STR_C("All"), static_cast(candidates.size())), format("%s (%d)", STR_C("Read by a path"), state.read), + format("%s (%d)", STR_C("Nearer to another path"), state.overruled), format("%s (%d)", STR_C("Not read"), state.unread)}; + choice_chips("infrafilter", state.filter, + {{0, labels[0].c_str()}, + {1, labels[1].c_str(), + "The memory cell of the object is read by a getvalues event of a path, listed by the path, inside a multiple\n" + "event or written loose as :event. The object is bound to the thread of that path, not to the nearest one"}, + {2, labels[2].c_str(), "By the distance alone these would go to the wrong thread. Check them in 3D: the dashed line goes to the nearer path"}, + {3, labels[3].c_str(), "The signal has a memory cell, but no event of a path reads it: the vehicles won't see it.\nBound to the nearest path"}}); + } + + ImGui::BeginChild("##infracandidates", ImVec2(0.f, 260.f), true); + std::vector rows; + for (auto const group : infra::categories()) + { + rows.clear(); + for (int i = 0; i < static_cast(candidates.size()); ++i) + if (candidates[i].binding.group == group && shown(candidates[i])) + rows.push_back(i); + if (rows.empty()) + continue; + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(colour(group))); + auto const open{ImGui::TreeNodeEx(format("%s (%d)", STR_C(infra::name(group)), static_cast(rows.size())).c_str(), group == infra::category::other || group == infra::category::environment ? 0 : ImGuiTreeNodeFlags_DefaultOpen)}; + ImGui::PopStyleColor(); + ImGui::SameLine(); + if (ImGui::SmallButton((std::string{STR_C("all##g")} + infra::name(group)).c_str())) + choose(group, true); + ImGui::SameLine(); + if (ImGui::SmallButton((std::string{STR_C("none##g")} + infra::name(group)).c_str())) + choose(group, false); + if (false == open) + continue; + ImGuiListClipper clipper; + clipper.Begin(static_cast(rows.size())); + while (clipper.Step()) + { + for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; ++row) + { + auto const i{rows[row]}; + auto &candidate{candidates[i]}; + auto const &anchor{candidate.binding.anchors.front()}; + ImGui::PushID(i); + if (candidate.bound) + ImGui::TextDisabled(STR_C("[bound]")); + else + ImGui::Checkbox("##chosen", &candidate.chosen); + ImGui::SameLine(); + if (ImGui::Selectable(candidate.binding.label.c_str(), false, ImGuiSelectableFlags_None, ImVec2(ImGui::CalcTextSize(candidate.binding.label.c_str()).x, 0.f)) && anchor.at.track != nullptr) + focus_track(*anchor.at.track, anchor.at.path, anchor.foot); + if (ImGui::IsItemHovered()) + { + state.hovered = i; + std::string text{format(STR_C("%s, %s\n%.2f m %s of the axis, %.2f m above the rail top\n%s"), infra::name(candidate.binding.type), anchor.at.track != nullptr ? anchor.at.track->name().c_str() : "-", std::abs(candidate.offset), + candidate.offset >= 0.0 ? STR_C("on the right") : STR_C("on the left"), anchor.height, candidate.reason.c_str())}; + if (candidate.reader != nullptr) + text += format(STR_C("\nRead by the path %s: event %s, getvalues of the memory cell %s"), candidate.reader->name().c_str(), candidate.event.c_str(), candidate.cell.c_str()) + + (candidate.loose ? STR(" (written loose, the path takes it by the name)") : std::string{}); + if (candidate.nearer != nullptr) + text += format(STR_C("\nThe path %s is nearer, but it doesn't read the object"), candidate.nearer->name().c_str()); + if (candidate.unread) + text += STR("\nNo path reads the memory cell of the signal"); + text += STR("\nClick to look at it"); + ImGui::SetTooltip("%s", text.c_str()); + } + ImGui::SameLine(); + ImGui::TextDisabled("%s %+.1f m", infra::name(candidate.binding.type), candidate.offset); + if (candidate.reader != nullptr) + { + ImGui::SameLine(); + ImGui::TextColored(readcolour, STR_C("read by %s"), candidate.reader->name().c_str()); + } + if (candidate.nearer != nullptr) + { + ImGui::SameLine(); + ImGui::TextColored(warncolour, STR_C("(nearer: %s)"), candidate.nearer->name().c_str()); + } + if (candidate.unread) + { + ImGui::SameLine(); + ImGui::TextColored(warncolour, "%s", STR_C("not read")); + } + ImGui::PopID(); + } + } + ImGui::TreePop(); + } + ImGui::EndChild(); +} + +void editor_mode::render_infra_bound() +{ + if (ImGui::TreeNode(STR_C("Bound objects along the scope"))) + { + auto const scope{infra_scope()}; + std::unordered_set const tracks(scope.begin(), scope.end()); + std::vector along; + for (std::size_t i = 0; i < m_bindings.size(); ++i) + if (false == m_bindings[i].adopted && std::any_of(m_bindings[i].anchors.begin(), m_bindings[i].anchors.end(), [&](infra::anchor const &Anchor) { return tracks.count(Anchor.at.track) > 0; })) + along.push_back(i); + ImGui::Text(STR_C("%d of %d"), static_cast(along.size()), infra_bound_count()); + if (false == along.empty()) + { + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Unbind all of these"))) + { + infra_unbind(along); + along.clear(); + } + } + std::optional unbind; + ImGui::BeginChild("##infrabound", ImVec2(0.f, 160.f), true); + ImGuiListClipper clipper; + clipper.Begin(static_cast(along.size())); + while (clipper.Step()) + { + for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; ++row) + { + auto const index{along[row]}; + auto const &binding{m_bindings[index]}; + ImGui::PushID(static_cast(index)); + if (ImGui::SmallButton(STR_C("unbind"))) + unbind = index; + ImGui::SameLine(); + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(binding.lost ? IM_COL32(255, 80, 70, 255) : colour(binding.group))); + ImGui::Text("%s%s", binding.label.c_str(), binding.lost ? STR_C(" (no path to follow)") : ""); + ImGui::PopStyleColor(); + ImGui::PopID(); + } + } + ImGui::EndChild(); + if (unbind) + infra_unbind({*unbind}); + ImGui::TreePop(); + } +} + +void editor_mode::draw_infra_overlay() const +{ + auto const &state{m_infra}; + if (false == state.open || false == state.show) + return; + Live.refresh(); + screen_projection const projection; + ImDrawList *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const camera{GfxRenderer->Camera_Position()}; + auto const draw = [&](infra::binding const &Binding, ImU32 const Colour, float const Size) { + if (Binding.anchors.empty() || glm::distance(Binding.anchors.front().foot, camera) > 2000.0) + return; + std::vector points; + std::optional yaw; + if (false == alive(Binding) || false == object_points(Binding, points, yaw)) + return; + for (std::size_t i = 0; i < points.size() && i < Binding.anchors.size(); ++i) + { + auto anchor{Binding.anchors[i]}; + auto const foot{infra::frame_at(anchor.at).point}; + projection.line(drawlist, foot, points[i], Colour, 1.5f); + } + ImVec2 screen; + if (projection.project(points.front(), screen)) + drawlist->AddCircleFilled(screen, Size, Colour); + }; + for (auto const &binding : m_bindings) + if (false == binding.adopted) + draw(binding, binding.lost ? overlay_color::invalid : IM_COL32(90, 230, 110, 220), 3.5f); + auto const object = [&](infra_candidate const &Candidate) { + std::vector points; + std::optional yaw; + return object_points(Candidate.binding, points, yaw) ? points.front() : Candidate.binding.anchors.front().foot; + }; + auto const dashed = [&](glm::dvec3 const &From, glm::dvec3 const &To, ImU32 const Colour) { + auto const steps{std::clamp(static_cast(glm::distance(From, To) / 0.5), 2, 40)}; + for (int k = 0; k < steps; k += 2) + projection.line(drawlist, glm::mix(From, To, static_cast(k) / steps), glm::mix(From, To, static_cast(k + 1) / steps), Colour, 2.f); + }; + for (int i = 0; i < static_cast(state.candidates.size()); ++i) + { + auto const &candidate{state.candidates[i]}; + if (candidate.nearer != nullptr && alive(candidate.binding) && glm::distance(candidate.nearer_foot, camera) <= 2000.0) + { + auto const point{object(candidate)}; + ImVec2 screen; + if (projection.project(point, screen)) + drawlist->AddCircle(screen, i == state.hovered ? 13.f : 8.f, IM_COL32(255, 190, 70, 230), 16, 2.f); + if (i == state.hovered) + dashed(point, candidate.nearer_foot, IM_COL32(255, 190, 70, 230)); + } + if (candidate.bound) + continue; + draw(candidate.binding, colour(candidate.binding.group, candidate.chosen ? 255 : 110), i == state.hovered ? 9.f : (candidate.chosen ? 5.f : 3.f)); + } + if (state.hovered >= 0 && state.hovered < static_cast(state.candidates.size())) + { + auto const &candidate{state.candidates[state.hovered]}; + auto const outline = [&](TTrack const *Track, ImU32 const Colour, float const Width) { + if (Track == nullptr || Track->m_editorremoved) + return; + for (auto const &path : Track->m_paths) + { + bezier const curve{path}; + auto const count{std::clamp(static_cast(curve.plan_length() / 3.0), 6, 64)}; + auto previous{curve.point(0.0)}; + for (int k = 1; k <= count; ++k) + { + auto const next{curve.point(static_cast(k) / count)}; + projection.line(drawlist, previous, next, Colour, Width); + previous = next; + } + } + }; + outline(candidate.binding.anchors.front().at.track, IM_COL32(255, 255, 255, 200), 3.f); + if (candidate.reader != candidate.binding.anchors.front().at.track) + outline(candidate.reader, IM_COL32(110, 215, 255, 220), 3.f); + } +} diff --git a/application/editormodejoints.cpp b/application/editormodejoints.cpp new file mode 100644 index 000000000..12c1e4357 --- /dev/null +++ b/application/editormodejoints.cpp @@ -0,0 +1,837 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormodejoints.h" +#include "editor/editorNmt.hpp" +#include "application/editormodeshared.h" +#include "application/editorprojection.h" +#include "editor/editorFormat.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorProfile.hpp" + +#include "scene/scene.h" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "world/Track.h" + +#include "imgui/imgui.h" +#include "utilities/translation.h" +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using geometry::grade_of; +using geometry::plan_of; + +double const kLinked{0.02}; // m, ends this close are joined by the simulation +double const kOverlayRange{3000.0}; +double const kGauge{1.5}; // m between the rails, for the cant +int const kRailCategory{1}; +double const kModelStep{5.0}; // m between the places of the tracks compared with the terrain model +std::size_t const kModelRun{200}; // places of a path whose model is asked for at once +double const kModelPoll{0.25}; // s between the looks whether the model is in +double const kUnfitted{30.0}; // m; a scenery whose tracks lie this far from the model as a whole isn't fitted to it +// a track over the model by more than the depth goes on a bridge or a viaduct the model leaves out where the model falls away by +// the abutments, steeper than the banks, within the reach along the track both ways; as the grade lines fitted to the model +// tell them. By the abutments the track is over the model by less +double const kBridgeDepth{1.0}; // m +double const kAbutment{100.0}; // per mille +double const kBridgeReach{200.0}; // m + +using kind = joints_tool::joint_issue::kind; + +bool rail(TTrack const &Track) +{ + return (Track.iCategoryFlag & 15) == kRailCategory && false == Track.m_editorremoved && editor_track::is_supported(Track); +} + +bool at_start(editor_track::point_ref const &Point) +{ + return Point.kind == editor_track::point_kind::start; +} + +// direction of the path at its end, into the path +glm::dvec3 into(TTrack const &Track, editor_track::point_ref const &Point) +{ + auto const &path{Track.m_paths[Point.path]}; + bool const start{at_start(Point)}; + auto const &point{path.points[start ? segment_data::point::start : segment_data::point::end]}; + auto const &control{path.points[start ? segment_data::point::control1 : segment_data::point::control2]}; + glm::dvec3 const direction{control != glm::dvec3{} ? control : path.points[start ? segment_data::point::end : segment_data::point::start] - point}; + return glm::length(direction) > 1e-9 ? glm::normalize(direction) : glm::dvec3{0.0, 0.0, 1.0}; +} + +// roll of the path at its end, for the travel into the path, in degrees +double roll_into(TTrack const &Track, editor_track::point_ref const &Point) +{ + auto const &path{Track.m_paths[Point.path]}; + return at_start(Point) ? path.rolls[0] : -path.rolls[1]; +} + +double plan_angle(glm::dvec3 const &A, glm::dvec3 const &B) +{ + auto const a{plan_of(A)}; + auto const b{plan_of(B)}; + if (glm::length(a) < 1e-9 || glm::length(b) < 1e-9) + return 0.0; + return glm::degrees(std::acos(std::clamp(glm::dot(glm::normalize(a), glm::normalize(b)), -1.0, 1.0))); +} + +std::tuple key_of(TTrack const *Track, editor_track::point_ref const &Point) +{ + return {Track, Point.path, static_cast(Point.kind)}; +} + +char const *kind_name(kind const Kind) +{ + switch (Kind) + { + case kind::gap: return "gap"; + case kind::step: return "step"; + case kind::kink: return "kink"; + case kind::cant: return "cant jump"; + case kind::grade: return "grade break"; + case kind::model: return "off the terrain model"; + default: return "free end"; + } +} + +std::string value_text(joints_tool::joint_issue const &Issue) +{ + switch (Issue.type) + { + case kind::gap: return format("%.3f m", Issue.value); + case kind::step: return format("%.1f mm", Issue.value * 1000.0); + case kind::kink: return format("%.3f\xc2\xb0", Issue.value); + case kind::cant: return format("%.1f mm", Issue.value); + case kind::grade: return format("%.1f \xe2\x80\xb0", Issue.value); + case kind::model: return format("%+.2f m", Issue.value); + default: return "-"; + } +} + +ImU32 kind_colour(kind const Kind) +{ + switch (Kind) + { + case kind::gap: return IM_COL32(255, 70, 60, 235); + case kind::step: return IM_COL32(255, 140, 50, 230); + case kind::kink: return IM_COL32(255, 190, 60, 225); + case kind::cant: return IM_COL32(200, 120, 255, 225); + case kind::grade: return IM_COL32(90, 200, 255, 220); + case kind::model: return IM_COL32(70, 200, 190, 235); + default: return IM_COL32(200, 200, 200, 200); + } +} + +std::string label_of(TTrack const *Track) +{ + return Track == nullptr ? std::string{"-"} : ::name_of(*Track); +} + +} // namespace + +void joints_tool::joints_start() +{ + auto &state{m_joints}; + state.queue.clear(); + state.next = 0; + state.issues.clear(); + state.selected = -1; + state.status.clear(); + m_reported.clear(); + glm::dvec3 const camera{Global.pCamera.Pos}; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || false == rail(*track)) + continue; + if (state.scope == 0 && glm::distance(track->location(), camera) > state.reach) + continue; + state.queue.push_back(track); + } + state.history = m_history.history_revision(); + state.places.clear(); + state.runs.clear(); + state.run_next = 0; + state.model_waiting = false; + state.model_asked = false; + state.model_polled = 0.0; + state.model_unplaced = false; + if (false == state.model_check || state.queue.empty()) + return; + m_ground.nmt_locate(); + if (false == m_ground.terrain_model().placed()) + { + state.model_unplaced = true; + return; + } + std::set const queued(state.queue.begin(), state.queue.end()); + for (auto const &place : m_ground.nmt_track_places(kModelStep)) + if (place.shapes && queued.count(place.track) > 0) + { + if (state.places.empty() || state.places.back().track != place.track || state.places.back().path != place.path || state.places.size() - state.runs.back().first >= kModelRun) + state.runs.emplace_back(state.places.size(), state.places.size()); + state.places.push_back(place); + state.runs.back().second = state.places.size(); + } + state.model_waiting = false == state.places.empty(); +} + +bool joints_tool::joints_model() +{ + auto &state{m_joints}; + auto const now{ImGui::GetTime()}; + if (state.model_asked && now - state.model_polled < kModelPoll) + return false; + state.model_polled = now; + auto const box = [&](std::pair const &Run, glm::dvec2 &Min, glm::dvec2 &Max) { + Min = glm::dvec2{std::numeric_limits::max()}; + Max = glm::dvec2{std::numeric_limits::lowest()}; + for (auto i = Run.first; i < Run.second; ++i) + { + glm::dvec2 const at{state.places[i].position.x, state.places[i].position.z}; + Min = glm::min(Min, at - kBridgeReach); + Max = glm::max(Max, at + kBridgeReach); + } + }; + glm::dvec2 low, high; + // all of it asked for once, then the runs looked over in turn as their squares come + if (false == state.model_asked) + { + for (auto const &run : state.runs) + { + box(run, low, high); + m_ground.terrain_model().request(low, high); + } + state.model_asked = true; + } + while (state.run_next < state.runs.size()) + { + box(state.runs[state.run_next], low, high); + if (false == m_ground.terrain_model().request(low, high)) + return false; + ++state.run_next; + } + std::vector differences(state.places.size(), std::numeric_limits::quiet_NaN()); + std::vector known; + for (std::size_t i = 0; i < state.places.size(); ++i) + if (double height; m_ground.terrain_model().height(state.places[i].position.x, state.places[i].position.z, height)) + { + differences[i] = state.places[i].crown - (height + m_ground.terrain_model_offset()); + known.push_back(differences[i]); + } + auto shift{0.0}; + if (false == m_ground.terrain_model_fitted() && false == known.empty()) + { + std::nth_element(known.begin(), known.begin() + known.size() / 2, known.end()); + if (std::abs(known[known.size() / 2]) > kUnfitted) + shift = known[known.size() / 2]; + } + // a place on a bridge or a viaduct the model leaves out isn't off it: the route through its track sampled both ways, the + // stretches over the model as on a bridge found along it + std::map, std::vector>> routes; + auto const on_bridge = [&](nmt_place const &Place) { + auto found{routes.find(Place.track)}; + if (found == routes.end()) + { + auto route{editor_track::run_route(*Place.track, kBridgeReach)}; + auto samples{editor_track::sample_route(route, 1.0)}; + std::vector chainages, heights, ground; + for (auto const &sample : samples) + { + chainages.push_back(sample.chainage); + heights.push_back(sample.position.y - route.spans[sample.span].track->rail_height()); + double height; + ground.push_back(m_ground.terrain_model().height(sample.position.x, sample.position.z, height) ? height + m_ground.terrain_model_offset() + shift : std::numeric_limits::quiet_NaN()); + } + auto spans{profile::bridged(chainages, heights, ground, kBridgeDepth, kAbutment)}; + found = routes.emplace(Place.track, std::make_pair(std::move(samples), std::move(spans))).first; + } + auto const &[samples, spans]{found->second}; + auto nearest{std::numeric_limits::max()}; + double at{0.0}; + for (auto const &sample : samples) + if (auto const distance{geometry::plan_distance(sample.position, Place.position)}; distance < nearest) + { + nearest = distance; + at = sample.chainage; + } + return nearest <= 1.0 && std::any_of(spans.begin(), spans.end(), [&](profile::departure const &Span) { return at >= Span.from - kModelStep && at <= Span.to + kModelStep; }); + }; + // the place of each path the farthest from the model + std::map, std::size_t> worst; + for (std::size_t i = 0; i < state.places.size(); ++i) + { + if (false == std::isfinite(differences[i])) + continue; + differences[i] -= shift; + if (std::abs(differences[i]) <= state.model || (differences[i] > 0.0 && on_bridge(state.places[i]))) + continue; + auto const key{std::make_pair(state.places[i].track, state.places[i].path)}; + auto const found{worst.find(key)}; + if (found == worst.end()) + worst.emplace(key, i); + else if (std::abs(differences[i]) > std::abs(differences[found->second])) + found->second = i; + } + for (auto const &entry : worst) + { + auto const &place{state.places[entry.second]}; + joint_issue issue; + issue.type = kind::model; + issue.track = place.track; + issue.point = {place.path, editor_track::point_kind::start}; + issue.position = place.position; + issue.value = differences[entry.second]; + state.issues.push_back(issue); + } + state.places.clear(); + state.runs.clear(); + state.model_waiting = false; + return true; +} + +void joints_tool::joints_check(TTrack &Track, std::vector &Issues, std::set> &Seen, bool const Open) const +{ + auto const &state{m_joints}; + auto const once = [&](end_key const &A, end_key const &B) { return Seen.insert(A < B ? std::make_pair(A, B) : std::make_pair(B, A)).second; }; + for (int i = 0; i < static_cast(Track.m_paths.size()); ++i) + { + for (auto const kind_of_end : {editor_track::point_kind::start, editor_track::point_kind::end}) + { + editor_track::point_ref const point{i, kind_of_end}; + auto const position{editor_track::point_position(Track, point)}; + auto const connections{editor_track::connected_points(Track, position)}; + if (connections.empty()) + { + joint_issue nearest; + nearest.value = std::numeric_limits::max(); + for (auto *section : simulation::Region->sections(position, static_cast(state.gap))) + for (auto const &cell : section->m_cells) + for (auto *other : cell.m_directories.paths) + { + if (other == nullptr || other == &Track || false == rail(*other)) + continue; + for (int k = 0; k < static_cast(other->m_paths.size()); ++k) + for (auto const theirkind : {editor_track::point_kind::start, editor_track::point_kind::end}) + { + editor_track::point_ref const theirs{k, theirkind}; + auto const distance{glm::distance(position, editor_track::point_position(*other, theirs))}; + if (distance > state.gap || distance >= nearest.value) + continue; + nearest.track = &Track; + nearest.point = point; + nearest.other = other; + nearest.theirs = theirs; + nearest.value = distance; + } + } + if (nearest.other != nullptr) + { + if (once(key_of(&Track, point), key_of(nearest.other, nearest.theirs))) + { + nearest.type = kind::gap; + nearest.position = position; + Issues.push_back(nearest); + } + } + else if (Open) + { + joint_issue open; + open.type = kind::open; + open.track = &Track; + open.point = point; + open.position = position; + Issues.push_back(open); + } + continue; + } + for (auto const &connection : connections) + { + auto *other{connection.first}; + auto const &theirs{connection.second}; + if (false == rail(*other) || false == once(key_of(&Track, point), key_of(other, theirs))) + continue; + joint_issue issue; + issue.track = &Track; + issue.point = point; + issue.other = other; + issue.theirs = theirs; + issue.position = position; + auto const step{glm::distance(position, editor_track::point_position(*other, theirs))}; + auto const ours{into(Track, point)}; + auto const their{into(*other, theirs)}; + auto const angle{plan_angle(ours, -their)}; + auto const cant{kGauge * 1000.0 * std::abs(std::sin(glm::radians(roll_into(Track, point) + roll_into(*other, theirs))))}; + auto const grade{std::abs(grade_of(ours) + grade_of(their)) * 1000.0}; + auto const add = [&](kind const Kind, double const Value) { + issue.type = Kind; + issue.value = Value; + Issues.push_back(issue); + }; + if (step > state.step) + add(kind::step, step); + if (angle > state.angle) + add(kind::kink, angle); + if (cant > state.cant) + add(kind::cant, cant); + if (grade > state.grade) + add(kind::grade, grade); + } + } + } +} + +void joints_tool::tracks_committed(std::vector const &Tracks) +{ + for (auto *track : Tracks) + if (track != nullptr) + m_live.pending.insert(track); +} + +void joints_tool::live_update() +{ + auto &live{m_live}; + auto const gone = [](TTrack const *Track) { return Track != nullptr && Track->m_editorremoved; }; + std::erase_if(live.issues, [&](joint_issue const &Issue) { return gone(Issue.track) || gone(Issue.other); }); + if (live.pending.empty() || ImGui::IsMouseDown(ImGuiMouseButton_Left) || ImGui::IsMouseDown(ImGuiMouseButton_Right)) + return; + // the joints of a track changed are looked at again, from its side and from the side of the tracks it joins + std::set checked; + for (auto *track : live.pending) + { + if (track->m_editorremoved || false == rail(*track)) + continue; + checked.insert(track); + for (auto const &path : track->m_paths) + for (auto const index : {segment_data::point::start, segment_data::point::end}) + for (auto const &connection : editor_track::connected_points(*track, path.points[index])) + if (rail(*connection.first)) + checked.insert(connection.first); + } + live.pending.clear(); + std::erase_if(live.issues, [&](joint_issue const &Issue) { return checked.contains(Issue.track) || checked.contains(Issue.other); }); + std::set> seen; + for (auto *track : checked) + joints_check(*track, live.issues, seen, false); +} + +void joints_tool::update() +{ + auto &state{m_joints}; + live_update(); + if (state.next >= state.queue.size() && false == state.model_waiting) + return; + auto const deadline{std::chrono::steady_clock::now() + std::chrono::milliseconds(15)}; + while (state.next < state.queue.size() && std::chrono::steady_clock::now() < deadline) + { + auto *track{state.queue[state.next++]}; + if (track->m_editorremoved) + continue; + joints_check(*track, state.issues, m_reported, state.free_ends); + } + if (state.next < state.queue.size()) + return; + if (state.model_waiting && false == joints_model()) + return; + std::stable_sort(state.issues.begin(), state.issues.end(), [](joint_issue const &A, joint_issue const &B) { + if (A.type != B.type) + return A.type < B.type; + return std::abs(A.value) > std::abs(B.value); + }); + std::array counts{}; + for (auto const &issue : state.issues) + ++counts[static_cast(issue.type)]; + state.status = format(STR_C("%zu paths checked: %d gaps, %d steps, %d kinks, %d cant jumps, %d grade breaks"), state.queue.size(), counts[0], counts[1], counts[2], counts[3], counts[4]); + if (state.model_check && state.model_unplaced) + state.status += STR_C(", the terrain model left out: the scenery isn't placed on the map (the orthophoto settings)"); + else if (state.model_check) + state.status += format(STR_C(", %d paths off the terrain model"), counts[5]); + if (state.free_ends) + state.status += format(STR_C(", %d free ends"), counts[6]); + WriteLog("Editor: joints check - " + state.status, logtype::generic); +} + +void joints_tool::joints_focus(int const Index) +{ + auto &state{m_joints}; + if (Index < 0 || Index >= static_cast(state.issues.size())) + return; + state.selected = Index; + auto const &issue{state.issues[Index]}; + auto const &paths{simulation::Paths.sequence()}; + if (std::find(paths.begin(), paths.end(), issue.track) == paths.end() || issue.track->m_editorremoved) + return; + m_selection.set_current_node(issue.track); + m_selection.clear_track_point(); + m_view.focus_track(*issue.track, issue.point.path, issue.position); +} + +bool joints_tool::joint_fix(joint_issue &Issue, std::vector> &States, std::vector &Changed) +{ + if (Issue.fixed || Issue.type == kind::open || Issue.type == kind::model || Issue.track == nullptr || Issue.other == nullptr || Issue.track->m_editorremoved || Issue.other->m_editorremoved) + return false; + auto const movable = [](TTrack const *Track) { + std::string reason; + return Track->eType == tt_Normal && editor_track::can_edit_geometry(*Track, reason) && scene::Layers.editable(Track); + }; + TTrack *mover{nullptr}; + editor_track::point_ref moved; + TTrack *fixed{nullptr}; + editor_track::point_ref held; + if (movable(Issue.track)) + { + mover = 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; + moved = Issue.theirs; + fixed = Issue.track; + held = Issue.point; + } + if (mover == 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); + editor_track::snap_target target; + target.track = fixed; + target.point = held; + target.position = editor_track::point_position(*fixed, held); + target.direction = into(*fixed, held); + switch (Issue.type) + { + case kind::gap: + case kind::kink: + case kind::grade: + editor_track::snap_point(*mover, moved, target, true); + break; + case kind::step: + editor_track::snap_point(*mover, moved, target, false); + break; + case kind::cant: + { + auto &path{mover->m_paths[moved.path]}; + auto const roll{static_cast(roll_into(*fixed, held))}; + if (at_start(moved)) + path.rolls[0] = -roll; + else + path.rolls[1] = roll; + break; + } + default: + break; + } + Issue.fixed = true; + return true; +} + +void joints_tool::joints_fix(std::vector const &Indices) +{ + auto &state{m_joints}; + std::vector> states; + std::vector changed; + std::vector chosen; + for (auto const index : Indices) + if (index >= 0 && index < static_cast(state.issues.size())) + chosen.push_back(&state.issues[index]); + std::size_t count{0}; + for (auto *issue : chosen) + if (joint_fix(*issue, states, changed)) + ++count; + if (count == 0) + { + state.status = STR_C("Nothing could be fixed: the paths are switches or in the files which can't be changed"); + return; + } + m_history.push_track_snapshot(std::move(states)); + editor_track::commit(changed); + for (auto *track : changed) + track->mark_dirty(); + state.history = m_history.history_revision(); + state.status = format(STR_C("%zu joints fixed, Ctrl+Z takes them back"), count); + WriteLog("Editor: joints check - " + state.status, logtype::generic); +} + +void joints_tool::render_options() +{ + auto &state{m_joints}; + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("Looks for faults at the joints of the tracks")); + ImGui::PopTextWrapPos(); + segmented("jointscope", state.scope, {{0, STR_C("Around the camera")}, {1, STR_C("Whole scenery")}}); + bool const running{state.next < state.queue.size() || state.model_waiting}; + if (running) + { + if (state.next < state.queue.size()) + { + auto const progress{static_cast(state.next) / static_cast(state.queue.size())}; + ImGui::ProgressBar(progress, ImVec2(-70.0f, 0.0f), format(STR_C("Checking %zu / %zu"), state.next, state.queue.size()).c_str()); + } + else + { + auto const progress{static_cast(state.run_next) / static_cast(std::max(1, state.runs.size()))}; + ImGui::ProgressBar(progress, ImVec2(-70.0f, 0.0f), format(STR_C("Terrain model %zu / %zu"), state.run_next, state.runs.size()).c_str()); + } + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Cancel"))) + { + state.queue.resize(state.next); + state.model_waiting = false; + } + } + else + { + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::ColorConvertU32ToFloat4(family_colour(2, 0.55f))); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImGui::ColorConvertU32ToFloat4(family_colour(2, 0.75f))); + if (ImGui::Button(STR_C("Check"), ImVec2(-1.0f, tall_button_height()))) + joints_start(); + ImGui::PopStyleColor(2); + item_tooltip("Finds the gaps between the ends of the tracks, the steps, the kinks and the jumps of the cant and of the grade"); + } + if (ImGui::TreeNode(STR_C("Thresholds"))) + { + if (begin_fields("##jointlimits", 0.55f)) + { + auto const limit = [](char const *Label, char const *Id, double &Value, char const *Format) { + field_row(Label); + ImGui::InputDouble(Id, &Value, 0.0, 0.0, Format); + }; + if (state.scope == 0) + limit("Around the camera (m)", "##jointreach", state.reach, "%.0f"); + limit("Gap up to (m)", "##jointgap", state.gap, "%.2f"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("A free end closer than this to the end of another path is a gap: the trains don't go across it.\nThe simulation joins the ends no more than 2 cm apart")); + limit("Step (m)", "##jointstep", state.step, "%.3f"); + limit("Kink (deg)", "##jointkink", state.angle, "%.2f"); + limit("Cant jump (mm)", "##jointcant", state.cant, "%.1f"); + limit("Grade break (per mille)", "##jointgrade", state.grade, "%.1f"); + limit("Off the terrain model (m)", "##jointmodel", state.model, "%.2f"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The track lies higher or lower than the terrain model (NMT) says the ground is, by more than this.\nEach path is listed once, at its place the farthest off; bridges and tunnels are left out")); + ImGui::EndTable(); + } + toggle_chips("jointflags", {{STR_C("Free ends too"), &state.free_ends}, {STR_C("Against the terrain model"), &state.model_check}}); + state.reach = std::clamp(state.reach, 50.0, 50000.0); + state.gap = std::clamp(state.gap, 0.03, 20.0); + state.step = std::max(0.001, state.step); + state.angle = std::max(0.01, state.angle); + state.cant = std::max(0.5, state.cant); + state.grade = std::max(0.5, state.grade); + state.model = std::max(0.05, state.model); + ImGui::TextDisabled("%s", STR_C("Change the thresholds, then Check again")); + ImGui::TreePop(); + } + if (false == state.status.empty()) + ImGui::TextWrapped("%s", state.status.c_str()); + if (state.issues.empty()) + return; + if (state.history != m_history.history_revision()) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), "%s", STR_C("The scenery changed since the check")); + int filter{state.filter + 1}; + ImGui::SetNextItemWidth(150.0f); + auto const filters{std::string{STR_C("All")} + '\0' + STR_C("gap") + '\0' + STR_C("step") + '\0' + STR_C("kink") + '\0' + STR_C("cant jump") + '\0' + STR_C("grade break") + '\0' + STR_C("off the terrain model") + '\0' + + STR_C("free end") + '\0' + '\0'}; + if (ImGui::Combo("##jointfilter", &filter, filters.c_str())) + state.filter = filter - 1; + std::vector listed; + std::vector fixable; + for (int i = 0; i < static_cast(state.issues.size()); ++i) + { + auto const &issue{state.issues[i]}; + if (state.filter >= 0 && static_cast(issue.type) != state.filter) + continue; + listed.push_back(i); + if (false == issue.fixed && issue.type != kind::open && issue.type != kind::model) + fixable.push_back(i); + } + if (false == fixable.empty()) + { + ImGui::SameLine(); + if (ImGui::Button(format(STR_C("Fix %zu listed"), fixable.size()).c_str())) + joints_fix(fixable); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Gaps: the free end goes to the other end, along it. Steps: the end goes to the other one.\n" + "Kinks and grade breaks: the end is turned in line with the other path. Cant: the cant of the other path.\n" + "The plain path moves, a switch stays as it is. One Ctrl+Z takes it all back")); + } + auto const namewidth{std::max(110.0f, ImGui::GetContentRegionAvail().x * 0.32f)}; + bool const chosen{state.selected >= 0 && state.selected < static_cast(state.issues.size())}; + auto const details{chosen ? ImGui::GetFrameHeightWithSpacing() + ImGui::GetTextLineHeightWithSpacing() * 2.0f : 0.0f}; + ImGui::BeginChild("jointresults", ImVec2(0.0f, -details), true); + ImGui::Columns(4, "jointrows", false); + ImGui::SetColumnWidth(0, 90.0f); + ImGui::SetColumnWidth(1, 80.0f); + ImGui::SetColumnWidth(2, namewidth); + ImGuiListClipper clipper; + clipper.Begin(static_cast(listed.size())); + while (clipper.Step()) + for (int row = clipper.DisplayStart; row < clipper.DisplayEnd; ++row) + { + auto const index{listed[row]}; + auto const &issue{state.issues[index]}; + auto const colour{ImGui::ColorConvertU32ToFloat4(kind_colour(issue.type))}; + ImGui::PushStyleColor(ImGuiCol_Text, issue.fixed ? ImVec4(0.5f, 0.8f, 0.5f, 1.0f) : colour); + if (ImGui::Selectable(format("%s##joint%d", STR_C(kind_name(issue.type)), index).c_str(), state.selected == index, ImGuiSelectableFlags_SpanAllColumns)) + joints_focus(index); + ImGui::PopStyleColor(); + ImGui::NextColumn(); + ImGui::TextUnformatted(issue.fixed ? STR_C("fixed") : value_text(issue).c_str()); + ImGui::NextColumn(); + ImGui::TextUnformatted(label_of(issue.track).c_str()); + ImGui::NextColumn(); + ImGui::TextUnformatted(label_of(issue.other).c_str()); + ImGui::NextColumn(); + } + ImGui::Columns(1); + ImGui::EndChild(); + if (chosen) + { + auto &issue{state.issues[state.selected]}; + ImGui::Text("%s %s: %s / %s", STR_C(kind_name(issue.type)), value_text(issue).c_str(), label_of(issue.track).c_str(), label_of(issue.other).c_str()); + if (false == issue.fixed && issue.type != kind::open && issue.type != kind::model && ImGui::Button(STR_C("Fix this one"))) + joints_fix({state.selected}); + } +} + +void joints_tool::draw_overlay() const +{ + auto const &state{m_joints}; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + glm::dvec3 const camera{Global.pCamera.Pos}; + if (false == state.open) + { + for (auto const &issue : m_live.issues) + { + ImVec2 screen; + if ((false == Global.EditorOrtho && glm::distance(issue.position, camera) > kOverlayRange) || false == projection.project(issue.position, screen)) + continue; + auto const colour{kind_colour(issue.type)}; + drawlist->AddCircle(screen, 9.0f, colour, 16, 2.0f); + auto const text{std::string{STR_C(kind_name(issue.type))} + " " + value_text(issue)}; + drawlist->AddRectFilled(ImVec2(screen.x + 11.0f, screen.y - 9.0f), ImVec2(screen.x + 17.0f + ImGui::CalcTextSize(text.c_str()).x, screen.y + 9.0f), IM_COL32(0, 0, 0, 150), 3.0f); + drawlist->AddText(ImVec2(screen.x + 14.0f, screen.y - 7.0f), colour, text.c_str()); + } + return; + } + if (state.issues.empty()) + return; + for (int i = 0; i < static_cast(state.issues.size()); ++i) + { + auto const &issue{state.issues[i]}; + if (issue.fixed || (state.filter >= 0 && static_cast(issue.type) != state.filter) || (false == Global.EditorOrtho && glm::distance(issue.position, camera) > kOverlayRange)) + continue; + ImVec2 screen; + if (false == projection.project(issue.position, screen)) + continue; + auto const colour{i == state.selected ? IM_COL32(255, 255, 80, 255) : kind_colour(issue.type)}; + drawlist->AddCircle(screen, 11.0f, colour, 16, 2.5f); + auto const text{std::string{STR_C(kind_name(issue.type))} + " " + value_text(issue)}; + drawlist->AddText(ImVec2(screen.x + 13.0f, screen.y - 7.0f), colour, text.c_str()); + } +} + +editor_selftest_result joints_tool::selftest(std::string const &Command, std::istringstream &Words) +{ + if (Command == "jointsmodel") + { + // the whole scenery against the terrain model, as the check of the panel does it, waiting for the model + static bool started{false}; + if (false == started) + { + double threshold{0.5}; + Words >> threshold; + m_joints.scope = 1; + m_joints.model_check = true; + m_joints.model = threshold; + joints_start(); + started = true; + } + update(); + if (m_joints.next < m_joints.queue.size() || m_joints.model_waiting) + return editor_selftest_result::again; + started = false; + std::size_t count{0}; + for (auto const &issue : m_joints.issues) + { + if (issue.type != joint_issue::kind::model) + continue; + if (count == 40) + break; + ++count; + WriteLog(format("SELFTEST jointsmodel: %+.2f m at %.1f %.1f, %s path %d", issue.value, issue.position.x, issue.position.z, issue.track != nullptr ? issue.track->name().c_str() : "-", issue.point.path)); + } + WriteLog("SELFTEST jointsmodel: " + m_joints.status); + return editor_selftest_result::handled; + } + if (Command == "jointslive") + { + live_update(); + std::string text; + for (auto const &issue : m_live.issues) + { + text += format(" [%s %s at %.1f %.1f, %s / %s", kind_name(issue.type), value_text(issue).c_str(), issue.position.x, issue.position.z, issue.track != nullptr ? issue.track->name().c_str() : "-", issue.other != nullptr ? issue.other->name().c_str() : "-"); + // which way the other end lies, across or up + if (issue.type == joint_issue::kind::gap && issue.other != nullptr) + { + auto const off{editor_track::point_position(*issue.other, issue.theirs) - issue.position}; + text += format(", off %+.3f %+.3f %+.3f", off.x, off.y, off.z); + } + text += "]"; + } + WriteLog(format("SELFTEST jointslive: %zu pending, %zu marked", m_live.pending.size(), m_live.issues.size()) + text); + return editor_selftest_result::handled; + } + if (Command == "joints") + { + std::vector points; + for (glm::dvec3 point{0.0}; Words >> point.x >> point.z;) + points.push_back(point); + auto const scope{m_joints.scope}; + auto const model{m_joints.model_check}; + m_joints.scope = 1; + m_joints.model_check = false; + joints_start(); + while (m_joints.next < m_joints.queue.size()) + update(); + m_joints.scope = scope; + m_joints.model_check = model; + char const *const kinds[]{"gap", "step", "kink", "cant jump", "grade break", "off the terrain model", "free end"}; + int around{0}; + for (auto const &issue : m_joints.issues) + { + if (false == points.empty() && issue.type == joint_issue::kind::open) + continue; + if (false == points.empty() && std::none_of(points.begin(), points.end(), [&](glm::dvec3 const &Point) { return geometry::plan_distance(Point, issue.position) < 5.0; })) + continue; + ++around; + auto const name = [](TTrack const *Track) { return Track == nullptr ? std::string{"-"} : Track->name() + (Track->eType == tt_Switch ? "(switch)" : ""); }; + auto const rise{issue.other != nullptr ? editor_track::point_position(*issue.other, issue.theirs).y - issue.position.y : 0.0}; + WriteLog(format("SELFTEST joints: %s %.3f at %.1f %.1f, %s / %s, rise %.3f", kinds[static_cast(issue.type)], issue.value, issue.position.x, issue.position.z, name(issue.track).c_str(), name(issue.other).c_str(), rise)); + } + WriteLog(format("SELFTEST joints: %d issues around the points, %zu in all", around, m_joints.issues.size())); + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} diff --git a/application/editormodejoints.h b/application/editormodejoints.h new file mode 100644 index 000000000..01617d889 --- /dev/null +++ b/application/editormodejoints.h @@ -0,0 +1,100 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.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 "application/editortool.h" + +#include +#include +#include +#include +#include + +class joints_tool final : public editor_tool +{ + public: + // joint of the paths found wrong by the joints check + struct joint_issue + { + enum class kind { gap, step, kink, cant, grade, model, open }; + kind type{kind::gap}; + TTrack *track{nullptr}; + editor_track::point_ref point; + TTrack *other{nullptr}; + editor_track::point_ref theirs; + glm::dvec3 position{0.0}; + double value{0.0}; // m, deg, mm, per mille; m of the track over the terrain model + bool fixed{false}; + }; + joints_tool(editor_selection &Selection, editor_view &View, editor_history &History, editor_ground &Ground) : m_selection{Selection}, m_view{View}, m_history{History}, m_ground{Ground} {} + void update() override; + void draw_overlay() const override; + void render_options() override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + void set_open(bool const Open) { m_joints.open = Open; } + // the tracks just changed, checked at their joints once the change is over + void tracks_committed(std::vector const &Tracks); + double kink_angle() const { return m_joints.angle; } + + private: + editor_selection &m_selection; + editor_view &m_view; + editor_history &m_history; + editor_ground &m_ground; + // joints of the paths: ends which almost meet, steps, kinks, jumps of the cant and of the grade + struct joints_state + { + bool open{false}; + int scope{0}; // 0: around the camera, 1: the whole scenery + double reach{2000.0}; + double gap{1.0}; // m, free ends closer than this to another end + double step{0.005}; // m + double angle{0.2}; // deg + double cant{5.0}; // mm + double grade{10.0}; // per mille + double model{0.5}; // m, the track over or under the terrain model (NMT) + bool free_ends{false}; + bool model_check{true}; + std::vector queue; + std::size_t next{0}; + // the places of the tracks compared with the terrain model, in runs of one path each, once the model under them is in + std::vector places; + std::vector> runs; + std::size_t run_next{0}; + bool model_waiting{false}; + bool model_asked{false}; + double model_polled{0.0}; + bool model_unplaced{false}; + std::vector issues; + int filter{-1}; + int selected{-1}; + std::size_t history{0}; + std::string status; + }; + joints_state m_joints; + using end_key = std::tuple; + // pairs of the ends already looked at in the check under way + std::set> m_reported; + // the joints of the tracks changed last, marked while the panel is closed + struct live_state + { + std::set pending; + std::vector issues; + }; + live_state m_live; + void live_update(); + void joints_start(); + void joints_check(TTrack &Track, std::vector &Issues, std::set> &Seen, bool const Open) const; + // the paths lying off the terrain model by more than the threshold. returns: false while the model under them is coming + bool joints_model(); + void joints_focus(int const Index); + bool joint_fix(joint_issue &Issue, std::vector> &States, std::vector &Changed); + void joints_fix(std::vector const &Indices); +}; diff --git a/application/editormodekm.cpp b/application/editormodekm.cpp new file mode 100644 index 000000000..2135d4afe --- /dev/null +++ b/application/editormodekm.cpp @@ -0,0 +1,1026 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormodekm.h" +#include "application/editorgestures.h" +#include "application/editormodeshared.h" +#include "application/editorprojection.h" +#include "editor/editorFormat.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorTrack.hpp" + +#include "simulation/simulation.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/utilities.h" +#include "world/Track.h" + +#include "imgui/imgui.h" +#include "utilities/translation.h" +#include +#include +#include +#include +#include +#include + +namespace +{ + +using geometry::plan_distance; +using geometry::plan_of; + +double constexpr kOverlayRange{3000.0}; +double constexpr kTickRange{1500.0}; // m, of the hectometres shown in the scenery +double constexpr kLabelRange{700.0}; // m, of the km written there, farther ones crowd the horizon +double constexpr kDigitRange{250.0}; // m, of the hectometres written there +double constexpr kRailHead{0.18}; // m, above the axis of a path +double constexpr kPickReach{15.0}; // m from a point of the km a click on a track takes it +double constexpr kReadoutReach{30.0}; // m from the axis of a line its km is shown by the mouse +double constexpr kPostReach{60000.0}; // m along the line each way, of the posts read +double constexpr kPostCorridor{15.0}; // m from the track, posts farther away belong to another line +double constexpr kPostTolerance{10.0}; // m, of the distance between two posts against their numbers +double constexpr kCurve{10000.0}; // m, of the radius a jump of the km is on a curve under +double constexpr kStation{300.0}; // m from a switch a jump of the km is at a station + +ImU32 constexpr kAxis{IM_COL32(110, 200, 255, 220)}; +ImU32 constexpr kGuessed{IM_COL32(110, 200, 255, 90)}; +ImU32 constexpr kTick{IM_COL32(235, 240, 250, 230)}; +ImU32 constexpr kKm{IM_COL32(255, 215, 90, 255)}; +ImU32 constexpr kJump{IM_COL32(255, 95, 215, 255)}; +ImU32 constexpr kMark{IM_COL32(95, 220, 140, 255)}; +ImU32 constexpr kAstray{IM_COL32(240, 90, 80, 255)}; + +// the digits after the rotation make the number of a hectometre post, the last one the hectometre +bool hectometres_of(std::vector const &Values, int &Hectometres) +{ + if (Values.size() < 6) + return false; + Hectometres = 0; + for (std::size_t i = 5; i < Values.size(); ++i) + { + double digit; + if (false == numeric(Values[i], digit) || digit < 0.0 || digit > 9.0) + return false; + Hectometres = Hectometres * 10 + static_cast(digit); + } + return true; +} + +// chainage of the point of the samples nearest to the point, and how far from them it is +double project(std::vector const &Samples, glm::dvec3 const &Point, double &Distance) +{ + Distance = std::numeric_limits::max(); + double chainage{0.0}; + auto const point{plan_of(Point)}; + for (std::size_t i = 1; i < Samples.size(); ++i) + { + auto const a{plan_of(Samples[i - 1].position)}; + auto const ab{plan_of(Samples[i].position) - a}; + auto const length2{glm::dot(ab, ab)}; + auto const t{length2 > 1e-12 ? std::clamp(glm::dot(point - a, ab) / length2, 0.0, 1.0) : 0.0}; + if (auto const distance{glm::length(point - (a + ab * t))}; distance < Distance) + { + Distance = distance; + chainage = Samples[i - 1].chainage + (Samples[i].chainage - Samples[i - 1].chainage) * t; + } + } + return chainage; +} + +std::size_t sample_at(std::vector const &Samples, double const Chainage) +{ + auto const found{std::lower_bound(Samples.begin(), Samples.end(), Chainage, [](editor_track::route_sample const &Sample, double const Value) { return Sample.chainage < Value; })}; + return std::min(static_cast(found - Samples.begin()), Samples.size() - 1); +} + +// the number of a line: blanks taken out +std::string line_of(std::string const &Text) +{ + std::string result; + for (auto const c : Text) + if (false == std::isspace(static_cast(c))) + result += c; + return result; +} + +// a km typed as PKP PLK write it, 100,234, or with a point +bool km_of(char const *Text, double &Km) +{ + std::string text{Text}; + std::replace(text.begin(), text.end(), ',', '.'); + char *end{nullptr}; + auto const value{std::strtod(text.c_str(), &end)}; + if (end == text.c_str() || false == std::isfinite(value)) + return false; + Km = value; + return true; +} + +std::string mark_text(kilometrage::mark const &Mark) +{ + return Mark.beyond.has_value() ? kilometrage::text(Mark.km) + " = " + kilometrage::text(*Mark.beyond) : kilometrage::text(Mark.km); +} + +void draw_label(ImDrawList *List, ImVec2 const At, ImU32 const Ground, ImU32 const Colour, std::string const &Text) +{ + auto const size{ImGui::CalcTextSize(Text.c_str())}; + List->AddRectFilled(ImVec2(At.x - size.x * 0.5f - 4.0f, At.y - size.y - 4.0f), ImVec2(At.x + size.x * 0.5f + 4.0f, At.y), Ground, 3.0f); + List->AddText(ImVec2(At.x - size.x * 0.5f, At.y - size.y - 2.0f), Colour, Text.c_str()); +} + +void draw_arrow(screen_projection const &Projection, ImDrawList *List, glm::dvec3 const &From, glm::dvec2 const &Way, double const Length, ImU32 const Colour) +{ + glm::dvec3 const along{Way.x, 0.0, Way.y}; + glm::dvec3 const across{-Way.y, 0.0, Way.x}; + auto const tip{From + along * Length}; + Projection.line(List, From, tip, Colour, 3.0f); + Projection.line(List, tip, tip - along * (Length * 0.3) + across * (Length * 0.15), Colour, 3.0f); + Projection.line(List, tip, tip - along * (Length * 0.3) - across * (Length * 0.15), Colour, 3.0f); +} + +} // namespace + +void km_tool::refresh() +{ + m_drawn.clear(); + for (auto const &line : kilometrage::lines()) + { + auto const *axis{kilometrage::axis_of(line)}; + if (axis == nullptr || axis->points.size() < 2) + continue; + drawn entry; + entry.line = line; + entry.points = axis->points; + auto const low{axis->anchors.front().chainage - 1.0}; + auto const high{axis->anchors.back().chainage + 1.0}; + for (auto const chainage : axis->chainage) + entry.guessed.push_back(chainage < low || chainage > high ? 1 : 0); + for (auto const &anchor : axis->anchors) + if (std::abs(anchor.after - anchor.before) >= 1e-6) + { + auto const way{kilometrage::direction_on(*axis, anchor.chainage)}; + entry.ticks.push_back({kilometrage::point_on(*axis, anchor.chainage), {-way.y, 0.0, way.x}, 0, true}); + } + for (auto const &hectometre : kilometrage::hectometres(*axis)) + entry.ticks.push_back({hectometre.at, {-hectometre.rising.y, 0.0, hectometre.rising.x}, hectometre.number, false}); + m_drawn.push_back(std::move(entry)); + // the shorter track where the tracks run apart + for (auto const &side : axis->sides) + { + drawn apart; + apart.line = line; + apart.points = side.points; + apart.guessed.assign(side.points.size(), 0); + m_drawn.push_back(std::move(apart)); + } + } + m_revision = kilometrage::revision(); + m_drawn_once = true; +} + +void km_tool::update() +{ + if (false == m_open) + return; + auto const &marks{kilometrage::marks()}; + // after an undo the point edited may be gone + if (m_edited >= 0 && (m_edited >= static_cast(marks.size()) || false == m_pick.has_value() || plan_distance(marks[m_edited].point, m_pick->point) > 0.5)) + m_edited = -1; + if (false == m_drawn_once || kilometrage::revision() != m_revision) + refresh(); +} + +void km_tool::forget(scene::basic_node const *Node) +{ + if (m_pick.has_value() && m_pick->track == Node) + m_pick->track = nullptr; +} + +glm::dvec2 km_tool::rising() const +{ + if (false == m_pick.has_value()) + return {0.0, 1.0}; + return m_pick->along * (m_against ? -1.0 : 1.0); +} + +std::string km_tool::jump_warning(glm::dvec3 const &Point) const +{ + auto *track{kilometrage::track_near(Point, 6.0)}; + if (track == nullptr) + return {}; + auto route{editor_track::run_route(*track, kStation + 50.0)}; + auto const samples{editor_track::sample_route(route, 2.0)}; + if (samples.size() < 2) + return {}; + double gap{0.0}; + auto const at{project(samples, Point, gap)}; + bool curve{false}; + bool station{false}; + for (auto const &sample : samples) + { + auto const apart{std::abs(sample.chainage - at)}; + if (apart <= 30.0 && std::abs(sample.curvature) > 1.0 / kCurve) + curve = true; + if (apart <= kStation && sample.span < route.spans.size() && route.spans[sample.span].track->eType != tt_Normal) + station = true; + } + if (curve && station) + return STR("Id-1 § 19: the km shouldn't jump on a curve nor at a station, move the jump to a straight on the open line"); + if (curve) + return STR("Id-1 § 19: the km shouldn't jump on a curve, move the jump to a straight"); + if (station) + return STR("Id-1 § 19: the km shouldn't jump at a station, move the jump out to the open line"); + return {}; +} + +void km_tool::pick(TTrack &Track, glm::dvec3 const &Point) +{ + auto const t{editor_track::nearest_parameter(Track, Point)}; + picked entry; + entry.track = &Track; + entry.point = editor_track::point_at(Track, t); + auto const ahead{plan_of(editor_track::point_at(Track, std::min(1.0, t + 0.01)) - editor_track::point_at(Track, std::max(0.0, t - 0.01)))}; + entry.along = glm::length(ahead) > 1e-9 ? glm::normalize(ahead) : glm::dvec2{0.0, 1.0}; + entry.path = kilometrage::path_near(Track, Point, entry.on); + m_status.clear(); + m_route_status.clear(); + m_edited = -1; + auto const &marks{kilometrage::marks()}; + auto nearest{kPickReach}; + for (std::size_t index = 0; index < marks.size(); ++index) + if (auto const distance{plan_distance(marks[index].point, entry.point)}; distance < nearest) + { + nearest = distance; + m_edited = static_cast(index); + } + if (m_edited >= 0) + { + auto const &mark{marks[m_edited]}; + entry.point = mark.point; + m_line = mark.line; + m_km = mark.km; + m_jump = mark.beyond.has_value(); + m_beyond = mark.beyond.value_or(mark.km); + m_against = glm::dot(mark.way, entry.along) < 0.0; + } + else + { + // the line the point lies on, and its km there + if (auto const line{kilometrage::line_at(entry.point, kReadoutReach)}; false == line.empty()) + m_line = line; + double km{0.0}; + if (false == m_line.empty() && kilometrage::km_at(m_line, entry.point, km, kReadoutReach)) + { + m_km = std::round(km * 1000.0) / 1000.0; + auto const *axis{kilometrage::axis_of(m_line)}; + double gap{0.0}; + auto const along{kilometrage::chainage_at(*axis, entry.point, gap)}; + m_against = glm::dot(kilometrage::direction_on(*axis, along) * static_cast(axis->growth), entry.along) < 0.0; + } + m_jump = false; + m_beyond = m_km; + } + m_pick = entry; +} + +std::string km_tool::readout(glm::dvec3 const &Point) const +{ + std::string result; + for (auto const &line : kilometrage::lines()) + { + double km{0.0}; + if (false == kilometrage::km_at(line, Point, km, kReadoutReach)) + continue; + if (false == result.empty()) + result += '\n'; + result += format(STR_C("line %s: km %s"), line.c_str(), kilometrage::text(km).c_str()); + } + return result; +} + +void km_tool::put() +{ + m_status.clear(); + if (false == m_pick.has_value()) + return; + auto const line{line_of(m_line)}; + if (line.empty()) + { + m_status = STR("Give the number of the line first"); + return; + } + if (m_jump && std::abs(m_beyond - m_km) < 0.0005) + { + m_status = STR("A jump needs another km on from the point"); + return; + } + kilometrage::mark entry; + entry.line = line; + entry.point = m_pick->point; + entry.way = rising(); + entry.km = m_km; + if (m_jump) + entry.beyond = m_beyond; + if (m_edited >= 0) + kilometrage::change(static_cast(m_edited), entry); + else + { + kilometrage::put(entry); + m_edited = static_cast(kilometrage::marks().size()) - 1; + } + m_line = line; + m_history.push_kilometrage_snapshot(); + m_status = format(STR_C("Line %s: km %s at the point"), line.c_str(), mark_text(entry).c_str()); +} + +void km_tool::remove() +{ + m_status.clear(); + if (m_edited < 0) + return; + kilometrage::remove(static_cast(m_edited)); + m_edited = -1; + m_history.push_kilometrage_snapshot(); + m_status = STR("The point of the km removed"); +} + +void km_tool::show(std::size_t const Index) +{ + auto const &marks{kilometrage::marks()}; + if (Index >= marks.size()) + return; + auto const point{marks[Index].point}; + if (auto *track{kilometrage::track_near(point, 6.0)}; track != nullptr) + pick(*track, point); + m_view.fly_to(point, glm::normalize(glm::dvec3{-1.0, -0.8, -1.0}), 40.0); +} + +void km_tool::show_via(std::size_t const Index) +{ + auto const &vias{kilometrage::vias()}; + if (Index >= vias.size()) + return; + auto const point{vias[Index].point}; + auto const line{vias[Index].line}; + int path{0}; + if (auto *track{kilometrage::track_near(point, 6.0, path)}; track != nullptr) + { + pick(*track, point); + m_line = line; + } + m_view.fly_to(point, glm::normalize(glm::dvec3{-1.0, -0.8, -1.0}), 40.0); +} + +int km_tool::via_here() const +{ + if (false == m_pick.has_value() || m_pick->track == nullptr) + return -1; + auto const &vias{kilometrage::vias()}; + for (std::size_t index = 0; index < vias.size(); ++index) + { + if (vias[index].line != m_line) + continue; + int path{0}; + if (kilometrage::track_near(vias[index].point, 6.0, path) == m_pick->track && path == m_pick->path) + return static_cast(index); + } + return -1; +} + +void km_tool::lead_along() +{ + m_route_status.clear(); + if (false == m_pick.has_value() || m_pick->track == nullptr) + return; + auto const line{line_of(m_line)}; + if (line.empty()) + { + m_route_status = STR("Give the number of the line first"); + return; + } + auto const astray_of = [&]() { + auto const *axis{kilometrage::axis_of(line)}; + return axis != nullptr ? axis->astray.size() : kilometrage::marks().size(); + }; + auto const before{kilometrage::current()}; + auto const astray{astray_of()}; + kilometrage::via entry; + entry.line = line; + entry.point = m_pick->on; + kilometrage::put(entry); + auto const *axis{kilometrage::axis_of(line)}; + if (axis == nullptr || false == axis->runs_along(m_pick->track, m_pick->path)) + { + kilometrage::restore(before); + m_route_status = STR("The line can't run along this track: no way leads from it onto the line"); + return; + } + m_line = line; + m_history.push_kilometrage_snapshot(); + m_route_status = format(STR_C("Line %s runs along this track now"), line.c_str()); + if (auto const lost{astray_of()}; lost > astray) + m_route_status += "\n" + format(STR_P("%zu point of the km is off the line now: the track leads it away from it", "%zu points of the km are off the line now: the track leads it away from them", lost - astray), lost - astray); +} + +void km_tool::drop_via() +{ + m_route_status.clear(); + auto const index{via_here()}; + if (index < 0) + return; + kilometrage::remove_via(static_cast(index)); + m_history.push_kilometrage_snapshot(); + m_route_status = format(STR_C("Line %s runs along the straight paths of the switches here again"), m_line.c_str()); +} + +void km_tool::read_posts() +{ + m_status.clear(); + auto const line{line_of(m_line)}; + if (false == m_pick.has_value() || m_pick->track == nullptr) + { + m_status = STR("Click a track of the line first"); + return; + } + if (line.empty()) + { + m_status = STR("Give the number of the line first"); + return; + } + auto route{editor_track::run_route(*m_pick->track, kPostReach)}; + auto const samples{editor_track::sample_route(route, 2.0)}; + if (samples.size() < 2) + { + m_status = STR("No line through this track"); + return; + } + auto const length{samples.back().chainage}; + struct post + { + double chainage{0.0}; + int hectometres{0}; + }; + std::vector posts; + for (auto const &standing : m_templates.standing_templates([](std::string const &File) { return File.find("hekto") != std::string::npos; })) + { + post entry; + if (false == hectometres_of(standing.values, entry.hectometres)) + continue; + double distance{0.0}; + entry.chainage = project(samples, standing.location, distance); + if (distance > kPostCorridor || entry.chainage <= 0.0 || entry.chainage >= length) + continue; + posts.push_back(entry); + } + if (posts.size() < 2) + { + m_status = STR("Fewer than two hectometre posts stand along the line, nothing to read"); + return; + } + std::sort(posts.begin(), posts.end(), [](post const &A, post const &B) { return A.chainage < B.chainage; }); + // runs of posts numbered by the distance between them, a post of the same number by the other track taken once + auto const fits = [](post const &From, post const &To, int const Sign) { + auto const counted{(To.hectometres - From.hectometres) * 100.0}; + auto const apart{To.chainage - From.chainage}; + return counted != 0.0 && (Sign == 0 || (counted > 0.0 ? 1 : -1) == Sign) && std::abs(std::abs(counted) - apart) <= std::max(kPostTolerance, apart * 0.02); + }; + auto const sign_of = [](std::vector const &Run) { return Run.size() < 2 ? 0 : Run.back().hectometres > Run.front().hectometres ? 1 : -1; }; + std::vector> runs; + std::size_t twins{0}; + for (auto const &entry : posts) + { + if (false == runs.empty()) + { + auto &run{runs.back()}; + if (entry.hectometres == run.back().hectometres && entry.chainage - run.back().chainage < kPostTolerance * 3.0) + { + ++twins; + continue; + } + if (fits(run.back(), entry, sign_of(run))) + { + run.push_back(entry); + continue; + } + } + runs.push_back({entry}); + } + // a post alone between the runs is one out of place + std::size_t stray{0}; + std::vector> kept; + for (auto &run : runs) + { + if (run.size() < 2) + { + ++stray; + continue; + } + if (false == kept.empty() && fits(kept.back().back(), run.front(), sign_of(kept.back())) && sign_of(kept.back()) == sign_of(run)) + kept.back().insert(kept.back().end(), run.begin(), run.end()); + else + kept.push_back(std::move(run)); + } + std::size_t rising{0}; + std::size_t falling{0}; + for (auto const &run : kept) + (sign_of(run) > 0 ? rising : falling) += run.size(); + auto const growth{rising >= falling ? 1 : -1}; + kept.erase(std::remove_if(kept.begin(), kept.end(), [&](std::vector const &Run) { + if (sign_of(Run) == growth) + return false; + stray += Run.size(); + return true; + }), kept.end()); + if (kept.empty()) + { + m_status = STR("The numbers of the posts don't go by 100 m anywhere along the line, nothing read"); + return; + } + auto const mark_at = [&](double const Chainage, double const Km, std::optional const Beyond) { + kilometrage::mark entry; + entry.line = line; + entry.point = editor_track::sampled_position(samples, Chainage); + entry.way = samples[sample_at(samples, Chainage)].direction * static_cast(growth); + entry.km = Km; + entry.beyond = Beyond; + return entry; + }; + std::vector made; + std::size_t jumps{0}; + std::size_t misplaced{0}; + for (std::size_t r = 0; r < kept.size(); ++r) + { + auto const &run{kept[r]}; + auto const &first{run.front()}; + auto const &last{run.back()}; + // the jump to the next run at the post it starts the irregular hectometre at, along the rising km + auto const jump_before{r > 0 && growth > 0}; + auto const jump_after{r + 1 < kept.size() && growth < 0}; + if (jump_before) + { + auto const &previous{kept[r - 1].back()}; + made.push_back(mark_at(first.chainage, previous.hectometres / 10.0 + (first.chainage - previous.chainage) / 1000.0, first.hectometres / 10.0)); + } + else + made.push_back(mark_at(first.chainage, first.hectometres / 10.0, std::nullopt)); + if (jump_after) + { + auto const &next{kept[r + 1].front()}; + made.push_back(mark_at(last.chainage, next.hectometres / 10.0 + (next.chainage - last.chainage) / 1000.0, last.hectometres / 10.0)); + } + else + made.push_back(mark_at(last.chainage, last.hectometres / 10.0, std::nullopt)); + if (jump_before || jump_after) + { + ++jumps; + if (false == jump_warning((jump_before ? made[made.size() - 2] : made.back()).point).empty()) + ++misplaced; + } + } + // the points of the line along the stretch read give way to the ones read + auto const &standing{kilometrage::marks()}; + for (auto index{static_cast(standing.size()) - 1}; index >= 0; --index) + { + if (standing[index].line != line) + continue; + double gap{0.0}; + project(samples, standing[index].point, gap); + if (gap <= kPostCorridor) + kilometrage::remove(static_cast(index)); + } + for (auto &entry : made) + kilometrage::put(std::move(entry)); + m_line = line; + m_edited = -1; + m_history.push_kilometrage_snapshot(); + m_status = format(STR_C("%zu posts read: %zu points of the km, %zu jumps"), posts.size() - twins, made.size(), jumps); + if (stray > 0) + m_status += "\n" + format(STR_P("%zu post doesn't fit its neighbours and was left out", "%zu posts don't fit their neighbours and were left out", stray), stray); + if (misplaced > 0) + m_status += "\n" + format(STR_P("%zu jump lies on a curve or at a station, Id-1 § 19 wants none there", "%zu jumps lie on a curve or at a station, Id-1 § 19 wants none there", misplaced), misplaced); +} + +void km_tool::render_options() +{ + ImGui::TextWrapped("%s", STR_C("One point of a known km is enough: the hectometre posts, the stations and the block signals of the line count from it")); + ImGui::TextDisabled("%s", STR_C("The km of a railway line: the points where the km is known, from a post or a document, and where it jumps. The km of the rest go from them along the axis of the line: between the tracks of a double-track one, along the longer track where the tracks run on formations of their own, the shorter one getting an irregular hectometre")); + ImGui::Spacing(); + gesture_rows({{"LMB on a track", "a point of the km there, or the one standing by it"}}); + auto const &marks{kilometrage::marks()}; + auto const lines{kilometrage::lines()}; + std::size_t jumps{0}; + for (auto const &mark : marks) + if (mark.beyond.has_value()) + ++jumps; + metric_tiles({{format("%zu", lines.size()), STR_C("lines"), kAxis}, {format("%zu", marks.size()), STR_C("points"), kMark}, {format("%zu", jumps), STR_C("jumps"), kJump}}); + + step_heading(1, STR_C("A point of the km")); + if (false == m_pick.has_value()) + ImGui::TextDisabled("%s", STR_C("Click a track where the km is known: by a post, a station or a bridge")); + else + { + if (begin_fields("##kmpoint")) + { + field_row("Line"); + std::array buffer{}; + m_line.copy(buffer.data(), buffer.size() - 1); + if (ImGui::InputTextWithHint("##kmline", "91", buffer.data(), buffer.size())) + m_line = line_of(buffer.data()); + item_tooltip("The number of the railway line, as 91: a scenery can hold several lines, each with its own km"); + auto const km_field = [&](char const *Label, char const *Id, double &Value) { + field_row(Label); + std::array text{}; + kilometrage::text(Value).copy(text.data(), text.size() - 1); + if (ImGui::InputText(Id, text.data(), text.size())) + km_of(text.data(), Value); + }; + km_field("Km", "##kmkm", m_km); + item_tooltip("The km of the point, as PKP PLK write it: 100,234 is km 100 and 234 m. At a jump: the km the point is reached at, coming along the rising km"); + field_row("Jump"); + ImGui::Checkbox("##kmjump", &m_jump); + item_tooltip("The km jumps at the point: a line built anew, shortened or lengthened keeps the km of the rest. The irregular hectometre is " + "marked by a black stripe under the digit of the post (Id-1 § 19)"); + if (m_jump) + { + km_field("Km on", "##kmbeyond", m_beyond); + item_tooltip("The km on from the point, along the rising km"); + } + ImGui::EndTable(); + } + auto const *axis{m_line.empty() ? nullptr : kilometrage::axis_of(m_line)}; + auto const fixed{axis != nullptr && axis->anchors.size() > 1 && std::abs(axis->anchors.back().before - axis->anchors.front().before) > 1e-6}; + if (false == fixed) + { + int way{m_against ? 1 : 0}; + if (segmented("##kmway", way, {{0, STR_C("Rise this way"), "The km rise the way the arrow at the point shows"}, {1, STR_C("Rise the other way"), "The km rise against the arrow"}})) + m_against = way == 1; + } + if (m_jump) + if (auto const warning{jump_warning(m_pick->point)}; false == warning.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), "%s", warning.c_str()); + if (main_button(m_edited >= 0 ? STR_C("Change the point") : STR_C("Put the point of the km"), ImVec2(-1.0f, tall_button_height()))) + put(); + item_tooltip("The point goes to the file of the scenery with the track, the simulation skips it. One step of undo"); + if (m_edited >= 0) + { + if (ImGui::Button(STR_C("Remove the point"), ImVec2(-1.0f, 0.0f))) + remove(); + item_tooltip("One step of undo"); + } + } + + step_heading(2, STR_C("The way through a station")); + auto const *line_axis{m_line.empty() ? nullptr : kilometrage::axis_of(m_line)}; + if (false == m_pick.has_value() || m_pick->track == nullptr) + ImGui::TextDisabled("%s", STR_C("Through a station the km run along the straight paths of the switches. Click a track of the station to lead them along it instead")); + else if (line_axis == nullptr) + ImGui::TextDisabled("%s", STR_C("Put a point of the km of the line first")); + else if (auto const via{via_here()}; via >= 0) + { + if (std::find(line_axis->blocked.begin(), line_axis->blocked.end(), static_cast(via)) != line_axis->blocked.end()) + ImGui::TextColored(ImVec4(1.0f, 0.45f, 0.4f, 1.0f), "%s", STR_C("The line doesn't run along this track: another track chosen leads it elsewhere")); + else + ImGui::TextUnformatted(format(STR_C("Line %s runs along this track, as chosen"), m_line.c_str()).c_str()); + if (ImGui::Button(STR_C("Back onto the straight paths"), ImVec2(-1.0f, 0.0f))) + drop_via(); + item_tooltip("The track chosen is forgotten, the line runs along the straight paths of the switches here again. One step of undo"); + } + else if (line_axis->runs_along(m_pick->track, m_pick->path)) + ImGui::TextDisabled("%s", format(STR_C("Line %s runs along this track"), m_line.c_str()).c_str()); + else + { + ImGui::TextDisabled("%s", format(STR_C("Line %s doesn't run along this track"), m_line.c_str()).c_str()); + if (ImGui::Button(STR_C("Lead the km along this track"), ImVec2(-1.0f, 0.0f))) + lead_along(); + item_tooltip("The line runs along the track clicked, along the path of the switch clicked, and on along the straight paths of the switches " + "until it meets its tracks again; where it doesn't, as at a junction, it goes on that way. One step of undo"); + } + if (false == m_route_status.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), "%s", m_route_status.c_str()); + + step_heading(3, STR_C("From the posts")); + if (ImGui::Button(STR_C("Read the km from the posts"), ImVec2(-1.0f, 0.0f))) + read_posts(); + item_tooltip("Reads the hectometre posts standing along the line through the track clicked: a point of the km at the first and the last " + "post of each run numbered by 100 m, a jump where two runs meet. The points of the line along it before give way. One step of undo"); + if (false == m_status.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), "%s", m_status.c_str()); + + step_heading(4, STR_C("The points of the lines")); + if (lines.empty()) + { + ImGui::TextDisabled("%s", STR_C("None yet")); + return; + } + for (auto const &line : lines) + { + auto const *axis{kilometrage::axis_of(line)}; + auto const count{static_cast(std::count_if(marks.begin(), marks.end(), [&](kilometrage::mark const &Mark) { return Mark.line == line; }))}; + if (false == ImGui::CollapsingHeader(format("%s %s (%zu)###kmline%s", STR_C("Line"), line.c_str(), count, line.c_str()).c_str(), ImGuiTreeNodeFlags_DefaultOpen)) + continue; + if (axis == nullptr) + { + ImGui::TextColored(ImVec4(1.0f, 0.45f, 0.4f, 1.0f), "%s", STR_C("No track by the points of the line")); + continue; + } + ImGui::TextDisabled("%s", format(STR_C("%.1f km of the axis, %s"), axis->length() / 1000.0, axis->between ? STR_C("between the tracks") : STR_C("along the track")).c_str()); + if (false == axis->sides.empty()) + { + ImGui::TextDisabled("%s", format(STR_P("%zu stretch with the tracks on formations of their own", "%zu stretches with the tracks on formations of their own", axis->sides.size()), axis->sides.size()).c_str()); + item_tooltip("Where the tracks part more than 15 m and come together again, the km run along the longer one, the shorter one goes by " + "its own length and its last hectometre before they meet takes up the difference, as PKP GK-1 gives it (6.1.12)"); + } + auto const &vias{kilometrage::vias()}; + for (std::size_t index = 0; index < vias.size(); ++index) + { + if (vias[index].line != line) + continue; + auto const blocked{std::find(axis->blocked.begin(), axis->blocked.end(), index) != axis->blocked.end()}; + double km{0.0}; + auto const label{kilometrage::km_at(line, vias[index].point, km, kReadoutReach) ? format(STR_C("Along the track chosen by km %s"), kilometrage::text(km).c_str()) : std::string{STR_C("Along the track chosen")}}; + if (blocked) + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.45f, 0.4f, 1.0f)); + if (ImGui::Selectable((label + "##kmvia" + std::to_string(index)).c_str(), false)) + show_via(index); + if (blocked) + ImGui::PopStyleColor(); + item_tooltip(blocked ? "The line doesn't run along this track: another track chosen leads it elsewhere" : "Through the station the line runs along this track, not along the straight paths of the switches"); + } + auto const rows{axis->anchors.size() + axis->astray.size()}; + if (false == ImGui::BeginTable(("##kmmarks" + line).c_str(), 4, ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY, ImVec2(0.0f, std::min(260.0f, ImGui::GetTextLineHeightWithSpacing() * (rows + 1.5f))))) + continue; + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn(STR_C("Km"), ImGuiTableColumnFlags_WidthStretch, 0.4f); + ImGui::TableSetupColumn(STR_C("In the scenery"), ImGuiTableColumnFlags_WidthStretch, 0.22f); + ImGui::TableSetupColumn(STR_C("By the km"), ImGuiTableColumnFlags_WidthStretch, 0.22f); + ImGui::TableSetupColumn(STR_C("Off by"), ImGuiTableColumnFlags_WidthStretch, 0.16f); + ImGui::TableHeadersRow(); + auto const growth{axis->growth}; + for (std::size_t i = 0; i < axis->anchors.size(); ++i) + { + auto const &anchor{axis->anchors[i]}; + auto const &mark{marks[anchor.mark]}; + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + if (ImGui::Selectable((mark_text(mark) + "##kmmark" + std::to_string(anchor.mark)).c_str(), static_cast(anchor.mark) == m_edited, ImGuiSelectableFlags_SpanAllColumns)) + show(anchor.mark); + if (i == 0) + continue; + auto const &previous{axis->anchors[i - 1]}; + auto const scenery{anchor.chainage - previous.chainage}; + auto const counted{std::abs((growth > 0 ? anchor.before - previous.after : previous.before - anchor.after) * 1000.0)}; + ImGui::TableNextColumn(); + ImGui::Text("%.0f m", scenery); + ImGui::TableNextColumn(); + ImGui::Text("%.0f m", counted); + ImGui::TableNextColumn(); + auto off{scenery > 1.0 ? (scenery - counted) / scenery * 100.0 : 0.0}; + if (std::abs(off) < 0.05) + off = 0.0; + if (std::abs(off) > 2.0) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), "%+.1f%%", off); + else + ImGui::Text("%+.1f%%", off); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("How much longer the stretch is in the scenery than by the km: the km between the points are stretched to it evenly")); + } + for (auto const index : axis->astray) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(1.0f, 0.45f, 0.4f, 1.0f)); + if (ImGui::Selectable((mark_text(marks[index]) + "##kmmark" + std::to_string(index)).c_str(), static_cast(index) == m_edited, ImGuiSelectableFlags_SpanAllColumns)) + show(index); + ImGui::PopStyleColor(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The point is away from the axis of the line the other points make: the main paths of the switches don't lead to it")); + } + ImGui::EndTable(); + } +} + +void km_tool::draw_overlay() const +{ + if (false == m_open) + return; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + glm::dvec3 const camera{Global.pCamera.Pos}; + auto const near_enough = [&](glm::dvec3 const &Point, double const Range) { return Global.EditorOrtho || glm::distance(Point, camera) < Range; }; + glm::dvec3 const lift{0.0, kRailHead, 0.0}; + for (auto const &entry : m_drawn) + { + // the axis, faint where the km run on past the last point + for (std::size_t i = 1; i < entry.points.size(); i += 5) + { + auto const next{std::min(i + 4, entry.points.size() - 1)}; + if (near_enough(entry.points[next], kOverlayRange)) + projection.line(drawlist, entry.points[i - 1] + lift, entry.points[next] + lift, entry.guessed[next] != 0 ? kGuessed : kAxis, Global.EditorOrtho ? 4.0f : 2.5f); + } + for (auto const &tick : entry.ticks) + { + if (false == near_enough(tick.at, kTickRange)) + continue; + auto const centre{tick.at + lift}; + auto const whole{tick.hectometres % 10 == 0}; + auto const reach{tick.jump ? 3.5 : whole ? 2.6 : 1.4}; + projection.line(drawlist, centre - tick.across * reach, centre + tick.across * reach, tick.jump ? kJump : whole ? kKm : kTick, tick.jump || whole ? 3.5f : 2.0f); + if (tick.jump) + continue; + ImVec2 screen; + if (whole && near_enough(tick.at, kLabelRange) && projection.project(centre + tick.across * reach + glm::dvec3{0.0, 0.6, 0.0}, screen)) + draw_label(drawlist, screen, IM_COL32(0, 0, 0, 170), kKm, format("km %d", tick.hectometres / 10)); + else if (false == whole && near_enough(tick.at, kDigitRange) && projection.project(centre + tick.across * reach + glm::dvec3{0.0, 0.4, 0.0}, screen)) + draw_label(drawlist, screen, IM_COL32(0, 0, 0, 140), kTick, std::to_string(std::abs(tick.hectometres) % 10)); + } + } + // the points of the km: a pole with the km over it, the arrow the way the km rise + auto const &marks{kilometrage::marks()}; + for (std::size_t index = 0; index < marks.size(); ++index) + { + auto const &mark{marks[index]}; + if (false == near_enough(mark.point, kLabelRange * 2.0)) + continue; + auto astray{true}; + for (auto const &entry : m_drawn) + if (entry.line == mark.line) + if (auto const *axis{kilometrage::axis_of(mark.line)}; axis != nullptr) + astray = std::find(axis->astray.begin(), axis->astray.end(), index) != axis->astray.end(); + auto const colour{astray ? kAstray : mark.beyond.has_value() ? kJump : kMark}; + auto const foot{mark.point + lift}; + auto const top{foot + glm::dvec3{0.0, 3.0, 0.0}}; + projection.line(drawlist, foot, top, colour, static_cast(index) == m_edited ? 4.0f : 2.5f); + draw_arrow(projection, drawlist, foot, mark.way, 6.0, colour); + ImVec2 screen; + if (projection.project(top, screen)) + draw_label(drawlist, screen, colour, IM_COL32(16, 18, 22, 255), mark.line + ": " + mark_text(mark)); + } + // the tracks chosen for the way through a station: a rhombus on the track + auto const &vias{kilometrage::vias()}; + for (std::size_t index = 0; index < vias.size(); ++index) + { + auto const &via{vias[index]}; + ImVec2 screen; + if (false == near_enough(via.point, kLabelRange * 2.0) || false == projection.project(via.point + lift, screen)) + continue; + auto blocked{false}; + if (auto const *axis{kilometrage::axis_of(via.line)}; axis != nullptr) + blocked = std::find(axis->blocked.begin(), axis->blocked.end(), index) != axis->blocked.end(); + auto const colour{blocked ? kAstray : kAxis}; + auto const r{8.0f}; + drawlist->AddQuadFilled(ImVec2(screen.x, screen.y - r), ImVec2(screen.x + r, screen.y), ImVec2(screen.x, screen.y + r), ImVec2(screen.x - r, screen.y), colour); + drawlist->AddQuad(ImVec2(screen.x, screen.y - r), ImVec2(screen.x + r, screen.y), ImVec2(screen.x, screen.y + r), ImVec2(screen.x - r, screen.y), IM_COL32(16, 18, 22, 255), 1.5f); + draw_label(drawlist, ImVec2(screen.x, screen.y - r - 2.0f), colour, IM_COL32(16, 18, 22, 255), format(STR_C("%s: this way"), via.line.c_str())); + } + if (m_pick.has_value() && m_edited < 0) + { + auto const foot{m_pick->point + lift}; + ImVec2 screen; + if (projection.project(foot, screen)) + drawlist->AddCircle(screen, 9.0f, kKm, 20, 2.5f); + draw_arrow(projection, drawlist, foot, rising(), 8.0, kKm); + } +} + +editor_selftest_result km_tool::selftest(std::string const &Command, std::istringstream &Words) +{ + if (Command == "kmpick") + { + // kmpick track= [at=<0..1>]: a click on the track + auto const values{selftest_values(Words)}; + auto const found{values.find("track")}; + auto *track{found != values.end() ? simulation::Paths.find(found->second) : nullptr}; + if (track == nullptr) + { + WriteLog("SELFTEST kmpick: no such track"); + return editor_selftest_result::handled; + } + auto const at{values.count("at") ? std::atof(values.at("at").c_str()) : 0.5}; + auto const path{values.count("path") ? std::atoi(values.at("path").c_str()) : 0}; + pick(*track, path > 0 && path < static_cast(track->m_paths.size()) ? geometry::bezier{track->m_paths[path]}.point(at) : editor_track::point_at(*track, at)); + auto const *axis{m_line.empty() ? nullptr : kilometrage::axis_of(m_line)}; + WriteLog(format("SELFTEST kmpick %s: line %s km %s jump %d against %d edited %d at %.1f %.1f path %d along %d via %d", track->name().c_str(), m_line.c_str(), kilometrage::text(m_km).c_str(), m_jump ? 1 : 0, m_against ? 1 : 0, m_edited, m_pick->point.x, m_pick->point.z, + m_pick->path, axis != nullptr && axis->runs_along(m_pick->track, m_pick->path) ? 1 : 0, via_here())); + return editor_selftest_result::handled; + } + if (Command == "kmset") + { + // kmset line= km= [beyond=] [against=1]: the fields set and the point put + auto const values{selftest_values(Words)}; + if (auto const line{values.find("line")}; line != values.end()) + m_line = line->second; + if (auto const km{values.find("km")}; km != values.end()) + km_of(km->second.c_str(), m_km); + m_jump = values.count("beyond") > 0; + if (m_jump) + km_of(values.at("beyond").c_str(), m_beyond); + if (auto const against{values.find("against")}; against != values.end()) + m_against = against->second == "1"; + put(); + WriteLog("SELFTEST kmset: " + m_status); + return editor_selftest_result::handled; + } + if (Command == "kmvia") + { + // kmvia [line=] [remove=1]: the line led along the track picked, or back onto the straight paths there + auto const values{selftest_values(Words)}; + if (auto const line{values.find("line")}; line != values.end()) + m_line = line->second; + if (values.count("remove") > 0) + drop_via(); + else + lead_along(); + auto text{m_route_status}; + std::replace(text.begin(), text.end(), '\n', ';'); + WriteLog("SELFTEST kmvia: " + text); + return editor_selftest_result::handled; + } + if (Command == "kmremove") + { + remove(); + WriteLog("SELFTEST kmremove: " + m_status); + return editor_selftest_result::handled; + } + if (Command == "kmposts") + { + // kmposts line=: the km read from the posts along the line through the track picked + auto const values{selftest_values(Words)}; + if (auto const line{values.find("line")}; line != values.end()) + m_line = line->second; + read_posts(); + WriteLog("SELFTEST kmposts: " + m_status); + return editor_selftest_result::handled; + } + if (Command == "kmstate") + { + WriteLog(format("SELFTEST kmstate: picked %d line %s km %s jump %d edited %d", m_pick.has_value() ? 1 : 0, m_line.c_str(), kilometrage::text(m_km).c_str(), m_jump ? 1 : 0, m_edited)); + return editor_selftest_result::handled; + } + if (Command == "kmshow") + { + // kmshow mark=: the point of the km picked, the camera over it + auto const values{selftest_values(Words)}; + auto const index{values.count("mark") ? std::atoi(values.at("mark").c_str()) : 0}; + show(static_cast(std::max(index, 0))); + WriteLog(format("SELFTEST kmshow %d: line %s km %s edited %d", index, m_line.c_str(), kilometrage::text(m_km).c_str(), m_edited)); + return editor_selftest_result::handled; + } + if (Command == "kmlist") + { + refresh(); + for (auto const &entry : m_drawn) + { + std::string list; + for (std::size_t i = 0; i < entry.ticks.size() && entry.points.size() < 2000; ++i) + list += format(" %d@%.0f,%.0f", entry.ticks[i].hectometres, entry.ticks[i].at.x, entry.ticks[i].at.z); + WriteLog(format("SELFTEST kmlist ticks %s: %zu points, %zu ticks", entry.line.c_str(), entry.points.size(), entry.ticks.size()) + list); + } + auto const &marks{kilometrage::marks()}; + WriteLog(format("SELFTEST kmlist: %zu points", marks.size())); + for (auto const &line : kilometrage::lines()) + { + auto const *axis{kilometrage::axis_of(line)}; + if (axis == nullptr) + { + WriteLog("SELFTEST kmlist line " + line + ": no axis"); + continue; + } + std::string list; + for (auto const &anchor : axis->anchors) + list += format(" %s@%.0f/%.1f", mark_text(marks[anchor.mark]).c_str(), anchor.chainage, anchor.gap); + for (auto const &side : axis->sides) + WriteLog(format("SELFTEST kmlist apart: %.1f m of track by %.1f m of axis (%.1f..%.1f), km %s..%s", side.length, side.to - side.from, side.from, side.to, kilometrage::text(kilometrage::km_on(*axis, side, 0.0)).c_str(), + kilometrage::text(kilometrage::km_on(*axis, side, side.length)).c_str())); + WriteLog(format("SELFTEST kmlist line %s: axis %.0f m %s growth %d, %zu astray, %zu blocked, km %s..%s:", line.c_str(), axis->length(), axis->between ? "between" : "along", axis->growth, axis->astray.size(), axis->blocked.size(), kilometrage::text(kilometrage::km_on(*axis, 0.0)).c_str(), + kilometrage::text(kilometrage::km_on(*axis, axis->length())).c_str()) + + list); + } + return editor_selftest_result::handled; + } + if (Command == "kmat") + { + // kmat track= [at=<0..1>]: the km of the lines there + auto const values{selftest_values(Words)}; + auto const found{values.find("track")}; + auto *track{found != values.end() ? simulation::Paths.find(found->second) : nullptr}; + if (track == nullptr) + { + WriteLog("SELFTEST kmat: no such track"); + return editor_selftest_result::handled; + } + auto const at{values.count("at") ? std::atof(values.at("at").c_str()) : 0.5}; + auto text{readout(editor_track::point_at(*track, at))}; + std::replace(text.begin(), text.end(), '\n', ';'); + WriteLog(format("SELFTEST kmat %s %.2f: ", track->name().c_str(), at) + (text.empty() ? std::string{"-"} : text)); + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} diff --git a/application/editormodekm.h b/application/editormodekm.h new file mode 100644 index 000000000..2e22bafb4 --- /dev/null +++ b/application/editormodekm.h @@ -0,0 +1,102 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.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 "application/editortool.h" +#include "editor/editorKilometrage.hpp" + +#include +#include +#include +#include + +// the kilometrage of the lines: the points of a line where its km is known and where it jumps, the km of the rest from them +class km_tool final : public editor_tool +{ + public: + km_tool(editor_selection &Selection, editor_view &View, editor_history &History, editor_templates &Templates) + : m_selection{Selection}, m_view{View}, m_history{History}, m_templates{Templates} + { + } + void update() override; + void draw_overlay() const override; + void render_options() override; + void forget(scene::basic_node const *Node) override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + void set_open(bool const Open) { m_open = Open; } + // the point of the track clicked: a new point of the km there, or the one standing by it + void pick(TTrack &Track, glm::dvec3 const &Point); + // the km of the lines at the point, a line of text each, empty where none reaches + std::string readout(glm::dvec3 const &Point) const; + + private: + editor_selection &m_selection; + editor_view &m_view; + editor_history &m_history; + editor_templates &m_templates; + bool m_open{false}; + struct picked + { + TTrack *track{nullptr}; + glm::dvec3 point{0.0}; // on the axis of the track + glm::dvec2 along{0.0, 1.0}; // of the track there, in the plan + int path{0}; // of the switch, the one nearest to the click + glm::dvec3 on{0.0}; // the point of it nearest to the click + }; + std::optional m_pick; + int m_edited{-1}; // of the marks, the one standing by the point picked, -1 for a new one + std::string m_line; + double m_km{0.0}; + bool m_jump{false}; + double m_beyond{0.0}; + bool m_against{false}; // the km rise against the track picked + std::string m_status; + std::string m_route_status; // of the way through a station + // what the overlay draws, made again when the axes change + struct tick + { + glm::dvec3 at{0.0}; + glm::dvec3 across{0.0}; // in the plan, a unit + int hectometres{0}; + bool jump{false}; + }; + struct drawn + { + std::string line; + std::vector points; + std::vector guessed; // of the points, beyond the last point of the km: the km run on from it + std::vector ticks; + }; + std::vector m_drawn; + std::size_t m_revision{0}; + bool m_drawn_once{false}; + + void refresh(); + void put(); + void remove(); + // the point of the km picked and the camera over it + void show(std::size_t const Index); + // the line of the field led along the track picked, along the path of the switch picked, instead of the straight paths of the + // switches; one step of the history + void lead_along(); + // the line back on the straight paths of the switches by the track picked; one step of the history + void drop_via(); + // of the vias of the line of the field, the one on the track picked, -1 for none + int via_here() const; + // the track of the via picked and the camera over it + void show_via(std::size_t const Index); + // the hectometre posts standing along the line through the track picked read into points of the km: the first and the last + // post of each run of them numbered by 100 m, a jump where the runs meet; one step of the history + void read_posts(); + // the way the km rise at the point picked, in the plan + glm::dvec2 rising() const; + // warnings of a jump at the point: Id-1 § 19 wants none on a curve nor at a station + std::string jump_warning(glm::dvec3 const &Point) const; +}; diff --git a/application/editormodelay.cpp b/application/editormodelay.cpp new file mode 100644 index 000000000..ed7e8c78b --- /dev/null +++ b/application/editormodelay.cpp @@ -0,0 +1,2515 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http: +*/ + + +#include "stdafx.h" +#include "application/editormode.h" +#include "editor/editorSettings.hpp" +#include "application/editoruilayer.h" +#include "application/editorprojection.h" +#include "application/editormodeshared.h" +#include "editor/editorFormat.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorSwitchStore.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorGroundFollow.hpp" +#include "editor/editorIncludeInfo.hpp" + +#include "utilities/Globals.h" +#include "rendering/renderer.h" +#include "world/Track.h" +#include "world/TrackFeatures.h" +#include "scene/scene.h" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" + +#include "imgui/imgui.h" +#include "imgui/ImGuizmo.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "application/editormodetrackshared.h" + +using namespace track_mode; + +namespace +{ + +// the curve of the track of a free end the line goes on from or into: the one of a plain track always, the one of the diverging track +// of a switch where a curve is traced from it, Traced; the bends of straights begin there with a straight, the curvature jumping as at +// the start of the switch +// the way a line through the points heads at the last of them: along the circle through the last three, along the last two where they +// keep straight +glm::dvec2 heading_at_end(std::vector const &Points) +{ + auto const count{Points.size()}; + auto const chord{Points[count - 1] - Points[count - 2]}; + if (count < 3) + return chord; + auto const &first{Points[count - 3]}; + auto const ab{Points[count - 2] - first}; + auto const ac{Points[count - 1] - first}; + auto const twice{2.0 * cross(ab, ac)}; + if (std::abs(twice) < 1e-6 * glm::length(ab) * glm::length(ac)) + return chord; + auto const centre{first + glm::dvec2{ac.y * glm::dot(ab, ab) - ab.y * glm::dot(ac, ac), ab.x * glm::dot(ac, ac) - ac.x * glm::dot(ab, ab)} / twice}; + auto const radial{Points[count - 1] - centre}; + glm::dvec2 tangent{-radial.y, radial.x}; + return glm::dot(tangent, chord) < 0.0 ? -tangent : tangent; +} + +// a stretch fitted from its far end back, its points the other way round and the first one last, as the line runs: the arcs of its curve +// and their transitions in the other order, the offsets of the points but the first, the heading it leaves the first point with +alignment::trace_stretch turned_round(alignment::trace_stretch const &Fit) +{ + auto result{Fit}; + auto const &curve{Fit.vertices.front()}; + auto &turned{result.vertices.front()}; + turned.transition_in = curve.transition_out; + turned.transition_out = curve.transition_in; + if (curve.compound && false == curve.arcs.empty()) + { + // the arcs from the far end: the first one of the vertex, then its arcs, each with the transition before it + std::vector arcs{{curve.radius, 0.0, curve.share, curve.first_cant}}; + arcs.insert(arcs.end(), curve.arcs.begin(), curve.arcs.end()); + std::reverse(arcs.begin(), arcs.end()); + // the transition between two arcs moves to the arc after it the other way round + for (std::size_t i = arcs.size(); i-- > 1;) + arcs[i].transition = arcs[i - 1].transition; + turned.radius = arcs.front().radius; + turned.share = arcs.front().share; + turned.first_cant = arcs.front().cant; + turned.arcs.assign(arcs.begin() + 1, arcs.end()); + } + if (false == result.offsets.empty()) + result.offsets.pop_back(); + std::reverse(result.offsets.begin(), result.offsets.end()); + result.leaving = -Fit.leaving; + return result; +} + +// only a curve traced next to a free end goes on from its curve; the bends of straights begin with a straight there, out of the curve +// of a plain track by a transition, not as a compound curve of its radius and the one of the bend +bool goes_on_curved(editor_track::snap_target const &End, bool const Traced) +{ + return End.track != nullptr && Traced && (End.track->eType == tt_Normal || End.track->eType == tt_Switch); +} + +// the curve of the track of a free end the line laid goes on from at its start, or into at its end: its radius, the side it turns to +// as the line runs and its cant leaning into the turn; nothing on a straight +void adjoining_curve(editor_track::snap_target const &End, bool const Atend, bool const Traced, double const Gauge, alignment::design &Design) +{ + if (false == goes_on_curved(End, Traced)) + return; + auto const bend{editor_track::bend_at(*End.track, End.position)}; + if (false == bend.has_value() || std::abs(bend->curvature) < 1e-4) + return; + // the curvature as the track goes on beyond its end: the way the line runs at its start, against it at its end + auto const curvature{Atend ? -bend->curvature : bend->curvature}; + auto const cant{Gauge * std::sin(glm::radians(bend->roll)) * (bend->curvature > 0.0 ? 1.0 : -1.0)}; + (Atend ? Design.end_radius : Design.start_radius) = 1.0 / std::abs(curvature); + (Atend ? Design.end_turn : Design.start_turn) = curvature > 0.0 ? 1 : -1; + (Atend ? Design.end_cant : Design.start_cant) = std::max(0.0, cant); + (Atend ? Design.end_curved : Design.start_curved) = true; + // the curve of a switch goes on at its radius, with no transition to another one in the switch's way + (Atend ? Design.end_held : Design.start_held) = End.track->eType == tt_Switch; +} + +} // namespace + +void editor_mode::update_build_tools() +{ + glm::dvec3 const ground{cursor_ground()}; + auto const &io{ImGui::GetIO()}; + glm::vec2 const cursor{io.MousePos.x, io.MousePos.y}; + m_straights.detour_mouse = ground; + auto const joining = [&](editor_track::snap_target const &Target) { + if (Target.track == m_join_track && Target.point == m_join_point) + return; + m_join_track = Target.track; + m_join_point = Target.point; + m_join_radius = 0.0; + m_join_variant = 0; + }; + bool const pointing{m_cursor_override.has_value() || ImGui::IsMousePosValid()}; + if (m_extend.active) + { + if (pointing) + m_extend.mouse = cursor_terrain(m_extend.point.y); + m_extend.snap = m_extend.track != nullptr ? snap_free_end(m_extend.mouse, cursor, m_extend.track, m_extend.track->iCategoryFlag & 15, {m_extend.track}) : editor_track::snap_target{}; + if (m_extend.snap.track == nullptr) + m_extend.mouse.y = EditorSettings.heights() == editorSettings::lay_heights::level ? m_extend.point.y : bed_height(m_extend.mouse, plan_of(m_extend.mouse - m_extend.point), m_extend.track); + joining(m_extend.snap); + } + if (m_switch.placing) + { + m_switch.mouse = cursor_level(m_switch.point.y); + recognise_connection(); + // a switch with no track takes the direction of its main track once the drag is long enough, dragged sideways after that it + // takes the side; back by its start the direction is free again + if (auto &tool{m_switch}; tool.free && tool.free_end.track == nullptr) + { + auto const offset{plan_of(tool.mouse - tool.point)}; + if (glm::length(offset) < kFreeSwitchRelease) + tool.free_heading.reset(); + else if (false == tool.free_heading.has_value() && glm::length(offset) >= kFreeSwitchLock) + tool.free_heading = glm::normalize(offset); + } + } + auto &lay{m_lay}; + lay.preview.clear(); + lay.preview_error.clear(); + lay.preview_length = 0.0; + if (false == lay.active) + return; + // a slow preview tells in the log where the time went: the cursor on the ground, the snap, the height, the plan of the line + auto stamp{std::chrono::steady_clock::now()}; + auto const lap = [&]() { + auto const now{std::chrono::steady_clock::now()}; + auto const time{std::chrono::duration(now - stamp).count()}; + stamp = now; + return time; + }; + // geometric ray, same as extend: Mouse_Position() is a delayed depth pick and lags the cursor + double const height{false == lay.points.empty() ? lay.points.back().y : lay.start.track != nullptr ? lay.start.position.y : ground.y}; + if (pointing) + lay.mouse = typed_lay(cursor_terrain(height)); + auto const oncursor{lap()}; + lay.skew.clear(); + if (pointing && ImGui::GetIO().KeyAlt && m_typed.empty() && false == lay.points.empty()) + lay.mouse = lay_angle_snap(lay.mouse, lay.skew); + lay.mouse_snap = m_typed.empty() ? snap_free_end(lay.mouse, cursor, nullptr, kRailCategory, {}) : editor_track::find_free_end(nullptr, kRailCategory, lay.mouse, kLaySnapRadius, {}); + auto const snapping{lap()}; + if (lay.mouse_snap.track == nullptr) + lay.mouse = lay_bed(lay.mouse); + auto const bedding{lap()}; + if (false == m_extend.active) + joining(lay.points.empty() ? editor_track::snap_target{} : lay.mouse_snap); + lay_trim(); + lay.plan = {}; + if (lay.points.empty()) + { + lay.shown.reset(); + lay.settling.reset(); + return; + } + // the line worked out last stays shown as long as the points clicked go on from its ones; one through a point taken back doesn't + if (lay.shown.has_value() && (lay.shown->points.size() > lay.points.size() || false == std::equal(lay.shown->points.begin(), lay.shown->points.end(), lay.points.begin()))) + lay.shown.reset(); + // the line is worked out for the cursor where it was when its fits were asked for, till the thread has done them all, frame after + // frame: then for where the cursor is by then. Another point clicked, or a track changed, the cursor is taken where it is + if (auto const &settling{lay.settling}; + false == lay.whole || (settling.has_value() && (settling->points != lay.points || settling->modes != lay.modes || settling->mode != lay.mode || settling->edits != m_track_edits))) + lay.settling.reset(); + if (false == lay.settling.has_value()) + lay.settling = lay_tool::settling_cursor{lay.mouse, lay.mouse_snap, lay.points, lay.modes, lay.mode, m_track_edits}; + auto const &mouse{lay.settling->mouse}; + // the cursor is the next point, in the mode it would be clicked in + auto points{lay.points}; + auto modes{lay.modes}; + auto end{lay.settling->snap}; + if (end.track != nullptr && glm::distance(end.position, points.front()) > 1.0) + { + points.push_back(end.position); + modes.push_back(lay.mode); + } + else + { + end = {}; + if (plan_distance(mouse, points.back()) > 1.0) + { + points.push_back(mouse); + modes.push_back(lay.mode); + } + } + m_fits_waiting = false; + m_follow_preview = true; + lay.preview = lay_pieces(points, modes, end, lay.preview_length, lay.preview_error, &lay.plan); + m_follow_preview = false; + if (false == m_fits_waiting || false == lay.whole) + { + lay.shown = lay_tool::worked_out{lay.preview, lay.preview_error, lay.preview_length, lay.plan, m_eased_last, m_join_last, lay.points}; + lay.settling.reset(); + } + else if (lay.shown.has_value()) + { + // all of what the line shown was worked out with: the readout tells of it too + auto const &shown{*lay.shown}; + lay.preview = shown.preview; + lay.preview_error = shown.error; + lay.preview_length = shown.length; + lay.plan = shown.plan; + m_eased_last = shown.eased; + m_join_last = shown.join; + } + auto const planning{lap()}; + if (oncursor + snapping + bedding + planning > 30.0) + { + std::string kinds; + for (auto const mode : modes) + kinds += mode == lay_mode::curve ? 'c' : 's'; + WriteLog(format("Editor: slow lay preview: cursor on the ground %.0f ms, snap %.0f ms, height %.0f ms, plan %.0f ms; points %s, from a free end %d, to one %d, %zu pieces, L %.0f m%s", oncursor, snapping, bedding, + planning, kinds.c_str(), lay.start.track != nullptr ? 1 : 0, end.track != nullptr ? 1 : 0, lay.preview.size(), lay.preview_length, + lay.preview_error.empty() ? "" : (", " + lay.preview_error).c_str()), + logtype::generic); + } +} + +bool editor_mode::free_end(TTrack &Track, int const Path, bool const Atend, extend_tool &Tool) +{ + editor_track::point_ref const point{Path, Atend ? editor_track::point_kind::end : editor_track::point_kind::start}; + if (Path < 0 || Path >= static_cast(Track.m_paths.size()) || editor_track::is_connected(Track, point)) + return false; + auto const &path{Track.m_paths[Path]}; + auto const &start{path.points[segment_data::point::start]}; + auto const &end{path.points[segment_data::point::end]}; + auto const &control1{path.points[segment_data::point::control1]}; + auto const &control2{path.points[segment_data::point::control2]}; + glm::dvec3 tangent; + if (Atend) + tangent = control2 != glm::dvec3{} ? -control2 : end - (start + control1); + else + tangent = -(control1 != glm::dvec3{} ? control1 : (end + control2) - start); + glm::dvec2 const planar{tangent.x, tangent.z}; + if (glm::length(planar) < 1e-6) + return false; + Tool.path = Path; + Tool.atend = Atend; + Tool.track = &Track; + Tool.point = editor_track::point_position(Track, point); + Tool.direction = glm::normalize(planar); + Tool.grade = tangent.y / glm::length(planar); + Tool.mouse = Tool.point; + return true; +} + +bool editor_mode::chosen_free_end(extend_tool &Tool) +{ + auto *track{selected_track()}; + if (track == nullptr || (track->eType != tt_Normal && track->eType != tt_Switch) || false == editor_track::is_supported(*track)) + return false; + if (m_track_point.valid() && editor_track::is_end(m_track_point.kind) && free_end(*track, m_track_point.path, m_track_point.kind == editor_track::point_kind::end, Tool)) + return true; + for (int i = 0; i < static_cast(track->m_paths.size()); ++i) + for (auto const atend : {true, false}) + if (free_end(*track, i, atend, Tool)) + return true; + return false; +} + +bool editor_mode::start_extend(editor_track::snap_target const &End) +{ + auto *track{End.track}; + if (track == nullptr || (track->eType != tt_Normal && track->eType != tt_Switch) || false == editor_track::is_supported(*track)) + return false; + extend_tool tool; + if (false == free_end(*track, End.point.path, End.point.kind == editor_track::point_kind::end, tool)) + return false; + auto const &io{ImGui::GetIO()}; + m_extend = tool; + m_extend.origin = End; + m_extend.pressed = {io.MousePos.x, io.MousePos.y}; + m_extend.active = true; + if (track->eType == tt_Switch && End.point.path == 1 && End.point.kind == editor_track::point_kind::end) + m_extend.line = editor_track::find_straight(*track, m_straights.tolerance).tracks; + return true; +} + +bool editor_mode::extend_snap(editor_track::snap_target &Target) const +{ + auto const &tool{m_extend}; + if (false == tool.active || tool.track == nullptr) + return false; + Target = tool.snap; + return Target.track != nullptr && glm::distance(Target.position, tool.point) > 0.5; +} + +glm::dvec3 editor_mode::cursor_ground() const +{ + glm::dvec3 const ground{Global.pCamera.Pos + GfxRenderer->Mouse_Position()}; + if (GfxRenderer->Mouse_Hit()) + return ground; + screen_projection const projection; + glm::dvec3 level; + if (projection.on_level(ImGui::GetIO().MousePos, 0.0, level)) + return level; + return {ground.x, 0.0, ground.z}; +} + +glm::dvec3 editor_mode::cursor_level(double const Height) const +{ + if (m_cursor_override.has_value()) + return glm::dvec3{m_cursor_override->x, Height, m_cursor_override->z}; + glm::dvec3 const ground{cursor_ground()}; + screen_projection const projection; + glm::dvec3 level; + if (false == projection.on_level(ImGui::GetIO().MousePos, Height, level) || (false == Global.editor_tracks && glm::distance(level, glm::dvec3{Global.pCamera.Pos}) > static_cast(kMaxPlacementDistance))) + return ground; + return level; +} + +editor_track::snap_target editor_mode::snap_free_end(glm::dvec3 const &Near, glm::vec2 const &Screen, TTrack const *Self, int const Category, std::vector const &Exclude) const +{ + screen_projection const projection; + auto const reach{Global.EditorOrtho ? std::max(kJointRange, static_cast(Global.EditorOrthoExtent) * 2.0) : kJointRange}; + editor_track::snap_target result; + auto best{kSnapPixels * kSnapPixels}; + for (auto const &candidate : editor_track::free_ends(Self, Category, glm::dvec3{Global.pCamera.Pos}, reach, Exclude)) + { + ImVec2 screen; + if (false == projection.project(candidate.position, screen)) + continue; + auto const distance{(screen.x - Screen.x) * (screen.x - Screen.x) + (screen.y - Screen.y) * (screen.y - Screen.y)}; + if (distance < best) + { + best = distance; + result = candidate; + } + } + if (result.track == nullptr && m_track_snap_radius > 0.0f) + result = editor_track::find_free_end(Self, Category, Near, m_track_snap_radius, Exclude); + return result; +} + +std::vector const &editor_mode::free_end_points(glm::dvec3 const &Centre, double const Reach) const +{ + auto &cache{m_free_end_cache}; + if (cache.edits != m_track_edits || glm::distance(cache.centre, Centre) > cache.reach * 0.25 || Reach > cache.reach * 1.01 || Reach < cache.reach * 0.5) + { + cache.edits = m_track_edits; + cache.centre = Centre; + cache.reach = Reach * 1.25; + cache.points.clear(); + for (auto const &end : editor_track::free_ends(nullptr, kRailCategory, Centre, cache.reach, {})) + cache.points.push_back(end.position); + } + return cache.points; +} + +// the cursor as a ring on the ground, of about the width of the track, to be laid over it on the photo +void editor_mode::draw_cursor_ring(glm::dvec3 const &Point) const +{ + screen_projection const projection; + ImVec2 centre; + if (ImGui::GetIO().WantCaptureMouse || false == projection.project(Point, centre)) + return; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + double constexpr kCursorRadius{0.75}; // m + int constexpr kCursorSteps{36}; + auto const on_ring = [&](int const Step) { + auto const angle{2.0 * glm::pi() * Step / kCursorSteps}; + return Point + glm::dvec3{std::cos(angle) * kCursorRadius, 0.0, std::sin(angle) * kCursorRadius}; + }; + for (int i = 0; i < kCursorSteps; ++i) + projection.line(drawlist, on_ring(i), on_ring(i + 1), IM_COL32(255, 255, 255, 240), 1.5f); + drawlist->AddCircleFilled(centre, 1.5f, IM_COL32(255, 255, 255, 240)); + ImGui::SetMouseCursor(ImGuiMouseCursor_None); +} + +void editor_mode::draw_free_ends(TTrack const *Self, int const Category, std::vector const &Exclude) const +{ + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const &display{ImGui::GetIO().DisplaySize}; + auto const reach{Global.EditorOrtho ? std::max(kJointRange, static_cast(Global.EditorOrthoExtent) * 2.0) : std::min(kJointRange, kDotsRange)}; + for (auto const &candidate : editor_track::free_ends(Self, Category, glm::dvec3{Global.pCamera.Pos}, reach, Exclude)) + { + ImVec2 screen; + if (projection.project(candidate.position, screen) && screen.x >= 0.0f && screen.y >= 0.0f && screen.x <= display.x && screen.y <= display.y) + drawlist->AddCircle(screen, 7.0f, IM_COL32(255, 60, 255, 170), 12, 1.5f); + } +} + +bool editor_mode::switch_reach(glm::dvec3 const &Ground, glm::dvec3 &Point) +{ + auto *selected{selected_track()}; + if (m_track_tab != track_tab::turnout || m_switch.armed < 0 || selected == nullptr || selected->eType != tt_Normal || selected->m_paths.empty()) + return false; + auto const &line{current_straight()}; + if (false == line.tracks.empty()) + { + auto const along{std::clamp(line.along(Ground), 0.0, line.length)}; + Point = line.start + glm::dvec3{line.direction.x, line.grade, line.direction.y} * along; + } + else + { + Point = editor_track::point_at(*selected, editor_track::nearest_parameter(*selected, Ground)); + } + return plan_distance(Point, Ground) <= kSwitchReach; +} + +void editor_mode::handle_drag_start(glm::dvec3 const &Anchor) +{ + auto const &io{ImGui::GetIO()}; + m_handle_drag = {}; + m_handle_drag.active = true; + m_handle_drag.from = {io.MousePos.x, io.MousePos.y}; + m_handle_drag.height = Anchor.y; + m_handle_drag.position = Anchor; + screen_projection const projection; + glm::dvec3 level; + if (projection.on_level(io.MousePos, Anchor.y, level)) + m_handle_drag.offset = {Anchor.x - level.x, 0.0, Anchor.z - level.z}; +} + +bool editor_mode::handle_drag_step(glm::dvec3 &Position, TTrack const *Ground) +{ + auto &drag{m_handle_drag}; + auto const &io{ImGui::GetIO()}; + if (false == drag.active) + return false; + if (false == io.MouseDown[0]) + { + drag = {}; + return false; + } + glm::vec2 const mouse{io.MousePos.x, io.MousePos.y}; + if (false == drag.moved && glm::length(mouse - drag.from) < kDragPixels) + return false; + drag.moved = true; + screen_projection const projection; + glm::dvec3 level; + if (projection.on_level(io.MousePos, drag.height, level) && (Global.editor_tracks || glm::distance(level, glm::dvec3{Global.pCamera.Pos}) <= static_cast(kMaxPlacementDistance))) + { + drag.position = level + drag.offset; + if (Ground != nullptr && false == io.KeyShift) + drag.position.y = bed_height(drag.position, {0.0, 0.0}, Ground); + else + drag.position.y = drag.height; + } + Position = drag.position; + return true; +} + +void editor_mode::point_drag_start(editor_track::point_ref const &Point) +{ + auto *track{selected_track()}; + m_track_point = Point; + m_point_drag = {}; + if (track == nullptr || false == Point.valid() || Point.path >= static_cast(track->m_paths.size())) + return; + auto const &io{ImGui::GetIO()}; + m_point_drag.active = true; + m_point_drag.from = {io.MousePos.x, io.MousePos.y}; + m_point_drag.height = editor_track::point_position(*track, Point).y; +} + +void editor_mode::point_drag_update() +{ + auto &drag{m_point_drag}; + if (false == drag.active) + return; + auto const &io{ImGui::GetIO()}; + if (false == io.MouseDown[0]) + { + point_drag_finish(); + return; + } + auto *track{selected_track()}; + if (track == nullptr || false == m_track_point.valid() || m_track_point.path >= static_cast(track->m_paths.size())) + { + drag = {}; + return; + } + glm::vec2 const mouse{io.MousePos.x, io.MousePos.y}; + if (false == drag.moved) + { + if (glm::length(mouse - drag.from) < kDragPixels) + return; + std::string reason; + if (false == editor_track::can_edit_geometry(*track, reason)) + { + ui()->set_status(reason, true); + drag = {}; + return; + } + drag.moved = true; + m_track_drag = {track}; + m_track_drag_points.clear(); + m_track_joints.clear(); + m_track_snap = {}; + if (editor_track::is_end(m_track_point.kind) && m_track_drag_connected) + { + for (auto const &connection : editor_track::connected_points(*track, editor_track::point_position(*track, m_track_point))) + { + std::string neighbourreason; + if (false == editor_track::can_edit_geometry(*connection.first, neighbourreason)) + continue; + m_track_drag_points.emplace_back(connection); + if (std::find(m_track_drag.begin(), m_track_drag.end(), connection.first) == m_track_drag.end()) + m_track_drag.emplace_back(connection.first); + } + } + std::vector> states; + for (auto *dragged : m_track_drag) + states.emplace_back(dragged, editor_track::capture(*dragged)); + push_track_snapshot(std::move(states)); + drag.step = m_history.size(); + records_watch_begin(); + } + screen_projection const projection; + glm::dvec3 position; + if (false == projection.on_level(io.MousePos, drag.height, position) || (false == Global.editor_tracks && glm::distance(position, glm::dvec3{Global.pCamera.Pos}) > static_cast(kMaxPlacementDistance))) + return; + // an end goes onto the ground at the height of the ballast, as a point laid; with Shift it keeps its height + if (editor_track::is_end(m_track_point.kind) && false == io.KeyShift) + { + auto const &path{track->m_paths[m_track_point.path]}; + auto const tangent{geometry::bezier{path}.first(m_track_point.kind == editor_track::point_kind::end ? 1.0 : 0.0)}; + position.y = bed_height(position, plan_of(tangent), track); + } + m_track_snap = {}; + if (editor_track::is_end(m_track_point.kind) && m_track_drag_points.empty()) + { + std::vector const exclude(m_track_drag.begin(), m_track_drag.end()); + m_track_snap = snap_free_end(position, mouse, track, track->iCategoryFlag & 15, exclude); + if (m_track_snap.track != nullptr) + position = m_track_snap.position; + } + editor_track::move_point(*track, m_track_point, position); + for (auto const &connection : m_track_drag_points) + editor_track::move_point(*connection.first, connection.second, position); + m_track_dirty = true; + commit_track_drag(false); +} + +void editor_mode::point_drag_finish() +{ + auto const drag{m_point_drag}; + m_point_drag = {}; + if (false == drag.active || false == drag.moved) + return; + if (auto *track{selected_track()}; track != nullptr && m_track_snap.track != nullptr && m_track_point.valid()) + { + editor_track::snap_point(*track, m_track_point, m_track_snap, m_track_align_tangent); + m_track_dirty = true; + } + m_track_snap = {}; + commit_track_drag(true); + records_watch_end(); + m_track_drag.clear(); + m_track_drag_points.clear(); + m_track_joints.clear(); +} + +std::optional editor_mode::eased_layout(TTrack const *From, glm::dvec3 const &Point, glm::dvec2 const &Direction, glm::dvec3 const &Target, double const Radius) const +{ + m_eased_last.reset(); + // from the end of a curved track the line goes on from its curvature: a curve from it, a straight after a transition out of it, never + // with a jump of the curvature at the end; at the diverging track of a switch a curve from it, a straight right from its end, as the + // switch goes on with a straight + if (From == nullptr || (From->eType != tt_Normal && (From->eType != tt_Switch || m_track_layout == track_layout::straight))) + return std::nullopt; + auto const end{editor_track::bend_at(*From, Point)}; + if (false == end.has_value()) + return std::nullopt; + alignment::lay_request request; + request.start.position = Point; + request.start.direction = Direction; + request.start.roll = end->roll; + request.curvature = end->curvature; + request.target = Target; + switch (m_track_layout) + { + case track_layout::straight: request.kind = alignment::lay_kind::straight; break; + case track_layout::arc: request.kind = alignment::lay_kind::arc; break; + case track_layout::straight_arc: request.kind = alignment::lay_kind::straight_arc; break; + default: request.kind = alignment::lay_kind::arc_straight; break; + } + request.radius = Radius; + request.speed = design_speed(From, nullptr); + request.piece_length = m_lay.piece_length; + request.norms = laying_norms(); + // the diverging track of a switch has no cant: the line out of its curve is laid for the speed the curve lets with the unbalanced + // acceleration alone, as ease_out_of does + if (From->eType == tt_Switch && std::abs(end->curvature) > 1e-9) + request.speed = std::min(request.speed, std::sqrt(12.96 * request.norms.unbalanced / std::abs(end->curvature))); + if (false == m_eased_cache.has_value() || m_eased_cache->first != request) + m_eased_cache.emplace(request, alignment::lay_on(request)); + m_eased_last = m_eased_cache->second; + return m_eased_last; +} + +namespace +{ + +// the cant of a track joined goes on into the track laid, whatever shape that one has: its difference fades along the pieces from the +// joint, over as many of them as the cant takes at the ramp a transition curve has at the least, or over all of them where they're shorter +void lead_cant(std::vector &Pieces, double const Roll, double const Gauge, bool const From_start) +{ + double constexpr ramp_slope{1.5}; // mm of the cant to a metre + if (Pieces.empty()) + return; + auto const here{From_start ? Pieces.front().rolls[0] : Pieces.back().rolls[1]}; + auto const difference{Roll - static_cast(here)}; + if (std::abs(difference) < 1e-3) + return; + auto const wanted{Gauge * std::abs(std::sin(glm::radians(difference))) / ramp_slope}; + std::vector lengths; + auto reach{0.0}; + for (std::size_t i = 0; i < Pieces.size(); ++i) + { + lengths.push_back(geometry::bezier{Pieces[From_start ? i : Pieces.size() - 1 - i]}.plan_length()); + if (reach < wanted) + reach += lengths.back(); + } + auto along{0.0}; + for (std::size_t i = 0; i < Pieces.size() && along < reach; ++i) + { + auto &piece{Pieces[From_start ? i : Pieces.size() - 1 - i]}; + auto const nearer{difference * (1.0 - along / reach)}; + along += lengths[i]; + auto const further{difference * (1.0 - std::min(along / reach, 1.0))}; + piece.rolls[From_start ? 0 : 1] += static_cast(nearer); + piece.rolls[From_start ? 1 : 0] += static_cast(further); + } +} + +} // namespace + +std::vector editor_mode::extend_pieces() const +{ + m_eased_last.reset(); + std::vector result; + auto const &tool{m_extend}; + editor_track::snap_target target; + if (extend_snap(target)) + { + editor_track::branch_link link; + std::string reason; + if (plan_branch_link(link, reason)) + { + m_join_last = {}; + return link.pieces; + } + double length; + std::string error; + return join_pieces(tool.track, {tool.path, tool.atend ? editor_track::point_kind::end : editor_track::point_kind::start}, tool.point, tool.direction, target, length, error); + } + m_join_last = {}; + auto radius{m_lay.radius}; + if (auto const values{typed_values()}; false == values.empty() && (m_track_layout == track_layout::arc_straight || m_track_layout == track_layout::straight_arc) && std::abs(values[0]) >= 1.0) + radius = std::abs(values[0]); + if (m_track_layout != track_layout::straight && tool.track != nullptr && tool.track->eType == tt_Switch && tool.track->m_paths.size() > 1 && tool.path == 1 && tool.atend) + { + auto const &diverging{tool.track->m_paths[1]}; + bezier const curve{diverging}; + auto const begin{plan_of(curve.first(0.0))}; + auto const finish{plan_of(curve.first(1.0))}; + auto const turn{glm::length(begin) > 1e-9 && glm::length(finish) > 1e-9 ? geometry::signed_angle(begin, finish) : 0.0}; + if (auto const branch{editor_track::branch_radius(diverging)}; branch > 0.0) + { + int const side{turn > 0.0 ? 1 : -1}; + auto const &direction{tool.direction}; + auto const centre{plan_of(tool.point) + glm::dvec2{-direction.y, direction.x} * (side * branch)}; + auto const angle{geometry::signed_angle(plan_of(tool.point) - centre, plan_of(tool.mouse) - centre) * side}; + if (angle * branch < 0.5) + return result; + auto pieces{arc_pieces(tool.point, direction, tool.grade, branch, std::min(angle, glm::pi()), side)}; + for (auto &piece : pieces) + piece.rolls = {diverging.rolls[1], diverging.rolls[1]}; + follow_ground(pieces, tool.point.y, tool.grade, tool.mouse.y, std::numeric_limits::quiet_NaN(), tool.track); + return pieces; + } + } + auto const eased{eased_layout(tool.track, tool.point, tool.direction, tool.mouse, radius)}; + auto pieces{eased.has_value() && false == eased->pieces.empty() ? eased->pieces : editor_track::layout_pieces(m_track_layout, tool.point, tool.direction, tool.grade, tool.mouse, radius)}; + follow_ground(pieces, tool.point.y, tool.grade, tool.mouse.y, std::numeric_limits::quiet_NaN(), tool.track); + if (tool.track != nullptr) + lead_cant(pieces, -editor_track::joint_roll(*tool.track, {tool.path, tool.atend ? editor_track::point_kind::end : editor_track::point_kind::start}), laying_norms().gauge, true); + return pieces; +} + +std::vector editor_mode::extend_preview() const +{ + auto const &tool{m_extend}; + auto const &io{ImGui::GetIO()}; + std::vector key{tool.mouse.x, tool.mouse.y, tool.mouse.z, tool.point.x, tool.point.z, io.MousePos.x, io.MousePos.y, tool.snap.position.x, tool.snap.position.z, + static_cast(reinterpret_cast(tool.track)), static_cast(reinterpret_cast(tool.snap.track)), static_cast(tool.path), + static_cast(tool.active) + 2.0 * tool.atend + 4.0 * io.KeyShift + 8.0 * io.KeyCtrl + 16.0 * io.KeyAlt, m_join_radius, static_cast(m_join_variant), + static_cast(m_track_layout), static_cast(m_history.size())}; + if (false == m_extend_memo.fresh(key)) + { + m_follow_preview = true; + m_extend_memo.keep(std::move(key), extend_pieces()); + m_follow_preview = false; + } + return m_extend_memo.result; +} + +TTrack const *editor_mode::speed_track(TTrack const *From, TTrack const *To) const +{ + if (m_lay.own_speed && m_lay.style.velocity > 0.0) + return nullptr; + TTrack const *result{nullptr}; + for (auto const *track : {From, To}) + if (track != nullptr && editor_track::velocity(*track) > 0.0 && (result == nullptr || editor_track::velocity(*track) < editor_track::velocity(*result))) + result = track; + return result; +} + +double editor_mode::design_speed(TTrack const *From, TTrack const *To) const +{ + if (auto const *track{speed_track(From, To)}; track != nullptr) + return editor_track::velocity(*track); + return m_lay.style.velocity > 0.0 ? m_lay.style.velocity : 100.0; +} + +std::pair editor_mode::laying_ends() const +{ + if (m_extend.active) + { + editor_track::snap_target target; + return {m_extend.track, extend_snap(target) ? target.track : nullptr}; + } + if (m_lay.active && false == m_lay.points.empty()) + return {m_lay.start.track, m_lay.points.size() == 1 ? m_lay.mouse_snap.track : nullptr}; + return {nullptr, nullptr}; +} + +std::string editor_mode::design_speed_of(TTrack const *From, TTrack const *To) const +{ + auto const speed{design_speed(From, To)}; + if (auto const *track{speed_track(From, To)}; track != nullptr) + return format(STR_C("design speed %.0f km/h, that of the track %s"), speed, name_of(*track).c_str()); + return format(STR_C("design speed %.0f km/h, set for the laying"), speed); +} + +std::vector editor_mode::switch_exit_warnings(TTrack const *From, glm::dvec3 const &Start, TTrack const *To, glm::dvec3 const &End, std::vector const &Pieces) const +{ + auto const *switched{From != nullptr && From->eType == tt_Switch ? From : To != nullptr && To->eType == tt_Switch ? To : nullptr}; + if (switched == nullptr || Pieces.empty()) + return {}; + auto const &joint{switched == From ? Start : End}; + // 1/m, positive to the left, as the piece runs + auto const curvature_at = [](segment_data const &Piece, double const T) { return bezier{Piece}.plan_curvature(T); }; + // the path of the switch ending at the joint, its pieces from the joint back into the switch, each with its curvature at its ends as + // the line runs on beyond the joint + std::vector> back; + for (auto const &path : switched->m_paths) + for (auto const atend : {false, true}) + { + if (false == back.empty() || glm::distance(path.points[atend ? segment_data::point::end : segment_data::point::start], joint) > 0.05) + continue; + std::vector pieces{path.pieces.empty() ? std::vector{path} : path.pieces}; + if (atend) + std::reverse(pieces.begin(), pieces.end()); + for (auto const &piece : pieces) + back.push_back({bezier{piece}.plan_length(), atend ? curvature_at(piece, 1.0) : -curvature_at(piece, 0.0), atend ? curvature_at(piece, 0.0) : -curvature_at(piece, 1.0)}); + } + // the curve the switch ends with, and the straight of a straight frog after it + double straight{0.0}; + std::optional curvature; + for (auto const &[length, inner, outer] : back) + { + if (std::abs(inner) > 1e-4 || std::abs(outer) > 1e-4) + { + curvature = inner; + break; + } + straight += length; + } + if (false == curvature.has_value()) + return {}; + // the pieces laid as the line runs on from the switch + std::vector> line; + if (switched == From) + for (auto const &piece : Pieces) + line.push_back({bezier{piece}.plan_length(), curvature_at(piece, 0.0), curvature_at(piece, 1.0)}); + else + for (auto piece{Pieces.rbegin()}; piece != Pieces.rend(); ++piece) + line.push_back({bezier{*piece}.plan_length(), -curvature_at(*piece, 1.0), -curvature_at(*piece, 0.0)}); + // no faster than the diverging track of the switch lets + auto const speed{std::min(design_speed(From, To), editor_track::diverging_speed(1.0 / std::abs(*curvature)))}; + return switch_curve::check_exit(*curvature, straight, line, speed, laying_norms().gauge).warnings; +} + +void editor_mode::give_own_speed(std::vector const &Created) const +{ + if (false == m_lay.own_speed || m_lay.style.velocity <= 0.0) + return; + for (auto *track : Created) + editor_track::velocity(*track, m_lay.style.velocity); +} + +std::vector editor_mode::join_pieces(TTrack const *From, editor_track::point_ref const &Frompoint, glm::dvec3 const &Start, glm::dvec2 const &Direction, editor_track::snap_target const &End, double &Length, + std::string &Error) const +{ + alignment::join_request request; + request.start.position = Start; + request.start.direction = Direction; + request.start.roll = From != nullptr ? -editor_track::joint_roll(*From, Frompoint) : 0.0; + request.end.position = End.position; + request.end.direction = plan_of(End.direction); + request.end.roll = End.track != nullptr ? editor_track::joint_roll(*End.track, End.point) : 0.0; + request.radius = m_join_radius; + request.variant = m_join_variant; + request.speed = design_speed(From, End.track); + request.kink = m_joints.kink_angle() * 0.5; + request.shape = m_route.design.shape; + request.norms = laying_norms(); + auto result{alignment::join(request)}; + if (result.kind != alignment::join_kind::straight && result.kind != alignment::join_kind::arc && glm::length(request.end.direction) > 1e-9) + { + auto const grade{(End.position.y - Start.y) / std::max(1.0, plan_distance(Start, End.position))}; + auto const curved = [](TTrack const *Track) { return Track != nullptr && (Track->eType == tt_Normal || Track->eType == tt_Switch); }; + auto const in{curved(From) ? editor_track::ease_out_of(*From, Start, grade, request.speed, request.norms) : editor_track::easing{}}; + auto const out{curved(End.track) ? editor_track::ease_out_of(*End.track, End.position, -grade, request.speed, request.norms) : editor_track::easing{}}; + if (auto eased{eased_join(request, in, out)}) + result = std::move(*eased); + } + Length = result.length; + std::vector notes; + for (auto const &warning : result.warnings) + if (m_join_radius > 0.0 || std::find(result.radius_warnings.begin(), result.radius_warnings.end(), warning) == result.radius_warnings.end()) + notes.push_back(warning); + if (result.kind == alignment::join_kind::bezier) + notes.insert(notes.begin(), STR_C("No curve fits between the ends, they are joined with a free curve")); + Error = lines_of(notes); + m_join_last = result; + return result.pieces; +} + +void editor_mode::finish_extend() +{ + auto const &io{ImGui::GetIO()}; + if (glm::length(glm::vec2{io.MousePos.x, io.MousePos.y} - m_extend.pressed) < kDragPixels) + { + m_extend.active = false; + if (m_lay.active && m_lay.points.empty() && m_extend.origin.track != nullptr) + { + m_lay.status.clear(); + m_lay.start = m_extend.origin; + m_lay.points.push_back(m_extend.origin.position); + } + else if (false == m_lay.active && m_extend.origin.track != nullptr && m_extend.origin.track == selected_track()) + m_track_point = m_extend.origin.point; + return; + } + std::string reason; + if (editor_track::branch_link link; plan_branch_link(link, reason)) + { + finish_branch_link(link); + return; + } + if (false == reason.empty()) + ui()->set_status(reason, true); + crossover_plan plan; + editor_track::snap_target target; + if (false == extend_snap(target) && plan_crossover(plan)) + { + auto *origin{m_extend.track}; + m_extend.active = false; + std::vector> states; + std::vector created; + std::vector removed; + if (false == place_switch_on_straight(plan.target, plan.shape, origin, plan.along, plan.direction, plan.side, false, states, created, removed, switch_name_for_new())) + return; + auto *placed{*std::find_if(created.begin(), created.end(), [](TTrack const *Track) { return Track != nullptr && Track->eType == tt_Switch; })}; + std::vector inserts; + for (auto piece : plan.inserts) + { + if (glm::distance(piece.points[segment_data::point::start], piece.points[segment_data::point::end]) <= 0.01) + continue; + // meeting the two switches at the heights they're at + for (auto const index : {segment_data::point::start, segment_data::point::end}) + for (auto const *track : {origin, placed}) + if (auto const &end{track->m_paths.back().points[segment_data::point::end]}; geometry::plan_distance(piece.points[index], end) < 0.05) + piece.points[index].y = end.y; + if (auto *insert{editor_track::create_path(*origin, piece)}) + inserts.push_back(insert); + } + editor_track::commit(inserts); + created.insert(created.end(), inserts.begin(), inserts.end()); + // kept as a crossover, so it's taken out, slid and followed as one + record_connection(connection::kind::crossover, {origin, placed}, plan.connection, editor_track::template_of_switch(origin).value_or(plan.shape)); + push_track_snapshot(std::move(states), std::move(created), std::move(removed)); + straight_refresh(); + if (place_switch_drive(*placed)) + join_last_steps(); + advance_switch_name(); + return; + } + auto const pieces{extend_pieces()}; + auto *style{m_extend.track}; + m_extend.active = false; + if (pieces.empty() || style == nullptr) + return; + // the track laid takes only its heights from the ground: the terrain is shaped under it by the buttons of the terrain model + m_nmt_state.laying = true; + std::vector created; + for (auto const &piece : pieces) + created.push_back(editor_track::create_path(*style, piece)); + give_own_speed(created); + editor_track::commit(created); + auto const from{m_history.size()}; + push_track_snapshot({}, created); + first_step_done(first_step::laid); + if (target.track != nullptr) + first_step_done(first_step::join); + if (auto const warnings{switch_exit_warnings(style, pieces.front().points[segment_data::point::start], target.track, target.position, pieces)}; false == warnings.empty()) + ui()->set_status(lines_of(warnings), true); + m_node = created.back(); + ui()->set_node(m_node); + nmt_fit_laid(from, created.back()->m_paths.front().points[segment_data::point::end]); + m_nmt_state.laying = false; + straight_refresh(); +} + +void editor_mode::extend_add(int const Side) +{ + extend_tool tool; + if (false == chosen_free_end(tool)) + return; + auto const length{std::max(0.5, m_extend_length)}; + std::vector pieces; + if (Side == 0) + { + segment_data path; + path.points[segment_data::point::start] = tool.point; + path.points[segment_data::point::end] = {tool.point.x + tool.direction.x * length, tool.point.y + tool.grade * length, tool.point.z + tool.direction.y * length}; + pieces.push_back(path); + } + else + { + auto const radius{std::max(10.0, m_extend_radius)}; + pieces = arc_pieces(tool.point, tool.direction, tool.grade, radius, std::min(length / radius, glm::radians(180.0)), Side); + } + std::vector created; + for (auto const &piece : pieces) + created.push_back(editor_track::create_path(*tool.track, piece)); + editor_track::commit(created); + push_track_snapshot({}, created); + m_node = created.back(); + ui()->set_node(m_node); + m_track_point = {}; + straight_refresh(); +} + +void editor_mode::render_extend_ui() +{ + extend_tool tool; + if (false == chosen_free_end(tool)) + return; + if (false == ImGui::CollapsingHeader(STR_C("Continue from the free end"))) + return; + if (begin_fields("##extendfields", 0.3f)) + { + field_row("Length (m)##extend"); + ImGui::DragScalar("##extendlength", ImGuiDataType_Double, &m_extend_length, 0.5f, nullptr, nullptr, "%.1f"); + item_tooltip("Length of the next piece, along the curve for the curves"); + field_row("R (m)##extend"); + ImGui::DragScalar("##extendradius", ImGuiDataType_Double, &m_extend_radius, 5.0f, nullptr, nullptr, "%.0f"); + item_tooltip("Radius of the curves added"); + ImGui::EndTable(); + } + m_extend_length = std::clamp(m_extend_length, 0.5, 5000.0); + m_extend_radius = std::clamp(m_extend_radius, 10.0, 100000.0); + auto const gap{std::round(ImGui::GetFontSize() * 0.3f)}; + auto const width{std::floor((ImGui::GetContentRegionAvail().x - 2.0f * gap) / 3.0f)}; + auto const at = [](ImVec2 const Low, ImVec2 const High, float const X, float const Y) { return ImVec2(Low.x + (High.x - Low.x) * X, Low.y + (High.y - Low.y) * Y); }; + auto const piece = [&](char const *Id, char const *Label, int const Bend) { + return sketch_tile(Id, Label, false, width, [&](ImDrawList &List, ImVec2 Low, ImVec2 High, ImU32 Line, ImU32) { + List.AddLine(at(Low, High, 0.0f, 0.5f), at(Low, High, 0.4f, 0.5f), Line, 2.0f); + List.AddCircleFilled(at(Low, High, 0.4f, 0.5f), 2.5f, IM_COL32(230, 90, 70, 255)); + if (Bend == 0) + List.AddLine(at(Low, High, 0.4f, 0.5f), at(Low, High, 1.0f, 0.5f), IM_COL32(255, 210, 60, 255), 2.0f); + else + List.AddBezierQuadratic(at(Low, High, 0.4f, 0.5f), at(Low, High, 0.75f, 0.5f), at(Low, High, 0.95f, Bend > 0 ? 0.08f : 0.92f), IM_COL32(255, 210, 60, 255), 2.0f); + }); + }; + if (piece("##extendstraight", STR_C("Straight"), 0)) + extend_add(0); + item_tooltip("Adds a straight at the free end; the new piece gets selected, so the next click goes on from it"); + ImGui::SameLine(0.0f, gap); + if (piece("##extendleft", STR_C("Curve left"), 1)) + extend_add(1); + ImGui::SameLine(0.0f, gap); + if (piece("##extendright", STR_C("Curve right"), -1)) + extend_add(-1); +} + +int editor_mode::wheel_step(double const Offset, bool const Gesture) +{ + auto const &io{ImGui::GetIO()}; + auto const now{ImGui::GetTime()}; + int const keys{(io.KeyCtrl ? 1 : 0) | (io.KeyShift ? 2 : 0) | (io.KeyAlt ? 4 : 0)}; + auto &wheel{m_wheel}; + if (now - wheel.time > 0.3 || keys != wheel.keys || (wheel.rest != 0.0 && (wheel.rest > 0.0) != (Offset > 0.0))) + { + wheel.rest = 0.0; + wheel.spent = false; + } + wheel.time = now; + wheel.keys = keys; + wheel.rest += Offset; + if ((Gesture && wheel.spent) || std::abs(wheel.rest) < 1.0 - 1e-6) + return 0; + int const step{wheel.rest > 0.0 ? 1 : -1}; + wheel.rest -= step; + wheel.spent = true; + return step; +} + +bool editor_mode::track_wheel(double const Offset) +{ + auto const &io{ImGui::GetIO()}; + if (m_switch.placing && m_switch.connection >= 0 && Offset != 0.0 && (io.KeyCtrl || io.KeyShift || io.KeyAlt)) + { + auto &tool{m_switch}; + int const step{wheel_step(Offset, false == io.KeyCtrl)}; + if (step == 0) + return true; + // the kind of a connection a switch dragged makes comes from where it's let go + if (io.KeyShift) + { + if (false == tool.recognised) + tool.connection = (tool.connection + step + connection::kind_count) % connection::kind_count; + } + else if (io.KeyCtrl) + { + static double const radii[]{0.0, 150.0, 190.0, 250.0, 300.0, 400.0, 500.0, 600.0, 800.0, 1000.0, 1200.0, 1500.0, 2000.0, 3000.0}; + int index{0}; + for (int i = 0; i < static_cast(std::size(radii)); ++i) + if (radii[i] <= tool.connection_radius + 1e-6) + index = i; + tool.connection_radius = radii[std::clamp(index + step, 0, static_cast(std::size(radii)) - 1)]; + } + else if (false == tool.recognised) + tool.connection_together = false == tool.connection_together; + return true; + } + if ((false == io.KeyCtrl && false == io.KeyShift) || Offset == 0.0) + return false; + bool const laying{m_lay.active && false == m_lay.points.empty()}; + if (false == m_extend.active && false == laying) + return false; + int const step{wheel_step(Offset, false == io.KeyCtrl)}; + if (step == 0) + return true; + editor_track::snap_target target; + bool const joined{m_extend.active ? extend_snap(target) : m_lay.mouse_snap.track != nullptr && m_lay.start.track != nullptr}; + static double const radii[]{100.0, 150.0, 190.0, 250.0, 300.0, 400.0, 500.0, 600.0, 800.0, 1000.0, 1200.0, 1500.0, 2000.0, 3000.0, 4000.0, 6000.0}; + auto const next_radius = [&](double const Current) { + if (step > 0) + { + for (auto const radius : radii) + if (radius > Current * 1.001) + return radius; + return std::end(radii)[-1]; + } + for (auto radius{std::rbegin(radii)}; radius != std::rend(radii); ++radius) + if (*radius < Current * 0.999) + return *radius; + return radii[0]; + }; + first_step_done(io.KeyCtrl ? first_step::wheel : first_step::shape); + if (io.KeyCtrl && io.KeyShift) + { + static double const speeds[]{20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 120.0, 140.0, 160.0, 200.0, 250.0}; + auto const [from, to]{laying_ends()}; + auto const current{design_speed(from, to)}; + int index{0}; + for (int i = 0; i < static_cast(std::size(speeds)); ++i) + if (speeds[i] <= current + 1e-6) + index = i; + if (step < 0 && speeds[index] < current - 1e-6) + ++index; + m_lay.style.velocity = speeds[std::clamp(index + step, 0, static_cast(std::size(speeds)) - 1)]; + m_lay.own_speed = true; + return true; + } + if (io.KeyCtrl) + { + if (false == joined) + m_lay.radius = next_radius(m_lay.radius); + else if (m_join_radius <= 0.0) + m_join_radius = next_radius(m_join_last.radius > 0.0 ? m_join_last.radius : 500.0); + else if (step > 0 && m_join_radius >= std::end(radii)[-1]) + m_join_radius = 0.0; + else + m_join_radius = next_radius(m_join_radius); + return true; + } + if (joined) + m_join_variant += step; + return true; +} + +std::vector editor_mode::lay_pieces(std::vector const &Points, std::vector const &Modes, editor_track::snap_target const &End, double &Length, std::string &Error, + lay_line_plan *Plan) const +{ + auto const &tool{m_lay}; + Length = 0.0; + m_eased_last.reset(); + if (Points.size() < 2) + return {}; + auto const unknown{std::numeric_limits::quiet_NaN()}; + if (Points.size() == 2 && End.track != nullptr) + { + // two free ends: the curve between them is the one the join finds + if (tool.start.track != nullptr) + { + auto const leaving{-plan_of(tool.start.direction)}; + if (glm::length(leaving) < 1e-6) + { + Error = STR_C("Two points lie on one another"); + return {}; + } + return join_pieces(tool.start.track, tool.start.point, Points[0], glm::normalize(leaving), End, Length, Error); + } + // from a point to a free end: the shape of the layout laid back from the end + m_join_last = {}; + std::vector pieces; + if (glm::length(plan_of(End.direction)) > 1e-6) + { + auto const eased{eased_layout(End.track, End.position, glm::normalize(-plan_of(End.direction)), Points[0], tool.radius)}; + auto const laid{eased.has_value() && false == eased->pieces.empty()}; + auto const back{laid ? eased->pieces : editor_track::layout_pieces(m_track_layout, End.position, glm::normalize(-plan_of(End.direction)), -grade_of(End.direction), Points[0], tool.radius)}; + for (auto piece{back.rbegin()}; piece != back.rend(); ++piece) + pieces.push_back(reversed(*piece)); + Error = laid ? narrowed(m_track_layout, tool.radius, eased->radius) : narrowed(pieces, m_track_layout, tool.radius); + follow_ground(pieces, Points[0].y, unknown, End.position.y, grade_of(End.direction), End.track); + } + for (auto const &piece : pieces) + Length += bezier{piece}.plan_length(); + if (pieces.empty()) + Error = STR_C("The track can't be laid through these points"); + lead_cant(pieces, editor_track::joint_roll(*End.track, End.point), laying_norms().gauge, false); + return pieces; + } + m_join_last = {}; + lay_line_plan plan; + if (false == lay_line(Points, Modes, End, plan, Error)) + return {}; + auto const &design{plan.design}; + auto const &shape{plan.shape}; + Error = lines_of(shape.warnings); + auto const count = [&](alignment::result const &Shape, alignment::design const &Design) { + return std::max(alignment::minimum_pieces(Shape, Design), static_cast(std::ceil(Shape.length / std::max(5.0, tool.piece_length)))); + }; + std::vector pieces; + // the curvature of the track laid has to go on from the one of the plain track it joins, a jump gets a transition curve between them + auto const grade{(Points.back().y - Points.front().y) / std::max(1.0, plan_distance(Points.front(), Points.back()))}; + // out of the curve of a plain track a line which doesn't go on with it begins by a transition; at the end of the diverging track of a + // switch it goes on with the curve of the switch or begins with a straight right there, as lay_line decided, never eased + auto const eased = [&](editor_track::snap_target const &Joint, double const Chainage, double const Sign) { + if (Joint.track == nullptr || Joint.track->eType != tt_Normal) + return editor_track::easing{}; + auto result{editor_track::ease_out_of(*Joint.track, Joint.position, grade * Sign, design.speed, design.norms)}; + auto const own{Sign * curvature_at(shape, Chainage)}; + if (std::abs(own - result.curvature) <= 0.05 * std::abs(result.curvature)) + result.pieces.clear(); + return result; + }; + auto const in{eased(tool.start, 0.0, 1.0)}; + auto const out{eased(End, shape.length, -1.0)}; + if ((false == in.pieces.empty() || false == out.pieces.empty()) && editor_track::eases_room(in, out, Points.front(), design.start_direction, Points.back(), design.end_direction)) + { + auto easeddesign{design}; + // an end moved out of the curve of the adjoining track is on a straight + if (false == in.pieces.empty()) + { + easeddesign.start = in.end; + easeddesign.start_direction = in.direction; + easeddesign.start_curved = false; + easeddesign.start_radius = 0.0; + easeddesign.start_turn = 0; + } + if (false == out.pieces.empty()) + { + easeddesign.end = out.end; + easeddesign.end_direction = -out.direction; + easeddesign.end_curved = false; + easeddesign.end_radius = 0.0; + easeddesign.end_turn = 0; + } + // a straight with no bend, clicked on from the end the way it went: after the transition it runs on the way the transition leaves, + // as far as the point clicked + if (false == in.pieces.empty() && out.pieces.empty() && End.track == nullptr && easeddesign.vertices.empty()) + { + auto const along{glm::normalize(in.direction)}; + auto const distance{glm::dot(plan_of(easeddesign.end - in.end), along)}; + easeddesign.end = {in.end.x + along.x * distance, easeddesign.end.y, in.end.z + along.y * distance}; + easeddesign.end_direction = along; + } + // the bends stay where they are, measured from the ends moved + if (easeddesign.vertices.size() >= 2 && shape.vertices.size() == easeddesign.vertices.size()) + { + easeddesign.vertices.front().offset = std::max(0.1, glm::dot(shape.vertices.front() - plan_of(easeddesign.start), glm::normalize(easeddesign.start_direction))); + easeddesign.vertices.back().offset = std::max(0.1, glm::dot(plan_of(easeddesign.end) - shape.vertices.back(), glm::normalize(easeddesign.end_direction))); + } + auto const easedshape{alignment::ease_corners(easeddesign, plan.corners, {}, bends_fit())}; + if (easedshape.valid) + { + Length = editor_track::eased_length(in, easedshape.length, out); + Error = lines_of(easedshape.warnings); + pieces = editor_track::eased_pieces(in, alignment::pieces(easedshape, easeddesign, count(easedshape, easeddesign)), out); + plan.design = easeddesign; + plan.shape = easedshape; + } + else + Error = STR("The curvature changes abruptly where the track joins, there's no room for a transition curve") + (easedshape.errors.empty() ? std::string{} : ": " + easedshape.errors.front()); + } + if (pieces.empty()) + { + Length = shape.length; + pieces = alignment::pieces(shape, design, count(shape, design)); + // a line lay_line begins at the end of the transition out of the curve of the free end keeps the transition before it + auto const after = [&](editor_track::easing const &Easing, glm::dvec3 const &Joint, glm::dvec3 const &Own) { return false == Easing.pieces.empty() && plan_distance(Joint, Own) > 0.01; }; + auto const &before{after(in, Points.front(), design.start) ? in : editor_track::easing{}}; + auto const &beyond{after(out, Points.back(), design.end) ? out : editor_track::easing{}}; + Length = editor_track::eased_length(before, Length, beyond); + pieces = editor_track::eased_pieces(before, pieces, beyond); + } + // the heights: fitted to the ground, or from point to point through the points clicked + TTrack const *style{tool.start.track != nullptr ? tool.start.track : End.track != nullptr ? End.track : tool.copy_selected ? selected_track() : nullptr}; + auto const grade0{tool.start.track != nullptr ? -grade_of(tool.start.direction) : unknown}; + auto const grade1{End.track != nullptr ? grade_of(End.direction) : unknown}; + if (EditorSettings.heights() == editorSettings::lay_heights::fitted) + follow_ground(pieces, Points.front().y, grade0, Points.back().y, grade1, style); + else + ground_follow::follow_points(pieces, plan.knots, {Points.front().y, grade0, Points.back().y, grade1}); + if (tool.start.track != nullptr) + lead_cant(pieces, -editor_track::joint_roll(*tool.start.track, tool.start.point), design.norms.gauge, true); + if (End.track != nullptr) + lead_cant(pieces, editor_track::joint_roll(*End.track, End.point), design.norms.gauge, false); + if (Plan != nullptr) + *Plan = std::move(plan); + return pieces; +} + +bool editor_mode::traced_from(std::vector const &Points, std::vector const &Modes, bool const AtEnd) +{ + if (Points.size() < (AtEnd ? 3u : 2u)) + return false; + auto const index{AtEnd ? Points.size() - 2 : std::size_t{1}}; + return index < Modes.size() && Modes[index] == lay_mode::curve; +} + +bool editor_mode::lay_line(std::vector const &Points, std::vector const &Modes, editor_track::snap_target const &End, lay_line_plan &Plan, std::string &Error, bool const Adjoining) const +{ + auto const &tool{m_lay}; + Plan = {}; + auto &design{Plan.design}; + design.norms = laying_norms(); + design.shape = m_route.design.shape; + design.speed = design_speed(tool.start.track, End.track); + design.start = Points.front(); + auto const joined{End.track != nullptr && glm::length(plan_of(End.direction)) > 1e-6}; + // from a free end on a curve, or to one, the curve laid next to it turning its way goes on from its curvature: it begins right at the + // end, not on a straight, its transition going from that curvature. A line which doesn't turn its way begins from a straight there: out + // of the curve of a plain track by the transition lay_pieces lays, right at the end of the diverging track of a switch, as the switch + // goes on with a straight. The curve goes on only with a curve traced from it, the bends of straights begin with a straight + if (Adjoining) + { + if (tool.start.track != nullptr && glm::length(plan_of(tool.start.direction)) > 1e-6) + adjoining_curve(tool.start, false, traced_from(Points, Modes, false), design.norms.gauge, design); + if (joined) + adjoining_curve(End, true, traced_from(Points, Modes, true), design.norms.gauge, design); + } + auto const curved{design.start_curved || design.end_curved}; + auto const from_straight = [&]() { return curved && lay_line(Points, Modes, End, Plan, Error, false); }; + // the end of the transition out of the curve of the free end, the start of the line where a curve traced next to it is laid from a + // straight there; the same at the end + std::optional> easedstart; + std::optional> easedend; + // the points between the start and the end: a free end reached is the last point + auto const inner{Points.size() - (joined ? 1 : 0)}; + auto const mode_of = [&](std::size_t const Index) { return Index < Modes.size() ? Modes[Index] : lay_mode::straights; }; + auto const lifted = [](glm::dvec2 const &Point, double const Height) { return glm::dvec3{Point.x, Height, Point.y}; }; + auto const apart = [&](glm::dvec2 const &Direction) { + if (glm::length(Direction) > 1e-6) + return true; + Error = STR_C("Two points lie on one another"); + return false; + }; + + // the straight the line goes on along: a point of it and, where it's fixed, its direction + auto anchor{Points.front()}; + std::optional along; + if (tool.start.track != nullptr && glm::length(plan_of(tool.start.direction)) > 1e-6) + along = glm::normalize(-plan_of(tool.start.direction)); + auto const startdirection{along}; + struct bend + { + glm::dvec3 position{0.0}; + alignment::vertex vertex; + bool corner{true}; + }; + std::vector bends; + // a bend clicked after a straight of a fixed direction goes onto it, as far along it as it was clicked + auto const onto = [&](glm::dvec3 const &Point) { + auto const distance{std::max(1.0, glm::dot(plan_of(Point - anchor), *along))}; + Plan.guides.emplace_back(anchor, lifted(plan_of(anchor) + *along * (distance + std::max(30.0, 0.2 * distance)), anchor.y)); + return lifted(plan_of(anchor) + *along * distance, Point.y); + }; + // the straights meet where the two lines cross, ahead of both points + auto const meeting = [](glm::dvec2 const &From, glm::dvec2 const &Along, glm::dvec2 const &To, glm::dvec2 const &Arriving, glm::dvec2 &Point) { + double t, u; + if (false == geometry::lines_cross(From, Along, To, Arriving, t, u) || t <= 0.0 || u <= 0.0) + return false; + Point = From + Along * t; + return true; + }; + auto const straight_bend = [&](glm::dvec3 Point) { + if (along.has_value()) + { + Point = onto(Point); + along.reset(); + } + bends.push_back({Point, {}, true}); + anchor = Point; + }; + + std::size_t i{1}; + while (i < inner) + { + auto last{i}; + while (last < inner && mode_of(last) == lay_mode::curve) + ++last; + auto const reaching{last == inner && joined}; + // the stretch right from the free end the line starts at, and whether the curve of the end goes on into it: where it turns its way + auto const fromend{bends.empty() && Plan.traces.empty() && along.has_value()}; + auto const goes_on = [&](glm::dvec2 const &Heading) { return fromend && design.start_curved && cross(*along, Heading) * design.start_turn > 1e-9; }; + // a line from the end of the diverging track of a switch which doesn't go on with its curve begins with a straight right there + auto const switched = [](editor_track::snap_target const &Joint) { return Joint.track != nullptr && Joint.track->eType == tt_Switch; }; + auto const straight_from_end = [&]() { + if (fromend && switched(tool.start)) + design.start_curved = false; + }; + // one point of a curve right after a free end on a curve: the curve of the end goes on as far as abreast of the point, seen from + // its centre, the line ending on it there; the curve fitted to the points once more of them are clicked + if (i == 1 && last == 2 && false == reaching && fromend && design.start_curved && design.start_radius > 0.0) + { + auto const radius{design.start_radius}; + auto const side{design.start_turn > 0 ? 1.0 : -1.0}; + auto const from{plan_of(anchor)}; + glm::dvec2 const inward{-along->y * side, along->x * side}; + auto const centre{from + inward * radius}; + auto const outward{plan_of(Points[1]) - centre}; + if (glm::length(outward) > 0.5) + { + // how far round the curve turns to there + auto sweep{std::fmod(side * (std::atan2(outward.y, outward.x) - std::atan2(from.y - centre.y, from.x - centre.x)), 2.0 * glm::pi())}; + if (sweep < 0.0) + sweep += 2.0 * glm::pi(); + if (sweep > 1e-3 && sweep < glm::pi()) + { + alignment::vertex curve; + curve.radius = radius; + curve.cant = design.start_cant; + bends.push_back({lifted(from + *along * (radius * std::tan(0.5 * sweep)), anchor.y), curve, false}); + anchor = lifted(centre + glm::normalize(outward) * radius, Points[1].y); + along = turned(*along, side * sweep); + i = last; + continue; + } + } + } + // a bend of straights, or a point of a curve too alone to make one + if (last == i || (last - i < 2 && false == reaching)) + { + straight_from_end(); + straight_bend(Points[i]); + ++i; + continue; + } + lay_trace trace; + std::vector traced; + for (auto k{i}; k < last; ++k) + { + trace.points.push_back(Points[k]); + traced.push_back(plan_of(Points[k])); + } + i = last; + // the straight the curve comes from: the one of the free end or of the curve before, else the one through the last two + // points clicked before the curve, the last of them then no bend + auto entry{anchor}; + glm::dvec2 entering; + // how far back the curve may begin before the point it comes from: up to the bend or the start before it, half the way back + // to a curve traced before, nothing before a free end + double behind{0.0}; + // the first point clicked, with no heading of its own: the curve fitted may start out of it any way + auto loose{false}; + if (along.has_value()) + { + entering = *along; + if (false == bends.empty()) + behind = 0.5 * plan_distance(entry, bends.back().position); + } + else if (false == bends.empty() && bends.back().corner) + { + entry = bends.back().position; + bends.pop_back(); + auto const before{bends.empty() ? Points.front() : bends.back().position}; + entering = plan_of(entry - before); + behind = plan_distance(entry, before) * (bends.empty() || bends.back().corner ? 1.0 : 0.5); + } + else + { + entering = traced.front() - plan_of(anchor); + loose = bends.empty(); + } + if (false == apart(entering)) + return false; + entering = glm::normalize(entering); + // where the curve ends: at the free end the line finishes at, else at the last point clicked, heading as the circle through the last + // three points does there; a point clicked after it in the mode of the straights, the curve heads for it there, the straight + // to it as clicked + auto exit{trace.points.back()}; + glm::dvec2 leaving; + auto const headed{false == reaching && last < inner}; + if (reaching) + { + exit = End.position; + leaving = glm::normalize(plan_of(End.direction)); + } + else if (headed) + { + leaving = plan_of(Points[last]) - plan_of(exit); + if (false == apart(leaving)) + return false; + leaving = glm::normalize(leaving); + } + else + { + std::vector chain{plan_of(entry)}; + chain.insert(chain.end(), traced.begin(), traced.end()); + leaving = heading_at_end(chain); + if (false == apart(leaving)) + return false; + leaving = glm::normalize(leaving); + } + auto base{design}; + base.start = entry; + base.start_direction = entering; + base.end = exit; + base.end_direction = leaving; + // the curve may begin before the point the straight was clicked at; it ends where the last point is + base.start_reserve = behind; + base.end_reserve = 0.0; + // the curve of the free end it starts at goes on into it where it turns its way, as the one of the free end it finishes at; + // otherwise it begins, or ends, from a straight there: right at a switch, out of the curve of a plain track by a transition + std::vector fitted_points{traced}; + auto const easing = [&](editor_track::snap_target const &Joint) { return switched(Joint) ? editor_track::easing{} : editor_track::ease_out_of(*Joint.track, Joint.position, 0.0, design.speed, design.norms); }; + base.start_curved = goes_on(leaving); + if (fromend && design.start_curved && false == base.start_curved) + { + design.start_curved = false; + if (auto const in{easing(tool.start)}; false == in.pieces.empty()) + { + base.start = in.end; + base.start_direction = in.direction; + easedstart = std::make_pair(in.end, in.direction); + std::erase_if(fitted_points, [&](glm::dvec2 const &Point) { return glm::distance(Point, plan_of(entry)) <= in.length; }); + } + } + base.end_curved = reaching && design.end_curved && cross(entering, leaving) * design.end_turn > 1e-9; + if (reaching && design.end_curved && false == base.end_curved) + { + design.end_curved = false; + if (auto const out{easing(End)}; false == out.pieces.empty()) + { + base.end = out.end; + base.end_direction = -out.direction; + easedend = std::make_pair(out.end, -out.direction); + std::erase_if(fitted_points, [&](glm::dvec2 const &Point) { return glm::distance(Point, plan_of(exit)) <= out.length; }); + } + } + { + auto const fit_to = [&](glm::dvec2 const &Leaving, bool const Meanwhile, bool &Exact) { + auto trial{base}; + trial.end_direction = Leaving; + return fitted_points.empty() ? std::optional{alignment::trace_stretch{}} : traced_stretch(trial, fitted_points, tool.radii, tool.straights_between, Meanwhile, &Exact); + }; + // a curve going on from the curve of the free end the line starts at: fitted as its curvature runs from that of the end to the + // last point, where it ends on the straight it comes out to; between the straights only where no such curve follows the points + bool exact{true}; + std::optional fitted; + std::optional going; + if (base.start_curved && false == reaching && false == headed && false == fitted_points.empty()) + if (auto const along{traced_stretch(base, fitted_points, tool.radii, tool.straights_between, true, &exact, true)}; along.has_value() && along->valid) + going = along; + // from a switch the curve goes on at its radius; where that doesn't keep to the points, m, and they show a straight right at the + // switch, as the switch goes on with one, the curve fitted from it beginning a few metres on at least, not a curve of another + // radius right there, and keeping to them much closer, that one + constexpr double kGoingClose{0.08}; + constexpr double kGoingWithin{0.3}; + constexpr double kStraightFirst{5.0}; + if (going.has_value() && base.start_held && (going->rms > kGoingClose || going->worst > kGoingWithin)) + { + auto straight{base}; + straight.start_curved = false; + auto const straight_first = [&](alignment::trace_stretch const &Fit) { + if (Fit.vertices.empty()) + return true; + auto trial{straight}; + trial.vertices = Fit.vertices; + trial.norms.checked = false; + auto const laid{alignment::compute(trial)}; + return laid.valid && false == laid.elements.empty() && laid.elements.front().kind == alignment::element_kind::straight && laid.elements.front().length >= kStraightFirst; + }; + if (auto const other{traced_stretch(straight, fitted_points, tool.radii, tool.straights_between, true)}; other.has_value() && other->valid && other->rms < 0.75 * going->rms && straight_first(*other)) + { + // the jump of the curvature there the switch has as it has one at its start: nothing to warn of + going.reset(); + base.start_curved = false; + design.start_curved = false; + design.start_radius = 0.0; + design.start_turn = 0; + } + } + // the same into the curve of the free end the line finishes at, from the first point clicked: fitted from that end back, the + // line starting from the first point on the straight the curve comes out of + std::optional into; + if (false == going.has_value() && reaching && base.end_curved && loose && false == fitted_points.empty()) + { + auto back{base}; + back.start = base.end; + back.start_direction = -leaving; + back.start_curved = true; + back.start_held = base.end_held; + back.start_radius = base.end_radius; + back.start_turn = -base.end_turn; + back.start_cant = base.end_cant; + back.end = entry; + back.end_direction = -entering; + back.end_curved = false; + back.end_held = false; + back.start_reserve = back.end_reserve = 0.0; + std::vector points{fitted_points.rbegin(), fitted_points.rend()}; + points.push_back(plan_of(entry)); + if (auto const fit{traced_stretch(back, points, tool.radii, tool.straights_between, true, &exact, true)}; fit.has_value() && fit->valid && false == fit->vertices.empty()) + into = turned_round(*fit); + } + if (going.has_value()) + { + fitted = going; + leaving = going->leaving; + base.end_direction = leaving; + // the arc of a switch going on ends abreast of the last point + exit = lifted(going->ending, exit.y); + } + else if (into.has_value()) + { + fitted = into; + entering = into->leaving; + base.start_direction = entering; + } + else + fitted = fit_to(leaving, true, exact); + // the curve ends at the last point: where the one fitted ends short of it, the straight after it going on to the point, the line + // leaves the point turning more, by bisection where it turns too much for a curve to reach the point. A few fits more, done on + // the thread from frame to frame while the cursor moves + if (false == going.has_value() && false == reaching && false == headed && exact && fitted.has_value() && fitted->valid && false == fitted->vertices.empty()) + { + // how far along the line laid its curves reach + auto const curves_reach = [](alignment::result const &Laid) { + double reach{0.0}; + for (auto const &element : Laid.elements) + if (element.kind != alignment::element_kind::straight) + reach = std::max(reach, element.chainage + element.length); + return reach; + }; + // the radius the last curve ends with + auto const end_radius = [](alignment::vertex const &Vertex) { return std::max(10.0, Vertex.arcs.empty() ? Vertex.radius : Vertex.arcs.back().radius); }; + auto const short_of = [&](alignment::trace_stretch const &Fit, glm::dvec2 const &Leaving) -> std::optional { + if (false == Fit.valid) + return std::nullopt; + auto trial{base}; + trial.end_direction = Leaving; + trial.vertices = Fit.vertices; + trial.norms.checked = false; + auto const laid{alignment::compute(trial)}; + if (false == laid.valid) + return std::nullopt; + return laid.length - curves_reach(laid); + }; + auto const turn{cross(entering, leaving) >= 0.0 ? 1.0 : -1.0}; + auto const turned = [&](double const Angle) { return geometry::turned(leaving, turn * Angle); }; + auto const ending{end_radius(fitted->vertices.back())}; + // the last two points clicked on the straight after the curve, as the mode asks for: the straight goes through them, the curve + // fitted with their heading ending before them; before the last one alone, where the last three points show a line much + // flatter than the end of the curve. Only points showing the curve going on draw it on to the last one + // a fit of the straight clicked after the curve is still on the thread + bool straight_waiting{false}; + auto const clicked_straight = [&]() -> std::optional> { + constexpr double kFlatter{4.0}; + auto const count{fitted_points.size()}; + if (count < 4) + return std::nullopt; + auto const chord{fitted_points[count - 1] - fitted_points[count - 2]}; + if (glm::length(chord) < 1e-6) + return std::nullopt; + auto const fitted_heading = [&](glm::dvec2 const &Heading) -> std::optional { + bool again{true}; + auto const fit{fit_to(Heading, false, again)}; + if (false == fit.has_value()) + straight_waiting = true; + if (false == fit.has_value() || false == fit->valid || fit->vertices.empty()) + return std::nullopt; + return fit; + }; + auto const chorded{glm::normalize(chord)}; + auto heading{chorded}; + // the heading of two points clicked a little off is a little off too: turned a bit either way, and to where the closeness + // to all the points says the bottom is, the heading the curve keeps closest to them with. A few fits more, done on the + // thread from frame to frame while the cursor moves + auto const rotated = [&](double const Angle) { return geometry::turned(chorded, Angle); }; + // none for points clicked as closely as this: their heading is good as it is + constexpr double kClose{0.05}; + auto const step{std::clamp(0.5 / glm::length(chord), 0.002, 0.03)}; + auto fit{fitted_heading(heading)}; + if (false == fit.has_value()) + { + // the two turned either way asked for with it, the thread fitting them one after another, not a frame after + if (straight_waiting && tool.whole) + { + fitted_heading(rotated(-step)); + fitted_heading(rotated(step)); + } + return std::nullopt; + } + auto const minus{fit->rms > kClose ? fitted_heading(rotated(-step)) : std::nullopt}; + auto const plus{fit->rms > kClose ? fitted_heading(rotated(step)) : std::nullopt}; + if (minus.has_value() && plus.has_value()) + { + auto const centre{fit->rms}; + auto angle{0.0}; + if (minus->rms < fit->rms) + { + fit = minus; + angle = -step; + } + if (plus->rms < fit->rms) + { + fit = plus; + angle = step; + } + if (auto const bend{minus->rms - 2.0 * centre + plus->rms}; bend > 1e-12) + { + auto const bottom{std::clamp(0.5 * step * (minus->rms - plus->rms) / bend, -2.0 * step, 2.0 * step)}; + if (auto const there{fitted_heading(rotated(bottom))}; there.has_value() && there->rms < fit->rms) + { + fit = there; + angle = bottom; + } + } + heading = rotated(angle); + } + auto trial{base}; + trial.end_direction = heading; + trial.vertices = fit->vertices; + trial.norms.checked = false; + auto const laid{alignment::compute(trial)}; + if (false == laid.valid) + return std::nullopt; + auto const reach{curves_reach(laid)}; + auto const projections{alignment::project(laid, {fitted_points[count - 2], fitted_points[count - 1]})}; + if (projections.size() < 2 || projections[1].chainage < reach) + return std::nullopt; + if (projections[0].chainage < reach) + { + // the circle through the last three points + auto const before{fitted_points[count - 2] - fitted_points[count - 3]}; + auto const turn{std::abs(cross(before, chord))}; + auto const circle{turn > 1e-12 ? glm::length(before) * glm::length(chord) * glm::length(before + chord) / (2.0 * turn) : std::numeric_limits::max()}; + if (circle < kFlatter * end_radius(fit->vertices.back())) + return std::nullopt; + } + return std::make_pair(*fit, heading); + }; + auto const first{short_of(*fitted, leaving)}; + auto const straight{first.has_value() && *first > 0.5 ? clicked_straight() : std::nullopt}; + if (straight.has_value()) + { + fitted = straight->first; + leaving = straight->second; + base.end_direction = leaving; + } + else if (straight_waiting && tool.whole) + { + // the line waits for the straight: no more turns asked for meanwhile, the thread fitting them before it + } + else if (first.has_value() && *first > 0.5) + { + auto low{0.0}; + auto lowshort{*first}; + std::optional high; + auto best{fitted}; + auto bestangle{0.0}; + // by 15 degrees at most: more is no longer the heading the points show + constexpr double kMost{0.26}; + auto angle{std::min(kMost, lowshort / ending)}; + // the turn the line before was given first: the cursor has moved on a little since, it's near enough most often + if (tool.whole && m_turned_last > 0.0) + angle = std::min(kMost, m_turned_last); + auto waited{false}; + for (int i = 0; i < 8; ++i) + { + bool again{true}; + auto const trial{fit_to(turned(angle), false, again)}; + if (false == trial.has_value()) + { + waited = true; + break; + } + if (auto const left{short_of(*trial, turned(angle))}; left.has_value() && *left >= 0.0) + { + low = angle; + lowshort = *left; + best = trial; + bestangle = angle; + if (lowshort <= 0.5) + break; + } + else + high = angle; + if (false == high.has_value() && low >= kMost) + break; + angle = high.has_value() ? 0.5 * (low + *high) : std::min(kMost, low + lowshort / ending); + } + if (false == waited) + m_turned_last = bestangle; + fitted = best; + leaving = turned(bestangle); + base.end_direction = leaving; + } + } + if (false == fitted.has_value()) + { + Error = STR_C("Fitting the curve to the points..."); + return false; + } + auto const &fit{*fitted}; + if (false == fit.valid) + { + Error = STR_C("No curve follows the points clicked along it"); + return from_straight(); + } + for (auto const &vertex : fit.vertices) + bends.push_back({lifted(vertex.position, entry.y), vertex, false}); + if (fit.vertices.empty()) + { + // a straight: the two lines are one + exit = lifted(plan_of(entry) + entering * glm::dot(plan_of(exit - entry), entering), exit.y); + leaving = entering; + } + trace.offsets = fit.offsets; + trace.rms = fit.rms; + trace.worst = fit.worst; + trace.curves = fit.vertices.size(); + } + Plan.traces.push_back(std::move(trace)); + anchor = exit; + along = leaving; + } + + // the end: the free end reached, the end of a curve traced, or the last point clicked + glm::dvec3 end; + glm::dvec2 ending; + if (joined) + { + end = End.position; + ending = glm::normalize(plan_of(End.direction)); + if (along.has_value() && (false == bends.empty() || false == Plan.traces.empty())) + { + // from the straight out of a curve traced to the one of the free end: a bend where they meet + glm::dvec2 corner; + if (meeting(plan_of(anchor), *along, plan_of(end), -ending, corner)) + bends.push_back({lifted(corner, anchor.y), {}, true}); + } + } + else if (along.has_value()) + { + end = anchor; + ending = *along; + } + else + { + if (bends.empty()) + { + Error = STR_C("Click at least two points"); + return false; + } + end = bends.back().position; + bends.pop_back(); + ending = plan_of(end) - plan_of(bends.empty() ? Points.front() : bends.back().position); + if (false == apart(ending)) + return false; + ending = glm::normalize(ending); + } + if (plan_distance(end, Points.front()) < 1.0) + { + Error = STR_C("Click at least two points"); + return false; + } + design.end = end; + design.end_direction = ending; + if (startdirection.has_value()) + design.start_direction = *startdirection; + else + { + auto const first{plan_of(bends.empty() ? end : bends.front().position) - plan_of(Points.front())}; + if (false == apart(first)) + return false; + design.start_direction = glm::normalize(first); + } + if (easedstart.has_value()) + std::tie(design.start, design.start_direction) = *easedstart; + if (easedend.has_value()) + { + std::tie(design.end, design.end_direction) = *easedend; + end = design.end; + } + // the last bend goes onto the line of the free end, as far before it as it was clicked: one clicked past it would come into the end + // the wrong way, the joint turned round + if (joined && false == bends.empty() && bends.back().corner && glm::dot(plan_of(end - bends.back().position), design.end_direction) <= 0.0) + { + Error = STR_C("The last point clicked lies past the free end: the track can't come into it from there"); + return false; + } + for (auto const &bend : bends) + { + auto vertex{bend.corner ? alignment::vertex{} : bend.vertex}; + vertex.position = plan_of(bend.position); + design.vertices.push_back(vertex); + Plan.corners.push_back(bend.corner ? 1 : 0); + } + if (design.vertices.size() >= 2) + { + design.vertices.front().offset = glm::dot(plan_of(bends.front().position - design.start), design.start_direction); + design.vertices.back().offset = glm::dot(plan_of(end - bends.back().position), design.end_direction); + } + Plan.shape = alignment::ease_corners(design, Plan.corners, {}, bends_fit()); + if (false == Plan.shape.valid) + { + Error = Plan.shape.errors.empty() ? std::string{STR_C("The track can't be laid through these points")} : Plan.shape.errors.front(); + return from_straight(); + } + // the grade breaks at the bends which stayed bends; along a curve, traced or made of bends, it goes on even from end to end + for (std::size_t k = 0; k < design.vertices.size() && k < Plan.corners.size(); ++k) + { + if (Plan.corners[k] != 1) + continue; + for (auto const &bend : bends) + if (bend.corner && glm::distance(plan_of(bend.position), design.vertices[k].position) < 1e-3) + { + Plan.knots.push_back(bend.position); + break; + } + } + return true; +} + +std::optional editor_mode::traced_stretch(alignment::design const &Base, std::vector const &Points, int const Radii, bool const Straights, bool const Meanwhile, + bool *Exact, bool const Going) const +{ + if (Exact != nullptr) + *Exact = true; + // the stretches traced before the one the cursor moves along are the same from frame to frame: their fits are kept + // the curves of the adjoining tracks it goes on from or into, signed by their turn, and their cants + auto const curvature = [](bool const Curved, double const Radius, int const Turn) { return Curved && Radius > 0.0 ? Turn / Radius : 0.0; }; + std::vector key{Base.start.x, Base.start.z, Base.start_direction.x, Base.start_direction.y, Base.end.x, Base.end.z, Base.end_direction.x, Base.end_direction.y, Base.speed, + static_cast(Base.shape), static_cast(Radii), Straights ? 1.0 : 0.0, Base.start_reserve, Base.end_reserve, + curvature(Base.start_curved, Base.start_radius, Base.start_turn), Base.start_curved ? Base.start_cant : 0.0, curvature(Base.end_curved, Base.end_radius, Base.end_turn), + Base.end_curved ? Base.end_cant : 0.0, (Going ? 1.0 : 0.0) + (Base.start_held ? 2.0 : 0.0) + (Base.end_held ? 4.0 : 0.0)}; + for (auto const &point : Points) + { + key.push_back(point.x); + key.push_back(point.y); + } + auto &cache{m_stretch_cache}; + for (auto entry{cache.begin()}; entry != cache.end(); ++entry) + if (entry->first == key) + { + std::rotate(cache.begin(), entry, std::next(entry)); + return cache.front().second; + } + auto const keep = [&](alignment::trace_stretch const &Fit) { + cache.insert(cache.begin(), {key, Fit}); + if (cache.size() > 16) + cache.pop_back(); + }; + alignment::trace_stretch fit; + if (false == m_follow_preview) + { + fit = Going ? alignment::fit_going_on(Base, Points) : alignment::fit_trace_stretch(Base, Points, Radii, Straights); + keep(fit); + return fit; + } + // shown while the cursor moves: fitted on the thread, the frames meanwhile drawn with the fit done last for the same points but + // the one at the cursor, or with no curve yet + if (m_stretch_fitter.done(key, fit)) + { + keep(fit); + return fit; + } + m_fits_waiting = true; + m_stretch_fitter.ask({key, Base, Points, Radii, Straights, Going}); + std::vector last; + auto const header{std::size_t{19}}; + if (Meanwhile && m_stretch_fitter.latest(last, fit) && last.size() >= header + 2 && key.size() >= header + 2 && std::equal(key.begin(), key.begin() + 4, last.begin()) && + std::equal(key.begin() + 8, key.begin() + header, last.begin() + 8)) + { + auto const common{std::min(last.size(), key.size()) - 2}; + if (std::equal(key.begin() + header, key.begin() + common, last.begin() + header)) + { + if (Exact != nullptr) + *Exact = false; + return fit; + } + } + return {}; +} + +void editor_mode::lay_trim() +{ + auto &tool{m_lay}; + tool.modes.resize(tool.points.size(), lay_mode::straights); +} + +void editor_mode::lay_switch_mode() +{ + auto &tool{m_lay}; + tool.mode = tool.mode == lay_mode::straights ? lay_mode::curve : lay_mode::straights; + m_track_layout = tool.mode == lay_mode::curve ? track_layout::arc_straight : track_layout::straight; + if (tool.mode == lay_mode::curve) + first_step_done(first_step::trace); + tool.status = tool.mode == lay_mode::curve ? STR("Curve: click points along the middle of the track, the curve ends at the last one. Tab: back to the straights") + : STR("Straights: each point clicked is a bend of the straights, eased with a large curve. Tab: a curve traced on the photo"); + tool.status_time = ImGui::GetTime(); +} + +void editor_mode::lay_click() +{ + auto &tool{m_lay}; + tool.status.clear(); + lay_trim(); + auto const snap{tool.mouse_snap}; + if (snap.track != nullptr && false == tool.points.empty() && glm::distance(snap.position, tool.points.front()) > 1.0) + { + // reaching a free end finishes the track there, in line with the path it joins + tool.points.push_back(snap.position); + tool.modes.push_back(tool.mode); + lay_finish(snap); + return; + } + if (tool.points.empty()) + { + tool.start = snap; + auto point{snap.track != nullptr ? snap.position : tool.mouse}; + if (auto const *axis{snap.track == nullptr && ImGui::GetIO().KeyAlt ? skew_reference(point, point, kSkewSeat) : nullptr}) + { + auto const &path{axis->m_paths.front()}; + auto const &from{path.points[segment_data::point::start]}; + auto const &to{path.points[segment_data::point::end]}; + auto const along{std::clamp(glm::dot(plan_of(point - from), plan_of(to - from)) / glm::dot(plan_of(to - from), plan_of(to - from)), 0.0, 1.0)}; + point = from + (to - from) * along; + } + tool.points.push_back(point); + tool.modes.push_back(tool.mode); + return; + } + // the points only make the line shown: it's laid by Enter, or by a click on a free end + auto const &point{tool.mouse}; + if (plan_distance(point, tool.points.back()) < 1.0) + return; + m_typed.clear(); + tool.points.push_back(point); + tool.modes.push_back(tool.mode); +} + +void editor_mode::lay_finish(editor_track::snap_target const &End) +{ + auto &tool{m_lay}; + lay_trim(); + double length; + std::string error; + lay_line_plan plan; + auto const pieces{lay_pieces(tool.points, tool.modes, End, length, error, &plan)}; + auto const eased{m_eased_last}; + tool.status_time = ImGui::GetTime(); + if (pieces.empty()) + { + tool.status = error.empty() ? std::string{STR_C("Click at least two points")} : error; + if (End.track != nullptr && false == tool.points.empty()) + { + tool.points.pop_back(); + lay_trim(); + } + return; + } + auto const *style{tool.start.track != nullptr ? tool.start.track : End.track}; + if (style == nullptr && tool.copy_selected) + style = selected_track(); + // the track laid takes only its heights from the ground: the terrain is shaped under it by the buttons of the terrain model + m_nmt_state.laying = true; + std::vector created; + for (auto const &piece : pieces) + created.push_back(style != nullptr ? editor_track::create_path(*style, piece) : editor_track::create_path(tool.style, piece)); + give_own_speed(created); + editor_track::commit(created); + // the scenery keeps the design the tracks were laid by, as it is, for the plan to edit; read from the paths again it wouldn't be + // the same, a compound curve with transitions between its arcs least of all. A track laid with no design of the line, between two + // free ends or back from one, keeps none: the plan reads its curves when it's opened + // with the points clicked, which the plan fits the curves to again when their transitions or cants change + if (plan.shape.valid && false == created.empty() && false == scene::Layers.empty()) + alignment_store::store(plan.design, plan.shape, 0.0, alignment_store::layer_of(*created.front()), "drawn", 0.0, tool.points); + tool.history = m_history.size(); + push_track_snapshot({}, created); + first_step_done(first_step::laid); + if (plan.shape.valid && false == plan.shape.curves.empty()) + first_step_done(first_step::bend); + if (End.track != nullptr) + first_step_done(first_step::join); + tool.status = format(STR_P("Laid %.1f m of track in %zu piece, Ctrl+Z takes it back", "Laid %.1f m of track in %zu pieces, Ctrl+Z takes it back", static_cast(created.size())), length, created.size()); + if (false == error.empty()) + tool.status += "\n" + error; + if (eased.has_value() && eased->compound) + tool.status += "\n" + format(STR_C("Compound curve: R %.0f m goes on into R %.0f m through a transition curve of %.0f m"), eased->from_radius, eased->radius, eased->entry); + // the curves next to the free ends going on from the curves of their tracks + if (plan.shape.valid) + for (auto const &curve : plan.shape.curves) + if (auto const on{curve_goes_on(curve)}; false == on.empty()) + tool.status += "\n" + format(STR_C("Curve %d %s"), curve.vertex + 1, on.c_str()); + if (eased.has_value() && false == eased->note.empty()) + tool.status += "\n" + eased->note; + for (auto const &warning : switch_exit_warnings(tool.start.track, tool.points.front(), End.track, End.position, pieces)) + tool.status += "\n" + warning; + { + std::vector> run; + if (tool.start.track != nullptr && tool.start.track->eType == tt_Normal) + run.emplace_back(tool.start.track, tool.start.point.kind == editor_track::point_kind::end); + for (auto *track : created) + run.emplace_back(track, true); + if (End.track != nullptr && End.track->eType == tt_Normal) + run.emplace_back(End.track, End.point.kind == editor_track::point_kind::start); + editor_track::curve curve; + if (run.size() > created.size() && editor_track::analyse_curve(run, m_route.design.norms.gauge, curve) && curve.compound) + for (std::size_t i = 1; i < curve.arcs.size(); ++i) + if (curve.arcs[i].transition < 1.0) + { + tool.status += "\n" + format(STR_C("Compound curve: R %.0f m meets R %.0f m with no transition curve between them"), curve.arcs[i - 1].radius, curve.arcs[i].radius); + break; + } + } + if (scene::Layers.active() == null_handle && style == nullptr) + tool.status += "\n" + STR("The scenery isn't opened for editing: new track won't be saved"); + m_node = created.back(); + ui()->set_node(m_node); + if (nmt_fit_laid(tool.history, created.back()->m_paths.front().points[segment_data::point::end])) + tool.status += "\n" + STR("The grade line of the whole track laid in a row fitted to the terrain model, as the tracks go onto the terrain"); + m_nmt_state.laying = false; + nmt_check_buried(tool.history); + WriteLog("Editor: " + tool.status, logtype::generic); + tool.points.clear(); + tool.modes.clear(); + tool.start = {}; + straight_refresh(); +} + +void editor_mode::lay_enter() +{ + auto &tool{m_lay}; + if (false == m_typed.empty()) + { + lay_click(); + return; + } + lay_trim(); + if (tool.points.empty()) + return; + auto const end{tool.mouse_snap}; + if (end.track != nullptr && glm::distance(end.position, tool.points.front()) > 1.0) + { + tool.points.push_back(end.position); + tool.modes.push_back(tool.mode); + lay_finish(end); + return; + } + // a single point is no track: Enter drops it + if (tool.points.size() < 2) + { + lay_cancel(); + return; + } + // the laying ends with the track laid: the next click starts anew where it's made, a click on the free end left goes on from + // it. Going on by itself, a click made elsewhere afterwards led a loop out of that end to it + lay_finish({}); +} + +void editor_mode::lay_cancel() +{ + auto &tool{m_lay}; + tool.points.clear(); + tool.modes.clear(); + tool.start = {}; + tool.preview.clear(); + tool.plan = {}; + tool.status.clear(); +} + +std::size_t editor_mode::lay_pending() const +{ + return m_lay.points.size(); +} + +void editor_mode::lay_escape() +{ + auto &tool{m_lay}; + lay_trim(); + // the points clicked are no track yet and nothing brings them back: a slip of Esc only warns, the second one drops them + auto const pending{lay_pending()}; + if (tool.points.size() < 2 || ImGui::GetTime() - tool.escape_time < 3.0) + { + lay_cancel(); + tool.escape_time = -100.0; + return; + } + tool.escape_time = ImGui::GetTime(); + tool.status = format(STR_P("Esc again drops the point not laid, Enter lays it", "Esc again drops the %zu points not laid, Enter lays them", static_cast(pending)), pending); + tool.status_time = tool.escape_time; +} + +void editor_mode::lay_after_history(bool const Undo) +{ + auto &tool{m_lay}; + if (tool.points.empty()) + return; + if (false == Undo) + { + lay_cancel(); + return; + } + // the free end the points go on from taken back + if (tool.start.track != nullptr && tool.start.track->m_editorremoved) + lay_cancel(); +} + +void editor_mode::lay_back() +{ + auto &tool{m_lay}; + lay_trim(); + // the points not laid yet, the last one first; the tracks laid go back with Ctrl+Z + if (tool.points.size() > 1) + { + tool.points.pop_back(); + tool.modes.pop_back(); + return; + } + tool.points.clear(); + tool.modes.clear(); + tool.start = {}; +} + +glm::dvec3 editor_mode::lay_angle_snap(glm::dvec3 const &Mouse, std::string &Label) const +{ + Label.clear(); + auto const &last{m_lay.points.back()}; + glm::dvec2 const offset{Mouse.x - last.x, Mouse.z - last.z}; + auto const length{glm::length(offset)}; + if (length < 1.0) + return Mouse; + auto const leaving{m_lay.start.track != nullptr ? -plan_of(m_lay.start.direction) : glm::dvec2{0.0}}; + glm::dvec2 reference{glm::length(leaving) > 1e-6 ? glm::normalize(leaving) : glm::dvec2{0.0, 1.0}}; + auto const step{glm::radians(15.0)}; + auto angle{std::round(signed_angle(reference, offset / length) / step) * step}; + if (auto const *axis{skew_reference(last, Mouse, kSkewReach)}) + { + auto const &path{axis->m_paths.front()}; + reference = glm::normalize(plan_of(path.points[segment_data::point::end] - path.points[segment_data::point::start])); + auto const relative{signed_angle(reference, offset / length)}; + angle = std::round(relative / step) * step; + double ratio{0.0}; + for (auto const n : kSkewRatios) + for (auto const base : {0.0, glm::pi()}) + for (auto const side : {-1.0, 1.0}) + { + auto const candidate{base + side * std::atan(1.0 / n)}; + if (std::abs(std::remainder(relative - candidate, 2.0 * glm::pi())) < std::abs(std::remainder(relative - angle, 2.0 * glm::pi()))) + { + angle = candidate; + ratio = n; + } + } + auto const name{name_of(*axis)}; + auto const degrees{glm::degrees(std::abs(std::remainder(angle, glm::pi())))}; + Label = ratio > 0.0 ? format(STR_C("1:%g to %s"), ratio, name.c_str()) : degrees < 0.1 ? format(STR_C("parallel to %s"), name.c_str()) : format(STR_C("%.0f deg to %s"), degrees, name.c_str()); + } + auto const heading{turned(reference, angle) * length}; + return {last.x + heading.x, Mouse.y, last.z + heading.y}; +} + +TTrack const *editor_mode::skew_reference(glm::dvec3 const &From, glm::dvec3 const &To, double const Reach) const +{ + auto const from{plan_of(From)}; + auto const leg{plan_of(To) - from}; + auto const length{glm::length(leg)}; + TTrack const *nearest{nullptr}; + auto best{std::numeric_limits::max()}; + for (auto *section : simulation::Region->sections((From + To) * 0.5, static_cast(std::min(0.5 * length + Reach, 2000.0)))) + for (auto const &cell : section->m_cells) + for (auto *track : cell.m_directories.paths) + { + if (track == nullptr || track->eType != tt_Normal || track->m_editorremoved || (track->iCategoryFlag & 15) != kRailCategory || track->m_paths.size() != 1 || + false == editor_track::is_straight(*track, m_straights.tolerance)) + continue; + auto const &path{track->m_paths.front()}; + auto const a{plan_of(path.points[segment_data::point::start])}; + auto const axis{plan_of(path.points[segment_data::point::end]) - a}; + auto const span{glm::length(axis)}; + if (span < 1.0) + continue; + auto const along{std::clamp(glm::dot(from - a, axis) / span, 0.0, span)}; + auto distance{glm::distance(from, a + axis / span * along)}; + if (distance > Reach) + distance = std::numeric_limits::max(); + if (auto const determinant{cross(leg, axis)}; length > 1.0 && std::abs(determinant) > 1e-9) + { + auto const t{cross(a - from, axis) / determinant}; + auto const u{cross(a - from, leg) / determinant}; + if (t >= 0.0 && t <= 1.0 && u >= 0.0 && u <= 1.0) + distance = std::min(distance, t * length); + } + if (distance < best) + { + best = distance; + nearest = track; + } + } + return nearest; +} + +track_hover editor_mode::split_spot() const +{ + auto const *selected{selected_track()}; + if (selected == nullptr || ui()->mode() != nodebank_panel::TRACK || ImGui::GetIO().WantCaptureMouse) + return {}; + return track_under_cursor(selected, 20.0f); +} + +alignment::limits editor_mode::laying_norms() const +{ + auto norms{m_route.design.norms}; + norms.checked = true; + return norms; +} + +void editor_mode::render_lay_ui() +{ + auto &tool{m_lay}; + // the points clicked are no track until they're laid: said first, with the keys as buttons + if (tool.points.size() > 1) + { + auto const pending{lay_pending()}; + ImGui::TextColored(ImVec4(1.0f, 0.83f, 0.3f, 1.0f), "%s", format(STR_P("Not laid yet: %zu point", "Not laid yet: %zu points", static_cast(pending)), pending).c_str()); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.18f, 0.45f, 0.22f, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.24f, 0.56f, 0.28f, 1.0f)); + if (ImGui::Button(STR_C("Lay (Enter)"))) + { + // the cursor is over the panel: no free end under it to join + tool.mouse_snap = {}; + lay_enter(); + } + ImGui::PopStyleColor(2); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Drop the points"))) + lay_cancel(); + item_tooltip("Esc twice does the same"); + ImGui::Separator(); + } + if (int mode{tool.mode == lay_mode::curve ? 1 : 0}; + segmented("laymode", mode, + {{0, STR_C("Straights Tab"), "Each point clicked is a bend of the straights: the bend eased with two transition curves meeting, with no cant, of a large radius; where they don't fit, an arc with the transitions and the cant of the norms, as large as fits"}, + {1, STR_C("Curve Tab"), "Click points along the middle of a curve seen on the photo: the curve, compound or with a straight in it, is fitted to them and ends at the last one, heading as they do there. It comes from the straight before it, of the points clicked before or of the free end, and goes on with the curve of a free end, a switch too, where the points turn its way"}}) && + (mode == 1) != (tool.mode == lay_mode::curve)) + lay_switch_mode(); + ImGui::PushItemWidth(120.0f); + if (tool.mode == lay_mode::straights) + { + ImGui::TextDisabled("%s", STR_C("Radius of the curves at the bends")); + ImGui::SameLine(); + if (ImGui::SmallButton("?##corners")) + { + m_first_steps_open = true; + m_tutorial_goto = "Radius of the curves at the bends"; + } + item_tooltip("What it is: the lesson of the tutorial"); + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("The largest radius that fits between your points is taken: two transition curves meeting, with no cant, from 6000 m down to 2000 m, and below that an arc with the transitions and the cant of the norms")); + ImGui::PopTextWrapPos(); + } + else + { + ImGui::PopItemWidth(); + segmented("layradii", tool.radii, + {{0, STR_C("Auto"), "As few radii as follow the points, up to three"}, {1, STR_C("1 R"), "One radius"}, {2, STR_C("2 R"), "A compound curve of two radii"}, {3, STR_C("3 R"), "A compound curve of three radii"}}); + ImGui::Checkbox(STR_C("Two curves with a straight between them, where the points show one"), &tool.straights_between); + item_tooltip("The points along the curve may make two curves, turning the same way or not, with a straight between them, where these follow the points much closer than one curve"); + if (auto const &traces{tool.plan.traces}; false == traces.empty() && false == traces.back().offsets.empty()) + { + auto const &trace{traces.back()}; + auto const colour = [](double const Departure) { return Departure <= 0.1 ? IM_COL32(90, 220, 110, 255) : Departure <= 0.3 ? IM_COL32(255, 200, 60, 255) : IM_COL32(255, 90, 70, 255); }; + metric_tiles({{format("%zu", trace.points.size()), STR_C("points"), ImGui::GetColorU32(ImGuiCol_Text)}, + {format("%.0f cm", trace.rms * 100.0), STR_C("departure"), colour(trace.rms)}, + {format("%.0f cm", trace.worst * 100.0), STR_C("at most"), colour(trace.worst)}}); + } + else + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("Click points along the middle of the track on the photo; the curve ends at the last one")); + ImGui::PopTextWrapPos(); + } + ImGui::PushItemWidth(120.0f); + } + ImGui::DragScalar(STR_C("Speed (km/h)"), ImGuiDataType_Double, &tool.style.velocity, 1.0f, nullptr, nullptr, "%.0f"); + item_tooltip("Speed limit of the new paths, and the design speed of the transition curves and of the cant; the speed of the track joined comes first, and none higher than the radius allows"); + value_chips("speeds", tool.style.velocity, {40.0, 60.0, 80.0, 100.0, 120.0, 160.0}, "%.0f"); + tool.style.velocity = std::clamp(tool.style.velocity, 0.0, 400.0); + ImGui::PopItemWidth(); + ImGui::Checkbox(STR_C("This speed also on from a track with a speed of its own"), &tool.own_speed); + item_tooltip("Off: a track laid on from another one, or joined to it, is designed for the speed of that track and takes it.\nOn: it's designed for the speed above and the new tracks get it.\nWhile laying: Ctrl+Shift+wheel"); + if (auto const [from, to]{laying_ends()}; from != nullptr || to != nullptr) + ImGui::TextDisabled("%s", design_speed_of(from, to).c_str()); + ImGui::TextDisabled("%s", STR_C("Height of the track on the ground")); + if (int heights{static_cast(EditorSettings.heights())}; + segmented("layheights", heights, + {{0, STR_C("Fitted"), "The grades fitted to the ground as Tracks onto the terrain fits them: vertical curves of the norms, the bumps of the ground gone past; the terrain is left as it is. On the terrain model the whole track laid in a row is fitted again at each click"}, + {1, STR_C("Point to point"), "Each bend of the straights clicked at the height of the ground, an even grade between them: the grade changes only at the bends. A curve traced, or bends clicked close along a curve, goes at an even grade from one end of it to the other"}, + {2, STR_C("Flat"), "The track goes on at the height it's laid from, whatever the ground; the first point on the ground"}})) + { + EditorSettings.heights(static_cast(heights)); + EditorSettings.save(); + } + // the curves of the line shown, those below the norms in the colour of a warning: they're laid all the same + if (auto const &plan{tool.plan}; tool.active && plan.shape.valid && false == plan.shape.curves.empty()) + { + ImGui::SeparatorText(STR_C("Curves of the track laid")); + ImGui::TextDisabled("%s", STR_C("R: radius, L: transition curve (m), h: cant (mm)")); + for (auto const &curve : plan.shape.curves) + { + auto const meets{alignment::meets_norms(curve, plan.design)}; + auto const text{format("%d. %s", curve.vertex + 1, curve_label(curve, laying_norms()).c_str())}; + if (meets) + ImGui::TextUnformatted(text.c_str()); + else + ImGui::TextColored(ImVec4(1.0f, 0.55f, 0.15f, 1.0f), "%s", text.c_str()); + if (ImGui::IsItemHovered()) + { + std::string notes; + auto const tag{format(STR_C("Vertex %zu"), static_cast(curve.vertex + 1))}; + for (auto const &warning : plan.shape.warnings) + if (warning.rfind(tag + ":", 0) == 0) + notes += (notes.empty() ? "" : "\n") + warning; + ImGui::SetTooltip("%s", notes.empty() ? STR_C("Meets the norms for the speed") : notes.c_str()); + } + } + } + if (auto *track{selected_track()}; track != nullptr) + { + std::string reason; + if (editor_track::can_edit_geometry(*track, reason)) + render_extend_ui(); + } + if (false == ImGui::TreeNode(STR_C("More settings"))) + { + render_lay_status(); + return; + } + ImGui::TextDisabled("%s", STR_C("Dragged from a free end, or laid from a point to one")); + ImGui::PushItemWidth(120.0f); + ImGui::DragScalar(STR_C("Curve radius (m)"), ImGuiDataType_Double, &tool.radius, 5.0f, nullptr, nullptr, "%.0f"); + item_tooltip("Drag to change, Ctrl+click to type the value. While dragging: Ctrl+wheel"); + value_chips("radii", tool.radius, {190.0, 300.0, 500.0, 800.0, 1200.0, 2000.0}, "%.0f"); + tool.radius = std::max(10.0, tool.radius); + ImGui::PopItemWidth(); + ImGui::Spacing(); + ImGui::PushItemWidth(120.0f); + ImGui::DragScalar(STR_C("Longest path (m)"), ImGuiDataType_Double, &tool.piece_length, 1.0f, nullptr, nullptr, "%.0f"); + tool.piece_length = std::clamp(tool.piece_length, 5.0, 1000.0); + ImGui::PopItemWidth(); + ImGui::TextDisabled("%s", STR_C("Look of the new track")); + int source{tool.copy_selected ? 1 : 0}; + if (segmented("laylook", source, + {{0, STR_C("These textures"), "The rails and the trackbed chosen below.\nA track started or finished at a free end always takes them from the track it joins"}, + {1, STR_C("Like the selected one"), "Takes the textures and the other parameters from the selected track.\nA track started or finished at a free end always takes them from the track it joins"}})) + tool.copy_selected = source == 1; + if (false == tool.copy_selected) + { + auto const column{std::round(ImGui::GetCursorPosX() + std::max(ImGui::CalcTextSize(STR_C("Rails")).x, ImGui::CalcTextSize(STR_C("Trackbed")).x) + ImGui::GetStyle().ItemSpacing.x)}; + auto const texture_row = [&](int const Kind, char const *Label, std::string &Value) { + ImGui::PushID(Kind); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(Label); + ImGui::SameLine(column); + auto const side{ImGui::GetFrameHeight()}; + auto const corner{ImGui::GetCursorScreenPos()}; + if (auto const image{Value.empty() || Value == "none" ? 0 : track_texture_image(Kind, Value)}; image != 0) + { + ImGui::Image(static_cast(image), ImVec2(side, side), ImVec2(0, 1), ImVec2(1, 0)); + if (ImGui::IsItemHovered()) + { + auto const big{std::round(ImGui::GetFontSize() * 14.0f)}; + ImGui::BeginTooltip(); + ImGui::Image(static_cast(image), ImVec2(big, big), ImVec2(0, 1), ImVec2(1, 0)); + ImGui::TextUnformatted(Value.c_str()); + ImGui::EndTooltip(); + } + } + else + { + ImGui::Dummy(ImVec2(side, side)); + ImGui::GetWindowDrawList()->AddRect(corner, ImVec2(corner.x + side, corner.y + side), ImGui::GetColorU32(ImGuiCol_Border)); + } + ImGui::SameLine(0.0f, 4.0f); + ImGui::SetNextItemWidth(-FLT_MIN); + ImGui::SetNextWindowSizeConstraints(ImVec2(ImGui::GetFontSize() * 36.0f, 0.0f), ImVec2(FLT_MAX, FLT_MAX)); + auto const slash{Value.find_last_of('/')}; + auto const preview{Value.empty() || Value == "none" ? std::string{STR_C("No texture")} : slash == std::string::npos ? Value : Value.substr(slash + 1)}; + if (ImGui::BeginCombo("##texture", preview.c_str(), ImGuiComboFlags_HeightLargest)) + { + if (std::string chosen; track_texture_picker(Kind, Value, false, chosen)) + { + Value = chosen; + ImGui::CloseCurrentPopup(); + } + ImGui::EndCombo(); + } + item_tooltip(Kind == 0 ? "Texture of the rails.\nA material dragged from the texture browser can be dropped here" : "Texture of the trackbed (ballast) under the rails.\nA material dragged from the texture browser can be dropped here"); + if (std::string dropped; material_drop(dropped)) + Value = dropped; + ImGui::PopID(); + }; + texture_row(0, STR_C("Rails"), tool.style.rail); + texture_row(1, STR_C("Trackbed"), tool.style.ballast); + } + ImGui::TreePop(); + render_lay_status(); +} + +void editor_mode::render_lay_status() +{ + auto const &tool{m_lay}; + if (scene::Layers.active() == null_handle) + ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), STR_C("The scenery isn't opened for editing: new track won't be saved")); + if (tool.active && false == tool.preview_error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.3f, 1.0f), "%s", tool.preview_error.c_str()); + if (false == tool.status.empty()) + ImGui::TextWrapped("%s", tool.status.c_str()); +} diff --git a/application/editormodelineside.cpp b/application/editormodelineside.cpp new file mode 100644 index 000000000..1c2fc9e9c --- /dev/null +++ b/application/editormodelineside.cpp @@ -0,0 +1,1232 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editormodelineside.h" +#include "application/editormodeshared.h" +#include "application/editoruilayer.h" +#include "application/editorprojection.h" +#include "editor/editorFormat.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorIncludeInfo.hpp" +#include "editor/editorKilometrage.hpp" +#include "editor/editorTrackTrace.hpp" + +#include "scene/scene.h" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/utilities.h" +#include "world/Track.h" + +#include "imgui/imgui.h" +#include "utilities/translation.h" +#include +#include +#include + +namespace +{ + +using geometry::bezier; +using geometry::plan_distance; +using geometry::heading_of; +using geometry::plan_of; + +double const kSampleStep{2.0}; // m between the samples of the line +double const kLineCorridor{15.0}; // m from the axis, posts farther away belong to another line +double const kOverlayRange{3000.0}; +float const kFoulingPick{12.0f}; // px from a point of the fouling overlay a click takes it +double const kFoulingTrace{250.0}; // m from the start of a switch the tracks are followed for +double const kRailHeight{0.18}; // m from the points of a track to the heads of its rails +int const kRailCategory{1}; +char const *const kHektoStyles[] = {"nowy", "stary", "zgnity"}; +char const *const kFoulingModels[] = {"ip/pkp/w17.inc", "ip/pkp/w17_new.inc", "ip/pkp/w17_old.inc", "ip/pkp/w17_dwuteo.inc"}; + +std::string number(double const Value, int const Decimals) +{ + auto text{format("%.*f", Decimals, Value)}; + if (text == "-0" || text.find_first_not_of("-0.") == std::string::npos) + text.erase(0, text.front() == '-' ? 1 : 0); + return text; +} + +// index of the sample at or before the chainage +std::size_t sample_index(std::vector const &Samples, double const Chainage) +{ + auto const found{std::upper_bound(Samples.begin(), Samples.end(), Chainage, [](double const Value, editor_track::route_sample const &Sample) { return Value < Sample.chainage; })}; + return found == Samples.begin() ? 0 : std::min(std::distance(Samples.begin(), found) - 1, Samples.size() - 2); +} + +glm::dvec2 sampled_direction(std::vector const &Samples, double const Chainage) +{ + auto const index{sample_index(Samples, Chainage)}; + auto const &a{Samples[index]}; + auto const &b{Samples[index + 1]}; + auto const span{b.chainage - a.chainage}; + auto const f{span > 1e-9 ? std::clamp((Chainage - a.chainage) / span, 0.0, 1.0) : 0.0}; + auto const direction{a.direction * (1.0 - f) + b.direction * f}; + return glm::length(direction) > 1e-9 ? glm::normalize(direction) : glm::dvec2{0.0, 1.0}; +} + +// chainage of the point of the line nearest to the point, and how far from the line it is +double project(std::vector const &Samples, glm::dvec3 const &Point, double &Distance) +{ + Distance = std::numeric_limits::max(); + double chainage{0.0}; + auto const point{plan_of(Point)}; + for (std::size_t i = 1; i < Samples.size(); ++i) + { + auto const a{plan_of(Samples[i - 1].position)}; + auto const b{plan_of(Samples[i].position)}; + auto const ab{b - a}; + auto const length2{glm::dot(ab, ab)}; + auto const t{length2 > 1e-12 ? std::clamp(glm::dot(point - a, ab) / length2, 0.0, 1.0) : 0.0}; + auto const distance{glm::length(point - (a + ab * t))}; + if (distance < Distance) + { + Distance = distance; + chainage = Samples[i - 1].chainage + (Samples[i].chainage - Samples[i - 1].chainage) * t; + } + } + return chainage; +} + +// the digits after the rotation make the number of the post, the last one the hectometre +bool hectometres_of(std::vector const &Values, int &Hectometres) +{ + if (Values.size() < 6) + return false; + Hectometres = 0; + for (std::size_t i = 5; i < Values.size(); ++i) + { + double digit; + if (false == numeric(Values[i], digit) || digit < 0.0 || digit > 9.0) + return false; + Hectometres = Hectometres * 10 + static_cast(digit); + } + return true; +} + +std::string hekto_file(int const Hectometres, int const Style) +{ + auto style{Style}; + if (style > 2) + { + auto const pick{LocalRandom(0.0, 1.0)}; + style = pick < 0.6 ? 0 : pick < 0.9 ? 1 : 2; + } + auto const size{Hectometres < 100 ? "1" : Hectometres < 1000 ? "10" : "100"}; + return std::string{"przytorowe/slupek_hekto_"} + kHektoStyles[style] + "_" + size + ".inc"; +} + +std::vector hekto_digits(int const Hectometres) +{ + return {std::to_string((Hectometres / 1000) % 10), std::to_string((Hectometres / 100) % 10), std::to_string((Hectometres / 10) % 10), std::to_string(Hectometres % 10)}; +} + +std::string km_text(int const Hectometres) +{ + return format("%d.%d", Hectometres / 10, Hectometres % 10); +} + +void draw_label(ImDrawList *Draw, ImVec2 const At, ImU32 const Colour, std::string const &Text) +{ + auto const size{ImGui::CalcTextSize(Text.c_str())}; + Draw->AddRectFilled(ImVec2(At.x + 8.0f, At.y - 8.0f), ImVec2(At.x + 14.0f + size.x, At.y - 6.0f + size.y), IM_COL32(0, 0, 0, 150), 3.0f); + Draw->AddText(ImVec2(At.x + 11.0f, At.y - 7.0f), Colour, Text.c_str()); +} + +} // namespace + +std::vector editor_mode::standing_templates(std::function const &Accept) const +{ + std::vector result; + for (scene::instance_handle handle = 1; handle <= scene::Layers.instance_count(); ++handle) + { + if (false == scene::Layers.tracked(handle)) + continue; + auto const &included{scene::Layers.instance(handle)}; + if (included.removed || included.dead || included.file == nullptr) + continue; + auto const file{editor_includes::normalized(*included.file)}; + if (false == Accept(file) || included.context.rotation != glm::vec3{0.f} || included.context.scale != glm::vec3{1.f}) + continue; + std::string target; + std::vector values; + if (false == editor_includes::parse_directive(scene::Layers.directive(handle), target, values) || values.size() < 5) + continue; + glm::dvec3 location; + double yaw; + if (false == numeric(values[1], location.x) || false == numeric(values[2], location.y) || false == numeric(values[3], location.z) || false == numeric(values[4], yaw)) + continue; + standing_template standing; + standing.instance = handle; + standing.file = file; + standing.location = included.context.offset + location; + standing.yaw = yaw; + standing.values = std::move(values); + result.push_back(std::move(standing)); + } + return result; +} + +scene::layer_handle editor_mode::output_layer(std::string const &Part) +{ + if (scene::Layers.empty()) + return null_handle; + auto stem{scene::Layers.layer(scene::layer_handle{1}).name}; + if (auto const slash{stem.find_last_of("/\\")}; slash != std::string::npos) + stem.erase(0, slash + 1); + if (auto const dot{stem.rfind('.')}; dot != std::string::npos) + stem.erase(dot); + stem.erase(0, stem.find_first_not_of('$')); + if (stem.empty()) + stem = "scenery"; + std::string reason; + auto const take = [&](scene::layer_handle const Layer) { + if (Layer == null_handle || false == scene::Layers.accepts(Layer, &reason)) + return false; + scene::Layers.visible(Layer, true); + scene::Layers.locked(Layer, false); + return true; + }; + // the first line of the files made here, which tells them from the files of the scenery named alike + auto const header{"// scenery layer created in the editor for its " + Part + " part"}; + auto const headed = [&](std::string const &Name) { + std::ifstream input{Global.asCurrentSceneryPath + Name, std::ios_base::binary}; + std::string first; + std::getline(input, first); + if (false == first.empty() && first.back() == '\r') + first.pop_back(); + return first == header; + }; + // the layer included which the test takes, by its name in lower case and its name as given, if it can take more. returns: + // null_handle if none + auto const included = [&](auto const &Named) -> scene::layer_handle { + for (std::size_t index = 1; index <= scene::Layers.size(); ++index) + if (auto const &existing{scene::Layers.layer(static_cast(index))}; false == existing.dead && false == existing.removed && Named(ToLower(existing.name), existing.name)) + if (auto const layer{scene::Layers.resolve(static_cast(index))}; take(layer)) + return layer; + return null_handle; + }; + auto const name_of = [&](int const Attempt) { return ToLower(stem + "_" + Part + (Attempt > 1 ? std::to_string(Attempt) : std::string{}) + ".scm"); }; + for (int attempt = 1; attempt <= 9; ++attempt) + if (auto const layer{included([&](std::string const &Name, std::string const &) { return Name == name_of(attempt); })}; layer != null_handle) + return layer; + // the one made here for the scenery saved under another name before, the file it was copied from: what the part made stays + // in one file. a file of the scenery of a name alike, without the first line written here, is left as it is + auto const part{"_" + ToLower(Part)}; + if (auto const layer{included([&](std::string const &Name, std::string const &Given) { + if (false == Name.ends_with(".scm")) + return false; + auto base{Name.substr(0, Name.size() - 4)}; + if (false == base.empty() && std::isdigit(static_cast(base.back()))) + base.pop_back(); + return base.size() > part.size() && base.ends_with(part) && headed(Given); + })}; + layer != null_handle) + return layer; + // a file of that name the scenery doesn't include, or one which can't take more, gives way to the next number + for (int attempt = 1; attempt <= 9; ++attempt) + { + auto const name{name_of(attempt)}; + auto known{false}; + for (std::size_t index = 1; index <= scene::Layers.size() && false == known; ++index) + if (auto const &existing{scene::Layers.layer(static_cast(index))}; false == existing.dead && false == existing.removed && ToLower(existing.name) == name) + known = true; + if (known) + continue; + if (auto const layer{scene::Layers.create(name, scene::layer_handle{1}, reason, false, header)}; take(layer)) + return layer; + } + WriteLog("Editor: no layer for " + Part + ", the active one takes it: " + reason, logtype::generic); + return null_handle; +} + +std::size_t editor_mode::place_templates(std::vector const &Items, std::string &Error, scene::layer_handle const Layer) +{ + m_drives_standing.reset(); + if (Items.empty()) + return 0; + if (scene::Layers.empty()) + { + Error = STR_C("Templates can be placed only in a scenery opened for editing (-edit)"); + return 0; + } + auto const layer{scene::Layers.resolve(Layer != null_handle ? Layer : scene::Layers.active())}; + if (std::string reason; false == scene::Layers.accepts(layer, &reason)) + { + Error = STR_C("The active layer can't take them: ") + (reason.empty() ? std::string{STR_C("there's no active layer")} : reason); + return 0; + } + auto const context{scene::Layers.layer(layer).context_insert()}; + if (context.rotation != glm::vec3{0.f} || context.scale != glm::vec3{1.f}) + { + Error = STR_C("The file of the active layer would receive them with a rotation or a scale in effect, pick another layer"); + return 0; + } + EditorSnapshot snap; + for (auto const &item : Items) + { + auto const local{context.to_local(item.location)}; + std::string directive; + if (item.described) + { + include_info info; + if (false == editor_includes::load(item.file, info, Error)) + continue; + directive = editor_includes::directive(item.file, info, editor_includes::parameter_count(item.file), local, static_cast(item.yaw), item.track, item.tilt, item.values); + } + else + { + auto const name{item.values.find("name")}; + std::vector values{name != item.values.end() ? name->second : std::string{"none"}, number(local.x, 3), number(local.y, 3), number(local.z, 3), number(item.yaw, 2)}; + values.insert(values.end(), item.rest.begin(), item.rest.end()); + directive = editor_includes::compose_directive(item.file, values); + } + auto const instance{scene::Layers.place(layer, item.file, directive)}; + if (instance == 0) + continue; + simulation::State.preview_include(directive, context, layer, instance); + snap.instances.push_back(instance); + } + if (snap.instances.empty()) + { + Error = STR_C("The active layer can't take them"); + return 0; + } + auto const count{snap.instances.size()}; + snap.node_name = Items.front().file; + trim_history(); + m_history.push_back(std::move(snap)); + g_redo.clear(); + return count; +} + +std::size_t editor_mode::move_templates(std::vector> const &Moves) +{ + EditorSnapshot snap; + for (auto const &[standing, item] : Moves) + { + if (false == scene::Layers.tracked(standing.instance) || false == scene::Layers.removable(standing.instance)) + continue; + auto const &included{scene::Layers.instance(standing.instance)}; + auto values{standing.values}; + auto const local{item.location - included.context.offset}; + values[1] = number(local.x, 3); + values[2] = number(local.y, 3); + values[3] = number(local.z, 3); + values[4] = number(item.yaw, 2); + auto before{scene::Layers.directive(standing.instance)}; + set_include_directive(standing.instance, editor_includes::compose_directive(*included.file, values)); + snap.directives.emplace_back(standing.instance, std::move(before)); + } + if (snap.directives.empty()) + return 0; + auto const count{snap.directives.size()}; + snap.node_name = Moves.front().first.file; + trim_history(); + m_history.push_back(std::move(snap)); + g_redo.clear(); + return count; +} + +std::size_t editor_mode::remove_templates(std::vector const &Instances) +{ + m_drives_standing.reset(); + EditorSnapshot snap; + for (auto const instance : Instances) + { + if (false == scene::Layers.tracked(instance) || false == scene::Layers.removable(instance)) + continue; + scene::Layers.removed(instance, true); + snap.instances.push_back(instance); + } + if (snap.instances.empty()) + return 0; + auto const count{snap.instances.size()}; + trim_history(); + m_history.push_back(std::move(snap)); + g_redo.clear(); + select_include(0); + return count; +} + +void hekto_tool::start(TTrack &Track, glm::dvec3 const &Point) +{ + auto &tool{m_hekto}; + tool.track = &Track; + tool.point = Point; + tool.km_read = false; + tool.dirty = true; + m_tab.expand = true; + tool.status.clear(); +} + +void hekto_tool::hekto_read_kilometrage() +{ + auto &tool{m_hekto}; + auto const &found{tool.found}; + if (found.empty()) + return; + if (found.size() == 1) + { + // one post doesn't tell the way the kilometrage grows: it's taken to grow along the longer part of the line past the post + auto const length{tool.samples.empty() ? 0.0 : tool.samples.back().chainage}; + tool.growth = found.front().chainage > 0.5 * length ? -1 : 1; + tool.km = found.front().hectometres / 10.0 + tool.growth * (tool.origin - found.front().chainage) / 1000.0; + tool.status = format(STR_C("Kilometrage read from the post %s, check which way it grows"), km_text(found.front().hectometres).c_str()); + return; + } + // a straight line through the numbers of the posts against where they stand + double sc{0.0}, sk{0.0}, scc{0.0}, sck{0.0}; + for (auto const &post : found) + { + auto const km{post.hectometres / 10.0}; + sc += post.chainage; + sk += km; + scc += post.chainage * post.chainage; + sck += post.chainage * km; + } + auto const n{static_cast(found.size())}; + auto const denominator{n * scc - sc * sc}; + if (std::abs(denominator) < 1e-9) + return; + auto const slope{(n * sck - sc * sk) / denominator}; + auto const intercept{(sk - slope * sc) / n}; + if (std::abs(std::abs(slope) * 1000.0 - 1.0) > 0.2) + { + tool.status = format(STR_C("The numbers of the %zu posts along the line don't go by 100 m, the kilometrage wasn't read from them"), found.size()); + return; + } + tool.growth = slope > 0.0 ? 1 : -1; + tool.km = std::round((intercept + slope * tool.origin) * 1000.0) / 1000.0; + tool.status = format(STR_C("Kilometrage read from %zu posts standing along the line"), found.size()); +} + +void hekto_tool::hekto_update() +{ + auto &tool{m_hekto}; + if (false == tool.dirty && tool.history == m_history.history_revision()) + return; + tool.dirty = false; + tool.history = m_history.history_revision(); + tool.posts.clear(); + tool.found.clear(); + tool.error.clear(); + tool.samples.clear(); + if (tool.track == nullptr || tool.track->m_editorremoved) + { + tool.track = nullptr; + return; + } + tool.route = editor_track::run_route(*tool.track, tool.reach); + if (tool.route.spans.empty()) + { + tool.error = STR_C("No line through this path"); + return; + } + tool.samples = editor_track::sample_route(tool.route, kSampleStep); + if (tool.samples.size() < 2) + { + tool.error = STR_C("No line through this path"); + return; + } + double distance; + tool.origin = project(tool.samples, tool.point, distance); + auto const length{tool.samples.back().chainage}; + for (auto const &standing : m_templates.standing_templates([](std::string const &File) { return File.find("hekto") != std::string::npos; })) + { + hekto_found post; + post.post = standing; + if (false == hectometres_of(standing.values, post.hectometres)) + continue; + post.chainage = project(tool.samples, standing.location, distance); + if (distance > kLineCorridor || post.chainage <= 0.0 || post.chainage >= length) + continue; + tool.found.push_back(post); + } + tool.line_set = kilometrage::line_at(tool.point); + tool.line = tool.own_km ? std::string{} : tool.line_set; + if (tool.line.empty() && false == tool.km_read) + { + tool.km_read = true; + hekto_read_kilometrage(); + } + auto const place = [&](hekto_post &Post) { + auto const axis{editor_track::sampled_position(tool.samples, Post.chainage)}; + auto const growing{sampled_direction(tool.samples, Post.chainage) * static_cast(Post.growth)}; + glm::dvec2 const left{-growing.y, growing.x}; + // alternately: the even hectometres on the right, the odd ones on the left of the growing kilometrage + auto const side{tool.side != 0 ? tool.side : (Post.hectometres % 2 == 0 ? 1 : -1)}; + auto const planar{plan_of(axis) + left * (side * tool.offset)}; + Post.position = m_ground.placement_on_ground({planar.x, axis.y, planar.y}); + Post.yaw = std::fmod(heading_of(growing) + tool.turn, 360.0); + tool.posts.push_back(Post); + }; + auto const *axis{tool.line.empty() ? nullptr : kilometrage::axis_of(tool.line)}; + if (axis != nullptr) + { + // the hectometres of the kilometrage of the line, the jumps in it too + double km{0.0}; + if (kilometrage::km_at(tool.line, tool.point, km)) + tool.km = std::round(km * 1000.0) / 1000.0; + tool.growth = kilometrage::growth_at(tool.line, tool.point, sampled_direction(tool.samples, tool.origin)) < 0 ? -1 : 1; + for (auto const &hectometre : kilometrage::hectometres(*axis)) + { + hekto_post post; + post.hectometres = hectometre.number; + post.chainage = project(tool.samples, hectometre.at, distance); + if (distance > kLineCorridor || post.chainage <= 0.0 || post.chainage >= length || hectometre.number < 0 || tool.posts.size() >= 5000) + continue; + post.growth = glm::dot(hectometre.rising, sampled_direction(tool.samples, post.chainage)) < 0.0 ? -1 : 1; + place(post); + } + std::sort(tool.posts.begin(), tool.posts.end(), [](hekto_post const &A, hekto_post const &B) { return A.chainage < B.chainage; }); + } + else + { + auto const km_at = [&](double const Chainage) { return tool.km + tool.growth * (Chainage - tool.origin) / 1000.0; }; + auto const low{std::max(0, static_cast(std::ceil(std::min(km_at(0.0), km_at(length)) * 10.0 - 1e-6)))}; + auto const high{static_cast(std::floor(std::max(km_at(0.0), km_at(length)) * 10.0 + 1e-6))}; + for (int hectometres = low; hectometres <= high && tool.posts.size() < 5000; ++hectometres) + { + hekto_post post; + post.hectometres = hectometres; + post.chainage = tool.origin + tool.growth * (hectometres / 10.0 - tool.km) * 1000.0; + post.growth = tool.growth; + if (post.chainage < 0.0 || post.chainage > length) + continue; + place(post); + } + } + // each post standing goes with the place of its number nearest to it; of the posts going with a place the one nearest to it + // stands for it, the others are duplicates. it stands wrong when it's farther from the place than allowed: along the line, + // across it, or on the other side + for (auto &found : tool.found) + { + found.outside = true; + found.place = -1; + for (int i = 0; i < static_cast(tool.posts.size()); ++i) + { + auto const &post{tool.posts[i]}; + if (post.hectometres != found.hectometres) + continue; + auto const distance{plan_distance(found.post.location, post.position)}; + if (found.place < 0 || distance < found.distance) + { + found.outside = false; + found.place = i; + found.distance = distance; + found.expected = post.chainage; + found.error = found.chainage - post.chainage; + } + } + } + for (int i = 0; i < static_cast(tool.found.size()); ++i) + { + auto const &found{tool.found[i]}; + if (found.place < 0) + continue; + auto &post{tool.posts[found.place]}; + if (post.standing < 0 || found.distance < tool.found[post.standing].distance) + post.standing = i; + } + for (int i = 0; i < static_cast(tool.found.size()); ++i) + { + auto &found{tool.found[i]}; + found.duplicate = found.place >= 0 && tool.posts[found.place].standing != i; + found.wrong = found.place >= 0 && false == found.duplicate && found.distance > tool.tolerance; + } +} + +void hekto_tool::hekto_remove_duplicates() +{ + auto &tool{m_hekto}; + hekto_update(); + std::vector instances; + for (auto const &found : tool.found) + if (found.duplicate) + instances.push_back(found.post.instance); + auto const removed{m_templates.remove_templates(instances)}; + tool.status = format(STR_P("%zu duplicate hectometre post removed, Ctrl+Z brings it back", "%zu duplicate hectometre posts removed, Ctrl+Z brings them back", static_cast(removed)), removed); + WriteLog("Editor: " + tool.status); + tool.dirty = true; +} + +void hekto_tool::hekto_place() +{ + auto &tool{m_hekto}; + hekto_update(); + std::vector items; + for (auto const &post : tool.posts) + { + if (post.standing >= 0) + continue; + template_item item; + item.file = hekto_file(post.hectometres, tool.style); + item.location = post.position; + item.yaw = post.yaw; + item.rest = hekto_digits(post.hectometres); + items.push_back(std::move(item)); + } + std::string error; + auto const layer{items.empty() ? null_handle : m_templates.output_layer("hektometry")}; + auto const placed{m_templates.place_templates(items, error, layer)}; + tool.status = placed > 0 ? format(STR_P("%zu hectometre post placed, Ctrl+Z takes it back", "%zu hectometre posts placed, Ctrl+Z takes them back", static_cast(placed)), placed) : error; + if (placed > 0 && layer != null_handle) + tool.status += format(STR_C(" (layer \"%s\")"), scene::Layers.layer(layer).name.c_str()); + if (placed > 0) + m_guide.first_step_done(editor_first_step::posts); + WriteLog("Editor: " + tool.status, logtype::generic); + tool.dirty = true; +} + +void hekto_tool::hekto_fix() +{ + auto &tool{m_hekto}; + hekto_update(); + std::vector> moves; + for (auto const &post : tool.posts) + { + if (post.standing < 0 || false == tool.found[post.standing].wrong) + continue; + template_item item; + item.location = post.position; + item.yaw = post.yaw; + moves.emplace_back(tool.found[post.standing].post, item); + } + auto const moved{m_templates.move_templates(moves)}; + tool.status = format(STR_P("%zu hectometre post moved to its place, Ctrl+Z takes it back", "%zu hectometre posts moved to their places, Ctrl+Z takes it back", static_cast(moved)), moved); + WriteLog("Editor: " + tool.status, logtype::generic); + tool.dirty = true; +} + +void hekto_tool::render_options() +{ + auto &tool{m_hekto}; + auto *selected{m_selection.selected_track()}; + if (tool.track == nullptr || (selected != nullptr && selected != tool.track && ImGui::SmallButton(STR_C("Along the line of the selected path")))) + { + if (selected == nullptr) + { + ImGui::TextDisabled("%s", STR_C("Select a path of the line, or RMB on it: Hectometre posts")); + return; + } + start(*selected, bezier{selected->m_paths.front()}.point(0.0)); + } + auto const changed = [&](bool const Changed) { + if (Changed) + tool.dirty = true; + }; + if (false == tool.line.empty()) + { + ImGui::TextWrapped("%s", format(STR_C("The km of line %s, as the Kilometrage tool sets them, its jumps too"), tool.line.c_str()).c_str()); + ImGui::TextDisabled("%s", format(STR_C("km %s at the point"), kilometrage::text(tool.km).c_str()).c_str()); + if (ImGui::SmallButton(STR_C("Give the km here instead"))) + { + tool.own_km = true; + tool.km_read = false; + tool.dirty = true; + } + item_tooltip("The posts go by the km given at the point and the way it grows, without the jumps of the line"); + } + else + { + if (false == tool.line_set.empty() && ImGui::SmallButton(format(STR_C("Follow the km of line %s"), tool.line_set.c_str()).c_str())) + { + tool.own_km = false; + tool.dirty = true; + } + if (tool.line_set.empty()) + { + // no km of the line yet: the one typed below is of the posts alone + ImGui::TextWrapped("%s", STR_C("The line has no km set yet: the posts count from the km typed here")); + if (ImGui::SmallButton(STR_C("Set the km of the line (X)"))) + m_guide.open_kilometrage(); + item_tooltip("Set with the Kilometrage tool, the km of the line serves the posts, the stations and the block signals, typed once"); + } + if (begin_fields("##hektokm", 0.45f)) + { + field_row("Kilometre at the point (km)"); + changed(ImGui::InputDouble("##hektokilometre", &tool.km, 0.0, 0.0, "%.3f")); + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(1); + if (ImGui::Button(STR_C("Read from the posts"), ImVec2(-FLT_MIN, 0.0f))) + { + tool.km_read = false; + tool.dirty = true; + } + ImGui::EndTable(); + } + ImGui::TextDisabled("%s", STR_C("The kilometrage grows")); + changed(segmented("growth", tool.growth, {{1, STR_C("along the line")}, {-1, STR_C("against it")}})); + } + ImGui::TextDisabled("%s", STR_C("Side, looking where it grows")); + changed(segmented("side", tool.side, {{1, STR_C("on the right")}, {-1, STR_C("on the left")}, {0, STR_C("alternately"), "The even hectometres on the right, the odd ones on the left"}})); + if (ImGui::TreeNode(STR_C("More settings"))) + { + ImGui::TextDisabled("%s", STR_C("Look")); + segmented("hektostyle", tool.style, {{0, STR_C("new")}, {1, STR_C("old")}, {2, STR_C("rotten")}, {3, STR_C("mixed"), "New, old and rotten ones at random, mostly new"}}); + ImGui::TextDisabled("%s", STR_C("Turned by (deg)")); + if (segmented("hektoturn", tool.turn, {{0, "0"}, {90, "90"}, {180, "180"}, {270, "270"}})) + tool.dirty = true; + if (begin_fields("##hektofields", 0.6f)) + { + field_row("From the axis (m)"); + changed(ImGui::InputDouble("##hektooffset", &tool.offset, 0.0, 0.0, "%.2f")); + field_row("Along the line each way (m)"); + changed(ImGui::InputDouble("##hektoreach", &tool.reach, 0.0, 0.0, "%.0f")); + field_row("Tolerance (m)"); + changed(ImGui::InputDouble("##hektotolerance", &tool.tolerance, 0.0, 0.0, "%.1f")); + item_tooltip("A post standing farther than this from its place counts as wrong"); + ImGui::EndTable(); + } + ImGui::TreePop(); + } + tool.offset = std::clamp(tool.offset, 1.5, 30.0); + tool.reach = std::clamp(tool.reach, 100.0, 100000.0); + tool.tolerance = std::clamp(tool.tolerance, 0.5, 50.0); + hekto_update(); + if (false == tool.error.empty()) + { + ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", tool.error.c_str()); + return; + } + auto const missing{std::count_if(tool.posts.begin(), tool.posts.end(), [](hekto_post const &Post) { return Post.standing < 0; })}; + auto const wrong{std::count_if(tool.found.begin(), tool.found.end(), [](hekto_found const &Post) { return Post.wrong; })}; + auto const duplicates{std::count_if(tool.found.begin(), tool.found.end(), [](hekto_found const &Post) { return Post.duplicate; })}; + ImGui::Text(STR_C("To place: %d"), static_cast(missing)); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Line %.0f m, km %s - %s. Standing: %zu, %d of them wrong"), tool.samples.empty() ? 0.0 : tool.samples.back().chainage, tool.posts.empty() ? "-" : km_text(std::min(tool.posts.front().hectometres, tool.posts.back().hectometres)).c_str(), + tool.posts.empty() ? "-" : km_text(std::max(tool.posts.front().hectometres, tool.posts.back().hectometres)).c_str(), tool.found.size(), static_cast(wrong)); + if (missing > 0) + { + if (main_button(format(STR_P("Place %d post", "Place %d posts", static_cast(missing)), static_cast(missing)).c_str(), ImVec2(-1.0f, tall_button_height()))) + hekto_place(); + } + if (duplicates > 0) + { + if (ImGui::Button(format(STR_P("Remove %d duplicate post", "Remove %d duplicate posts", static_cast(duplicates)), static_cast(duplicates)).c_str())) + hekto_remove_duplicates(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Posts with a number another post nearer to its place already has")); + } + if (wrong > 0 || duplicates > 0) + { + if (wrong > 0) + { + if (duplicates > 0) + ImGui::SameLine(); + if (ImGui::Button(format(STR_P("Move %d wrong post to its place", "Move %d wrong posts to their places", static_cast(wrong)), static_cast(wrong)).c_str())) + hekto_fix(); + } + ImGui::BeginChild("##hektowrong", ImVec2(0.0f, std::min(6, static_cast(wrong + duplicates)) * ImGui::GetTextLineHeightWithSpacing() + 6.0f), true); + for (auto const &post : tool.found) + { + if (false == post.wrong && false == post.duplicate) + continue; + auto const label{post.duplicate ? format(STR_C("km %s duplicate##%u"), km_text(post.hectometres).c_str(), post.post.instance) : format(STR_C("km %s stands %.1f m from its place##%u"), km_text(post.hectometres).c_str(), post.distance, post.post.instance)}; + if (ImGui::Selectable(label.c_str())) + { + m_view.fly_to(post.post.location, glm::normalize(glm::dvec3{-1.0, -0.8, -1.0}), 20.0); + } + } + ImGui::EndChild(); + } + if (false == tool.status.empty()) + ImGui::TextWrapped("%s", tool.status.c_str()); +} + +void hekto_tool::draw_overlay() const +{ + auto const &tool{m_hekto}; + if (false == m_tab.open || tool.track == nullptr) + return; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + glm::dvec3 const camera{Global.pCamera.Pos}; + for (auto const &post : tool.posts) + { + if (glm::distance(post.position, camera) > kOverlayRange) + continue; + ImVec2 screen; + if (false == projection.project(post.position, screen)) + continue; + bool const standing{post.standing >= 0 && false == tool.found[post.standing].wrong}; + auto const colour{standing ? IM_COL32(180, 180, 180, 200) : IM_COL32(90, 255, 120, 235)}; + drawlist->AddCircleFilled(screen, 4.0f, colour); + draw_label(drawlist, screen, colour, km_text(post.hectometres)); + } + for (auto const &post : tool.found) + { + if ((false == post.wrong && false == post.duplicate) || glm::distance(post.post.location, camera) > kOverlayRange) + continue; + ImVec2 screen; + if (false == projection.project(post.post.location, screen)) + continue; + auto const colour{post.duplicate ? IM_COL32(255, 160, 40, 235) : IM_COL32(255, 70, 60, 235)}; + drawlist->AddCircle(screen, 9.0f, colour, 16, 2.5f); + draw_label(drawlist, screen, colour, post.duplicate ? format(STR_C("km %s duplicate"), km_text(post.hectometres).c_str()) : format(STR_C("km %s, %.1f m from its place"), km_text(post.hectometres).c_str(), post.distance)); + if (post.duplicate) + continue; + for (auto const &target : tool.posts) + if (target.hectometres == post.hectometres) + projection.line(drawlist, post.post.location, target.position, IM_COL32(255, 70, 60, 160), 1.5f); + } + ImVec2 screen; + if (projection.project(tool.point, screen)) + { + drawlist->AddCircle(screen, 7.0f, IM_COL32(90, 200, 255, 235), 16, 2.5f); + draw_label(drawlist, screen, IM_COL32(90, 200, 255, 235), format("km %.3f", tool.km)); + } +} + +void fouling_tool::fouling_update() +{ + auto &tool{m_fouling}; + auto *selected{m_selection.selected_track()}; + if (tool.scope == 0 && selected != tool.selected) + tool.dirty = true; + if (false == tool.dirty && tool.history == m_history.history_revision()) + return; + tool.dirty = false; + tool.history = m_history.history_revision(); + tool.selected = selected; + tool.points.clear(); + tool.found.clear(); + tool.error.clear(); + std::vector switches; + glm::dvec3 const camera{Global.pCamera.Pos}; + if (tool.scope == 0) + { + if (selected == nullptr || selected->eType != tt_Switch) + { + tool.error = STR_C("Select a switch, or check around the camera"); + return; + } + switches.push_back(selected); + } + else + { + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && track->eType == tt_Switch && false == track->m_editorremoved && (track->iCategoryFlag & 15) == kRailCategory && track->m_paths.size() >= 2 && + (tool.scope == 2 || glm::distance(track->location(), camera) <= tool.reach)) + switches.push_back(track); + } + for (auto *track : switches) + { + if (track->m_paths.size() < 2 || false == editor_track::is_supported(*track)) + continue; + track_trace::fouling found; + if (false == track_trace::fouling_of(*track, tool.spacing, kFoulingTrace, found)) + continue; + fouling_point point; + point.track = track; + auto const middle{(found.branch + found.main) * 0.5}; + // the points of the paths are at the rail foot, the heads of the rails are the height of the rail over them + point.position = tool.height_mode == 1 ? glm::dvec3{middle.x, 0.5 * (found.branch.y + found.main.y) + kRailHeight + tool.height, middle.z} : m_ground.placement_on_ground({middle.x, std::max(found.branch.y, found.main.y), middle.z}); + point.yaw = std::fmod(heading_of(found.back) + tool.turn, 360.0); + tool.points.push_back(point); + } + // markers standing: each goes to the nearest fouling point, the others are left alone + auto const markers{m_templates.standing_templates([](std::string const &File) { return File.find("w17") != std::string::npos || File.find("ukres") != std::string::npos; })}; + for (auto const &marker : markers) + { + int nearest{-1}; + double best{std::numeric_limits::max()}; + for (int i = 0; i < static_cast(tool.points.size()); ++i) + { + auto const distance{plan_distance(marker.location, tool.points[i].position)}; + if (distance < best) + { + best = distance; + nearest = i; + } + } + if (nearest < 0 || best > 40.0) + continue; + auto &point{tool.points[nearest]}; + if (point.standing >= 0 && tool.found[point.standing].error <= best) + continue; + fouling_found found; + found.marker = marker; + found.point = nearest; + found.error = best; + found.height_error = marker.location.y - point.position.y; + found.wrong = best > tool.tolerance || (tool.height_mode == 1 && std::abs(found.height_error) > tool.height_tolerance); + if (point.standing >= 0) + tool.found[point.standing] = found; + else + { + point.standing = static_cast(tool.found.size()); + tool.found.push_back(found); + } + } + auto const missing{std::count_if(tool.points.begin(), tool.points.end(), [](fouling_point const &Point) { return Point.standing < 0; })}; + auto const wrong{std::count_if(tool.found.begin(), tool.found.end(), [](fouling_found const &Found) { return Found.wrong; })}; + tool.status = format(STR_C("%zu switches, %zu fouling points: %d without a marker, %d markers standing wrong"), switches.size(), tool.points.size(), static_cast(missing), static_cast(wrong)); +} + +void fouling_tool::place(int const Only) +{ + auto &tool{m_fouling}; + fouling_update(); + std::vector items; + for (int i = 0; i < static_cast(tool.points.size()); ++i) + { + auto const &point{tool.points[i]}; + if (point.standing >= 0 || (Only >= 0 && i != Only)) + continue; + template_item item; + item.file = kFoulingModels[std::clamp(tool.model, 0, 3)]; + item.location = point.position; + item.yaw = point.yaw; + if (tool.model != 2) + item.rest = {"0"}; + items.push_back(std::move(item)); + } + std::string error; + auto const placed{m_templates.place_templates(items, error)}; + tool.status = placed > 0 ? format(STR_P("%zu fouling point marker placed, Ctrl+Z takes it back", "%zu fouling point markers placed, Ctrl+Z takes them back", static_cast(placed)), placed) : error; + WriteLog("Editor: " + tool.status, logtype::generic); + tool.dirty = true; +} + +void fouling_tool::fix(int const Only) +{ + auto &tool{m_fouling}; + fouling_update(); + std::vector> moves; + for (int i = 0; i < static_cast(tool.found.size()); ++i) + { + auto const &found{tool.found[i]}; + if (false == found.wrong || (Only >= 0 && i != Only)) + continue; + template_item item; + auto const &point{tool.points[found.point]}; + if (found.error <= tool.tolerance) + { + // in its place, only too high or too low + item.location = {found.marker.location.x, point.position.y, found.marker.location.z}; + item.yaw = found.marker.yaw; + } + else + { + item.location = point.position; + item.yaw = point.yaw; + } + moves.emplace_back(found.marker, item); + } + auto const moved{m_templates.move_templates(moves)}; + tool.status = format(STR_P("%zu fouling point marker moved to its place, Ctrl+Z takes it back", "%zu fouling point markers moved to their places, Ctrl+Z takes it back", static_cast(moved)), moved); + WriteLog("Editor: " + tool.status, logtype::generic); + tool.dirty = true; +} + +std::optional> fouling_tool::hit() const +{ + auto const &tool{m_fouling}; + screen_projection const projection; + auto const &mouse{ImGui::GetIO().MousePos}; + glm::dvec3 const camera{Global.pCamera.Pos}; + std::optional> result; + auto best{kFoulingPick * kFoulingPick}; + auto const consider = [&](glm::dvec3 const &Position, int const Index, bool const Marker) { + ImVec2 screen; + if (glm::distance(Position, camera) > kOverlayRange || false == projection.project(Position, screen)) + return; + auto const distance2{(screen.x - mouse.x) * (screen.x - mouse.x) + (screen.y - mouse.y) * (screen.y - mouse.y)}; + if (distance2 < best) + { + best = distance2; + result = std::make_pair(Index, Marker); + } + }; + for (int i = 0; i < static_cast(tool.points.size()); ++i) + if (tool.points[i].standing < 0) + consider(tool.points[i].position, i, false); + for (int i = 0; i < static_cast(tool.found.size()); ++i) + if (tool.found[i].wrong) + consider(tool.found[i].marker.location, i, true); + return result; +} + +void fouling_tool::render_options() +{ + auto &tool{m_fouling}; + auto const changed = [&](bool const Changed) { + if (Changed) + tool.dirty = true; + }; + changed(segmented("foulingscope", tool.scope, {{0, STR_C("The selected switch")}, {1, STR_C("Around the camera")}, {2, STR_C("Whole scenery")}})); + fouling_update(); + if (false == tool.error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.8f, 0.3f, 1.0f), "%s", tool.error.c_str()); + else + { + ImGui::TextWrapped("%s", tool.status.c_str()); + auto const missing{std::count_if(tool.points.begin(), tool.points.end(), [](fouling_point const &Point) { return Point.standing < 0; })}; + auto const wrong{std::count_if(tool.found.begin(), tool.found.end(), [](fouling_found const &Found) { return Found.wrong; })}; + auto const tall{tall_button_height()}; + if (missing > 0) + { + if (main_button(format(STR_P("Place %d marker", "Place %d markers", static_cast(missing)), static_cast(missing)).c_str(), ImVec2(-1.0f, tall))) + place(); + } + if (wrong > 0) + { + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.6f, 0.4f, 0.1f, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.7f, 0.48f, 0.15f, 1.0f)); + if (ImGui::Button(format(STR_P("Move %d wrong marker to its place", "Move %d wrong markers to their places", static_cast(wrong)), static_cast(wrong)).c_str(), ImVec2(-1.0f, tall))) + fix(); + ImGui::PopStyleColor(2); + } + if (missing + wrong > 0) + { + // each one: a click flies there, the button fixes it alone; in the view a click on its point does the same + ImGui::TextDisabled("%s", STR_C("Click the green or red point in the view: that one only")); + ImGui::BeginChild("##foulinglist", ImVec2(0.0f, std::min(8, static_cast(missing + wrong)) * ImGui::GetFrameHeightWithSpacing() + 6.0f), true); + auto const look{glm::normalize(glm::dvec3{-1.0, -0.8, -1.0})}; + for (int i = 0; i < static_cast(tool.points.size()); ++i) + { + auto const &point{tool.points[i]}; + if (point.standing >= 0) + continue; + ImGui::PushID(i); + if (ImGui::SmallButton(STR_C("Place"))) + place(i); + ImGui::SameLine(); + if (ImGui::Selectable(format(STR_C("%s: no W17"), point.track->name().c_str()).c_str())) + m_view.fly_to(point.position, look, 25.0); + ImGui::PopID(); + } + for (int i = 0; i < static_cast(tool.found.size()); ++i) + { + auto const &found{tool.found[i]}; + if (false == found.wrong) + continue; + ImGui::PushID(1000000 + i); + if (ImGui::SmallButton(STR_C("Fix"))) + fix(i); + ImGui::SameLine(); + if (ImGui::Selectable(format(STR_C("%s: W17 %.1f m off, %+.2f m high"), tool.points[found.point].track->name().c_str(), found.error, found.height_error).c_str())) + m_view.fly_to(found.marker.location, look, 25.0); + ImGui::PopID(); + } + ImGui::EndChild(); + } + } + if (ImGui::TreeNode(STR_C("More settings"))) + { + if (begin_fields("##foulingfields", 0.6f)) + { + if (tool.scope == 1) + { + field_row("Around the camera (m)"); + changed(ImGui::InputDouble("##foulingreach", &tool.reach, 0.0, 0.0, "%.0f")); + } + field_row("Spacing of the axes (m)"); + changed(ImGui::InputDouble("##foulingspacing", &tool.spacing, 0.0, 0.0, "%.2f")); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s\n%s", STR_C("W17 where the axes of the tracks meeting at a switch are the spacing apart,\nhalf way between them"), STR_C("Nominally 3.50 m (Standardy techniczne PLK, tom II, 6.5). Where a track lies there in a curve under 250 m,\nthe widening of the gauge from its radius on the side of the other track is added by itself, of both tracks summed (6.6),\nand the leaning of the cars of a track on its cant towards the other one, taken 3.25 m up (Ie-1, bD)")); + field_row("Tolerance (m)"); + changed(ImGui::InputDouble("##foulingtolerance", &tool.tolerance, 0.0, 0.0, "%.1f")); + item_tooltip("A marker standing farther than this from its place counts as wrong"); + ImGui::EndTable(); + } + changed(segmented("foulingheight", tool.height_mode, {{0, STR_C("On the ground")}, {1, STR_C("Over the rail heads")}})); + if (tool.height_mode == 1 && begin_fields("##foulingheights", 0.6f)) + { + field_row("by (m)"); + changed(ImGui::InputDouble("##foulingby", &tool.height, 0.0, 0.0, "%.3f")); + field_row("Height tolerance (m)"); + changed(ImGui::InputDouble("##foulingheighttolerance", &tool.height_tolerance, 0.0, 0.0, "%.3f")); + item_tooltip("A marker higher or lower than its place by more than this counts as wrong"); + tool.height_tolerance = std::clamp(tool.height_tolerance, 0.005, 1.0); + ImGui::EndTable(); + } + ImGui::TextDisabled("%s", STR_C("Marker")); + segmented("foulingmodel", tool.model, + {{0, "w17", "Round post (ip/pkp/w17.inc)"}, {1, "w17_new", "Round post, taller than w17 (ip/pkp/w17_new.inc)"}, {2, "w17_old", "Square post (ip/pkp/w17_old.inc)"}, {3, STR_C("I-beam"), "Post of an HEB I-beam (ip/pkp/w17_dwuteo.inc)"}}); + ImGui::TextDisabled("%s", STR_C("Turned by (deg)")); + if (segmented("foulingturn", tool.turn, {{0, "0"}, {90, "90"}, {180, "180"}, {270, "270"}})) + tool.dirty = true; + ImGui::TreePop(); + } + tool.reach = std::clamp(tool.reach, 50.0, 50000.0); + tool.spacing = std::clamp(tool.spacing, 2.0, 10.0); + tool.tolerance = std::clamp(tool.tolerance, 0.2, 20.0); +} + +void fouling_tool::draw_overlay() const +{ + auto const &tool{m_fouling}; + if (false == m_tab.open) + return; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + glm::dvec3 const camera{Global.pCamera.Pos}; + for (auto const &point : tool.points) + { + if (glm::distance(point.position, camera) > kOverlayRange) + continue; + ImVec2 screen; + if (false == projection.project(point.position, screen)) + continue; + bool const standing{point.standing >= 0 && false == tool.found[point.standing].wrong}; + auto const colour{standing ? IM_COL32(180, 180, 180, 200) : IM_COL32(90, 255, 120, 235)}; + drawlist->AddCircleFilled(screen, 4.0f, colour); + draw_label(drawlist, screen, colour, "W17"); + } + for (auto const &found : tool.found) + { + if (false == found.wrong || glm::distance(found.marker.location, camera) > kOverlayRange) + continue; + ImVec2 screen; + if (false == projection.project(found.marker.location, screen)) + continue; + drawlist->AddCircle(screen, 9.0f, IM_COL32(255, 70, 60, 235), 16, 2.5f); + draw_label(drawlist, screen, IM_COL32(255, 70, 60, 235), format(STR_C("W17 %.1f m off, %+.2f m high"), found.error, found.height_error)); + projection.line(drawlist, found.marker.location, tool.points[found.point].position, IM_COL32(255, 70, 60, 160), 1.5f); + } +} + +editor_selftest_result hekto_tool::selftest(std::string const &Command, std::istringstream &Words) +{ + if (Command == "hekto") + { + auto values{selftest_values(Words)}; + auto *track{simulation::Paths.find(values["track"])}; + if (track == nullptr) + { + WriteLog("SELFTEST hekto: no such track"); + return editor_selftest_result::handled; + } + start(*track, track->m_paths.front().points[segment_data::point::start]); + auto &tool{m_hekto}; + if (values.count("reach")) + tool.reach = std::stod(values["reach"]); + tool.own_km = values["own"] == "1"; + tool.dirty = true; + hekto_update(); + if (values.count("km")) + { + tool.km = std::stod(values["km"]); + tool.growth = values["growth"] == "-1" ? -1 : 1; + } + tool.side = values["side"] == "alt" ? 0 : values["side"] == "left" ? -1 : 1; + tool.dirty = true; + hekto_update(); + auto const missing{std::count_if(tool.posts.begin(), tool.posts.end(), [](hekto_post const &Post) { return Post.standing < 0; })}; + auto const wrong{std::count_if(tool.found.begin(), tool.found.end(), [](hekto_found const &Post) { return Post.wrong; })}; + auto const duplicates{std::count_if(tool.found.begin(), tool.found.end(), [](hekto_found const &Post) { return Post.duplicate; })}; + WriteLog(format("SELFTEST hekto: line %s km %.3f growth %d, %zu posts along %.0f m, %d to place, %zu standing, %d wrong, %d duplicate. %s", tool.line.empty() ? "-" : tool.line.c_str(), tool.km, tool.growth, tool.posts.size(), tool.samples.empty() ? 0.0 : tool.samples.back().chainage, static_cast(missing), tool.found.size(), + static_cast(wrong), static_cast(duplicates), tool.status.c_str())); + for (std::size_t i = 0; i < tool.posts.size() && i < 4; ++i) + { + auto const &post{tool.posts[i]}; + double lateral; + glm::dvec3 const axis{editor_track::sampled_position(tool.samples, post.chainage)}; + auto const direction{editor_track::sampled_position(tool.samples, post.chainage + 1.0) - axis}; + glm::dvec2 const offset{post.position.x - axis.x, post.position.z - axis.z}; + lateral = glm::length(offset); + auto const right{(direction.x * offset.y - direction.z * offset.x) * post.growth >= 0.0}; + WriteLog(format("SELFTEST hekto post %d.%d at %.1f m, %.2f m from the axis, %s of the growing kilometrage, at %.1f %.1f %.1f", post.hectometres / 10, post.hectometres % 10, post.chainage, lateral, right ? "right" : "left", post.position.x, post.position.y, + post.position.z)); + } + if (values["list"] == "1") + { + std::string list; + for (auto const &post : tool.posts) + list += format(" %d@%.0f", post.hectometres, post.chainage); + WriteLog("SELFTEST hekto posts:" + list); + } + if (values["place"] == "1") + { + hekto_place(); + WriteLog("SELFTEST hekto: " + tool.status); + } + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} + +glm::dvec3 fouling_tool::position_of(std::pair const &Hit) const +{ + return Hit.second ? m_fouling.found[Hit.first].marker.location : m_fouling.points[Hit.first].position; +} + +void fouling_tool::check_selected_switch() +{ + m_fouling.scope = 0; + m_fouling.dirty = true; + m_tab.expand = true; +} + +editor_selftest_result fouling_tool::selftest(std::string const &Command, std::istringstream &Words) +{ + if (Command == "fouling") + { + auto values{selftest_values(Words)}; + auto &tool{m_fouling}; + if (values["show"] == "1") + { + m_view.show_track_tab(editor_track_tab::lineside); + m_tab.expand = true; + } + tool.scope = std::stoi(values.count("scope") ? values["scope"] : "2"); + tool.height_mode = values["mode"] == "ground" ? 0 : 1; + tool.height = std::stod(values.count("height") ? values["height"] : "0"); + tool.dirty = true; + fouling_update(); + WriteLog("SELFTEST fouling: " + tool.status); + int shown{0}; + for (auto const &found : tool.found) + { + if (false == found.wrong) + continue; + if (shown == 5) + break; + ++shown; + WriteLog(format("SELFTEST fouling: %s %.2f m off, %+.3f m high", found.marker.file.c_str(), found.error, found.height_error)); + } + if (values["place"] == "one") + { + // the first fouling point without a marker alone, as a click on it in the view + for (int index = 0; index < static_cast(tool.points.size()); ++index) + if (tool.points[index].standing < 0) + { + place(index); + break; + } + tool.dirty = true; + fouling_update(); + WriteLog("SELFTEST fouling one: " + tool.status); + } + if (values["place"] == "1") + { + place(); + tool.dirty = true; + fouling_update(); + WriteLog("SELFTEST fouling after placing: " + tool.status); + } + if (values["fix"] == "1") + { + fix(); + tool.dirty = true; + fouling_update(); + WriteLog("SELFTEST fouling after the fix: " + tool.status); + } + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} diff --git a/application/editormodelineside.h b/application/editormodelineside.h new file mode 100644 index 000000000..1ace4a1ce --- /dev/null +++ b/application/editormodelineside.h @@ -0,0 +1,156 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.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 "application/editortool.h" + +#include +#include +#include +#include + +// hectometre posts along the line, at every 100 m of the kilometrage +class hekto_tool final : public editor_tool +{ + public: + hekto_tool(editor_selection &Selection, editor_view &View, editor_history &History, editor_templates &Templates, editor_ground &Ground, editor_guide &Guide) : m_selection{Selection}, m_view{View}, m_history{History}, m_templates{Templates}, m_ground{Ground}, m_guide{Guide} {} + void draw_overlay() const override; + void render_options() override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + tool_tab &tab() { return m_tab; } + void start(TTrack &Track, glm::dvec3 const &Point); + + private: + editor_selection &m_selection; + editor_view &m_view; + editor_history &m_history; + editor_templates &m_templates; + editor_ground &m_ground; + editor_guide &m_guide; + tool_tab m_tab; + struct hekto_post + { + int hectometres{0}; + double chainage{0.0}; + glm::dvec3 position{0.0}; + double yaw{0.0}; + int growth{1}; // 1: the kilometrage grows along the line there, -1: against + int standing{-1}; // post already there with this number + }; + struct hekto_found + { + standing_template post; + int hectometres{0}; + double chainage{0.0}; // where it stands along the line + double expected{0.0}; // where its number belongs + double error{0.0}; // m along the line + double distance{0.0}; // m from where it belongs, in the plan + bool wrong{false}; + bool duplicate{false}; // another post with the same number stands nearer to its place + bool outside{false}; // its number belongs past the ends of the line + int place{-1}; // of the posts, the one with its number nearest to it + }; + struct hekto_state + { + TTrack *track{nullptr}; // the line runs through it + glm::dvec3 point{0.0}; // where the kilometrage is given + double km{0.0}; + bool km_read{false}; // the kilometrage was read from the posts already standing + int growth{1}; // 1: grows along the line, -1: against + std::string line; // of the kilometrage set for the line in the Kilometrage tool the posts follow, empty for the one given here + std::string line_set; // the line the Kilometrage tool sets the kilometrage of at the point, empty for none + bool own_km{false}; // the kilometrage given here, even where the line has one set + int side{1}; // 1: to the right of the growing kilometrage, -1: to the left, 0: alternately + double offset{3.0}; // m from the axis + int style{0}; // nowy, stary, zgnity, mixed + int turn{0}; // degrees added to the rotation + double reach{10000.0}; // m each way + double tolerance{5.0}; // m along the line, for the posts standing + bool dirty{true}; + std::size_t history{0}; + editor_track::route route; + std::vector samples; + double origin{0.0}; // chainage of the point + std::vector posts; + std::vector found; + std::string status; + std::string error; + }; + hekto_state m_hekto; + void hekto_update(); + void hekto_read_kilometrage(); + void hekto_place(); + void hekto_fix(); + void hekto_remove_duplicates(); +}; + +// fouling point markers (W17) where the tracks meeting at a switch are the spacing apart +class fouling_tool final : public editor_tool +{ + public: + fouling_tool(editor_selection &Selection, editor_view &View, editor_history &History, editor_templates &Templates, editor_ground &Ground) : m_selection{Selection}, m_view{View}, m_history{History}, m_templates{Templates}, m_ground{Ground} {} + void draw_overlay() const override; + void render_options() override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + tool_tab &tab() { return m_tab; } + // the markers put at the fouling points without one, or at the one only + void place(int const Only = -1); + // the markers standing wrong moved to their places, or the one found only + void fix(int const Only = -1); + // the fouling point without a marker or the marker standing wrong under the cursor: the index of the point or of the + // marker found, and whether it's a marker + std::optional> hit() const; + glm::dvec3 position_of(std::pair const &Hit) const; + void check_selected_switch(); + + private: + editor_selection &m_selection; + editor_view &m_view; + editor_history &m_history; + editor_templates &m_templates; + editor_ground &m_ground; + tool_tab m_tab; + struct fouling_point + { + TTrack *track{nullptr}; // the switch + glm::dvec3 position{0.0}; + double yaw{0.0}; + int standing{-1}; // marker already there + }; + struct fouling_found + { + standing_template marker; + int point{-1}; // the fouling point it belongs to + double error{0.0}; // m from where it belongs + double height_error{0.0}; // m over where it belongs + bool wrong{false}; + }; + struct fouling_state + { + int scope{1}; // 0: the selected switch, 1: around the camera, 2: the whole scenery + double reach{1500.0}; + double spacing{3.5}; // m between the axes + double tolerance{2.0}; // m, a marker farther than this from its point is wrong + int height_mode{1}; // 0: on the ground, 1: at the height given over the rail heads + double height{0.0}; // m over the rail heads + double height_tolerance{0.03}; // m, a marker standing higher or lower than this is wrong + int model{0}; // w17, w17_new, w17_old, w17_dwuteo + int turn{0}; + bool dirty{true}; + std::size_t history{0}; + TTrack *selected{nullptr}; + std::vector points; + std::vector found; + std::string status; + std::string error; + }; + fouling_state m_fouling; + void fouling_update(); +}; diff --git a/application/editormodeminimap.cpp b/application/editormodeminimap.cpp new file mode 100644 index 000000000..2717cd447 --- /dev/null +++ b/application/editormodeminimap.cpp @@ -0,0 +1,530 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormodeminimap.h" +#include "application/editormoderide.h" +#include "application/editoruilayer.h" +#include "editor/editorFormat.hpp" +#include "editor/editorKilometrage.hpp" +#include "simulation/simulation.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" +#include "utilities/utilities.h" +#include "vehicle/Camera.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/Segment.h" +#include "world/Track.h" +#include "imgui/imgui.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +constexpr char const *stop_prefix{"PassengerStopPoint:"}; + +// the name of the station out of the text of a stop point, cut at '#' which only makes the text unique +std::string stop_name(std::string const &Text) +{ + auto name{Text.substr(std::string{stop_prefix}.size())}; + if (auto const hash{name.find('#')}; hash != std::string::npos) + name.erase(hash); + while (false == name.empty() && std::isspace(static_cast(name.back()))) + name.pop_back(); + return name; +} + +// lower case without the polish letters, of a text in windows-1250 +std::string folded(std::string Text) +{ + win1250_to_ascii(Text); + std::transform(Text.begin(), Text.end(), Text.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return Text; +} + +// the way the camera looks in the plan +glm::dvec3 camera_look() +{ + return {-std::sin(Global.pCamera.Angle.y), 0.0, -std::cos(Global.pCamera.Angle.y)}; +} + +// the path of the track nearest to the point and the point of it, for a track and a point given +int path_at(TTrack const &Track, glm::dvec3 const &Point, glm::dvec3 &On) +{ + return kilometrage::path_near(Track, Point, On); +} + +} // namespace + +bool minimap_tool::stale(std::size_t &Seen) const +{ + auto const now{m_history.history_revision() * 1000003u ^ simulation::Paths.sequence().size() * 7919u ^ simulation::Memory.sequence().size() * 104729u ^ simulation::Events.sequence().size()}; + if (now == Seen) + return false; + Seen = now; + return true; +} + +void minimap_tool::gather_lines() +{ + if (false == stale(m_lines_seen)) + return; + m_lines.clear(); + m_low = glm::dvec2{std::numeric_limits::max()}; + m_high = glm::dvec2{std::numeric_limits::lowest()}; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || (track->iCategoryFlag & 1) == 0 || track->eType == tt_Cross) + continue; + for (int path = 0; path < track->path_count(); ++path) + { + track_ride_walk::place const place{track, track->eType == tt_Switch ? path : -1, 0.0}; + auto const *segment{track_ride_walk::segment(place)}; + if (segment == nullptr || segment->GetLength() <= 0.0) + continue; + line drawn; + drawn.track = track; + drawn.low = glm::dvec2{std::numeric_limits::max()}; + drawn.high = glm::dvec2{std::numeric_limits::lowest()}; + auto const count{std::clamp(static_cast(segment->GetLength() / 10.0), 1, 32)}; + for (int i = 0; i <= count; ++i) + { + auto const point{segment->FastGetPoint(static_cast(i) / count)}; + glm::dvec2 const plan{point.x, point.z}; + drawn.points.push_back(plan); + drawn.low = glm::min(drawn.low, plan); + drawn.high = glm::max(drawn.high, plan); + } + m_low = glm::min(m_low, drawn.low); + m_high = glm::max(m_high, drawn.high); + m_lines.push_back(std::move(drawn)); + } + } +} + +void minimap_tool::gather_stations() +{ + if (false == stale(m_stations_seen)) + return; + std::map found; + // the texts are in windows-1250; the ones of the events lost their polish letters as they were read + auto const add = [&](std::string const &Text, bool const Letters, glm::dvec3 const &Point, TTrack *Track) { + auto const name{stop_name(Text)}; + if (name.empty()) + return; + auto const key{folded(name)}; + auto &entry{found[key]}; + entry.key = key; + // the timetables join the words with underscores + if (entry.name.empty() || Letters) + { + entry.name = win1250_to_utf8(name); + std::replace(entry.name.begin(), entry.name.end(), '_', ' '); + } + if (Track == nullptr) + { + int path{0}; + Track = kilometrage::track_near(Point, 15.0, path); + } + entry.stops.push_back({Point, Track}); + }; + for (auto *cell : simulation::Memory.sequence()) + if (cell != nullptr && cell->Text().starts_with(stop_prefix)) + add(cell->Text(), true, cell->location(), cell->Track); + for (auto *event : simulation::Events.sequence()) + if (auto const *values{dynamic_cast(event)}; values != nullptr && values->input_command() == TCommandType::cm_PassengerStopPoint) + add(values->input_text(), false, values->input_location(), nullptr); + std::vector stations; + for (auto &entry : found) + stations.push_back(std::move(entry.second)); + // the next stop kept for the stations still there + for (auto &station : stations) + for (auto const &old : m_stations) + if (old.key == station.key) + station.next = old.next; + m_stations = std::move(stations); +} + +std::vector const &minimap_tool::stations() +{ + gather_stations(); + return m_stations; +} + +void minimap_tool::go_to(station &Station) +{ + if (Station.stops.empty()) + return; + auto const &stop{Station.stops[Station.next % Station.stops.size()]}; + ++Station.next; + m_marked = Station.key; + // a map not going with the camera goes over to the stop + if (false == m_follow) + m_centre = {stop.point.x, stop.point.z}; + glm::dvec3 on{stop.point}; + auto const path{stop.track != nullptr ? path_at(*stop.track, stop.point, on) : 0}; + if (m_ride.active()) + { + if (stop.track != nullptr && m_ride.enter(stop.track, path, stop.point, camera_look(), true)) + return; + m_ride.leave(); + } + // from behind and above the stop, looking along the track and down to it + auto ahead{camera_look()}; + if (stop.track != nullptr) + { + track_ride_walk::place place{stop.track, stop.track->eType == tt_Switch ? path : -1, 0.0}; + if (auto const *segment{track_ride_walk::segment(place)}) + { + place.s = track_ride_walk::nearest_distance(*segment, stop.point); + glm::dvec3 point, forward; + if (track_ride_walk::frame(place, point, forward)) + { + on = point; + ahead = glm::dot(glm::dvec2{forward.x, forward.z}, glm::dvec2{ahead.x, ahead.z}) >= 0.0 ? forward : -forward; + } + } + } + auto const plan{std::hypot(ahead.x, ahead.z)}; + glm::dvec3 const look{glm::normalize(glm::dvec3{ahead.x / std::max(plan, 1e-9) * 0.9, -0.42, ahead.z / std::max(plan, 1e-9) * 0.9})}; + m_view.fly_to(on, look, 45.0, 0.8); +} + +void minimap_tool::go_to_point(glm::dvec3 const &Point, double const Reach) +{ + int path{0}; + auto *track{kilometrage::track_near(Point, Reach, path)}; + glm::dvec3 on{Point}; + if (track != nullptr) + kilometrage::path_near(*track, Point, on); + if (m_ride.active()) + { + if (track != nullptr && m_ride.enter(track, path, on, camera_look(), false)) + return; + m_ride.leave(); + } + auto const ahead{camera_look()}; + glm::dvec3 const look{glm::normalize(glm::dvec3{ahead.x * 0.8, -0.6, ahead.z * 0.8})}; + if (track != nullptr) + m_view.fly_to(on, look, 60.0, 0.6); + else + m_view.fly_to(glm::dvec3{Point.x, m_view.camera_position().y, Point.z}, look, 0.0, 0.6); +} + +void minimap_tool::forget(scene::basic_node const *Node) +{ + if (Node == nullptr) + return; + for (auto &station : m_stations) + for (auto &stop : station.stops) + if (stop.track == Node) + stop.track = nullptr; + for (auto &drawn : m_lines) + if (drawn.track == Node) + drawn.track = nullptr; +} + +void minimap_tool::render_search() +{ + gather_stations(); + ImGui::SetNextItemWidth(-1.0f); + // enter goes to the first one found + auto const entered{ImGui::InputTextWithHint("##stationsearch", STR_C("Find a station"), m_search, sizeof(m_search), ImGuiInputTextFlags_EnterReturnsTrue)}; + if (m_stations.empty()) + { + ImGui::TextDisabled("%s", STR_C("No W4 in the scenery")); + return; + } + auto const wanted{folded(utf8_to_win1250(m_search))}; + std::vector shown; + for (int i = 0; i < static_cast(m_stations.size()); ++i) + if (wanted.empty() || m_stations[i].key.find(wanted) != std::string::npos) + shown.push_back(i); + auto const rows{std::min(static_cast(shown.size()), 6)}; + if (shown.empty()) + { + ImGui::TextDisabled("%s", STR_C("Nothing found")); + return; + } + if (entered) + { + // the field lets the keys go, they drive the ride from there; a click on the station goes on to its next stop + go_to(m_stations[shown.front()]); + } + if (ImGui::BeginChild("##stations", ImVec2(0.0f, (rows + 0.3f) * ImGui::GetTextLineHeightWithSpacing()), ImGuiChildFlags_Borders)) + { + for (auto const index : shown) + { + auto &station{m_stations[index]}; + auto const label{station.stops.size() > 1 ? format("%s (%d)##%d", station.name.c_str(), static_cast(station.stops.size()), index) : format("%s##%d", station.name.c_str(), index)}; + if (ImGui::Selectable(label.c_str(), station.key == m_marked)) + go_to(station); + if (ImGui::IsItemHovered() && station.stops.size() > 1) + ImGui::SetTooltip("%s", STR_C("Click again for the next W4")); + } + } + ImGui::EndChild(); +} + +void minimap_tool::render_map(float const Height) +{ + gather_lines(); + auto const width{ImGui::GetContentRegionAvail().x}; + ImVec2 const size{std::max(width, 50.0f), std::max(Height, 80.0f)}; + auto const origin{ImGui::GetCursorScreenPos()}; + auto const camera{m_view.camera_position()}; + if (false == m_fitted && false == m_lines.empty()) + { + m_fitted = true; + m_centre = {camera.x, camera.z}; + m_scale = 2.0; + } + if (m_follow) + m_centre = {camera.x, camera.z}; + + // a window of its own: its own list of what's drawn, which mustn't go over 65536 vertices on the renderers without offsets + if (false == ImGui::BeginChild("##minimapcanvas", size, ImGuiChildFlags_None, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) + { + ImGui::EndChild(); + return; + } + ImGui::InvisibleButton("##minimap", size); + auto const hovered{ImGui::IsItemHovered()}; + auto const &io{ImGui::GetIO()}; + glm::vec2 const mouse{io.MousePos.x, io.MousePos.y}; + glm::dvec2 const middle{origin.x + size.x * 0.5, origin.y + size.y * 0.5}; + // x to the right, z down: as the top view looking north along -z + auto const to_world = [&](glm::vec2 const &Screen) { return glm::dvec2{m_centre.x + (Screen.x - middle.x) * m_scale, m_centre.y + (Screen.y - middle.y) * m_scale}; }; + auto const to_screen = [&](glm::dvec2 const &World) { return ImVec2(static_cast(middle.x + (World.x - m_centre.x) / m_scale), static_cast(middle.y + (World.y - m_centre.y) / m_scale)); }; + if (hovered && io.MouseWheel != 0.0f) + { + auto const under{to_world(mouse)}; + m_scale = std::clamp(m_scale * std::pow(0.8, static_cast(io.MouseWheel)), 0.05, 500.0); + if (false == m_follow) + m_centre = {under.x - (mouse.x - middle.x) * m_scale, under.y - (mouse.y - middle.y) * m_scale}; + } + if (ImGui::IsItemActivated()) + { + m_pressed = mouse; + m_dragging = false; + } + if (ImGui::IsItemActive()) + { + if (glm::length(mouse - m_pressed) > 4.0f) + m_dragging = true; + if (m_dragging && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)) + { + m_follow = false; + m_centre.x -= io.MouseDelta.x * m_scale; + m_centre.y -= io.MouseDelta.y * m_scale; + } + } + if (ImGui::IsItemDeactivated() && false == m_dragging) + { + auto const world{to_world(mouse)}; + go_to_point(glm::dvec3{world.x, camera.y, world.y}, std::max(20.0, 12.0 * m_scale)); + } + + auto *drawlist{ImGui::GetWindowDrawList()}; + ImVec2 const corner{origin.x + size.x, origin.y + size.y}; + drawlist->PushClipRect(origin, corner, true); + drawlist->AddRectFilled(origin, corner, IM_COL32(28, 32, 36, 255)); + auto const low{to_world({origin.x, origin.y})}; + auto const high{to_world({corner.x, corner.y})}; + auto const *ridden{m_ride.track()}; + // what's left of the vertices for the tracks, some kept for the stations, the camera and the scale + auto const budget{drawlist->VtxBuffer.Size + 56000}; + auto full{false}; + std::vector points; + std::unordered_set dots; + for (auto const &drawn : m_lines) + { + if (drawn.track == nullptr || drawn.high.x < low.x || drawn.low.x > high.x || drawn.high.y < low.y || drawn.low.y > high.y) + continue; + if (drawlist->VtxBuffer.Size > budget) + { + full = true; + break; + } + auto const colour{drawn.track == ridden ? IM_COL32(255, 170, 40, 255) : drawn.track->eType == tt_Switch ? IM_COL32(150, 200, 255, 230) : IM_COL32(200, 200, 200, 210)}; + auto const extent{std::max(drawn.high.x - drawn.low.x, drawn.high.y - drawn.low.y) / m_scale}; // px + // a track a pixel long a dot, one dot a pixel + if (extent < 1.5) + { + auto const at{to_screen(drawn.low)}; + if (dots.insert((static_cast(static_cast(static_cast(std::floor(at.x)))) << 32) | static_cast(static_cast(std::floor(at.y)))).second) + drawlist->AddRectFilled(at, ImVec2(at.x + 1.0f, at.y + 1.0f), colour); + continue; + } + auto const width{drawn.track == ridden ? 3.0f : 1.0f}; + // a short one from end to end, the longer ones through their points a few pixels apart + if (extent < 16.0 && drawn.track != ridden) + { + drawlist->AddLine(to_screen(drawn.points.front()), to_screen(drawn.points.back()), colour, width); + continue; + } + points.clear(); + for (auto const &point : drawn.points) + { + auto const at{to_screen(point)}; + if (points.empty() || &point == &drawn.points.back() || std::abs(at.x - points.back().x) + std::abs(at.y - points.back().y) > 4.0f) + points.push_back(at); + } + drawlist->AddPolyline(points.data(), static_cast(points.size()), colour, ImDrawFlags_None, width); + } + // the stations: a dot at each stop, the name at the first one in sight + for (int i = 0; i < static_cast(m_stations.size()); ++i) + { + auto const &station{m_stations[i]}; + auto const marked{station.key == m_marked}; + bool named{false}; + for (auto const &stop : station.stops) + { + auto const at{to_screen({stop.point.x, stop.point.z})}; + if (at.x < origin.x - 50.0f || at.x > corner.x + 50.0f || at.y < origin.y - 20.0f || at.y > corner.y + 20.0f) + continue; + // the stops stop short of the limit of the list too, a few hundred vertices kept for the camera and the scale + if (drawlist->VtxBuffer.Size > 64500) + { + full = true; + break; + } + drawlist->AddCircleFilled(at, marked ? 5.0f : 3.5f, marked ? IM_COL32(255, 80, 60, 255) : IM_COL32(255, 220, 60, 255)); + if (false == named && (marked || m_scale < 25.0)) + { + named = true; + drawlist->AddText(ImVec2(at.x + 6.0f, at.y - ImGui::GetTextLineHeight() * 0.5f), IM_COL32(255, 235, 150, 255), station.name.c_str()); + } + } + } + // the camera, a triangle the way it looks + { + auto const at{to_screen({camera.x, camera.z})}; + auto const look{camera_look()}; + ImVec2 const forward{static_cast(look.x), static_cast(look.z)}; + ImVec2 const side{-forward.y, forward.x}; + auto const point = [&](float const Ahead, float const Across) { return ImVec2(at.x + forward.x * Ahead + side.x * Across, at.y + forward.y * Ahead + side.y * Across); }; + drawlist->AddTriangleFilled(point(11.0f, 0.0f), point(-6.0f, 6.0f), point(-6.0f, -6.0f), IM_COL32(255, 60, 60, 255)); + drawlist->AddTriangle(point(11.0f, 0.0f), point(-6.0f, 6.0f), point(-6.0f, -6.0f), IM_COL32(0, 0, 0, 255), 1.0f); + } + // the scale bar + { + auto metres{100.0 * m_scale}; + auto const magnitude{std::pow(10.0, std::floor(std::log10(metres)))}; + metres = metres / magnitude >= 5.0 ? 5.0 * magnitude : metres / magnitude >= 2.0 ? 2.0 * magnitude : magnitude; + auto const pixels{static_cast(metres / m_scale)}; + ImVec2 const from{origin.x + 8.0f, corner.y - 10.0f}; + drawlist->AddLine(from, ImVec2(from.x + pixels, from.y), IM_COL32(255, 255, 255, 220), 2.0f); + auto const text{metres >= 1000.0 ? format("%g km", metres / 1000.0) : format("%g m", metres)}; + drawlist->AddText(ImVec2(from.x, from.y - ImGui::GetTextLineHeight() - 2.0f), IM_COL32(255, 255, 255, 220), text.c_str()); + } + if (full) + { + auto const *text{STR_C("Zoom in to see all the tracks")}; + drawlist->AddText(ImVec2(origin.x + 8.0f, origin.y + 6.0f), IM_COL32(255, 200, 120, 255), text); + } + drawlist->PopClipRect(); + ImGui::EndChild(); +} + +void minimap_tool::render_windows() +{ + if (false == m_open) + return; + // first in the top right corner of the view, over the scene rather than over the panels + ImVec2 const size{340.0f * Global.ui_scale, 460.0f * Global.ui_scale}; + ImGui::SetNextWindowPos(ImVec2(editor_ui::view_max().x - size.x - 60.0f, editor_ui::view_min().y + 50.0f), ImGuiCond_FirstUseEver); + ImGui::SetNextWindowSize(size, ImGuiCond_FirstUseEver); + ImGui::SetNextWindowBgAlpha(0.97f); + if (false == ImGui::Begin((std::string(STR_C("Minimap")) + "###minimap").c_str(), &m_open)) + { + ImGui::End(); + return; + } + render_search(); + ImGui::Checkbox(STR_C("Follow the camera"), &m_follow); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Whole scenery")) && false == m_lines.empty()) + { + m_fitted = true; + m_follow = false; + m_centre = (m_low + m_high) * 0.5; + auto const room{ImGui::GetContentRegionAvail()}; + m_scale = std::max((m_high.x - m_low.x) / std::max(room.x, 50.0f), (m_high.y - m_low.y) / std::max(room.y, 80.0f)) * 1.05; + } + render_map(ImGui::GetContentRegionAvail().y); + ImGui::End(); +} + +editor_selftest_result minimap_tool::selftest(std::string const &Command, std::istringstream &Words) +{ + if (Command == "minimap") + { + // minimap <0|1|2>: the window shown or hidden, 2: shown with the whole scenery in it, as its button does + int open{1}; + Words >> open; + m_open = open != 0; + if (open == 2) + { + gather_lines(); + m_fitted = true; + m_follow = false; + m_centre = (m_low + m_high) * 0.5; + m_scale = std::max(m_high.x - m_low.x, m_high.y - m_low.y) / 300.0; + } + return editor_selftest_result::handled; + } + if (Command == "stations") + { + // stations: logs the stations the W4 name, with their stops + gather_stations(); + WriteLog(format("SELFTEST stations: %d", static_cast(m_stations.size()))); + for (auto const &station : m_stations) + for (auto const &stop : station.stops) + WriteLog(format("SELFTEST station %s at %.2f %.2f %.2f track %s", station.name.c_str(), stop.point.x, stop.point.y, stop.point.z, stop.track != nullptr ? stop.track->name().c_str() : "-")); + return editor_selftest_result::handled; + } + if (Command == "station") + { + // station : the camera to the next stop of the first station whose name holds the text, as a click on the list + std::string text; + std::getline(Words >> std::ws, text); + gather_stations(); + auto const wanted{folded(utf8_to_win1250(text))}; + auto const found{std::find_if(m_stations.begin(), m_stations.end(), [&](station const &Station) { return Station.key.find(wanted) != std::string::npos; })}; + if (found == m_stations.end()) + WriteLog("SELFTEST station " + text + ": none"); + else + { + go_to(*found); + WriteLog("SELFTEST station " + text + ": " + found->name); + } + return editor_selftest_result::handled; + } + if (Command == "minimapclick") + { + // minimapclick : as a click on the map there + double x{0.0}; + double z{0.0}; + Words >> x >> z; + go_to_point(glm::dvec3{x, m_view.camera_position().y, z}, 30.0); + WriteLog(format("SELFTEST minimapclick %.2f %.2f", x, z)); + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} diff --git a/application/editormodeminimap.h b/application/editormodeminimap.h new file mode 100644 index 000000000..07ceaebb5 --- /dev/null +++ b/application/editormodeminimap.h @@ -0,0 +1,85 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.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 "application/editortool.h" + +#include +#include + +class track_ride; + +// the tracks of the scenery seen from above with the camera on them, and the stations the stop indicators (W4) name, to find +// one by its name and go there +class minimap_tool final : public editor_tool +{ + public: + // a stop of passenger trains, as a W4 marks it + struct stop + { + glm::dvec3 point{0.0}; + TTrack *track{nullptr}; + }; + struct station + { + std::string name; // as shown + std::string key; // lower case, without the polish letters, the stops of the same name gathered by it + std::vector stops; + std::size_t next{0}; // the stop gone to the next time + }; + + minimap_tool(editor_view &View, editor_history &History, track_ride &Ride) : m_view{View}, m_history{History}, m_ride{Ride} {} + void render_windows() override; + void forget(scene::basic_node const *Node) override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + bool is_open() const { return m_open; } + void toggle() { m_open = !m_open; } + // the stations of the scenery, gathered again where the scenery changed + std::vector const &stations(); + // the camera to the next stop of the station: riding along the track it rides on from there, else it flies over to it + void go_to(station &Station); + // the camera to the track nearest to the point of the plan, or above the point where there's none near + void go_to_point(glm::dvec3 const &Point, double const Reach); + + private: + // a path of a rail track as the map draws it + struct line + { + TTrack *track{nullptr}; + glm::dvec2 low{0.0}; + glm::dvec2 high{0.0}; + std::vector points; // x, z + }; + void gather_lines(); + void gather_stations(); + void render_search(); + void render_map(float const Height); + bool stale(std::size_t &Seen) const; + + editor_view &m_view; + editor_history &m_history; + track_ride &m_ride; + bool m_open{false}; + std::vector m_lines; + glm::dvec2 m_low{0.0}; // of all the lines + glm::dvec2 m_high{0.0}; + std::size_t m_lines_seen{~std::size_t{0}}; + std::vector m_stations; + std::size_t m_stations_seen{~std::size_t{0}}; + char m_search[64]{}; + std::string m_marked; // the key of the station last gone to, drawn larger + // the map + glm::dvec2 m_centre{0.0}; // x, z + double m_scale{4.0}; // m a pixel + bool m_follow{true}; // the centre goes with the camera + bool m_fitted{false}; + glm::vec2 m_pressed{0.0f}; + bool m_dragging{false}; +}; diff --git a/application/editormodenmt.cpp b/application/editormodenmt.cpp new file mode 100644 index 000000000..13465a006 --- /dev/null +++ b/application/editormodenmt.cpp @@ -0,0 +1,4733 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.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 heightmap terrain made from the digital terrain model of GUGiK: the scenery placed as its orthophoto is, the heights +// of the model moved up or down to meet the tracks it has already, the chunks around the camera or along the tracks made as +// the model comes in, and the formation of each track with its slopes kept as a modifier of the terrain + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editormodeshared.h" +#include "application/editoruilayer.h" +#include "application/editorprojection.h" +#include "editor/editorFormat.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorKilometrage.hpp" +#include "editor/editorSettings.hpp" +#include "model/AnimModel.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" +#include "world/Track.h" + +#include "imgui/imgui.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +// how many places of the tracks the offset of the model is worked out from at most, each needing its square of the model +std::size_t constexpr fit_places{48}; +// the terrain under the tracks: places along them every so many m, the squares they're kept in, how far from the tracks the +// difference at them draws the model; past that the offset of the whole scenery +double constexpr anchor_step{25.0}; +double constexpr anchor_cell{100.0}; +double constexpr anchor_reach{300.0}; +double constexpr anchor_near{5.0}; + +std::pair anchor_cell_of(double const X, double const Z) +{ + return {static_cast(std::floor(X / anchor_cell)), static_cast(std::floor(Z / anchor_cell))}; +} + +// a path whose ends lie this far apart is an error of the scenery, as a point typed wrong: no grade line, no formation and no +// terrain along it +double constexpr broken_path{5000.0}; + +bool rail(TTrack const &Track) +{ + if ((Track.iCategoryFlag & 15) != 1 || Track.m_editorremoved || Track.m_paths.empty()) + return false; + auto const &path{Track.m_paths.front()}; + return geometry::plan_distance(path.points[segment_data::point::start], path.points[segment_data::point::end]) <= broken_path; +} + +// a choice of the new scenery as a card: a sketch of the ground a track lies on, the name and what it means; true when clicked. +// the real terrain: hills under an aerial photo, the track along them; none: the flat plane at 0 drawn as a grid +bool ground_card(char const *Id, char const *Title, char const *Text, bool const Hills, bool const Enabled, float const Width) +{ + auto const font{ImGui::GetFontSize()}; + auto const pad{std::round(font * 0.6f)}; + auto const sketch{std::round(font * 4.0f)}; + auto const wrap{Width - 2.0f * pad}; + auto const title{ImGui::CalcTextSize(Title, nullptr, false, wrap)}; + auto const text{ImGui::CalcTextSize(Text, nullptr, false, wrap)}; + auto const height{pad + sketch + pad * 0.6f + title.y + pad * 0.3f + text.y + pad}; + auto const top{ImGui::GetCursorScreenPos()}; + ImGui::BeginDisabled(false == Enabled); + auto const clicked{ImGui::InvisibleButton(Id, ImVec2(Width, height))}; + ImGui::EndDisabled(); + auto const hovered{Enabled && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)}; + auto *list{ImGui::GetWindowDrawList()}; + ImVec2 const bottom{top.x + Width, top.y + height}; + auto const rounding{std::round(font * 0.4f)}; + auto const accent{family_colour(0)}; + list->AddRectFilled(top, bottom, ImGui::GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), rounding); + list->AddRect(top, bottom, hovered ? accent : ImGui::GetColorU32(ImGuiCol_Border), rounding, 0, hovered ? 2.0f : 1.0f); + auto const alpha{Enabled ? 1.0f : 0.35f}; + auto const tint = [&](ImU32 const Colour) { return (Colour & ~IM_COL32_A_MASK) | (static_cast(((Colour >> IM_COL32_A_SHIFT) & 0xFF) * alpha) << IM_COL32_A_SHIFT); }; + ImVec2 const low{top.x + pad, top.y + pad}; + ImVec2 const high{top.x + Width - pad, top.y + pad + sketch}; + list->AddRectFilled(low, high, tint(IM_COL32(20, 26, 34, 255)), rounding * 0.6f); + list->PushClipRect(low, high, true); + int constexpr steps{48}; + auto const x_of = [&](float const Share) { return low.x + (high.x - low.x) * Share; }; + if (Hills) + { + auto const ground = [](float const Share) { return 0.45f + 0.18f * std::sin(Share * 7.0f + 0.4f) + 0.08f * std::sin(Share * 17.0f); }; + std::vector line; + for (int i = 0; i <= steps; ++i) + { + auto const share{static_cast(i) / steps}; + line.emplace_back(x_of(share), low.y + (high.y - low.y) * ground(share)); + } + // the strips under the line drawn without the soft edges, else seams show between them + auto const flags{list->Flags}; + list->Flags &= ~ImDrawListFlags_AntiAliasedFill; + for (int i = 0; i < steps; ++i) + list->AddQuadFilled(line[i], line[i + 1], ImVec2(line[i + 1].x, high.y), ImVec2(line[i].x, high.y), tint(IM_COL32(70, 110, 55, 200))); + list->Flags = flags; + list->AddPolyline(line.data(), static_cast(line.size()), tint(IM_COL32(150, 200, 110, 255)), 0, 1.5f); + // the track goes along the ground, a little above it on embankments, below it in cuttings + std::vector track; + for (int i = 0; i <= steps; ++i) + { + auto const share{static_cast(i) / steps}; + auto const smooth{0.45f + 0.09f * std::sin(share * 7.0f + 0.4f)}; + track.emplace_back(x_of(share), low.y + (high.y - low.y) * smooth - 2.0f); + } + list->AddPolyline(track.data(), static_cast(track.size()), tint(IM_COL32(235, 235, 235, 255)), 0, 2.5f); + } + else + { + auto const horizon{low.y + (high.y - low.y) * 0.35f}; + auto const grid{tint(IM_COL32(120, 130, 150, 120))}; + for (int i = 0; i <= 4; ++i) + { + auto const t{static_cast(i) / 4.0f}; + auto const y{horizon + (high.y - horizon) * t * t}; + list->AddLine(ImVec2(low.x, y), ImVec2(high.x, y), grid); + } + auto const middle{(low.x + high.x) * 0.5f}; + for (int i = -6; i <= 6; ++i) + list->AddLine(ImVec2(middle + i * (high.x - low.x) * 0.06f, horizon), ImVec2(middle + i * (high.x - low.x) * 0.22f, high.y), grid); + auto const level{horizon + (high.y - horizon) * 0.45f}; + list->AddLine(ImVec2(low.x, level), ImVec2(high.x, level), tint(IM_COL32(235, 235, 235, 255)), 2.5f); + } + list->PopClipRect(); + auto y{high.y + pad * 0.6f}; + list->AddText(nullptr, 0.0f, ImVec2(low.x, y), tint(ImGui::GetColorU32(ImGuiCol_Text)), Title, nullptr, wrap); + y += title.y + pad * 0.3f; + list->AddText(nullptr, 0.0f, ImVec2(low.x, y), tint(ImGui::GetColorU32(ImGuiCol_TextDisabled)), Text, nullptr, wrap); + return clicked && Enabled; +} + +// what a way of putting the tracks and the terrain together does, drawn along a track: onto, the track goes along the hills of +// the model; under, the track stays level and the ground comes to it; only, the hills of the model as they are over a level track +enum class way_sketch { onto, under, only }; + +// a way of the tracks and the terrain as a card the width of the panel: the sketch on the left, the name and what it's for on +// the right, the one to take first lit green; true when clicked +bool way_card(char const *Id, char const *Title, char const *Text, way_sketch const Sketch, bool const First, bool const Enabled) +{ + auto const font{ImGui::GetFontSize()}; + auto const pad{std::round(font * 0.5f)}; + auto const width{ImGui::GetContentRegionAvail().x}; + ImVec2 const sketch{std::round(font * 4.5f), std::round(font * 2.8f)}; + auto const left{pad + sketch.x + pad}; + auto const wrap{std::max(font * 4.0f, width - left - pad)}; + auto const title{ImGui::CalcTextSize(Title, nullptr, false, wrap)}; + auto const text{ImGui::CalcTextSize(Text, nullptr, false, wrap)}; + auto const height{pad + std::max(sketch.y, title.y + pad * 0.25f + text.y) + pad}; + auto const top{ImGui::GetCursorScreenPos()}; + ImGui::BeginDisabled(false == Enabled); + auto const clicked{ImGui::InvisibleButton(Id, ImVec2(width, height))}; + ImGui::EndDisabled(); + auto const hovered{Enabled && ImGui::IsItemHovered()}; + auto const held{Enabled && ImGui::IsItemActive()}; + auto *list{ImGui::GetWindowDrawList()}; + ImVec2 const bottom{top.x + width, top.y + height}; + auto const rounding{std::round(font * 0.4f)}; + auto const lit{First && Enabled}; + auto const green{IM_COL32(70, 170, 85, 255)}; + auto const fill{lit ? (held ? IM_COL32(45, 110, 55, 255) : hovered ? IM_COL32(40, 95, 50, 255) : IM_COL32(32, 72, 40, 255)) + : ImGui::GetColorU32(held ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg)}; + list->AddRectFilled(top, bottom, fill, rounding); + list->AddRect(top, bottom, lit ? green : hovered ? family_colour(0) : ImGui::GetColorU32(ImGuiCol_Border), rounding, 0, lit || hovered ? 2.0f : 1.0f); + auto const alpha{Enabled ? 1.0f : 0.35f}; + auto const tint = [&](ImU32 const Colour) { return (Colour & ~IM_COL32_A_MASK) | (static_cast(((Colour >> IM_COL32_A_SHIFT) & 0xFF) * alpha) << IM_COL32_A_SHIFT); }; + ImVec2 const low{top.x + pad, top.y + (height - sketch.y) * 0.5f}; + ImVec2 const high{low.x + sketch.x, low.y + sketch.y}; + list->AddRectFilled(low, high, tint(IM_COL32(20, 26, 34, 255)), rounding * 0.6f); + list->PushClipRect(low, high, true); + int constexpr steps{40}; + auto const at = [&](float const Share, float const Height) { return ImVec2(low.x + sketch.x * Share, low.y + sketch.y * Height); }; + auto const hills = [](float const Share) { return 0.52f + 0.2f * std::sin(Share * 6.0f + 0.4f) + 0.07f * std::sin(Share * 15.0f); }; + auto const level{0.5f}; + // the ground as a line and the strips under it, drawn without the soft edges, else seams show between them + auto const ground = [&](auto const &Height, ImU32 const Colour) { + std::vector line; + for (int i = 0; i <= steps; ++i) + { + auto const share{static_cast(i) / steps}; + line.push_back(at(share, Height(share))); + } + auto const flags{list->Flags}; + list->Flags &= ~ImDrawListFlags_AntiAliasedFill; + for (int i = 0; i < steps; ++i) + list->AddQuadFilled(line[i], line[i + 1], ImVec2(line[i + 1].x, high.y), ImVec2(line[i].x, high.y), tint(Colour)); + list->Flags = flags; + list->AddPolyline(line.data(), static_cast(line.size()), tint(IM_COL32(150, 200, 110, 255)), 0, 1.5f); + }; + auto const track = [&](auto const &Height) { + std::vector line; + for (int i = 0; i <= steps; ++i) + { + auto const share{static_cast(i) / steps}; + line.push_back(at(share, Height(share))); + line.back().y -= 2.0f; + } + list->AddPolyline(line.data(), static_cast(line.size()), tint(IM_COL32(235, 235, 235, 255)), 0, 2.5f); + }; + switch (Sketch) + { + case way_sketch::onto: + // the track goes along the ground, a little above it on embankments, below it in cuttings + ground(hills, IM_COL32(70, 110, 55, 220)); + track([](float const Share) { return 0.52f + 0.1f * std::sin(Share * 6.0f + 0.4f); }); + break; + case way_sketch::under: + { + // the hills of the model faint where they were, the ground drawn up and down to the level track, fading out of it + std::vector was; + for (int i = 0; i <= steps; ++i) + { + auto const share{static_cast(i) / steps}; + was.push_back(at(share, hills(share))); + } + list->AddPolyline(was.data(), static_cast(was.size()), tint(IM_COL32(150, 200, 110, 90)), 0, 1.0f); + ground([&](float const Share) { return level + 0.04f + 0.25f * (hills(Share) - level); }, IM_COL32(70, 110, 55, 220)); + track([&](float) { return level; }); + break; + } + case way_sketch::only: + // the level track first, the hills over it: it shows above the hollows and goes into the hills + track([&](float) { return level; }); + ground(hills, IM_COL32(70, 110, 55, 235)); + break; + } + list->PopClipRect(); + auto const x{top.x + left}; + auto y{top.y + (height - (title.y + pad * 0.25f + text.y)) * 0.5f}; + list->AddText(nullptr, 0.0f, ImVec2(x, y), tint(ImGui::GetColorU32(ImGuiCol_Text)), Title, nullptr, wrap); + y += title.y + pad * 0.25f; + list->AddText(nullptr, 0.0f, ImVec2(x, y), tint(lit ? IM_COL32(200, 225, 200, 255) : ImGui::GetColorU32(ImGuiCol_TextDisabled)), Text, nullptr, wrap); + return clicked && Enabled; +} + +// m, the squares of the plan the points of the lines are kept in +double constexpr kPlanCell{50.0}; + +// a bridge or a tunnel keeps the model under it as it is, and a turntable its pit +bool shapes_ground(TTrack const &Track) +{ + return Track.eEnvironment != e_bridge && Track.eEnvironment != e_tunnel && Track.eType != tt_Table; +} + +// the name the formation of a track is known by in the terrain, of a track with no name where it lies: two of the same name +// would be one formation +std::string formation_name(TTrack const &Track) +{ + if (false == Track.name().empty() || Track.m_paths.empty()) + return Track.name(); + auto const &points{Track.m_paths.front().points}; + auto const &start{points[segment_data::point::start]}; + auto const &end{points[segment_data::point::end]}; + return format("@%.2f,%.2f>%.2f,%.2f", start.x, start.z, end.x, end.z); +} + +// an end of a path no other path is linked to +struct loose_end +{ + TTrack *track{nullptr}; + int path{0}; + bool atend{false}; + glm::dvec3 point{0.0}; + glm::dvec3 outward{0.0}; // off the path along it +}; + +loose_end end_of(TTrack &Track, int const Path, bool const Atend) +{ + auto const &points{Track.m_paths[Path].points}; + auto const &point{points[Atend ? segment_data::point::end : segment_data::point::start]}; + auto const &control{points[Atend ? segment_data::point::control2 : segment_data::point::control1]}; + auto const &other{points[Atend ? segment_data::point::start : segment_data::point::end]}; + return {&Track, Path, Atend, point, control != glm::dvec3{} ? -control : point - other}; +} + +// a track runs up to a turntable with its end this near the rim, facing the centre this closely (the cosine), as high as the +// table give or take, the table dropped into its pit too; the model this far past the rim lies beside the pit, past its wall; +// the line keeps level this far off the rim +double constexpr kRimNear{0.3}; // m +double constexpr kRimFacing{0.9}; +double constexpr kRimLevel{3.0}; // m +double constexpr kPitWall{1.5}; // m +double constexpr kRunUp{10.0}; // m + +bool on_rim(loose_end const &End, glm::dvec3 const &Centre, double const Rim) +{ + auto const outward{geometry::plan_of(End.outward)}; + auto const inward{geometry::plan_of(Centre - End.point)}; + return std::abs(glm::length(inward) - Rim) <= kRimNear && std::abs(End.point.y - Centre.y) <= kRimLevel && glm::length(outward) > 1e-6 && + glm::dot(outward, inward) >= kRimFacing * glm::length(outward) * glm::length(inward); +} + +// ends which meet in the plan facing each other, laid apart in height by hand, so the game doesn't join them; farther apart +// than a track over another can be, they lie on two levels +std::vector> loose_pairs() +{ + double constexpr kLevel{2.0}; // m + auto const linked = [](TTrack const &Track, int const Path, bool const Atend) { + if (Track.eType == tt_Switch && Track.SwitchExtension) + return (Atend ? Track.SwitchExtension->pNexts[Path & 1] : Track.SwitchExtension->pPrevs[Path & 1]) != nullptr; + return (Atend ? Track.trNext : Track.trPrev) != nullptr; + }; + std::map, std::vector> cells; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || false == rail(*track) || track->Length() < 0.01) + continue; + for (int i = 0; i < static_cast(track->m_paths.size()); ++i) + for (auto const atend : {false, true}) + if (false == linked(*track, i, atend)) + { + auto const end{end_of(*track, i, atend)}; + cells[{static_cast(std::floor(end.point.x)), static_cast(std::floor(end.point.z))}].push_back(end); + } + } + std::vector> result; + std::set> taken; + for (auto const &[cell, ends] : cells) + for (auto const &a : ends) + { + if (taken.contains({a.track, a.path, a.atend})) + continue; + loose_end const *match{nullptr}; + for (int dx = -1; dx <= 1 && match == nullptr; ++dx) + for (int dz = -1; dz <= 1 && match == nullptr; ++dz) + { + auto const found{cells.find({cell.first + dx, cell.second + dz})}; + if (found == cells.end()) + continue; + auto const outward{geometry::plan_of(a.outward)}; + for (auto const &b : found->second) + if (b.track != a.track && false == taken.contains({b.track, b.path, b.atend}) && geometry::plan_distance(a.point, b.point) <= geometry::same_point && + std::abs(a.point.y - b.point.y) <= kLevel && glm::dot(outward, geometry::plan_of(b.outward)) < -0.5 * glm::length(outward) * glm::length(geometry::plan_of(b.outward))) + { + match = &b; + break; + } + } + if (match == nullptr) + continue; + taken.insert({a.track, a.path, a.atend}); + taken.insert({match->track, match->path, match->atend}); + result.emplace_back(a, *match); + } + return result; +} + +} // namespace + +std::vector editor_mode::nmt_track_places(double const Step) const +{ + std::vector result; + // a track with no trackbed of its own, as the switches of the older sceneries whose bed is an include, lies in the bed of + // the others + std::vector depths; + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && rail(*track) && profile_own_bed(*track)) + depths.push_back(profile_ballast(*track).first); + std::nth_element(depths.begin(), depths.begin() + depths.size() / 2, depths.end()); + auto const usual{depths.empty() ? 0.0 : depths[depths.size() / 2]}; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || false == rail(*track)) + continue; + auto const rails{static_cast(track->rail_height())}; + for (std::size_t path = 0; path < track->m_paths.size(); ++path) + { + // the ballast drawn under the path: a switch has it of the plain track it goes on into, as the renderer lays it + auto const *source{track}; + if (track->eType == tt_Switch && track->SwitchExtension != nullptr && path < 2) + { + auto const *previous{track->SwitchExtension->pPrevs[path]}; + auto const *next{track->SwitchExtension->pNexts[path]}; + source = previous != nullptr && previous->eType != tt_Switch ? previous : next != nullptr && next->eType != tt_Switch ? next : track; + } + auto ballast{profile_ballast(*source)}; + if (false == profile_own_bed(*source)) + ballast.first = usual; + geometry::bezier const curve{track->m_paths[path]}; + auto const &points{track->m_paths[path].points}; + auto const chord{glm::distance(points[segment_data::point::start], points[segment_data::point::end])}; + auto const count{std::max(1, static_cast(std::ceil(chord * 1.1 / Step)))}; + for (int i = 0; i <= count; ++i) + { + auto const at{curve.point(static_cast(i) / count)}; + result.push_back({at, at.y - ballast.first, at.y - rails, ballast.second, track, static_cast(path), shapes_ground(*track)}); + } + } + } + // a track passing over another one by more than the clearance, as at a flyover whose bridge is a model: where the slopes of its + // embankment would bury the track below, it stands on a bridge, and the ground there is the lower track's + double constexpr clearance{3.0}; + double constexpr cell{20.0}; + auto const key_of = [&](double const X, double const Z) { return (static_cast(std::floor(X / cell)) << 32) ^ (static_cast(std::floor(Z / cell)) & 0xffffffff); }; + std::unordered_map> grid; + double widest{0.0}; + double lowest{std::numeric_limits::max()}, highest{std::numeric_limits::lowest()}; + for (std::size_t i = 0; i < result.size(); ++i) + { + grid[key_of(result[i].position.x, result[i].position.z)].push_back(i); + widest = std::max(widest, result[i].half_width); + lowest = std::min(lowest, result[i].crown); + highest = std::max(highest, result[i].formation); + } + // the farthest the slopes of an embankment over a track can reach + auto const reach{2.0 * widest + m_nmt_state.slope * std::max(0.0, highest - lowest)}; + auto const span{static_cast(std::ceil(std::min(reach, 60.0) / cell))}; + std::vector over(result.size(), 0); + for (std::size_t i = 0; i < result.size(); ++i) + { + auto const &place{result[i]}; + if (false == place.shapes) + continue; + auto const cx{static_cast(std::floor(place.position.x / cell))}; + auto const cz{static_cast(std::floor(place.position.z / cell))}; + for (auto dz = -span; dz <= span && 0 == over[i]; ++dz) + for (auto dx = -span; dx <= span && 0 == over[i]; ++dx) + { + auto const found{grid.find(((cx + dx) << 32) ^ ((cz + dz) & 0xffffffff))}; + if (found == grid.end()) + continue; + for (auto const j : found->second) + { + auto const &other{result[j]}; + if (other.track == place.track) + continue; + auto const height{place.formation - other.crown}; + if (height < clearance) + continue; + auto const distance{glm::distance(glm::dvec2{place.position.x, place.position.z}, glm::dvec2{other.position.x, other.position.z})}; + if (distance <= place.half_width + other.half_width + m_nmt_state.slope * height) + { + over[i] = 1; + break; + } + } + } + } + for (std::size_t i = 0; i < result.size(); ++i) + if (over[i] != 0) + result[i].shapes = false; + // nor where the grade lines went over the model falling away by the abutments of a bridge or a viaduct + double constexpr bridged_near{1.0}; + double constexpr bridged_level{1.0}; + auto const &bridged{m_nmt_state.bridged}; + if (false == bridged.empty()) + for (auto &place : result) + { + if (false == place.shapes) + continue; + auto const cx{static_cast(std::floor(place.position.x / kPlanCell))}; + auto const cz{static_cast(std::floor(place.position.z / kPlanCell))}; + for (int dx = -1; dx <= 1 && place.shapes; ++dx) + for (int dz = -1; dz <= 1 && place.shapes; ++dz) + if (auto const cell{bridged.find({cx + dx, cz + dz})}; cell != bridged.end()) + for (auto const &point : cell->second) + if (glm::length(glm::dvec2{point.x - place.position.x, point.z - place.position.z}) <= bridged_near && std::abs(point.y - place.position.y) <= bridged_level) + { + place.shapes = false; + break; + } + } + return result; +} + +void editor_mode::nmt_locate() +{ + auto const &config{m_orthophoto.settings()}; + m_nmt.place(config.north, config.east); +} + +void editor_mode::nmt_fit() +{ + nmt_locate(); + auto &state{m_nmt_state}; + state.error.clear(); + state.under = false; + state.fit.clear(); + auto const places{nmt_track_places(25.0)}; + std::vector shaped; + std::copy_if(places.begin(), places.end(), std::back_inserter(shaped), [](nmt_place const &Place) { return Place.shapes; }); + if (shaped.empty()) + { + state.offset = 0.0; + state.fitted = true; + state.status = STR("No tracks to fit the terrain model to: its heights are taken as they are"); + return; + } + // spread over the whole scenery, each place asking for its square of the model + auto const every{std::max(1, shaped.size() / fit_places)}; + for (std::size_t i = 0; i < shaped.size(); i += every) + state.fit.push_back(shaped[i]); + state.fitting = true; + state.fetch_most = 0; + state.status = STR("Fetching the terrain model under the tracks..."); +} + +void editor_mode::nmt_under_start() +{ + nmt_locate(); + auto &state{m_nmt_state}; + state.error.clear(); + state.fit.clear(); + state.anchors.clear(); + state.anchor_cells.clear(); + for (auto const &place : nmt_track_places(anchor_step)) + if (place.shapes) + state.fit.push_back(place); + if (state.fit.empty()) + { + state.status = STR("No tracks to make the terrain under"); + return; + } + state.under = true; + state.fitting = true; + state.fetch_most = 0; + state.result = false; + state.findings.clear(); + state.status = STR("Fetching the terrain model under the tracks..."); +} + +void editor_mode::nmt_under_anchors() +{ + auto &state{m_nmt_state}; + struct found + { + glm::dvec2 at; + double difference; + TTrack const *track; + int path; + }; + std::vector places; + for (auto const &place : state.fit) + if (double height; m_nmt.height(place.position.x, place.position.z, height)) + places.push_back({{place.position.x, place.position.z}, place.crown - height, place.track, place.path}); + state.anchors.clear(); + state.anchor_cells.clear(); + for (std::size_t i = 0; i < places.size(); ++i) + { + // a place where the model is off, as a bridge it doesn't know of or a cutting dug since, doesn't pull the terrain around + // it: the median of the places around it along the same path + std::vector around; + for (auto j{i >= 4 ? i - 4 : 0}; j < std::min(places.size(), i + 5); ++j) + if (places[j].track == places[i].track && places[j].path == places[i].path) + around.push_back(places[j].difference); + std::nth_element(around.begin(), around.begin() + around.size() / 2, around.end()); + state.anchor_cells[anchor_cell_of(places[i].at.x, places[i].at.y)].push_back(state.anchors.size()); + state.anchors.emplace_back(places[i].at.x, places[i].at.y, around[around.size() / 2]); + } +} + +double editor_mode::nmt_offset_at(double const X, double const Z) const +{ + auto const &state{m_nmt_state}; + if (false == state.under || state.anchors.empty()) + return state.offset; + // the places near weigh the most, down to nothing at the reach; the offset of the scenery weighs as one place at the reach + auto const cell{anchor_cell_of(X, Z)}; + auto const span{static_cast(std::ceil(anchor_reach / anchor_cell))}; + auto const outermost{1.0 / (anchor_reach * anchor_reach + anchor_near * anchor_near)}; + double sum{state.offset * outermost}; + double weights{outermost}; + for (int dz = -span; dz <= span; ++dz) + for (int dx = -span; dx <= span; ++dx) + { + auto const found{state.anchor_cells.find({cell.first + dx, cell.second + dz})}; + if (found == state.anchor_cells.end()) + continue; + for (auto const index : found->second) + { + auto const &anchor{state.anchors[index]}; + auto const squared{(anchor.x - X) * (anchor.x - X) + (anchor.y - Z) * (anchor.y - Z)}; + if (squared >= anchor_reach * anchor_reach) + continue; + auto const weight{1.0 / (squared + anchor_near * anchor_near) - outermost}; + sum += anchor.z * weight; + weights += weight; + } + } + return sum / weights; +} + +void editor_mode::nmt_finish_fit() +{ + auto &state{m_nmt_state}; + std::vector differences; + for (auto const &place : state.fit) + if (double height; m_nmt.height(place.position.x, place.position.z, height)) + differences.push_back(place.crown - height); + state.fitting = false; + if (differences.empty()) + { + state.status = STR("The terrain model has no data under the tracks: is the scenery placed where it is?"); + return; + } + std::sort(differences.begin(), differences.end()); + state.offset = differences[differences.size() / 2]; + std::vector deviations; + for (auto const difference : differences) + deviations.push_back(std::abs(difference - state.offset)); + std::sort(deviations.begin(), deviations.end()); + state.spread = deviations[deviations.size() / 2]; + state.fitted = true; + state.samples = differences.size(); + state.status = format(STR_P("The tracks lie %+.2f m against the terrain model (%zu place, they differ by %.2f m around it)", "The tracks lie %+.2f m against the terrain model (%zu places, they differ by %.2f m around it)", state.samples), state.offset, state.samples, state.spread); + if (state.spread > 10.0) + state.status += STR(". That's far too much: the place of the scenery is likely wrong, check the orthophoto"); + WriteLog("Editor: NMT - " + state.status, logtype::generic); + if (false == state.under) + return; + // the terrain under the tracks: drawn to them place by place, then made along them + nmt_under_anchors(); + auto const status{state.status}; + nmt_make(nmt_keys_along_tracks(), true); + state.status = status + "\n" + state.status; +} + +std::vector editor_mode::nmt_keys_around() const +{ + std::vector result; + auto const centre{heightmap::chunk_at(Camera.Pos.x, Camera.Pos.z)}; + auto const first{-(m_terrain_add_count - 1) / 2}; + for (int dz = 0; dz < m_terrain_add_count; ++dz) + for (int dx = 0; dx < m_terrain_add_count; ++dx) + { + heightmap::chunk_key const key{centre.first + first + dx, centre.second + first + dz}; + // none outside the download area + if (auto const low{heightmap::chunk_corner(key)}; in_download_area(low, low + glm::dvec2{heightmap::chunk_size})) + result.push_back(key); + } + return result; +} + +std::vector editor_mode::nmt_keys_along_tracks() const +{ + std::set keys; + auto const reach{static_cast(std::ceil(m_nmt_state.band / heightmap::chunk_size))}; + for (auto const &place : nmt_track_places(heightmap::chunk_size * 0.5)) + { + auto const at{heightmap::chunk_at(place.position.x, place.position.z)}; + for (int dz = -reach; dz <= reach; ++dz) + for (int dx = -reach; dx <= reach; ++dx) + { + heightmap::chunk_key const key{at.first + dx, at.second + dz}; + auto const low{heightmap::chunk_corner(key)}; + // the chunk reaches within the band of the track + glm::dvec2 const nearest{std::clamp(place.position.x, low.x, low.x + heightmap::chunk_size), std::clamp(place.position.z, low.y, low.y + heightmap::chunk_size)}; + if (glm::distance(nearest, glm::dvec2{place.position.x, place.position.z}) <= m_nmt_state.band && in_download_area(low, low + glm::dvec2{heightmap::chunk_size})) + keys.insert(key); + } + } + return {keys.begin(), keys.end()}; +} + +void editor_mode::nmt_make(std::vector const &Keys, bool const Reshape) +{ + auto &state{m_nmt_state}; + if (false == ensure_terrain()) + { + state.status = STR("The heightmap terrain can't be opened"); + return; + } + nmt_locate(); + state.given_up.clear(); + std::size_t queued{0}; + for (auto const &key : Keys) + { + if (std::find(state.pending.begin(), state.pending.end(), key) != state.pending.end()) + continue; + // a chunk of flat ground there, as made with no model or no ground under it, gets the ground of the model as a new one would + if (m_streamer.exists(key)) + { + if (false == nmt_flat_chunk(key)) + continue; + state.refill.insert(key); + } + state.pending.push_back(key); + ++queued; + } + state.made = 0; + state.empty = 0; + state.foreign = 0; + state.fetch_most = 0; + state.error.clear(); + // the chunks are the last step of the tracks put onto the terrain only after their grade lines + if (false == Reshape || queued == 0) + state.run = false; + if (queued > 0) + { + state.grown = false; + state.reshape = Reshape; + } + // the terrain comes with its photos, unless the user turned them off + if (queued > 0 && false == m_orthophoto.enabled() && false == m_orthophoto_chosen) + m_orthophoto.enabled(true); + state.status = queued > 0 ? format(STR_P("%zu chunk to make from the terrain model", "%zu chunks to make from the terrain model", queued), queued) : STR("There's terrain there already"); + // with chunks to make the formations are laid once they're made + if (Reshape && queued == 0 && state.shape) + { + nmt_shape_tracks(); + state.status += format(STR_P("; the formation of %zu path shaped", "; the formation of %zu paths shaped", state.shaped), state.shaped); + } +} + +bool editor_mode::nmt_ready(glm::dvec2 const &Min, glm::dvec2 const &Max) +{ + return m_nmt.request(Min, Max) && false == m_nmt.retrying(Min, Max); +} + +std::optional editor_mode::nmt_terrain_offset(std::vector const &Points, bool &Foreign) const +{ + Foreign = false; + std::vector differences; + for (auto const &point : Points) + if (double terrain, model; m_streamer.height_at(point.x, point.y, terrain) && m_nmt.height(point.x, point.y, model)) + differences.push_back(terrain - model); + if (differences.size() < 5) + return std::nullopt; + std::nth_element(differences.begin(), differences.begin() + differences.size() / 2, differences.end()); + auto const median{differences[differences.size() / 2]}; + // the formations of the tracks and the touch-ups of the brushes leave the terrain here and there, the rest keeps to the model + auto const along{std::count_if(differences.begin(), differences.end(), [&](double const Difference) { return std::abs(Difference - median) <= 0.3; })}; + if (static_cast(along) < 0.7 * static_cast(differences.size())) + { + Foreign = true; + return std::nullopt; + } + return median; +} + +std::optional editor_mode::nmt_chunk_offset(heightmap::chunk_key const &Key) const +{ + // the one rule for every chunk made from the model where there's no terrain, under the track laid, around the camera in the area or + // by the buttons: beside terrain made from the model it goes on at its height over the model, so no step is left at the seam; + // otherwise, beside terrain made by hand or none, at the offset of the scenery. no chunk is left out for what lies beside it + // the terrain drawn to the tracks place by place (under the tracks) keeps to their heights near it: the height of the chunk beside + // would carry one offset on along a run of chunks, metres off the tracks + if (auto const &state{m_nmt_state}; state.under && false == state.anchors.empty()) + return std::nullopt; + bool foreign{false}; + auto const offset{nmt_seam_offset(Key, foreign)}; + return foreign ? std::nullopt : offset; +} + +std::optional editor_mode::nmt_seam_offset(heightmap::chunk_key const &Key, bool &Foreign) const +{ + auto const low{heightmap::chunk_corner(Key)}; + auto const size{heightmap::chunk_size}; + int constexpr steps{16}; + struct side + { + int dx; + int dz; + glm::dvec2 from; + glm::dvec2 to; + }; + side const sides[]{{-1, 0, low, {low.x, low.y + size}}, {1, 0, {low.x + size, low.y}, low + glm::dvec2{size}}, {0, -1, low, {low.x + size, low.y}}, {0, 1, {low.x, low.y + size}, low + glm::dvec2{size}}}; + std::vector points; + for (auto const &edge : sides) + if (m_streamer.exists({Key.first + edge.dx, Key.second + edge.dz})) + for (int i = 0; i <= steps; ++i) + points.push_back(edge.from + (edge.to - edge.from) * (static_cast(i) / steps) + glm::dvec2{edge.dx, edge.dz} * 0.01); + return nmt_terrain_offset(points, Foreign); +} + +void editor_mode::nmt_track_changed(std::vector const &Tracks) +{ + auto &state{m_nmt_state}; + if (state.restoring || state.laying || state.stage != nmt_state::automatic::idle || Tracks.empty() || false == m_streamer.active()) + return; + for (auto *track : Tracks) + if (track != nullptr) + state.changed.insert(track); + state.changed_time = ImGui::GetTime(); +} + +void editor_mode::nmt_track_gone(TTrack const &Track) +{ + auto &state{m_nmt_state}; + if (state.restoring || state.stage != nmt_state::automatic::idle || Track.name().empty() || false == m_streamer.active()) + return; + state.gone.insert(Track.name()); + state.changed_time = ImGui::GetTime(); +} + +void editor_mode::nmt_follow_tracks() +{ + auto &state{m_nmt_state}; + if (state.changed.empty() && state.gone.empty()) + return; + if (false == state.follow) + { + state.changed.clear(); + state.gone.clear(); + return; + } + if (state.stage != nmt_state::automatic::idle || state.fitting || ImGui::GetTime() - state.changed_time < 0.3 || ImGui::IsMouseDown(ImGuiMouseButton_Left) || ImGui::IsMouseDown(ImGuiMouseButton_Right)) + return; + // laying on, from the end of the track laid or dragged from a free end, the terrain waits for the laying to end: shaping it + // goes through every chunk under the tracks, a stall each click + if ((m_lay.active && false == m_lay.points.empty()) || m_extend.active) + return; + if (false == m_streamer.active()) + { + state.changed.clear(); + state.gone.clear(); + return; + } + auto const &modifiers{m_streamer.modifiers()}; + auto const of = [](heightmap::modifier const &Modifier, std::string const &Track) { return Modifier.name == "nmt " + Track || Modifier.name.starts_with("nmt " + Track + " "); }; + std::vector dropped; + for (auto const &name : state.gone) + if (simulation::Paths.find(name) == nullptr) + for (auto const &modifier : modifiers) + if (of(modifier, name)) + dropped.push_back(modifier.name); + state.gone.clear(); + // the tracks with a formation take it along; one with none leaves the terrain as it is, until it's drawn to the track + std::vector shaped; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || false == state.changed.contains(track) || track->m_editorremoved || false == rail(*track) || track->name().empty()) + continue; + if (std::any_of(modifiers.begin(), modifiers.end(), [&](heightmap::modifier const &Modifier) { return of(Modifier, track->name()); })) + shaped.push_back(track); + } + state.changed.clear(); + if (dropped.empty() && shaped.empty()) + return; + // the terrain follows in the step of the history of the change of the tracks + terrain_history_step(); + auto const *top{m_history.empty() ? nullptr : m_history.back().terrain.get()}; + m_streamer.remove_modifiers(dropped); + auto const laid{shaped.empty() ? std::size_t{0} : nmt_shape_tracks(&shaped)}; + if (false == dropped.empty()) + forget_ground(); + terrain_history_step(); + auto const count{m_history.size()}; + auto const of_tracks = [](EditorSnapshot const &Step) { return Step.action == EditorSnapshot::Action::TrackEdit || (Step.action == EditorSnapshot::Action::Terrain && Step.joined); }; + if (count >= 2 && m_history.back().action == EditorSnapshot::Action::Terrain && m_history.back().terrain.get() != top && of_tracks(m_history[count - 2])) + m_history.back().joined = true; + WriteLog(format("Editor: NMT - the terrain followed the tracks: %zu formations laid, %zu taken away", laid, dropped.size()), logtype::generic); +} + +bool editor_mode::nmt_ahead(double const X, double const Z, double &Height) const +{ + auto const &state{m_nmt_state}; + if (false == state.grow || false == state.ahead.has_value() || false == m_nmt.placed() || false == m_nmt.height(X, Z, Height)) + return false; + Height += *state.ahead; + return true; +} + +bool editor_mode::nmt_ground(double const X, double const Z, double &Height) const +{ + if (nmt_ahead(X, Z, Height)) + return true; + if (false == m_nmt.placed() || false == m_nmt.height(X, Z, Height)) + return false; + Height += nmt_offset_at(X, Z); + return true; +} + +editor_mode::nmt_chunk editor_mode::add_chunk_from_nmt(heightmap::chunk_key const &Key, std::optional const Offset) +{ + auto const low{heightmap::chunk_corner(Key)}; + auto const high{low + glm::dvec2{heightmap::chunk_size}}; + if (false == nmt_ready(low - glm::dvec2{2.0}, high + glm::dvec2{2.0})) + return nmt_chunk::waiting; + auto const cells{heightmap::cells_for(m_terrain_spacing)}; + auto const side{static_cast(cells) + 1}; + auto const step{heightmap::chunk_size / cells}; + std::vector heights(side * side, m_terrain_baseheight); + std::vector found(side * side, 0); + // the offset over the chunk, every sixteenth of its side and between them along straight lines: it changes slowly + int constexpr coarse{16}; + std::array offsets; + for (int iz = 0; iz <= coarse; ++iz) + for (int ix = 0; ix <= coarse; ++ix) + offsets[iz * (coarse + 1) + ix] = Offset.has_value() ? *Offset : nmt_offset_at(low.x + ix * heightmap::chunk_size / coarse, low.y + iz * heightmap::chunk_size / coarse); + auto const offset_at = [&](double const X, double const Z) { + auto const u{std::clamp((X - low.x) / heightmap::chunk_size * coarse, 0.0, static_cast(coarse))}; + auto const v{std::clamp((Z - low.y) / heightmap::chunk_size * coarse, 0.0, static_cast(coarse))}; + auto const i{std::min(static_cast(u), coarse - 1)}; + auto const j{std::min(static_cast(v), coarse - 1)}; + auto const fu{u - i}; + auto const fv{v - j}; + auto const at = [&](int const I, int const J) { return offsets[J * (coarse + 1) + I]; }; + return (at(i, j) * (1.0 - fu) + at(i + 1, j) * fu) * (1.0 - fv) + (at(i, j + 1) * (1.0 - fu) + at(i + 1, j + 1) * fu) * fv; + }; + bool any{false}; + for (std::size_t iz = 0; iz < side; ++iz) + for (std::size_t ix = 0; ix < side; ++ix) + { + auto const index{iz * side + ix}; + if (double height; m_nmt.height(low.x + ix * step, low.y + iz * step, height)) + { + heights[index] = height + offset_at(low.x + ix * step, low.y + iz * step); + found[index] = 1; + any = true; + } + } + if (false == any) + return nmt_chunk::empty; + // where the model has no data the chunk goes on level with its nearest point + fill_from_nearest(heights, found, side); + auto const height = [&](double const X, double const Z) { + auto const ix{static_cast(std::clamp(std::lround((X - low.x) / step), 0, cells))}; + auto const iz{static_cast(std::clamp(std::lround((Z - low.y) / step), 0, cells))}; + return static_cast(heights[iz * side + ix]); + }; + if (false == m_streamer.exists(Key)) + { + m_streamer.add_chunk(Key.first, Key.second, m_terrain_spacing, height); + return nmt_chunk::made; + } + // a chunk of flat ground there already takes the heights of the model under the formations laid on it, which stay: the ground + // under them shaped, not a touch-up over them + auto const touchup{m_streamer.touch_up()}; + m_streamer.touch_up(false); + m_streamer.reshape(low, high, [&](double const X, double const Z, float &Height) { + Height = height(X, Z); + return true; + }); + m_streamer.touch_up(touchup); + return nmt_chunk::made; +} + +bool editor_mode::nmt_flat_chunk(heightmap::chunk_key const &Key) const +{ + auto const middle{heightmap::chunk_corner(Key) + glm::dvec2{0.5 * heightmap::chunk_size}}; + auto const *terrain{m_streamer.terrain_at(middle.x, middle.y)}; + if (terrain == nullptr || terrain->key() != Key) + return false; + auto const &data{terrain->data()}; + auto const &ground{data.base.empty() ? data.heights : data.base}; + if (ground.empty()) + return false; + auto const [lowest, highest]{std::minmax_element(ground.begin(), ground.end())}; + return *highest - *lowest < 0.01f; +} + +std::size_t editor_mode::nmt_shape_tracks(std::vector const *Only) +{ + auto &state{m_nmt_state}; + if (false == ensure_terrain()) + return 0; + auto const wanted = [&](TTrack const *Track) { return Only == nullptr || std::find(Only->begin(), Only->end(), Track) != Only->end(); }; + // one modifier per path: the formation under its axis and the slopes from its edges to the ground. laid over each other the + // modifiers keep the highest of the slopes going down and the lowest of those going up, so tracks side by side share one + // formation instead of a saw of their own ones + // a path broken by a bridge, as over another track, gets a modifier for each piece on the ground + std::map, heightmap::modifier> modifiers; + std::map, int> pieces; + double constexpr step{5.0}; + std::pair previous{nullptr, -1}; + bool broken{false}; + std::vector over; + for (auto const &place : nmt_track_places(step)) + { + if (false == wanted(place.track)) + continue; + std::pair const path{place.track, place.path}; + if (path != previous) + broken = false; + previous = path; + if (false == place.shapes) + { + broken = true; + over.push_back(place); + continue; + } + auto &piece{pieces[path]}; + if (broken) + { + ++piece; + broken = false; + } + auto &modifier{modifiers[{place.track, place.path, piece}]}; + if (modifier.name.empty()) + { + modifier.name = "nmt " + formation_name(*place.track) + (place.track->m_paths.size() > 1 ? " " + std::to_string(place.path) : std::string{}) + (piece > 0 ? " #" + std::to_string(piece) : std::string{}); + modifier.slope = state.slope; + modifier.reach = state.reach; + } + modifier.points.push_back({{place.position.x, place.position.z}, place.formation, place.half_width}); + } + // a formation which ends by a bridge or a tunnel ends square against its abutment, its portal, whichever path goes on over it + auto const walled = [&](heightmap::corridor_point const &End) { + return std::any_of(over.begin(), over.end(), [&](nmt_place const &Place) { + return glm::distance(glm::dvec2{Place.position.x, Place.position.z}, End.position) <= step * 1.5 && std::abs(Place.formation - End.formation) <= 1.0; + }); + }; + std::vector laid; + for (auto &[path, modifier] : modifiers) + if (modifier.points.size() >= 2) + { + modifier.open_start = walled(modifier.points.front()); + modifier.open_end = walled(modifier.points.back()); + laid.push_back(std::move(modifier)); + } + if (Only != nullptr) + { + // the formations as they are already aren't led into the terrain again + auto const same = [](heightmap::modifier const &A, heightmap::modifier const &B) { + return A.slope == B.slope && A.reach == B.reach && A.rounding == B.rounding && A.open_start == B.open_start && A.open_end == B.open_end && A.points.size() == B.points.size() && + std::equal(A.points.begin(), A.points.end(), B.points.begin(), [](heightmap::corridor_point const &P, heightmap::corridor_point const &Q) { + return glm::distance(P.position, Q.position) < 1e-6 && std::abs(P.formation - Q.formation) < 1e-6 && std::abs(P.half_width - Q.half_width) < 1e-6; + }); + }; + auto const &existing{m_streamer.modifiers()}; + // the formations the tracks have, the ones as they are already too: those only aren't led again, nor taken out as gone + std::unordered_set kept; + for (auto const &modifier : laid) + kept.insert(modifier.name); + std::erase_if(laid, [&](heightmap::modifier const &Modifier) { + auto const found{std::find_if(existing.begin(), existing.end(), [&](heightmap::modifier const &Other) { return Other.name == Modifier.name; })}; + return found != existing.end() && same(*found, Modifier); + }); + for (auto *track : *Only) + state.changed.erase(track); + // the modifiers the tracks don't have any more: of the pieces of a path gone, of the tracks removed + std::vector gone; + for (auto const *track : *Only) + { + if (track == nullptr || track->name().empty()) + continue; + auto const own{"nmt " + track->name()}; + for (auto const &modifier : m_streamer.modifiers()) + if ((modifier.name == own || modifier.name.starts_with(own + " ")) && false == kept.contains(modifier.name)) + gone.push_back(modifier.name); + } + m_streamer.remove_modifiers(gone); + } + if (Only == nullptr) + { + // the formations of the tracks there are no more, or are on bridges now, and of the tracks with no name laid over each + // other under one name before + std::vector gone; + for (auto const &modifier : m_streamer.modifiers()) + if (modifier.name.starts_with("nmt ") && std::none_of(laid.begin(), laid.end(), [&](heightmap::modifier const &Laid) { return Laid.name == modifier.name; })) + gone.push_back(modifier.name); + m_streamer.remove_modifiers(gone); + } + auto const count{laid.size()}; + m_streamer.modifiers(std::move(laid)); + forget_ground(); + if (Only == nullptr) + { + state.shaped = modifiers.size(); + state.changed.clear(); + state.gone.clear(); + } + return count; +} + +void editor_mode::nmt_area_terrain() +{ + auto &area{m_area_terrain}; + auto const &config{m_orthophoto.settings()}; + auto const &state{m_nmt_state}; + // what holds it, logged as it changes: nothing was made and nothing told why + auto const held = [&](char const *Reason) { + if (area.held != Reason) + { + area.held = Reason; + WriteLog(std::string{"Editor: NMT - the terrain of the download area "} + (*Reason != '\0' ? std::string{"held: "} + Reason : std::string{"goes on"}), logtype::generic); + } + }; + if (false == area.run_only.value_or(EditorSettings.terrain_model().area)) + return held("turned off"); + if (m_orthophoto.area().empty()) + return held("no area"); + if (m_area_paused) + return held("the area paused"); + if (config.north == 0.0 && config.east == 0.0) + return held("no origin of the scenery"); + // after the work with the model the user asked for + if (state.stage != nmt_state::automatic::idle || state.fitting || false == state.pending.empty()) + return held("other work with the model"); + // a stroke of the terrain brush keeps its step of the history open to its end: closed around a chunk, its undo would lose the + // part brushed before + if (terrain_brush() && mouseHold) + return held("a stroke of the terrain brush"); + held(""); + // light: the time after a chunk set by how long it took. not held by slow frames: a large scenery has them all the time, and + // nothing was made there + auto const now{ImGui::GetTime()}; + if (now < area.resume) + return; + // the chunks of the area in the square around the camera, the nearest first + int constexpr reach{4}; + auto const centre{heightmap::chunk_at(Camera.Pos.x, Camera.Pos.z)}; + if (false == area.listed || centre != area.centre) + { + area.keys.clear(); + area.next = 0; + area.centre = centre; + area.listed = true; + area.waiting = -1.0; + area.square_made = 0; + area.took = 0.0; + area.took_most = 0.0; + for (int dz = -reach; dz <= reach; ++dz) + for (int dx = -reach; dx <= reach; ++dx) + { + heightmap::chunk_key const key{centre.first + dx, centre.second + dz}; + if (auto const low{heightmap::chunk_corner(key)}; false == area.empty.contains(key) && in_download_area(low, low + glm::dvec2{heightmap::chunk_size})) + area.keys.push_back(key); + } + std::stable_sort(area.keys.begin(), area.keys.end(), [&](heightmap::chunk_key const &Left, heightmap::chunk_key const &Right) { + auto const distance = [&](heightmap::chunk_key const &Key) { return sq(Key.first - centre.first) + sq(Key.second - centre.second); }; + return distance(Left) < distance(Right); + }); + auto const missing{std::count_if(area.keys.begin(), area.keys.end(), [&](heightmap::chunk_key const &Key) { return false == m_streamer.active() || false == m_streamer.exists(Key); })}; + // told only where there's terrain to make: the camera crosses a chunk every few seconds + if (missing > 0) + WriteLog(format("Editor: NMT - the download area around the camera (chunk %d,%d): %zu chunks in it, %zu with no terrain yet", centre.first, centre.second, area.keys.size(), + static_cast(missing)), + logtype::generic); + } + // those there already cost a lookup only, a few of them a frame; the terrain made by hand is left as it is + for (int looked = 0; looked < 8 && area.next < area.keys.size(); ++looked) + { + auto const key{area.keys[area.next]}; + if (m_streamer.active() && m_streamer.exists(key)) + { + ++area.next; + continue; + } + if (false == ensure_terrain()) + return; + nmt_locate(); + auto const low{heightmap::chunk_corner(key)}; + auto const high{low + glm::dvec2{heightmap::chunk_size}}; + // the model under it and a little around, for the heights along the terrain beside: read from the cache or downloaded + // meanwhile; one that doesn't come is left for the camera's next move + if (false == nmt_ready(low - glm::dvec2{2.0}, high + glm::dvec2{2.0})) + { + if (area.waiting < 0.0) + area.waiting = now; + else if (now - area.waiting > 5.0) + { + area.waiting = -1.0; + ++area.next; + } + return; + } + area.waiting = -1.0; + ++area.next; + auto const started{std::chrono::steady_clock::now()}; + // the editor keeps a step of the history of the terrain open all the time: the chunk isn't a step of it, as the terrain grown + // under the track laid; the step there is closed before, and a new one opened after + auto const recording{m_streamer.recording()}; + if (recording) + { + terrain_history_step(); + m_streamer.end_change(); + } + auto const chunk{add_chunk_from_nmt(key, nmt_chunk_offset(key))}; + if (recording) + m_streamer.begin_change(); + auto const took{std::chrono::duration(std::chrono::steady_clock::now() - started).count()}; + // a chunk at most every 0.1 s, and the editor left at least three times as long for itself as the chunk took + area.resume = now + std::max(0.1, 3.0 * took); + area.took += took; + area.took_most = std::max(area.took_most, took); + // one outside the region of the scenery isn't added either + if (chunk == nmt_chunk::made && m_streamer.exists(key)) + { + ++area.made; + ++area.square_made; + area.refit = true; + forget_ground_in(low, high); + } + else + area.empty.insert(key); + return; + } + // the square done: the photos laid onto the new ground once, not after each chunk + if (area.next >= area.keys.size() && std::exchange(area.refit, false)) + { + m_orthophoto.refit(); + for (auto &layer : m_wms) + layer->refit(); + WriteLog(format("Editor: NMT - the download area: %zu chunks made around the camera in %.0f ms, the longest %.1f ms, %zu in all", area.square_made, area.took * 1000.0, + area.took_most * 1000.0, area.made), + logtype::generic); + } +} + +void editor_mode::nmt_update() +{ + auto &state{m_nmt_state}; + // the squares of the model in the download area to the disk cache, as the area promises the model with the photos: the area is in + // PUWG 1992 already, so it needs neither the model placed (its panel opened) nor the terrain of the scenery begun + if (auto const &wanted{m_orthophoto.area()}; wanted != m_nmt_prefetched) + { + m_nmt_prefetched = wanted; + m_nmt.prefetch(wanted); + // the terrain around the camera looked at again within the new area + m_area_terrain.listed = false; + m_area_terrain.empty.clear(); + } + nmt_offer(); + nmt_follow_tracks(); + // the terrain of the download area, when nothing else is done with the model: it tells what holds it + nmt_area_terrain(); + if (state.stage != nmt_state::automatic::idle) + { + nmt_auto_step(); + return; + } + if (state.fitting) + { + bool all{true}; + for (auto const &place : state.fit) + all = nmt_ready(glm::dvec2{place.position.x, place.position.z} - glm::dvec2{1.0}, glm::dvec2{place.position.x, place.position.z} + glm::dvec2{1.0}) && all; + if (all) + nmt_finish_fit(); + return; + } + nmt_grow(); + if (state.pending.empty()) + { + if (std::exchange(state.camera_check, false) && false == Global.EditorOrtho) + camera_above_ground(); + return; + } + state.camera_check = true; + // the terrain of the scenery opened, or begun, for the chunks grown under the track laid as well: they don't need terrain there before + if (false == ensure_terrain()) + { + state.pending.clear(); + state.refill.clear(); + state.status = STR("The heightmap terrain can't be opened"); + return; + } + // a few chunks a frame, those whose model is in. the terrain made ahead of the track laid isn't a step of the history: + // Ctrl+Z takes back the track, not the ground under it + auto const unrecorded{state.grown && m_streamer.recording()}; + if (unrecorded) + { + terrain_history_step(); + m_streamer.end_change(); + } + int made{0}; + std::vector changed; + for (auto it{state.pending.begin()}; it != state.pending.end() && made < 4;) + { + auto const refilled{state.refill.contains(*it)}; + if (false == refilled && m_streamer.exists(*it)) + { + it = state.pending.erase(it); + continue; + } + // the model under it and a little around first: the height along the terrain beside is read from it + if (auto const low{heightmap::chunk_corner(*it)}; false == nmt_ready(low - glm::dvec2{2.0}, low + glm::dvec2{heightmap::chunk_size + 2.0})) + { + ++it; + continue; + } + // a new chunk at the height nmt_chunk_offset() gives it; one of flat ground refilled keeps to the offset of the scenery + auto const offset{refilled ? std::nullopt : nmt_chunk_offset(*it)}; + auto const chunk{add_chunk_from_nmt(*it, offset)}; + if (chunk == nmt_chunk::waiting) + { + ++it; + continue; + } + // the height the track laid goes on at, over the model: from the terrain grown under it only, not from the buttons' chunks + if (state.grown && offset.has_value() && chunk == nmt_chunk::made) + state.ahead = offset; + if (chunk == nmt_chunk::made) + changed.push_back(*it); + state.refill.erase(*it); + it = state.pending.erase(it); + ++made; + if (chunk == nmt_chunk::made) + ++state.made; + else + ++state.empty; + } + // the last ones may have got here as chunks the streamer has read in meanwhile, nothing made: all waited for is there all the same, + // the formations of the tracks led into it + if (made > 0 || state.pending.empty()) + { + // the ground gathered again only where the chunks were made: the rest of it is as it was, gathering all of it again frame after + // frame as the terrain grows around the cursor was felt + for (auto const &key : changed) + { + auto const low{heightmap::chunk_corner(key)}; + forget_ground_in(low, low + glm::dvec2{heightmap::chunk_size}); + } + state.status = format(STR_C("Chunks made from the terrain model: %zu, waiting for it: %zu"), state.made, state.pending.size()); + if (state.empty > 0) + state.status += format(STR_P("; %zu chunk not made, the model has no data there", "; %zu chunks not made, the model has no data there", state.empty), state.empty); + if (state.foreign > 0) + state.status += format(STR_P("; %zu chunk not made ahead, the terrain beside isn't the real one", "; %zu chunks not made ahead, the terrain beside isn't the real one", state.foreign), state.foreign); + if (state.pending.empty()) + { + state.run = false; + // not after the chunks grown around the cursor: the streamer leads the formations there are into a chunk as it's made, and + // shaping all of them again took the whole scenery through the terrain, 12 s of a frame each time the laying went on + if (state.shape && state.reshape && false == state.grown) + { + nmt_shape_tracks(); + state.status += format(STR_P("; the formation of %zu path shaped", "; the formation of %zu paths shaped", state.shaped), state.shaped); + } + // the photos laid onto the new ground + m_orthophoto.refit(); + for (auto &layer : m_wms) + layer->refit(); + first_step_done(first_step::nmt); + } + } + if (unrecorded) + m_streamer.begin_change(); +} + +void editor_mode::nmt_grow() +{ + auto &state{m_nmt_state}; + auto const now{ImGui::GetTime()}; + if (false == state.grow || now - state.grow_time < 0.5) + return; + state.grow_time = now; + // around the cursor of the tool laying the tracks, the terrain under them once they're laid: from the first point placed, or as a + // track is dragged from a free end; not around the camera, nor with the tool merely chosen + if (false == m_lay.active && false == m_extend.active) + return; + // the model placed where the origin of the orthophoto puts the scenery: it was only once the terrain panel had been open, and + // nothing grew under the track laid before that + nmt_locate(); + if (false == m_nmt.placed()) + return; + auto const at{m_extend.active ? m_extend.mouse : m_lay.mouse}; + // nothing asked for outside the download area + if (false == in_download_area({at.x - 100.0, at.z - 100.0}, {at.x + 100.0, at.z + 100.0})) + return; + // the model under it meanwhile, for the height of the first point laid where there's no terrain yet, as over the base map + m_nmt.request({at.x - 100.0, at.z - 100.0}, {at.x + 100.0, at.z + 100.0}); + auto const laying{m_extend.active || false == m_lay.points.empty()}; + // also in a scenery with no terrain yet, and far from the terrain there is: the chunks are made where the track goes. a scenery + // with no name yet can't have its terrain: nothing asked for, or it would be asked again and dropped every half a second + if (false == laying || (false == m_streamer.active() && m_orthophoto_scenery.empty())) + return; + glm::dvec2 const cursor{at.x, at.z}; + double constexpr grow_reach{400.0}; // m around the cursor + auto const reach{static_cast(std::ceil(grow_reach / heightmap::chunk_size))}; + auto const centre{heightmap::chunk_at(at.x, at.z)}; + std::vector> missing; + for (int dz = -reach; dz <= reach; ++dz) + for (int dx = -reach; dx <= reach; ++dx) + { + heightmap::chunk_key const key{centre.first + dx, centre.second + dz}; + auto const low{heightmap::chunk_corner(key)}; + glm::dvec2 const nearest{std::clamp(cursor.x, low.x, low.x + heightmap::chunk_size), std::clamp(cursor.y, low.y, low.y + heightmap::chunk_size)}; + auto const distance{glm::distance(nearest, cursor)}; + if (distance <= grow_reach && false == m_streamer.exists(key) && false == state.given_up.contains(key) && std::find(state.pending.begin(), state.pending.end(), key) == state.pending.end() && + in_download_area(low, low + glm::dvec2{heightmap::chunk_size})) + missing.emplace_back(distance, key); + } + if (missing.empty()) + return; + std::sort(missing.begin(), missing.end()); + if (state.pending.empty()) + { + state.grown = true; + state.made = 0; + state.empty = 0; + state.foreign = 0; + } + for (auto const &chunk : missing) + state.pending.push_back(chunk.second); + if (false == m_orthophoto.enabled() && false == m_orthophoto_chosen) + m_orthophoto.enabled(true); + WriteLog(format("Editor: NMT - %zu chunks around the cursor to make", missing.size()), logtype::generic); +} + +bool editor_mode::nmt_busy() const +{ + auto const &state{m_nmt_state}; + return state.fitting || state.stage != nmt_state::automatic::idle || (false == state.pending.empty() && false == state.grown); +} + +void editor_mode::nmt_stop() +{ + auto &state{m_nmt_state}; + if (false == nmt_busy()) + return; + auto const lines{state.stage == nmt_state::automatic::fitting && state.lines > 0}; + m_nmt.cancel(); + state.fitting = false; + state.fit.clear(); + state.probes.clear(); + state.left.clear(); + state.done.clear(); + state.laid.clear(); + state.paths.clear(); + state.loose.clear(); + state.turntables.clear(); + state.stage = nmt_state::automatic::idle; + state.pending.clear(); + state.refill.clear(); + state.run = false; + // the lines fitted so far stay, and what they found is told + state.result = state.result || lines; + m_profile.open = false; + state.status = format(STR_P("Stopped: %zu chunk made stays", "Stopped: %zu chunks made stay", state.made), state.made); + if (lines) + state.status += STR("; so do the grade lines fitted, Ctrl+Z takes them back"); + WriteLog("Editor: NMT - " + state.status, logtype::generic); +} + +void editor_mode::render_nmt_progress(bool const Compact) +{ + auto &state{m_nmt_state}; + float fraction{0.0f}; + std::string text; + // of the tracks put onto the terrain the step too: the model, the grade lines, the chunks + int step{0}; + if (state.stage == nmt_state::automatic::fetching || state.fitting) + { + auto const waiting{m_nmt.waiting()}; + // the squares asked for come in one by one: how many of the most waited for are in; none waited for, only read from the disk + state.fetch_most = std::max(state.fetch_most, waiting); + fraction = state.fetch_most > 0 ? 1.0f - static_cast(waiting) / static_cast(state.fetch_most) : -1.0f * static_cast(ImGui::GetTime()); + text = format(STR_P("Terrain model: %zu square left", "Terrain model: %zu squares left", waiting), waiting); + step = 1; + } + else if (state.stage == nmt_state::automatic::fitting && state.tracks > 0) + { + fraction = 1.0f - static_cast(state.left.size()) / static_cast(std::max(state.tracks, state.left.size())); + text = format(STR_P("Grade lines: %zu fitted, %zu track left", "Grade lines: %zu fitted, %zu tracks left", state.left.size()), state.lines, state.left.size()); + step = 2; + } + else if (false == state.pending.empty()) + { + auto const total{state.made + state.empty + state.pending.size()}; + fraction = static_cast(state.made + state.empty) / static_cast(std::max(1, total)); + text = format(STR_C("Chunks: %zu of %zu"), state.made + state.empty, total); + step = 3; + } + else + return; + if (state.run) + text = format("%d/3 ", step) + text; + auto const stoppable{nmt_busy()}; + auto const stop{STR_C("Stop")}; + auto const button{ImGui::CalcTextSize(stop).x + ImGui::GetStyle().FramePadding.x * 2.0f}; + auto const width{Compact ? std::round(ImGui::GetFontSize() * 16.0f) : stoppable ? -(button + ImGui::GetStyle().ItemSpacing.x) : -FLT_MIN}; + ImGui::ProgressBar(fraction, ImVec2(width, Compact ? 0.0f : tall_button_height()), text.c_str()); + if (false == stoppable) + return; + ImGui::SameLine(); + if (ImGui::Button(stop, ImVec2(0.0f, Compact ? 0.0f : tall_button_height()))) + nmt_stop(); + item_tooltip("Stops loading: the terrain made so far stays"); +} + +void editor_mode::nmt_pull_terrain(std::vector const &Tracks) +{ + auto &state{m_nmt_state}; + std::vector rails; + for (auto *track : Tracks) + if (track != nullptr && false == track->m_editorremoved && rail(*track)) + rails.push_back(track); + if (rails.empty()) + { + state.status = STR("No tracks to draw the terrain to"); + return; + } + if (false == ensure_terrain()) + { + state.status = STR("The heightmap terrain can't be opened"); + return; + } + terrain_history_step(); + auto const laid{nmt_shape_tracks(&rails)}; + terrain_history_step(); + state.status = format(STR_P("The terrain drawn to %zu track: %zu formations led into it, Ctrl+Z takes it back", "The terrain drawn to %zu tracks: %zu formations led into it, Ctrl+Z takes it back", rails.size()), rails.size(), laid); + WriteLog("Editor: NMT - " + state.status, logtype::generic); +} + +void editor_mode::nmt_restore_terrain(std::vector const &Tracks) +{ + auto &state{m_nmt_state}; + if (false == m_streamer.active()) + return; + std::vector gone; + for (auto const *track : Tracks) + { + if (track == nullptr) + continue; + auto const own{"nmt " + formation_name(*track)}; + for (auto const &modifier : m_streamer.modifiers()) + if ((modifier.name == own || modifier.name.starts_with(own + " ")) && std::find(gone.begin(), gone.end(), modifier.name) == gone.end()) + gone.push_back(modifier.name); + } + terrain_history_step(); + m_streamer.remove_modifiers(gone); + if (false == gone.empty()) + forget_ground(); + terrain_history_step(); + state.status = format(STR_P("%zu formation taken out of the terrain, Ctrl+Z takes it back", "%zu formations taken out of the terrain, Ctrl+Z takes it back", gone.size()), gone.size()); + WriteLog("Editor: NMT - " + state.status, logtype::generic); +} + +void editor_mode::render_track_terrain(std::vector const &Tracks) +{ + auto &state{m_nmt_state}; + // a scenery with no terrain made nor any place on the map has nothing to draw to its tracks + if (false == m_streamer.active() && false == m_nmt.placed()) + return; + if (false == ImGui::CollapsingHeader(format("%s###trackterrain", STR_C("Terrain")).c_str())) + return; + auto const busy{nmt_busy()}; + auto const spacing{ImGui::GetStyle().ItemSpacing.x}; + auto const half{std::floor((ImGui::GetContentRegionAvail().x - spacing) * 0.5f)}; + { + std::size_t rails{0}, done{0}; + for (auto const *track : Tracks) + if (track != nullptr && rail(*track)) + { + ++rails; + if (grade_fitted(*track)) + ++done; + } + if (rails == 1) + ImGui::TextDisabled("%s", done > 0 ? STR_C("Its grade line is fitted to the terrain") : STR_C("Its grade line isn't fitted to the terrain yet")); + else if (rails > 1) + ImGui::TextDisabled(STR_C("Grade lines fitted to the terrain: %zu of %zu"), done, rails); + item_tooltip("A track is fitted when its grade line was fitted to the terrain model or applied with the profile, and it wasn't changed since"); + } + ImGui::BeginDisabled(busy); + if (ImGui::Button(STR_C("Draw the terrain to the track"), ImVec2(half, 0.0f))) + nmt_pull_terrain(Tracks); + item_tooltip("The formation and the slopes of the selected tracks led into the terrain, down or up to it; elsewhere the terrain stays as it is"); + ImGui::SameLine(); + if (ImGui::Button(STR_C("The whole run"), ImVec2(-FLT_MIN, 0.0f))) + { + m_track_set = Tracks; + track_set_grow(); + select_tracks(m_track_set); + nmt_pull_terrain(m_track_set); + } + item_tooltip("The tracks joined to the selected ones added to the selection, by the rules of the spread, and the terrain drawn to all of them"); + if (ImGui::Button(STR_C("Restore the terrain"), ImVec2(half, 0.0f))) + nmt_restore_terrain(Tracks); + item_tooltip("The formations of the selected tracks taken out of the terrain: the ground goes back to how it was before them"); + ImGui::EndDisabled(); + toggle_chips("nmtfollow", {{STR_C("The terrain follows the tracks edited"), &state.follow, "A track with its formation moved or changed takes it along; off: the terrain stays as it is until it's drawn to the tracks again"}}); + ImGui::Separator(); + ImGui::TextDisabled("%s", STR_C("All the tracks of the scenery")); + render_nmt_all_tracks(false); + if (busy) + render_nmt_progress(true); + else if (false == state.status.empty()) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", state.status.c_str()); + ImGui::PopTextWrapPos(); + } +} + +// the tracks of the whole scenery and the terrain model: the way to take first big, what it does told under it, then the other +// two, each with the case it's for; step 3 of the terrain model in the field of the terrain (Terrain_panel), and in the panel of +// the tracks +void editor_mode::render_nmt_all_tracks(bool const Terrain_panel) +{ + auto &state{m_nmt_state}; + auto const busy{nmt_busy()}; + auto const placed{m_nmt.placed()}; + std::size_t unfitted{0}, all{0}, hand{0}; + std::unordered_map named; + for (auto const *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && rail(*track)) + { + ++all; + ++named[track->name()]; + if (false == grade_fitted(*track)) + ++unfitted; + else if (grade_hand(*track)) + ++hand; + } + auto const told{[](char const *Text) { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", Text); + ImGui::PopTextWrapPos(); + }}; + if (false == placed) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), "%s", STR_C("First the place of the scenery on the map: F5 Terrain, Terrain model (NMT), step 1")); + ImGui::PopTextWrapPos(); + } + // three ways as cards, each with a sketch and the case it's for, the one to take first lit: what to click is seen at a glance. + // The tracks fitted already stay as they are: a track laid or changed since goes onto the model, all of them only when asked + auto const ready{false == busy && placed}; + auto const onto_text{unfitted == all ? std::string{STR_C("Recommended: the tracks go down or up onto the real terrain, each line on a grade line within its norms, with the formation and the slopes")} + : unfitted > 0 ? format(STR_C("The tracks laid or changed since the last time go onto the terrain model (%zu of %zu); the ones fitted stay as they are"), unfitted, all) + : std::string{STR_C("All the tracks are fitted to the terrain; a track changed since goes onto it again")}}; + if (way_card("##nmtonto", STR_C("Tracks onto the terrain"), onto_text.c_str(), way_sketch::onto, true, ready && unfitted > 0)) + nmt_auto_start(true); + item_tooltip("The terrain model is loaded along the tracks and the tracks go onto it, wherever the scenery was built: the top of the ballast at the height of the model, the grade line of every line fitted to it within the limits of the line, switches and the tracks beside them on one grade line, the formation and the slopes made along them. Where the model is off the tracks keep their line and it's reported. A turntable stays level in its pit at the height of the tracks running up to it, which reach it level. The tracks fitted already, by it or with the profile, and not changed since stay as they are, and the new lines meet them"); + // the fitted ones too, and which are left after it: under the card they belong to + ImGui::BeginDisabled(false == ready || all == 0); + if (unfitted < all && ImGui::SmallButton(STR_C("All anew, the fitted ones too"))) + ImGui::OpenPopup("##nmtallanew"); + item_tooltip("All the tracks are fitted to the terrain model again, the ones fitted already too: their grade lines may change; the scenery isn't moved"); + if (ImGui::BeginPopup("##nmtallanew")) + { + ImGui::TextUnformatted(format(STR_C("%zu tracks get new grade lines; Ctrl+Z takes it back"), all - (state.redo_hand ? 0 : hand)).c_str()); + if (hand > 0) + ImGui::Checkbox(format(STR_C("The %zu edited by hand too"), hand).c_str(), &state.redo_hand); + if (ImGui::Button(STR_C("Fit them anew"))) + { + nmt_auto_start(false); + state.redo_hand = false; + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button(STR_C("Cancel"))) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + ImGui::EndDisabled(); + if (unfitted > 0 && unfitted < all) + { + ImGui::SameLine(); + // which they are, a few after the putting onto the terrain: the ones it couldn't fit + if (ImGui::SmallButton(format(STR_P("Show the %zu track not fitted", "Show the %zu tracks not fitted", unfitted), unfitted).c_str())) + { + std::vector those; + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && rail(*track) && false == grade_fitted(*track)) + those.push_back(track); + if (false == those.empty()) + { + select_tracks(those); + focus_track(*those.front(), 0, geometry::bezier{those.front()->m_paths.front()}.point(0.5)); + } + } + item_tooltip("They are selected, the first one in the 3d view"); + } + ImGui::Spacing(); + if (way_card("##nmtunder", STR_C("Terrain under the tracks"), STR_C("The tracks stay at their heights and the terrain comes up or down to them: for a scenery built level or at heights of its own"), way_sketch::under, false, ready && all > 0)) + nmt_under_start(); + item_tooltip("The tracks aren't touched: the terrain model is loaded along them and drawn to them, at each place by as much as the tracks lie above or below it there, fading out away from them, so its relief stays and the tracks don't end up in deep cuttings; then the formation and the slopes along them. For a scenery built level or at its own heights"); + ImGui::Spacing(); + if (way_card("##nmtonly", STR_C("The terrain of the model only"), STR_C("The real terrain along the tracks as it is; the tracks stay where they are, under it or over it"), way_sketch::only, false, ready)) + nmt_make(nmt_keys_along_tracks()); + item_tooltip("Loads the terrain model as it is along the tracks, with the height offset above; the tracks stay where they are"); + // under the three ways, which stay seen together: what the last of them did + render_nmt_result(); + std::string twice; + std::size_t repeated{0}; + for (auto const &[name, count] : named) + if (count > 1 && false == name.empty() && name != "none") + { + if (++repeated <= 12) + twice += (twice.empty() ? "" : ", ") + name; + } + if (repeated > 0) + { + told(format(STR_P("%zu track name is used more than once in the scenery", "%zu track names are used more than once in the scenery", repeated), repeated).c_str()); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s%s", twice.c_str(), repeated > 12 ? ", ..." : ""); + } + if (hand > 0) + told(format(STR_P("%zu track with its grade line edited by hand stays as it is", "%zu tracks with their grade lines edited by hand stay as they are", hand), hand).c_str()); + if (Terrain_panel) + { + ImGui::Spacing(); + told(STR_C("The terrain to some of the tracks only: select them (F3), Terrain in the inspector")); + } +} + +void editor_mode::nmt_note(nmt_state::finding::kind const What, TTrack *From, TTrack *To, double const Length, glm::dvec3 const &Where, std::string Text, double const Size) +{ + // only of the tracks put onto the terrain all together: a track laid onto it is told of as it's laid + if (m_nmt_state.stage != nmt_state::automatic::fitting) + return; + m_nmt_state.findings.push_back({What, From, To, Length, Where, std::move(Text), Size}); +} + +void editor_mode::nmt_show(nmt_state::finding const &Finding, bool const Profile) +{ + double constexpr reach{10.0}; // m, a track this near the place is the one of the line, if it was split since + int path{0}; + auto *track{kilometrage::track_near(Finding.where, reach, path)}; + if (track != nullptr) + { + select_track(track); + focus_track(*track, path, Finding.where); + } + else + fly_to(Finding.where, glm::normalize(glm::dvec3{0.0, -0.5, 1.0}), 40.0); + if (false == Profile) + return; + show_track_tab(track_tab::profile); + auto const alive = [](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved; }; + if (alive(Finding.from) && alive(Finding.to)) + profile_open(Finding.from, Finding.to); + else if (track != nullptr) + profile_open_run(*track); +} + +void editor_mode::render_nmt_result() +{ + auto &state{m_nmt_state}; + if (false == state.result || nmt_busy()) + return; + using kind = nmt_state::finding::kind; + auto const count = [&](kind const What) { return static_cast(std::count_if(state.findings.begin(), state.findings.end(), [&](nmt_state::finding const &Finding) { return Finding.what == What; })); }; + ImVec4 const good{0.45f, 0.85f, 0.45f, 1.0f}; + ImVec4 const bad{1.0f, 0.45f, 0.35f, 1.0f}; + ImVec4 const doubt{1.0f, 0.75f, 0.3f, 1.0f}; + ImVec4 const calm{0.6f, 0.62f, 0.66f, 1.0f}; + auto const refused{count(kind::refused)}; + auto const off{count(kind::off)}; + auto const parted{count(kind::parted)}; + ImGui::Spacing(); + ImGui::TextUnformatted(STR_C("What the last putting onto the terrain did")); + metric_tiles({{std::to_string(state.lines), STR_C("lines fitted"), ImGui::ColorConvertFloat4ToU32(good)}, + {std::to_string(refused), STR_C("refused"), ImGui::ColorConvertFloat4ToU32(refused > 0 ? bad : calm)}, + {std::to_string(off), STR_C("off the line"), ImGui::ColorConvertFloat4ToU32(off > 0 ? doubt : calm)}, + {std::to_string(parted), STR_C("apart from the model"), ImGui::ColorConvertFloat4ToU32(parted > 0 ? doubt : calm)}}); + if (state.levelled > 0) + ImGui::TextDisabled(STR_C("Turntables set level: %zu"), state.levelled); + if (state.findings.empty()) + { + ImGui::TextColored(good, "%s", STR_C("Nothing to look at: every line lies on the model")); + return; + } + // the refused first, then the paths off their lines, then the lines apart from the model, the farther the sooner + std::vector order(state.findings.size()); + for (std::size_t i = 0; i < order.size(); ++i) + order[i] = i; + std::stable_sort(order.begin(), order.end(), [&](std::size_t const A, std::size_t const B) { + auto const &a{state.findings[A]}; + auto const &b{state.findings[B]}; + return a.what != b.what ? a.what < b.what : a.size > b.size; + }); + auto const rows{std::min(7.0f, static_cast(order.size()))}; + auto const row{ImGui::GetTextLineHeightWithSpacing() * 2.0f}; + ImGui::TextDisabled("%s", STR_C("To look at, each with its place and its profile:")); + ImGui::BeginChild("##nmtfindings", ImVec2(0.0f, std::round(row * rows + ImGui::GetStyle().WindowPadding.y * 2.0f)), true); + auto const show{STR_C("Show")}; + auto const profile{STR_C("Profile")}; + ImGuiListClipper clipper; + clipper.Begin(static_cast(order.size()), row); + std::optional> clicked; + while (clipper.Step()) + for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; ++i) + { + auto const &finding{state.findings[order[i]]}; + ImGui::PushID(static_cast(order[i])); + // the buttons first, where the long names of the tracks don't push them out of the panel + if (ImGui::SmallButton(show)) + clicked = {order[i], false}; + item_tooltip("The place in the 3d view, the track there selected"); + ImGui::SameLine(); + if (ImGui::SmallButton(profile)) + clicked = {order[i], true}; + item_tooltip("The profile of the line opened: its grade line, the terrain model under it and what the checks say"); + ImGui::SameLine(); + auto const colour{finding.what == kind::refused ? bad : doubt}; + auto const *label{finding.what == kind::refused ? STR_C("refused") : finding.what == kind::off ? STR_C("off the line") : STR_C("apart from the model")}; + ImGui::TextColored(colour, "%s", label); + ImGui::SameLine(); + ImGui::TextUnformatted(finding.text.c_str()); + if (ImGui::IsItemHovered() && false == finding.text.empty()) + ImGui::SetTooltip("%s", finding.text.c_str()); + auto const alive = [](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved; }; + auto const ends{alive(finding.from) && alive(finding.to) ? (finding.from == finding.to ? finding.from->name() : finding.from->name() + " .. " + finding.to->name()) : std::string{}}; + ImGui::TextDisabled("%s", format(STR_C("the line %s, %.0f m"), ends.c_str(), finding.length).c_str()); + ImGui::PopID(); + } + ImGui::EndChild(); + if (clicked) + nmt_show(state.findings[clicked->first], clicked->second); +} + +void editor_mode::draw_nmt_pending() const +{ + auto const &state{m_nmt_state}; + auto const imagery{m_orthophoto.waiting()}; + if (state.pending.empty() && imagery.empty()) + return; + // where the ground will be: by the terrain there or beside it, else the model with the offset of the scenery, else level + // with the nearest chunk there is, or the nearest track + glm::dvec2 const camera{Camera.Pos.x, Camera.Pos.z}; + double fallback{0.0}; + { + auto nearest{std::numeric_limits::max()}; + std::vector chunks; + m_streamer.collect(chunks); + for (auto const *chunk : chunks) + if (auto const middle{chunk->centre()}; glm::distance(glm::dvec2{middle.x, middle.z}, camera) < nearest) + { + nearest = glm::distance(glm::dvec2{middle.x, middle.z}, camera); + fallback = middle.y; + } + if (chunks.empty()) + for (auto const *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_paths.empty()) + if (auto const &point{track->m_paths.front().points[segment_data::point::start]}; glm::distance(geometry::plan_of(point), camera) < nearest) + { + nearest = glm::distance(geometry::plan_of(point), camera); + fallback = point.y; + } + } + auto const height = [&](double const X, double const Z, double &Height) { + if (m_streamer.height_at(X, Z, Height) || nmt_ground(X, Z, Height)) + return true; + Height = fallback; + return true; + }; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList()}; + auto const time{ImGui::GetTime()}; + auto const pulse{static_cast(0.5 + 0.5 * std::sin(time * 4.0))}; + auto const dots{std::string(static_cast(time * 3.0) % 4, '.')}; + int constexpr steps{8}; // points along each edge, the outline following the ground + auto const square = [&](glm::dvec2 const &Low, glm::dvec2 const &High, int const Red, int const Green, int const Blue, std::string const &Label) { + auto const size{High - Low}; + std::vector outline; + for (int side = 0; side < 4; ++side) + for (int i = 0; i < steps; ++i) + { + auto const along{static_cast(i) / steps}; + glm::dvec2 const point{side == 0 ? Low + glm::dvec2{size.x * along, 0.0} : side == 1 ? Low + glm::dvec2{size.x, size.y * along} : side == 2 ? High - glm::dvec2{size.x * along, 0.0} : High - glm::dvec2{size.x, size.y * along}}; + double y; + ImVec2 screen; + if (false == height(point.x, point.y, y) || false == projection.project({point.x, y + 0.5, point.y}, screen)) + return; + outline.push_back(screen); + } + auto const edge{IM_COL32(Red, Green, Blue, static_cast(140.0f + 100.0f * pulse))}; + drawlist->AddConvexPolyFilled(outline.data(), static_cast(outline.size()), IM_COL32(Red, Green, Blue, static_cast(10.0f + 15.0f * pulse))); + drawlist->AddPolyline(outline.data(), static_cast(outline.size()), edge, ImDrawFlags_Closed, 2.0f); + // named where the name fits in + auto const middle{(Low + High) * 0.5}; + auto const text{Label + dots}; + auto const extent{ImGui::CalcTextSize(text.c_str())}; + auto const [left, right]{std::minmax_element(outline.begin(), outline.end(), [](ImVec2 const &A, ImVec2 const &B) { return A.x < B.x; })}; + double y; + ImVec2 label; + if (right->x - left->x > extent.x * 1.1f && height(middle.x, middle.y, y) && projection.project({middle.x, y + 0.5, middle.y}, label)) + drawlist->AddText({label.x - extent.x * 0.5f, label.y - extent.y * 0.5f}, edge, text.c_str()); + }; + // the nearest first, as many as can be drawn without the frame feeling it + auto const nearest = [&](std::vector> Areas, std::size_t const Most) { + auto const away = [&](std::pair const &Area) { return glm::distance((Area.first + Area.second) * 0.5, camera); }; + if (Areas.size() > Most) + { + std::nth_element(Areas.begin(), Areas.begin() + Most, Areas.end(), [&](auto const &A, auto const &B) { return away(A) < away(B); }); + Areas.resize(Most); + } + return Areas; + }; + for (auto const &[low, high] : nearest(imagery, 64)) + square(low, high, 255, 190, 70, STR("Orthophoto loading")); + std::vector> chunks; + for (auto const &key : state.pending) + chunks.emplace_back(heightmap::chunk_corner(key), heightmap::chunk_corner(key) + glm::dvec2{heightmap::chunk_size}); + for (auto const &[low, high] : nearest(chunks, 64)) + square(low, high, 90, 170, 255, STR("Terrain model loading")); +} + +// --------------------------------------------------------------------------------------------- +// the download area + +void editor_mode::area_start() +{ + auto &drawing{m_area_drawing}; + drawing = {}; + drawing.active = true; + // the area there is taken up to be changed + for (auto const &point : m_orthophoto.area()) + drawing.points.push_back(m_orthophoto.to_world(point)); + // drawn over the orthophoto of the top view, unless the user turned it off + if (false == m_orthophoto.enabled() && false == m_orthophoto_chosen) + m_orthophoto.enabled(true); + if (false == Global.EditorOrtho) + toggle_ortho(); + WriteLog("Editor: drawing the download area"); +} + +void editor_mode::area_finish(bool const Keep) +{ + auto &drawing{m_area_drawing}; + if (Keep && drawing.points.size() >= 3) + { + std::vector polygon; + for (auto const &point : drawing.points) + polygon.push_back(m_orthophoto.to_puwg(point)); + m_orthophoto.area(std::move(polygon)); + WriteLog(format("Editor: the download area of %zu points, %d tiles of the orthophoto", drawing.points.size(), m_orthophoto.stats().area_tiles)); + } + drawing = {}; +} + +glm::dvec3 editor_mode::area_point(glm::dvec2 const &Point) const +{ + double height{Camera.Pos.y - 2.0}; + if (false == Global.EditorOrtho && false == m_streamer.height_at(Point.x, Point.y, height) && false == nmt_ground(Point.x, Point.y, height)) + height = 0.0; + return {Point.x, height, Point.y}; +} + +void editor_mode::area_click(bool const Shift) +{ + auto &drawing{m_area_drawing}; + screen_projection const projection; + // the point under the cursor, within 10 pixels + int nearest{-1}; + auto best{100.0f}; + for (std::size_t i = 0; i < drawing.points.size(); ++i) + if (auto const distance{projection.mouse_distance2(area_point(drawing.points[i]))}; distance < best) + { + best = distance; + nearest = static_cast(i); + } + if (nearest >= 0) + { + if (Shift) + drawing.points.erase(drawing.points.begin() + nearest); + else + drawing.dragged = nearest; + return; + } + if (Shift) + return; + auto const cursor{std::as_const(*this).cursor_ground()}; + drawing.points.emplace_back(cursor.x, cursor.z); +} + +void editor_mode::area_update() +{ + auto &drawing{m_area_drawing}; + if (false == drawing.active || drawing.dragged < 0) + return; + if (false == ImGui::IsMouseDown(0) || drawing.dragged >= static_cast(drawing.points.size())) + { + drawing.dragged = -1; + return; + } + auto const cursor{std::as_const(*this).cursor_ground()}; + drawing.points[drawing.dragged] = {cursor.x, cursor.z}; +} + +void editor_mode::draw_download_area() const +{ + auto const &drawing{m_area_drawing}; + std::vector points; + if (drawing.active) + points = drawing.points; + else + for (auto const &point : m_orthophoto.area()) + points.push_back(m_orthophoto.to_world(point)); + // shown while it's drawn and with the settings of the orthophoto open + if (points.empty() || (false == drawing.active && false == orthophoto_settings_open())) + return; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList()}; + // the tiles of the area which failed: those in the cache or waiting left clear, the green over all the cached ones got in the way + if (false == drawing.active && orthophoto_settings_open()) + for (auto const &square : m_orthophoto.area_squares()) + { + if (square.state != 2) + continue; + std::array corners; + auto seen{true}; + glm::dvec2 const at[]{square.low, {square.high.x, square.low.y}, square.high, {square.low.x, square.high.y}}; + for (int i = 0; i < 4 && seen; ++i) + seen = projection.project(area_point(at[i]), corners[i]); + if (seen) + drawlist->AddQuadFilled(corners[0], corners[1], corners[2], corners[3], IM_COL32(240, 80, 70, 80)); + } + auto const edge{IM_COL32(80, 220, 255, 230)}; + auto const closing{IM_COL32(80, 220, 255, drawing.active ? 110 : 230)}; + // the edge back to the first point from three points on + auto const edges{points.size() >= 3 ? points.size() : points.size() - 1}; + for (std::size_t i = 0; i < edges; ++i) + { + auto const last{i + 1 == points.size()}; + projection.line(drawlist, area_point(points[i]), area_point(points[(i + 1) % points.size()]), last ? closing : edge, 2.0f); + } + if (false == drawing.active) + return; + // the points, the one under the cursor larger, and the line on to the cursor + ImVec2 screen; + for (auto const &point : points) + if (projection.project(area_point(point), screen)) + drawlist->AddCircleFilled(screen, projection.mouse_distance2(area_point(point)) < 100.0f ? 6.0f : 4.0f, edge); + if (false == points.empty() && drawing.dragged < 0 && false == ImGui::GetIO().WantCaptureMouse) + { + auto const cursor{std::as_const(*this).cursor_ground()}; + projection.line(drawlist, area_point(points.back()), area_point({cursor.x, cursor.z}), closing, 1.5f); + } +} + +void editor_mode::area_square(int const Side) +{ + auto const centre{m_orthophoto.to_puwg({Camera.Pos.x, Camera.Pos.z})}; + auto const half{Side * 500.0}; + m_orthophoto.area({{centre.x - half, centre.y - half}, {centre.x + half, centre.y - half}, {centre.x + half, centre.y + half}, {centre.x - half, centre.y + half}}); + WriteLog(format("Editor: the download area a square of %d km around the camera, %d tiles of the orthophoto", Side, m_orthophoto.stats().area_tiles)); +} + +bool editor_mode::in_download_area(glm::dvec2 const &Low, glm::dvec2 const &High) const +{ + auto const &area{m_orthophoto.area()}; + if (area.empty()) + return true; + // the square in PUWG: the easting grows to the west of the scenery, the northing with z + auto const &config{m_orthophoto.settings()}; + return geometry::square_touches(area, config.east - High.x, config.north + Low.y, High.x - Low.x); +} + +void editor_mode::render_download_area_ui(editor_orthophoto::statistics const &Stats) +{ + auto &drawing{m_area_drawing}; + ImGui::TextUnformatted(STR_C("Download area")); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("A polygon drawn on the map: what the settings ask for inside it, the orthophoto and the terrain model,\n" + "goes to the disk cache in the background, and nothing outside it is downloaded, also around the camera")); + if (drawing.active) + { + ImGui::TextColored(ImVec4(1.0f, 0.85f, 0.3f, 1.0f), "%s", STR_C("Click the points of the area on the map. Enter closes it, Backspace takes the last point back, Esc gives up;\n" + "a point dragged moves, Shift+click removes it")); + ImGui::Text(STR_C("%zu points"), drawing.points.size()); + ImGui::SameLine(); + if (drawing.points.size() >= 3 && ImGui::Button(STR_C("Done"))) + area_finish(true); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Cancel"))) + area_finish(false); + return; + } + auto const &area{m_orthophoto.area()}; + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", area.empty() ? STR_C("None: the photos are downloaded around the camera, wherever it goes") + : STR_C("The aerial photos and the shape of the ground are downloaded only inside it; outside it there are none")); + ImGui::PopTextWrapPos(); + if (ImGui::Button(area.empty() ? STR_C("Draw on the map") : STR_C("Draw again"))) + area_start(); + if (false == area.empty()) + { + ImGui::SameLine(); + if (ImGui::Button(STR_C("Remove"))) + m_orthophoto.area({}); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("No range: the photos around the camera, wherever it goes. The photos downloaded already stay on the disk")); + } + // a square around the camera, in place of the one drawn: what the wizard of a new scenery gives. Where the scenery lies on + // the map must be known for it, or the square would lie anywhere + auto const &config{m_orthophoto.settings()}; + auto const located{config.north != 0.0 || config.east != 0.0}; + ImGui::BeginDisabled(false == located); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(STR_C("Square around the camera:")); + for (auto const side : {1, 2, 5, 10}) + { + ImGui::SameLine(); + if (ImGui::SmallButton(format(STR_C("%d x %d km##areasquare"), side, side).c_str())) + { + // the area there is, drawn with care, or one this large, replaced only with a yes + m_area_square = side; + if (area.empty() && side < 10) + area_square(side); + else + ImGui::OpenPopup("##areasquare"); + } + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + ImGui::SetTooltip("%s", located ? format(STR_C("The range of the photos a square of %d x %d km, the camera in its middle"), side, side).c_str() : STR_C("Enter the origin of this scenery first")); + } + ImGui::EndDisabled(); + if (ImGui::BeginPopup("##areasquare")) + { + auto const size{static_cast(m_area_square) * m_area_square}; + ImGui::Text(STR_C("The range of the photos a square of %d x %d km around the camera?"), m_area_square, m_area_square); + if (false == area.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), "%s", STR_C("It replaces the area there is now, which can't be taken back")); + if (size >= 50.0) + ImGui::TextColored(ImVec4(1.0f, 0.75f, 0.3f, 1.0f), STR_C("%.0f sq km: the download takes long and needs a lot of disk space"), size); + if (ImGui::Button(STR_C("Replace"))) + { + area_square(m_area_square); + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button(STR_C("Cancel"))) + ImGui::CloseCurrentPopup(); + ImGui::EndPopup(); + } + if (area.empty()) + return; + ImGui::Text(STR_C("Area: %d of %d tiles in the cache, %d failed"), Stats.area_cached, Stats.area_tiles, Stats.area_failed); + ImGui::SameLine(); + if (ImGui::SmallButton(m_area_paused ? STR_C("Resume") : STR_C("Pause"))) + { + m_area_paused = false == m_area_paused; + m_orthophoto.area_paused(m_area_paused); + m_nmt.prefetch_paused(m_area_paused); + } + if (auto const terrain{m_nmt.prefetched()}; terrain.total > 0) + { + ImGui::Text(STR_C("Terrain model: %d of %d squares in the cache, %d failed"), terrain.cached, terrain.total, terrain.failed); + // the ones there are only looked up again + if (terrain.failed > 0) + { + ImGui::SameLine(); + if (ImGui::SmallButton((std::string{STR_C("Retry")} + "##terrainarea").c_str())) + m_nmt.prefetch(m_nmt_prefetched); + } + } + auto &model{EditorSettings.terrain_model()}; + if (ImGui::Checkbox(STR_C("The terrain of the scenery around the camera"), &model.area)) + EditorSettings.save(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Makes the terrain from the terrain model within the area, around the camera wherever it goes,\n" + "a chunk at a time while the editor is idle. The terrain there is already isn't touched.\n" + "The chunks made wait in memory until the scenery is saved (Ctrl+S).")); + if (model.area && m_area_terrain.made > 0) + { + ImGui::SameLine(); + ImGui::TextDisabled("%s", format(STR_P("%zu chunk made", "%zu chunks made", m_area_terrain.made), m_area_terrain.made).c_str()); + } +} + +void editor_mode::render_nmt_banner() +{ + auto const &state{m_nmt_state}; + if (false == nmt_busy() || state.shown >= ImGui::GetFrameCount() - 1) + return; + auto const low{editor_ui::view_min()}; + auto const high{editor_ui::view_max()}; + ImGui::SetNextWindowPos(ImVec2((low.x + high.x) * 0.5f, low.y + std::round(ImGui::GetFontSize() * 3.6f)), ImGuiCond_Always, ImVec2(0.5f, 0.0f)); + ImGui::SetNextWindowViewport(ImGui::GetMainViewport()->ID); + ImGui::SetNextWindowBgAlpha(0.88f); + if (ImGui::Begin("##nmtbanner", nullptr, + ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoDocking)) + { + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(STR_C("Loading the real terrain")); + ImGui::SameLine(); + render_nmt_progress(true); + bool again{false}; + if (auto const error{m_nmt.error(&again)}; false == error.empty()) + { + ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", STR(error).c_str()); + if (again) + { + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Try again"))) + m_nmt.retry(); + } + } + } + ImGui::End(); +} + +void editor_mode::nmt_check_buried(std::size_t const From) +{ + auto &state{m_nmt_state}; + state.buried.clear(); + state.buried_length = 0.0; + if (false == EditorSettings.terrain_buried_ask() || false == m_streamer.active()) + return; + // the top of the rails this near the ground leaves the sleepers and the ballast under it + double constexpr clearance{0.1}; + double constexpr step{5.0}; + double constexpr noticed{1.0}; + std::vector laid; + std::unordered_set seen; + double hidden{0.0}; + for (auto index{From}; index < m_history.size(); ++index) + for (auto const *track : m_history[index].created) + { + if (track == nullptr || track->m_editorremoved || false == rail(*track) || false == seen.insert(track).second) + continue; + laid.push_back(track->name()); + auto const &path{track->m_paths.front()}; + geometry::bezier const curve{path}; + auto const length{geometry::chord_length(path)}; + auto const count{std::max(1, static_cast(std::ceil(length / step)))}; + std::vector along, probes; + for (int i = 0; i < count; ++i) + { + along.push_back(curve.point((i + 0.5) / count)); + probes.emplace_back(along.back().x, 5000.0, along.back().z); + } + std::vector found; + auto const ground{ground_heights(probes, true, &found)}; + for (int i = 0; i < count; ++i) + if (found[i] != 0 && along[i].y < ground[i] + clearance) + hidden += length / count; + } + if (hidden < noticed) + return; + state.buried = std::move(laid); + state.buried_length = hidden; +} + +void editor_mode::render_nmt_buried() +{ + auto &state{m_nmt_state}; + if (state.buried.empty()) + return; + // gone on to other work the message would only be in the way: the same is done by Terrain in the inspector + if (current_work_area() == work_area::terrain || (ui()->mode() == nodebank_panel::TRACK && m_track_tab != track_tab::lay && m_track_tab != track_tab::path)) + { + state.buried.clear(); + return; + } + // taken back with Ctrl+Z there's nothing to tell of + std::vector tracks; + for (auto const &name : state.buried) + if (auto *track{simulation::Paths.find(name)}; track != nullptr && false == track->m_editorremoved) + tracks.push_back(track); + if (tracks.empty()) + { + state.buried.clear(); + return; + } + auto const low{editor_ui::view_min()}; + auto const high{editor_ui::view_max()}; + ImGui::SetNextWindowPos(ImVec2((low.x + high.x) * 0.5f, low.y + std::round(ImGui::GetFontSize() * (nmt_busy() ? 7.0f : 3.6f))), ImGuiCond_Always, ImVec2(0.5f, 0.0f)); + ImGui::SetNextWindowViewport(ImGui::GetMainViewport()->ID); + ImGui::SetNextWindowBgAlpha(0.94f); + if (ImGui::Begin("##nmtburied", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoDocking)) + { + ImGui::Text(STR_C("%.0f m of the new track is hidden in the ground, you can't see it there"), state.buried_length); + ImGui::TextDisabled("%s", STR_C("Only the ground along the track changes; Ctrl+Z takes it back")); + ImGui::BeginDisabled(nmt_busy()); + if (main_button(STR_C("Fit the ground to the track"), ImVec2(0.0f, tall_button_height()))) + { + nmt_pull_terrain(tracks); + ui()->set_status(state.status, false); + state.buried.clear(); + } + ImGui::EndDisabled(); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Leave it"), ImVec2(0.0f, tall_button_height()))) + state.buried.clear(); + ImGui::SameLine(); + ImGui::AlignTextToFramePadding(); + bool ask{EditorSettings.terrain_buried_ask()}; + if (ImGui::Checkbox(STR_C("Tell me each time"), &ask)) + { + EditorSettings.terrain_buried_ask(ask); + EditorSettings.save(); + } + } + ImGui::End(); +} + +void editor_mode::render_empty_scenery_hint() +{ + // the panel of the empty scenery of the tracks shown, in this frame or the last: it says the same + if (m_lay.active || m_terrain_open || m_nmt_state.prompt || m_streamer.resident() > 0 || ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId) || ImGui::GetFrameCount() - m_empty_hint_frame <= 1) + return; + auto const &tracks{simulation::Paths.sequence()}; + if (std::any_of(tracks.begin(), tracks.end(), [](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved && rail(*Track); })) + return; + auto const low{editor_ui::view_min()}; + auto const high{editor_ui::view_max()}; + auto *list{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const line = [&](char const *Text, float const Size, float const Y, ImU32 const Color) { + auto const width{ImGui::GetFont()->CalcTextSizeA(Size, FLT_MAX, 0.0f, Text).x}; + list->AddText(ImGui::GetFont(), Size, ImVec2(std::round((low.x + high.x - width) * 0.5f), Y), Color, Text); + }; + auto const font{ImGui::GetFontSize()}; + auto const middle{(low.y + high.y) * 0.5f}; + line(STR_C("This scenery is still empty"), font * 1.6f, middle - font * 2.2f, IM_COL32(255, 255, 255, 255)); + line(STR_C("Click Laying on the toolbar or press L, then click the points of the track"), font, middle, IM_COL32(210, 215, 225, 255)); +} + +void editor_mode::render_outside_area_hint() +{ + auto const &area{m_orthophoto.area()}; + auto const &config{m_orthophoto.settings()}; + // with no place of the scenery on the map the camera is nowhere in it + if (area.empty() || false == m_orthophoto.enabled() || (config.north == 0.0 && config.east == 0.0)) + return; + if (geometry::point_in_polygon(area, m_orthophoto.to_puwg({Camera.Pos.x, Camera.Pos.z}))) + { + m_outside_area_closed = false; + return; + } + // the camera riding a track has its own lines at the bottom of the view, where this one would cover them + if (m_outside_area_closed || m_area_drawing.active || m_ride.active() || ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId)) + return; + auto const low{editor_ui::view_min()}; + auto const high{editor_ui::view_max()}; + auto const font{ImGui::GetFontSize()}; + // above the strip of the profile and above the row of the keys of the tools at the bottom of the view + auto const bottom{m_profile.strip_top > low.y + 4.0f * font ? std::min(high.y, m_profile.strip_top) : high.y}; + ImGui::SetNextWindowPos(ImVec2((low.x + high.x) * 0.5f, bottom - std::round(font * 2.8f)), ImGuiCond_Always, ImVec2(0.5f, 1.0f)); + ImGui::SetNextWindowViewport(ImGui::GetMainViewport()->ID); + ImGui::SetNextWindowBgAlpha(0.88f); + if (ImGui::Begin("##outsidearea", nullptr, ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav | ImGuiWindowFlags_NoDocking)) + { + ImGui::AlignTextToFramePadding(); + ImGui::TextColored(ImVec4(1.0f, 0.8f, 0.35f, 1.0f), "%s", STR_C("The camera is outside the range: no aerial photos and no terrain model here")); + ImGui::SameLine(); + if (ImGui::SmallButton(orthophoto_settings_open() ? STR_C("Draw the range again") : STR_C("Range settings..."))) + { + if (orthophoto_settings_open()) + area_start(); + else + { + ui()->show_layers(); + m_orthophoto_window = true; + } + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The range is the download area in Map > Orthophoto settings...; drawn again it can take this place in")); + ImGui::SameLine(); + if (ImGui::SmallButton("x##outsidearea")) + m_outside_area_closed = true; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Hidden until the camera is back inside the range and out again")); + } + ImGui::End(); +} + +void editor_mode::camera_above_ground() +{ + std::vector found; + auto const ground{ground_heights({glm::dvec3{Camera.Pos.x, 5000.0, Camera.Pos.z}}, true, &found).front()}; + if (found.front() == 0 || Camera.Pos.y > ground + 2.0) + return; + Camera.Pos.y = ground + 40.0; + // looking down, to see what the view from above showed around it + Camera.Angle.x = -0.9; + Camera.Velocity = {}; + m_focus_active = false; + Global.pCamera = Camera; +} + +bool editor_mode::render_nmt_place(bool const Moving, bool const Button) +{ + auto &state{m_nmt_state}; + auto &map{m_nmt_map}; + auto const width{ImGui::GetContentRegionAvail().x}; + auto const height{std::round(std::min(width * 0.65f, ImGui::GetFontSize() * 16.0f))}; + ImGui::TextWrapped("%s", STR_C("Click the middle of the scenery on the map")); + item_tooltip("The point 0,0,0 of the scenery. The wheel zooms the map, a drag moves it"); + ImGui::BeginChild("##nmtmap", ImVec2(width, height), false, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); + if (map.render({width, height})) + { + auto const degrees{editor_geo::to_degrees(map.point())}; + std::snprintf(state.place, sizeof(state.place), "%.6f, %.6f", degrees.x, degrees.y); + } + ImGui::EndChild(); + ImGui::SetNextItemWidth(-FLT_MIN); + glm::dvec2 typed; + auto const understood{editor_geo::parse_place(state.place, typed)}; + if (ImGui::InputTextWithHint("##nmtplace", STR_C("or type it: 52.2297, 21.0122"), state.place, sizeof(state.place)) && editor_geo::parse_place(state.place, typed)) + { + map.pick(typed); + map.show(typed, 8.0); + } + item_tooltip("Degrees as the online maps copy them (latitude, longitude), or the X and Y of PUWG 1992, the coordinates of the Polish maps of geoportal.gov.pl"); + if (state.place[0] != '\0' && false == understood) + ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", STR_C("Not a place in Poland: two numbers, degrees or the X and Y of PUWG 1992")); + else if (map.picked()) + ImGui::TextDisabled(STR_C("X %.0f, Y %.0f in PUWG 1992"), map.point().y, map.point().x); + if (Moving && m_streamer.resident() > 0) + { + ImGui::PushStyleColor(ImGuiCol_Text, ImVec4(0.95f, 0.75f, 0.3f, 1.0f)); + ImGui::TextWrapped("%s", STR_C("The terrain made already stays as it is")); + ImGui::PopStyleColor(); + } + if (false == Button) + return false; + auto const cancel{STR_C("Cancel")}; + auto const cancel_width{ImGui::CalcTextSize(cancel).x + ImGui::GetStyle().FramePadding.x * 2.0f}; + bool placed{false}; + ImGui::BeginDisabled(false == map.picked()); + if (main_button(STR_C("The scenery is here"), ImVec2(Moving ? -(cancel_width + ImGui::GetStyle().ItemSpacing.x) : -FLT_MIN, tall_button_height()))) + { + nmt_place_scenery(map.point()); + placed = true; + } + ImGui::EndDisabled(); + if (Moving) + { + ImGui::SameLine(); + if (ImGui::Button(cancel, ImVec2(0.0f, tall_button_height()))) + state.moving = false; + } + return placed; +} + +void editor_mode::render_nmt_ui() +{ + auto &state{m_nmt_state}; + state.shown = ImGui::GetFrameCount(); + nmt_locate(); + auto const busy{nmt_busy()}; + step_heading(1, STR_C("Location")); + if (false == m_nmt.placed() || state.moving) + { + if (render_nmt_place(state.moving, true)) + state.moving = false; + if (false == m_nmt.placed()) + return; + } + else + { + auto const &config{m_orthophoto.settings()}; + auto const degrees{editor_geo::to_degrees({config.east, config.north})}; + ImGui::AlignTextToFramePadding(); + ImGui::Text(STR_C("%.5f N, %.5f E"), degrees.x, degrees.y); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("X %.0f, Y %.0f in PUWG 1992, the coordinates of the Polish maps; the place is shared with the orthophoto"), config.north, config.east); + ImGui::SameLine(); + ImGui::BeginDisabled(busy); + if (ImGui::SmallButton(STR_C("Change..."))) + { + glm::dvec2 const point{config.east, config.north}; + m_nmt_map.pick(point); + m_nmt_map.show(point, 8.0); + std::snprintf(state.place, sizeof(state.place), "%.6f, %.6f", degrees.x, degrees.y); + state.moving = true; + } + ImGui::EndDisabled(); + } + + auto const tracks{std::any_of(simulation::Paths.sequence().begin(), simulation::Paths.sequence().end(), [](TTrack const *Track) { return Track != nullptr && rail(*Track); })}; + // the progress shown at the step whose button began it + auto const tracks_busy{state.stage != nmt_state::automatic::idle || (state.fitting && state.under)}; + if (tracks) + { + step_heading(2, STR_C("Tracks and terrain")); + if (tracks_busy) + render_nmt_progress(false); + else + render_nmt_all_tracks(true); + ImGui::Spacing(); + if (busy && false == tracks_busy) + render_nmt_progress(false); + } + else + { + // no tracks yet: the model as it is around the camera, a square of it + step_heading(2, STR_C("Load")); + if (busy) + render_nmt_progress(false); + else + { + if (main_button(STR_C("Load around the camera"), ImVec2(-FLT_MIN, tall_button_height()))) + { + if (m_streamer.resident() == 0) + state.offset = 0.0; + nmt_make(nmt_keys_around()); + } + item_tooltip("Loads the terrain model as it is around the camera, with the height offset above; the tracks stay where they are"); + if (begin_fields("##nmtload", 0.5f)) + { + field_row("Area"); + segmented("nmtarea", m_terrain_add_count, {{2, "0.5 km", "A square of 500 m around the camera"}, {4, "1 km", "A square of 1 km around the camera"}, {8, "2 km", "A square of 2 km around the camera"}}); + ImGui::EndTable(); + } + } + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("A chunk there is already is never made anew")); + ImGui::PopTextWrapPos(); + } + if (ImGui::TreeNode(STR_C("Settings"))) + { + if (toggle_chips("nmtgrow", {{STR_C("Terrain of the model right away while laying"), &state.grow, + "Where the terrain of the scenery ends, the terrain model is made under the tracks as they're laid, around the cursor from the first point placed; " + "the chunks there are stay as they are. Off, it's made only when asked for"}}) >= 0) + { + EditorSettings.terrain_while_laying(state.grow); + EditorSettings.save(); + } + // with tracks the model as it is is a card of step 2, the band of it and the square around the camera are here + if (tracks && begin_fields("##nmtoffset", 0.5f)) + { + field_row("Band along the tracks (m)"); + ImGui::InputDouble("##nmtbandwidth", &state.band, 50.0, 250.0, "%.0f"); + item_tooltip("How far from the tracks, on both sides, the terrain model is loaded"); + field_row("Height offset of the model (m)"); + ImGui::InputDouble("##nmtheightoffset", &state.offset, 0.1, 1.0, "%.2f"); + item_tooltip("Added to the heights of the model, for a scenery built at heights of its own; the tracks put onto the terrain find it by themselves"); + ImGui::TableNextRow(); + ImGui::TableSetColumnIndex(1); + ImGui::BeginDisabled(busy); + if (ImGui::Button(STR_C("Fit to the tracks"), ImVec2(-FLT_MIN, 0.0f))) + nmt_fit(); + ImGui::EndDisabled(); + item_tooltip("Compares the formation of the tracks with the terrain model and moves the model up or down to meet them, as a scenery built at height 0 needs"); + ImGui::EndTable(); + } + if (tracks) + { + ImGui::BeginDisabled(busy); + if (ImGui::Button(STR_C("Load around the camera"), ImVec2(-FLT_MIN, 0.0f))) + nmt_make(nmt_keys_around()); + item_tooltip("Loads the terrain model as it is around the camera, with the height offset above; the tracks stay where they are"); + ImGui::EndDisabled(); + } + ImGui::TreePop(); + } + state.band = std::clamp(state.band, 50.0, 3000.0); + ImGui::Spacing(); + // while the work goes on the bar above tells how far it got + if (false == state.status.empty() && false == busy) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", state.status.c_str()); + ImGui::PopTextWrapPos(); + } + if (false == state.error.empty()) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", state.error.c_str()); + ImGui::PopTextWrapPos(); + } + bool again{false}; + if (auto const error{m_nmt.error(&again)}; false == error.empty()) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", STR(error).c_str()); + ImGui::PopTextWrapPos(); + if (again && ImGui::Button(STR_C("Try again"))) + m_nmt.retry(); + if (again) + item_tooltip("The squares of the model the service didn't give are asked for again; it happens by itself every 15 s too"); + } + ImGui::TextDisabled("%s", STR_C("Terrain model: GUGiK, geoportal.gov.pl")); +} + +void editor_mode::nmt_place_scenery(glm::dvec2 const &Point) +{ + auto &state{m_nmt_state}; + auto config{m_orthophoto.settings()}; + config.north = Point.y; + config.east = Point.x; + m_orthophoto.settings(config); + m_orthophoto_origin_edit = {config.north, config.east}; + save_orthophoto_settings(); + nmt_locate(); + // the heights fitted to the tracks at the place before mean nothing here + state.offset = 0.0; + state.fitted = false; + state.under = false; + state.anchors.clear(); + state.anchor_cells.clear(); +} + +void editor_mode::nmt_offer() +{ + auto &state{m_nmt_state}; + if (state.offered || false == m_lay.active || false == EditorSettings.terrain_offer()) + return; + state.offered = true; + if (m_streamer.resident() > 0 || std::any_of(simulation::Paths.sequence().begin(), simulation::Paths.sequence().end(), [](TTrack const *Track) { return Track != nullptr && rail(*Track); })) + return; + nmt_locate(); + state.prompt = true; +} + +void editor_mode::nmt_accept_offer() +{ + auto &state{m_nmt_state}; + if (false == m_nmt.placed() && m_nmt_map.picked()) + nmt_place_scenery(m_nmt_map.point()); + // no tracks to fit to: the heights of the model as they are + state.offset = 0.0; + nmt_make(nmt_keys_around()); + state.prompt = false; +} + +void editor_mode::render_nmt_prompt() +{ + auto &state{m_nmt_state}; + if (false == state.prompt) + return; + char const *const title{STR_C("Terrain for the new scenery###nmtoffer")}; + if (false == ImGui::IsPopupOpen(title)) + ImGui::OpenPopup(title); + ImGui::SetNextWindowSize(ImVec2(520.0f * Global.ui_scale, 0.0f)); + if (false == ImGui::BeginPopupModal(title, nullptr, ImGuiWindowFlags_NoResize)) + return; + ImGui::TextWrapped("%s", STR_C("The scenery has no terrain yet. Load the terrain model and the aerial photos around here? The tracks laid then go along the real ground.")); + bool const placed{m_nmt.placed()}; + if (false == placed) + render_nmt_place(false, false); + auto const known{placed || m_nmt_map.picked()}; + ImGui::Spacing(); + auto const gap{std::round(ImGui::GetFontSize() * 0.6f)}; + auto const width{std::floor((ImGui::GetContentRegionAvail().x - gap) * 0.5f)}; + if (ground_card("##terrain", STR_C("Load the terrain"), STR_C("The terrain model and the aerial photos of geoportal.gov.pl around here; the tracks go along the real ground"), true, known, width)) + { + nmt_accept_offer(); + ImGui::CloseCurrentPopup(); + } + if (false == known) + item_tooltip("Pick where the scenery lies first"); + ImGui::SameLine(0.0f, gap); + if (ground_card("##flat", STR_C("Without terrain"), STR_C("The tracks lie on the flat plane at the height 0; the terrain can be loaded later in Terrain (F5)"), false, true, width)) + { + state.prompt = false; + ImGui::CloseCurrentPopup(); + } + ImGui::Spacing(); + bool ask{EditorSettings.terrain_offer()}; + if (ImGui::Checkbox(STR_C("Ask with every new scenery"), &ask)) + { + EditorSettings.terrain_offer(ask); + EditorSettings.save(); + } + ImGui::EndPopup(); +} + +std::size_t editor_mode::nmt_join_ends() +{ + // the loose ends are one joint before the grade lines run over them; of two switches, which can't be changed alone, the + // lines over them take each other over as they're fitted + std::vector> states; + std::vector changed; + auto const remember = [&](TTrack *Track) { + if (std::find(changed.begin(), changed.end(), Track) != changed.end()) + return; + states.emplace_back(Track, editor_track::capture(*Track)); + changed.push_back(Track); + }; + std::size_t joined{0}; + m_nmt_state.loose.clear(); + for (auto pair : loose_pairs()) + { + if (pair.first.track->eType != tt_Normal) + std::swap(pair.first, pair.second); + auto const &a{pair.first}; + auto const &b{pair.second}; + if (a.track->eType != tt_Normal) + { + // two switches: the lines over them meet as they're fitted + m_nmt_state.loose[{a.track, a.path, a.atend}] = {b.track, b.path, b.atend}; + m_nmt_state.loose[{b.track, b.path, b.atend}] = {a.track, a.path, a.atend}; + continue; + } + if (b.track->eType != tt_Normal && false == editor_track::is_supported(*b.track)) + continue; + auto const height{b.track->eType == tt_Normal ? (a.point.y + b.point.y) * 0.5 : b.point.y}; + for (auto const *side : {&a, &b}) + { + if (side->track->eType != tt_Normal) + continue; + remember(side->track); + side->track->m_paths[side->path].points[side->atend ? segment_data::point::end : segment_data::point::start].y = height; + } + ++joined; + } + if (changed.empty()) + return 0; + editor_track::commit(changed); + push_track_snapshot(std::move(states)); + WriteLog(format("Editor: NMT - %zu joints of tracks laid apart in height joined", joined), logtype::generic); + return joined; +} + +std::vector editor_mode::nmt_turntables() const +{ + std::vector result; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->eType != tt_Table || false == rail(*track)) + continue; + auto const &points{track->m_paths.front().points}; + nmt_state::turntable table; + table.table = track; + table.centre = glm::mix(points[segment_data::point::start], points[segment_data::point::end], 0.5); + table.rim = 0.5 * geometry::plan_distance(points[segment_data::point::start], points[segment_data::point::end]); + if (table.rim < 1.0) + continue; + result.push_back(std::move(table)); + } + if (result.empty()) + return result; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->eType == tt_Table || false == rail(*track)) + continue; + for (int path = 0; path < static_cast(track->m_paths.size()); ++path) + for (auto const atend : {false, true}) + { + auto const end{end_of(*track, path, atend)}; + for (auto &table : result) + if (on_rim(end, table.centre, table.rim)) + table.ends.emplace_back(track, path, atend); + } + } + return result; +} + +std::size_t editor_mode::nmt_level_turntables() +{ + auto &state{m_nmt_state}; + state.turntables = nmt_turntables(); + std::vector> states; + std::vector changed; + std::vector> moves; + std::vector> models; + std::vector standing; + if (false == state.turntables.empty()) + standing = standing_templates([](std::string const &) { return true; }); + for (auto &table : state.turntables) + { + // the height of the tracks running up to it: of the ones fitted already, which stay as they are, else of the model beside + // the rim past the wall of the pit, out along each of them + std::vector fitted, model; + for (auto const &[track, path, atend] : table.ends) + { + auto const end{end_of(*track, path, atend)}; + if (nmt_stays(*track)) + fitted.push_back(end.point.y); + auto const away{geometry::plan_of(end.point - table.centre) / std::max(1e-6, geometry::plan_distance(end.point, table.centre))}; + for (int metre = 0; metre <= 6; ++metre) + if (double height; m_nmt.height(end.point.x + away.x * (kPitWall + metre), end.point.z + away.y * (kPitWall + metre), height)) + model.push_back(height + state.offset + track->rail_height()); + } + auto &heights{fitted.empty() ? model : fitted}; + if (heights.empty()) + { + WriteLog(format("Editor: NMT - turntable %s left at %.2f m: %s", table.table->name().c_str(), table.centre.y, table.ends.empty() ? "no tracks run up to it" : "no terrain model beside it"), logtype::generic); + continue; + } + std::nth_element(heights.begin(), heights.begin() + heights.size() / 2, heights.end()); + auto const height{heights[heights.size() / 2]}; + auto const rise{height - table.centre.y}; + WriteLog(format("Editor: NMT - turntable %s level at %.2f m, from %.2f m (%+.2f), the height of its %zu tracks %s", table.table->name().c_str(), height, table.centre.y, rise, table.ends.size(), + fitted.empty() ? "on the model beside its rim" : "fitted already"), + logtype::generic); + auto &points{table.table->m_paths.front().points}; + table.centre.y = height; + if (std::abs(points[segment_data::point::start].y - height) < 0.001 && std::abs(points[segment_data::point::end].y - height) < 0.001) + continue; + states.emplace_back(table.table, editor_track::capture(*table.table)); + points[segment_data::point::start].y = height; + points[segment_data::point::end].y = height; + points[segment_data::point::control1].y = 0.0; + points[segment_data::point::control2].y = 0.0; + table.table->m_paths.front().pieces.clear(); + changed.push_back(table.table); + // its include, the pit and the bridge, by the name of the table in its parameters; a model of its name standing apart + std::set included; + for (auto const &item : standing) + if (false == item.values.empty() && ToLower(item.values.front()) == table.table->name() && geometry::plan_distance(item.location, table.centre) <= 1.0) + { + template_item moved; + moved.file = item.file; + moved.location = item.location + glm::dvec3{0.0, rise, 0.0}; + moved.yaw = item.yaw; + moves.emplace_back(item, moved); + included.insert(item.instance); + } + auto const apart{models.size()}; + if (auto *model{simulation::Instances.find(table.table->name())}; model != nullptr && false == included.contains(model->m_instance) && geometry::plan_distance(model->location(), table.centre) <= table.rim) + models.emplace_back(model, rise); + WriteLog(format("Editor: NMT - turntable %s moved %+.2f m with %zu include(s) and %zu model(s) of its name", table.table->name().c_str(), rise, included.size(), models.size() - apart), logtype::generic); + } + if (changed.empty()) + return 0; + editor_track::commit(changed); + push_track_snapshot(std::move(states)); + if (move_templates(moves) > 0 && m_history.size() >= 2) + m_history.back().joined = true; + for (auto const &[model, rise] : models) + { + push_snapshot(model, EditorSnapshot::Action::Move); + m_history.back().joined = true; + m_editor.translate(model, model->location() + glm::dvec3{0.0, rise, 0.0}, true); + } + return changed.size(); +} + +bool editor_mode::nmt_stays(TTrack const &Track) +{ + auto const &state{m_nmt_state}; + return (state.unfitted && grade_fitted(Track)) || (false == state.redo_hand && grade_hand(Track)); +} + +void editor_mode::nmt_auto_start(bool const Unfitted) +{ + auto &state{m_nmt_state}; + state.error.clear(); + state.under = false; + state.unfitted = Unfitted; + state.result = false; + state.findings.clear(); + nmt_locate(); + state.probes.clear(); + state.probes_kept = 0; + // the tracks fitted already, when they stay as they are, tell the offset of the model they were fitted to, which isn't kept + // from one opening of the scenery to the next: a few hundred of their places are measured too, after the others + std::vector kept; + for (auto const &place : nmt_track_places(20.0)) + if (place.shapes) + (nmt_stays(*place.track) ? kept : state.probes).push_back(place); + if (state.probes.empty()) + { + state.status = Unfitted && false == kept.empty() ? STR("All the tracks are fitted to the terrain already") : STR("No tracks to put onto the terrain"); + return; + } + auto const every{std::max(1, kept.size() / 400)}; + for (std::size_t i = 0; i < kept.size(); i += every) + state.probes.push_back(kept[i]); + state.probes_kept = (kept.size() + every - 1) / every; + state.lines = 0; + state.refused = 0; + state.departures = 0; + state.levelled = 0; + state.findings.clear(); + state.result = false; + state.run = true; + state.fetch_most = 0; + state.stage = nmt_state::automatic::fetching; + state.status = STR("Fetching the terrain model under the tracks..."); +} + +bool editor_mode::nmt_fit_line(TTrack &Track, std::function const &Fitted, bool const Laid) +{ + auto &profile{m_profile}; + auto const &fitted{Fitted}; + // the line runs over the tracks not fitted yet around the track: the ones fitted stay as they are + auto route{editor_track::run_route(Track, profile.run_length)}; + auto const at{std::find_if(route.spans.begin(), route.spans.end(), [&](auto const &Span) { return Span.track == &Track; })}; + auto const middle{geometry::bezier{Track.m_paths.front()}.point(0.5)}; + if (at == route.spans.end()) + { + nmt_note(nmt_state::finding::kind::refused, &Track, &Track, Track.Length(), middle, STR("No line of tracks runs over the track")); + return false; + } + auto first{at}; + while (first != route.spans.begin() && false == fitted(std::prev(first)->track)) + --first; + auto last{at}; + while (std::next(last) != route.spans.end() && false == fitted(std::next(last)->track)) + ++last; + route.spans = {first, std::next(last)}; + profile.open = true; + profile.status.clear(); + profile.error.clear(); + auto *from{route.spans.front().track}; + auto *to{route.spans.back().track}; + profile_take(std::move(route), from, to); + if (false == profile.error.empty() || profile.samples.empty()) + { + nmt_note(nmt_state::finding::kind::refused, from, to, profile.route.length, middle, profile.error.empty() ? STR("The line has no profile") : profile.error); + return false; + } + // an end which goes on into a line fitted already keeps its height and grade; any other end is free, the tracks past it are + // fitted later and meet this line then + auto const joint = [&](bool const Atend, double &Height) { + double grade; + TTrack *adjoining{nullptr}; + int path{0}; + if (false == editor_track::adjoining_grade(profile.route, Atend, grade, &adjoining, &path) || adjoining == nullptr || false == fitted(adjoining)) + return false; + auto const &end{Atend ? profile.samples.back().position : profile.samples.front().position}; + auto const &points{adjoining->m_paths[path].points}; + auto const &start{points[segment_data::point::start]}; + auto const &finish{points[segment_data::point::end]}; + Height = geometry::plan_distance(start, end) < geometry::plan_distance(finish, end) ? start.y : finish.y; + return true; + }; + profile.context.start_joined = profile.context.start_joined && joint(false, profile.context.start_elevation); + profile.context.end_joined = profile.context.end_joined && joint(true, profile.context.end_elevation); + auto const on_route = [&](TTrack const *Other) { return std::any_of(profile.route.spans.begin(), profile.route.spans.end(), [&](auto const &Span) { return Span.track == Other; }); }; + // an end on a switch which meets a switch fitted already unlinked, laid apart in height, takes it over as if it went on into it + auto const partner_of = [&](editor_track::route_span const &Span, bool const Atend) -> std::optional { + auto const found{m_nmt_state.loose.find({Span.track, Span.path, Atend})}; + if (found == m_nmt_state.loose.end() || on_route(std::get<0>(found->second))) + return std::nullopt; + auto const end{end_of(*std::get<0>(found->second), std::get<1>(found->second), std::get<2>(found->second))}; + if (glm::length(geometry::plan_of(end.outward)) < 1e-6) + return std::nullopt; + return end; + }; + auto const loose_into = [&](editor_track::route_span const &Span, bool const Atend) -> std::optional { + auto const end{partner_of(Span, Atend)}; + return end.has_value() && fitted(end->track) ? end : std::nullopt; + }; + // rising off the end met, into the route at its start and against it at its end + auto const rising = [](loose_end const &End) { return End.outward.y / glm::length(geometry::plan_of(End.outward)); }; + if (false == profile.context.start_joined) + if (auto const end{loose_into(profile.route.spans.front(), false == profile.route.spans.front().forward)}) + { + profile.context.start_joined = true; + profile.context.start_elevation = end->point.y; + profile.context.start_grade = rising(*end); + } + if (false == profile.context.end_joined) + if (auto const end{loose_into(profile.route.spans.back(), profile.route.spans.back().forward)}) + { + profile.context.end_joined = true; + profile.context.end_elevation = end->point.y; + profile.context.end_grade = -rising(*end); + } + // the ground of the line: the terrain model on its axis, the top of the ballast with the rails on it, and the rail tops of + // the lines fitted already beside it on the same level as the model here, which tell its height the more closely the + // nearer they are. What doesn't agree with the line, a bridge over it, the ground under a viaduct, the fit lets go of by + // itself + double constexpr kModel{0.15}; // m, the tolerance of the model + double constexpr kRail{0.02}; // m, of a rail top next to the line, growing by kSpread a metre of the distance + double constexpr kSpread{0.01}; + double constexpr kLevel{0.5}; // m, a rail top farther from the model or from the line lies on another level + double constexpr kSameLevel{1.0}; // m, tracks authored closer in height lie on one level, farther one over the other + double constexpr kReach{50.0}; + auto const nearest = [&](glm::dvec3 const &Point, double &Distance) { + Distance = std::numeric_limits::max(); + double height{0.0}; + auto const cx{static_cast(std::floor(Point.x / kPlanCell))}; + auto const cz{static_cast(std::floor(Point.z / kPlanCell))}; + for (int dx = -1; dx <= 1; ++dx) + for (int dz = -1; dz <= 1; ++dz) + { + auto const cell{m_nmt_state.laid.find({cx + dx, cz + dz})}; + if (cell == m_nmt_state.laid.end()) + continue; + for (auto const &laid : cell->second) + if (auto const distance{glm::length(glm::dvec2{laid.position.x - Point.x, laid.position.z - Point.z})}; distance < Distance) + { + Distance = distance; + height = laid.position.y; + } + } + return height; + }; + // an end of the line, or the other path of a switch of it, which leads through the tracks not fitted yet into a line fitted + // already, as at a crossover, ties the two where it leaves the line: there the line keeps to the height of the other, on + // along its grade over the tracks between, give or take what the plain tracks among these can climb with curves of the least + // radius. A switch lies in its plane and climbs nothing. Where they can climb more than a little, the curves of the norms of + // the line come first: what it can't keep to, the tracks between take over + double constexpr kJoin{0.002}; // m + double constexpr kClimbing{0.05}; // m + double constexpr kFarthest{200.0}; + profile::ground_fit options; + // an end on the rim of a turntable runs up to it level at its height, as far as kRunUp off it or half the line, which turns to + // the ground only past that, not at the edge of the pit; the model in the pit isn't its ground + auto const first_chainage{profile.samples.front().chainage}; + auto const last_chainage{profile.samples.back().chainage}; + for (auto const atend : {false, true}) + { + auto const &span{atend ? profile.route.spans.back() : profile.route.spans.front()}; + auto const end{end_of(*span.track, span.path, atend ? span.forward : false == span.forward)}; + auto const table{std::find_if(m_nmt_state.turntables.begin(), m_nmt_state.turntables.end(), [&](nmt_state::turntable const &Table) { return on_rim(end, Table.centre, Table.rim); })}; + if (table == m_nmt_state.turntables.end()) + continue; + auto const height{table->centre.y}; + auto const level{std::min(kRunUp, 0.5 * (last_chainage - first_chainage))}; + auto const from{atend ? last_chainage - level : first_chainage}; + (atend ? profile.context.end_joined : profile.context.start_joined) = true; + (atend ? profile.context.end_elevation : profile.context.start_elevation) = height; + (atend ? profile.context.end_grade : profile.context.start_grade) = 0.0; + profile.context.switches.push_back({from, from + level, table->table->name()}); + for (int metre = 0; from + metre <= from + level + 1e-6; ++metre) + options.bounds.push_back({from + metre, height - kJoin, height + kJoin, false}); + WriteLog(format("Editor: NMT line %s runs up to turntable %s level at %.2f m over %.1f m", Track.name().c_str(), table->table->name().c_str(), height, level), logtype::generic); + } + auto const in_pit =[&](glm::dvec3 const &Point) { + return std::any_of(m_nmt_state.turntables.begin(), m_nmt_state.turntables.end(), [&](nmt_state::turntable const &Table) { return geometry::plan_distance(Point, Table.centre) < Table.rim + kPitWall; }); + }; + auto const length_of =[](TTrack const &Track, int const Path) { return Track.eType == tt_Switch ? Track.SwitchExtension->Segments[Path]->GetLength() : Track.Segment->GetLength(); }; + std::vector exits; + exits.push_back({profile.route.spans.front().track, profile.route.spans.front().path, false == profile.route.spans.front().forward}); + exits.push_back({profile.route.spans.back().track, profile.route.spans.back().path, profile.route.spans.back().forward}); + for (auto const &span : profile.route.spans) + if (span.track->eType == tt_Switch && span.track->m_paths.size() >= 2) + for (auto const outward : {true, false}) + exits.push_back({span.track, 1 - span.path, outward}); + // a switch entered at the far end of a path has the far end of its other path on its plane as high, when as far along it + auto const frog_beside = [](TTrack const &Switch, int const Path) { + if (Switch.m_paths.size() < 2) + return false; + auto const &entered{Switch.m_paths[Path].points}; + auto const &other{Switch.m_paths[1 - Path].points}; + auto const &origin{entered[segment_data::point::start]}; + auto const &control{entered[segment_data::point::control1]}; + auto const along{geometry::plan_of(control != glm::dvec3{} ? control : entered[segment_data::point::end] - origin)}; + if (glm::length(along) < 1e-6) + return false; + auto const ahead = [&](glm::dvec3 const &Point) { return glm::dot(geometry::plan_of(Point - origin), glm::normalize(along)); }; + return std::abs(ahead(entered[segment_data::point::end]) - ahead(other[segment_data::point::end])) <= 0.5; + }; + for (auto const &exiting : exits) + { + auto const &exit{exiting.track->m_paths[exiting.path].points[exiting.forward ? segment_data::point::end : segment_data::point::start]}; + auto const bind = [&](double const Height, double const Between, double const Bending) { + std::size_t nearest{0}; + for (std::size_t i = 1; i < profile.samples.size(); ++i) + if (geometry::plan_distance(profile.samples[i].position, exit) < geometry::plan_distance(profile.samples[nearest].position, exit)) + nearest = i; + auto const climbing{Bending * Between / (4.0 * profile.line.norms.radius_min)}; + options.bounds.push_back({profile.samples[nearest].chainage, Height - kJoin - climbing, Height + kJoin + climbing, climbing >= kClimbing}); + }; + // the tracks it leads into, the nearest first, through both paths of a switch met at its start and across the frog of one + // met at the end of a path, onto the end of its other path + struct walk + { + editor_track::route_span span; + double between{0.0}; // m, over the tracks not fitted yet + double bending{0.0}; // m, of these the plain tracks + }; + std::vector open{{exiting, 0.0, 0.0}}; + std::set> seen; + while (false == open.empty()) + { + auto const nearest{std::min_element(open.begin(), open.end(), [](walk const &A, walk const &B) { return A.between < B.between; })}; + auto const step{*nearest}; + open.erase(nearest); + if (step.between >= kFarthest || false == seen.insert({step.span.track, step.span.path, step.span.forward}).second) + continue; + auto onward{editor_track::continuations(step.span)}; + onward.erase(std::remove_if(onward.begin(), onward.end(), [&](editor_track::continuation const &Next) { return on_route(Next.span.track); }), onward.end()); + // met unlinked, laid apart in height: on as if linked + if (onward.empty()) + if (auto const end{partner_of(step.span, step.span.forward)}) + onward.push_back({{end->track, end->path, false == end->atend}, -rising(*end)}); + for (auto const &[next, grade] : onward) + { + auto const &points{next.track->m_paths[next.path].points}; + auto const entry{points[next.forward ? segment_data::point::start : segment_data::point::end].y}; + if (fitted(next.track)) + { + bind(entry - grade * step.between, step.between, step.bending); + continue; + } + auto const length{length_of(*next.track, next.path)}; + open.push_back({next, step.between + length, step.bending + (next.track->eType == tt_Switch ? 0.0 : length)}); + if (false == next.forward && next.track->eType == tt_Switch && frog_beside(*next.track, next.path)) + open.push_back({{next.track, 1 - next.path, true}, step.between, step.bending}); + } + } + } + // the lines fitted already close beside it on its level, as authored, are ground it never lets go of, however far they are + // off: side by side the tracks lie on one formation, in one plane, as near as the curves of the norms let them. The nearest + // on each side. Where they run so near that the timbers carry both, at a switch, a crossover, they are at one height, on + // any vertical curve the timbers lie on + double constexpr kNear{8.0}; // m between the axes + double constexpr kHeld{5.0}; // m, the reach of their rail tops + double constexpr kTimbers{2.65}; // m between the axes, about the length of a sleeper + double constexpr kTimbered{0.005}; // m + // the stretches of the line about a track it crosses on another level, as the model tells it further on: the rails at the height + // of that track are nothing to the line there, however near and however the file has them + double constexpr kOtherSide{2.0}; // m + struct other_level + { + TTrack const *track; + double chainage; + double reach; // m along the line on both sides + double height; + }; + std::vector other_levels; + auto const on_other_level = [&](double const Chainage, double const Height) { + return std::any_of(other_levels.begin(), other_levels.end(), [&](other_level const &Other) { return std::abs(Chainage - Other.chainage) <= Other.reach && std::abs(Height - Other.height) < kOtherSide; }); + }; + auto const alongside = [&](editor_track::route_sample const &Sample) { + std::array, 2> sides{std::pair{kNear, nullptr}, std::pair{kNear, nullptr}}; + auto const along{glm::normalize(Sample.direction)}; + auto const cx{static_cast(std::floor(Sample.position.x / kPlanCell))}; + auto const cz{static_cast(std::floor(Sample.position.z / kPlanCell))}; + for (int dx = -1; dx <= 1; ++dx) + for (int dz = -1; dz <= 1; ++dz) + { + auto const cell{m_nmt_state.laid.find({cx + dx, cz + dz})}; + if (cell == m_nmt_state.laid.end()) + continue; + for (auto const &point : cell->second) + { + glm::dvec2 const offset{point.position.x - Sample.position.x, point.position.z - Sample.position.z}; + auto const across{along.x * offset.y - along.y * offset.x}; + if (std::abs(glm::dot(offset, along)) > 1.0 || std::abs(across) >= kNear || std::abs(point.was - Sample.position.y) > kSameLevel || on_other_level(Sample.chainage, point.position.y)) + continue; + auto &side{sides[across > 0.0 ? 0 : 1]}; + if (std::abs(across) < side.first) + side = {std::abs(across), &point}; + } + } + return sides; + }; + auto const count{profile.samples.size()}; + std::vector sampled(count), model(count, std::numeric_limits::quiet_NaN()); + std::vector plan(count); + std::vector chainages, ground, tolerances, reaches; + // where the line crosses another track at an angle, with no joint with it, the model shows the formation of the one on top and tells + // nothing of the other: there it's no ground of the line, the height comes from the terrain on both sides, a line low there going under + double constexpr kCrossedNear{2.0}; // m + double constexpr kCrossedSine{0.5}; // 30 degrees + double constexpr kCrossedReach{20.0}; // m along the line on both sides, about what the formation with its slopes takes + std::vector crossed(count, 0); + for (std::size_t i = 0; i < count; ++i) + { + auto const &sample{profile.samples[i]}; + auto const along{glm::normalize(sample.direction)}; + auto const cx{static_cast(std::floor(sample.position.x / kPlanCell))}; + auto const cz{static_cast(std::floor(sample.position.z / kPlanCell))}; + for (int dx = -1; dx <= 1 && crossed[i] == 0; ++dx) + for (int dz = -1; dz <= 1 && crossed[i] == 0; ++dz) + if (auto const cell{m_nmt_state.paths.find({cx + dx, cz + dz})}; cell != m_nmt_state.paths.end()) + for (auto const &point : cell->second) + if (false == on_route(point.track) && glm::length(glm::dvec2{point.position.x - sample.position.x, point.position.z - sample.position.z}) < kCrossedNear && std::abs(along.x * glm::normalize(point.direction).y - along.y * glm::normalize(point.direction).x) > kCrossedSine) + { + crossed[i] = 1; + break; + } + } + std::vector no_ground(count, 0); + for (std::size_t i = 0; i < count; ++i) + if (crossed[i] != 0) + for (std::size_t j = 0; j < count; ++j) + if (std::abs(profile.samples[j].chainage - profile.samples[i].chainage) <= kCrossedReach) + no_ground[j] = 1; + for (std::size_t i = 0; i < count; ++i) + { + auto const &sample{profile.samples[i]}; + auto const *track{sample.span < profile.route.spans.size() ? profile.route.spans[sample.span].track : nullptr}; + sampled[i] = sample.chainage; + plan[i] = {sample.position.x, sample.position.z}; + if (double height; no_ground[i] == 0 && track != nullptr && shapes_ground(*track) && false == in_pit(sample.position) && m_nmt.height(sample.position.x, sample.position.z, height)) + model[i] = height + m_nmt_state.offset + track->rail_height(); + } + // a path which the line crosses on its level, as authored, makes a crossing with it: over it the two lie in one plane, the + // grade doesn't break nor does a vertical curve reach; the line crosses a line fitted already at its height, the rail tops + // of the two at one + double constexpr kCrossing{0.75}; // m, the nearest the samples of the two come, a metre apart + double constexpr kCrossed{0.035}; // the sine of the least angle the axes cross at + double constexpr kGauge{1.435}; // m + struct crossing + { + double chainage; + double height; + double sine; + double distance; + TTrack const *track; + glm::dvec2 at; // where the axes meet + glm::dvec2 along; // the way of the line there + }; + auto const crossings_of = [&](std::map, std::vector> const &Points) { + std::vector found; + auto const across = [](glm::dvec2 const &A, glm::dvec2 const &B) { return A.x * B.y - A.y * B.x; }; + for (auto const &sample : profile.samples) + { + auto const *track{profile.route.spans[sample.span].track}; + auto const cx{static_cast(std::floor(sample.position.x / kPlanCell))}; + auto const cz{static_cast(std::floor(sample.position.z / kPlanCell))}; + auto const along{glm::normalize(sample.direction)}; + for (int dx = -1; dx <= 1; ++dx) + for (int dz = -1; dz <= 1; ++dz) + { + auto const cell{Points.find({cx + dx, cz + dz})}; + if (cell == Points.end()) + continue; + for (auto const &point : cell->second) + { + glm::dvec2 const offset{point.position.x - sample.position.x, point.position.z - sample.position.z}; + auto const other{glm::normalize(point.direction)}; + auto const sine{across(along, other)}; + if (point.track == track || glm::length(offset) > kCrossing || std::abs(point.was - sample.position.y) > kSameLevel || std::abs(sine) < kCrossed) + continue; + // where the axes meet + auto const here{across(offset, other) / sine}; + auto const there{across(offset, along) / sine}; + found.push_back({sample.chainage + here, point.position.y + there * point.grade + point.rails - track->rail_height(), std::abs(sine), glm::length(offset), point.track, glm::dvec2{sample.position.x, sample.position.z} + along * here, along}); + } + } + } + // the nearest samples of each crossing tell it + std::sort(found.begin(), found.end(), [](crossing const &A, crossing const &B) { return std::tie(A.track, A.chainage) < std::tie(B.track, B.chainage); }); + std::vector result; + for (auto const &one : found) + if (one.chainage < 0.0 || one.chainage > profile.route.length || on_route(one.track)) + continue; + else if (result.empty() || result.back().track != one.track || one.chainage - result.back().chainage > 5.0) + result.push_back(one); + else if (one.distance < result.back().distance) + result.back() = one; + return result; + }; + // the height of a crossing of a line fitted already is ground the line keeps to as closely as to the switches beside, though + // not past the curves of the norms: where an end fitted another way is too near, as near as they let it + double constexpr kCrossingHeight{0.005}; // m + struct crossing_hold + { + double chainage; + double height; + double tolerance; + double reach; + }; + std::vector crossing_holds; + for (auto const &found : crossings_of(m_nmt_state.laid)) + { + // the ground on both sides well below the track crossed, or well above it: one goes under the other, however the file has them, + // which often lays both at one height. It's read past the formation of the track crossed, which takes the longer stretch of the + // line the lower the angle: nearer the model shows that formation, or the cutting under it, and tells nothing of this line + double constexpr kFormation{10.0}; // m to the side of the axis of the track crossed + double constexpr kFormationReach{150.0}; // m along the line at most + auto const reach{std::clamp(kFormation / found.sine, kCrossedReach, kFormationReach)}; + auto const terrain_towards = [&](int const Way) { + auto const last{static_cast(count) - 1}; + auto const from{std::min(last, static_cast(std::distance(sampled.begin(), std::lower_bound(sampled.begin(), sampled.end(), found.chainage + Way * reach))))}; + for (auto at{from}; at >= 0 && at <= last; at += Way) + if (std::isfinite(model[at])) + return model[at]; + return std::numeric_limits::quiet_NaN(); + }; + auto const before{terrain_towards(-1)}; + auto const after{terrain_towards(1)}; + auto const sides{std::isfinite(before) && std::isfinite(after)}; + auto const above{sides && before > found.height + kOtherSide && after > found.height + kOtherSide}; + auto const below{sides && before < found.height - kOtherSide && after < found.height - kOtherSide}; + if (above || below) + other_levels.push_back({found.track, found.chainage, std::max(reach, kNear / found.sine), found.height}); + if (above) + continue; + if (below) + { + // under it far enough for a train and what carries the track above, whatever the model has of the formation of that track + double constexpr kUnder{6.0}; // m, rail to rail + double constexpr kUnderReach{30.0}; // m, the ground the line lets go of for it + for (std::size_t i = 0; i < count; ++i) + if (std::abs(sampled[i] - found.chainage) <= reach && model[i] > std::max(before, after) + kOtherSide) + model[i] = std::numeric_limits::quiet_NaN(); + crossing_holds.push_back({found.chainage, std::min(found.height - kUnder, std::max(before, after)), kRail, kUnderReach}); + continue; + } + crossing_holds.push_back({found.chainage, found.height, kCrossingHeight, kLevel}); + } + for (std::size_t i = 0; i < count; ++i) + { + auto const &sample{profile.samples[i]}; + auto const *track{sample.span < profile.route.spans.size() ? profile.route.spans[sample.span].track : nullptr}; + chainages.push_back(sample.chainage); + ground.push_back(model[i]); + tolerances.push_back(kModel); + reaches.push_back(kModel); + double distance; + auto const beside{nearest(sample.position, distance)}; + if (no_ground[i] == 0 && distance < kReach && (false == std::isfinite(model[i]) || std::abs(beside - model[i]) <= kLevel) && false == on_other_level(sample.chainage, beside)) + { + chainages.push_back(sample.chainage); + ground.push_back(beside); + tolerances.push_back(std::max(kRail, kSpread * distance)); + reaches.push_back(kLevel); + } + if (track != nullptr && no_ground[i] == 0) + for (auto const &[apart, point] : alongside(sample)) + if (point != nullptr) + { + chainages.push_back(sample.chainage); + ground.push_back(point->position.y + point->rails - track->rail_height()); + tolerances.push_back(apart < kTimbers ? kTimbered : std::max(kRail, kSpread * apart)); + reaches.push_back(kHeld); + } + // a line fitted already crossing it or beside it on another level, one track going under the other, as authored: the difference + // stays, whatever the model has there, which knows nothing of the cutting or of the bridge + double constexpr kOtherLevel{2.5}; // m in the plan + double constexpr kOtherFarthest{25.0}; // m in height, more isn't a track it has anything to do with + double constexpr kOtherReach{30.0}; // m, the ground the line lets go of for it + auto closest{kOtherLevel}; + nmt_state::laid_point const *other{nullptr}; + auto const cx{static_cast(std::floor(sample.position.x / kPlanCell))}; + auto const cz{static_cast(std::floor(sample.position.z / kPlanCell))}; + for (int dx = -1; dx <= 1; ++dx) + for (int dz = -1; dz <= 1; ++dz) + if (auto const cell{m_nmt_state.laid.find({cx + dx, cz + dz})}; cell != m_nmt_state.laid.end()) + for (auto const &point : cell->second) + { + auto const levels{std::abs(point.was - sample.position.y)}; + auto const distance{glm::length(glm::dvec2{point.position.x - sample.position.x, point.position.z - sample.position.z})}; + if (point.track != track && levels > kSameLevel && levels <= kOtherFarthest && distance < closest && false == on_other_level(sample.chainage, point.position.y)) + { + closest = distance; + other = &point; + } + } + if (other != nullptr) + { + chainages.push_back(sample.chainage); + ground.push_back(other->position.y + (sample.position.y - other->was)); + tolerances.push_back(kRail); + reaches.push_back(kOtherReach); + } + } + if (std::none_of(ground.begin(), ground.end(), [](double const Height) { return std::isfinite(Height); })) + { + nmt_note(nmt_state::finding::kind::refused, from, to, profile.route.length, middle, STR("The terrain model has no data under the line")); + return false; + } + // no farther than the path crossed has rails: the middle of a double slip, a few metres crossed at a low angle, keeps to + // itself, the switches about it have zones of their own + for (auto const &found : crossings_of(m_nmt_state.paths)) + { + // a track going over or under isn't crossed on the rails + if (std::any_of(other_levels.begin(), other_levels.end(), [&](other_level const &Other) { return Other.track == found.track; })) + continue; + auto const half{std::min(30.0, kGauge / found.sine + 1.5)}; + auto first{std::numeric_limits::max()}; + auto last{std::numeric_limits::lowest()}; + for (auto const &path : found.track->m_paths) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + { + auto const along{glm::dot(glm::dvec2{path.points[end].x, path.points[end].z} - found.at, found.along)}; + first = std::min(first, along); + last = std::max(last, along); + } + auto const from{std::max(-half, first - 1.5)}; + auto const to{std::min(half, last + 1.5)}; + if (from < to) + profile.context.switches.push_back({found.chainage + from, found.chainage + to, found.track->name()}); + } + for (auto const &hold : crossing_holds) + { + auto const at{static_cast(std::distance(chainages.begin(), std::upper_bound(chainages.begin(), chainages.end(), hold.chainage)))}; + chainages.insert(chainages.begin() + at, hold.chainage); + ground.insert(ground.begin() + at, hold.height); + tolerances.insert(tolerances.begin() + at, hold.tolerance); + reaches.insert(reaches.begin() + at, hold.reach); + } + // the switches of the tracks beside, the ones of the crossovers above all, lie on bearers common with this track or close + // to it: no break of the grade on them either, so the tracks of the station stay in one plane + double constexpr kShared{7.0}; // m, about the spacing of the tracks + for (auto *other : simulation::Paths.sequence()) + { + if (other == nullptr || other->eType != tt_Switch || other->m_paths.empty() || false == rail(*other)) + continue; + if (std::any_of(profile.route.spans.begin(), profile.route.spans.end(), [&](auto const &Span) { return Span.track == other; })) + continue; + auto const &points{other->m_paths.front().points}; + double from{std::numeric_limits::max()}; + double to{std::numeric_limits::lowest()}; + for (auto const end : {segment_data::point::start, segment_data::point::end}) + { + auto const &point{points[end]}; + double best{kShared}; + double chainage{0.0}; + for (auto const &sample : profile.samples) + if (auto const distance{glm::length(glm::dvec2{sample.position.x - point.x, sample.position.z - point.z})}; distance < best) + { + best = distance; + chainage = sample.chainage; + } + if (best < kShared) + { + from = std::min(from, chainage); + to = std::max(to, chainage); + } + } + if (from < to) + profile.context.switches.push_back({from, to, other->name()}); + } + std::sort(profile.context.switches.begin(), profile.context.switches.end(), [](auto const &Left, auto const &Right) { return Left.from < Right.from; }); + auto settings{profile.line}; + settings.join_start = true; + settings.join_end = true; + settings.speed = editor_track::route_speed(profile.route); + // the grades as steep as the ground has them, up to 50 per mille whatever the norms of the line; the vertical curves of the norms, + // sharper only on a hump of a marshalling yard + options.tolerance = kModel; + options.grade_max = 50.0; + options.follow_length = 60.0; + options.follow_height = 4.0; + options.follow_steepest = 100.0; + options.follow_tolerance = 0.05; + options.humps = profile::humps(chainages, ground, profile.context, kModel, tolerances); + options.hump_radius = 300.0; + for (auto const &hump : options.humps) + profile.context.humps.push_back({hump.from, hump.to, {}}); + auto line{profile::fit_ground(chainages, ground, profile.context, settings, options, tolerances, reaches)}; + if (line.points.size() < 2) + { + nmt_note(nmt_state::finding::kind::refused, from, to, profile.route.length, middle, STR("No grade line fits the terrain model under the line")); + return false; + } + profile.line = std::move(line); + profile.selected = -1; + profile_check(); + auto const fitted_line{profile.line}; + auto const authored{profile.samples}; + // where the model falls away under the line by the abutments, the line goes over on a bridge or a viaduct: its paths there + // are cut off and set to the bridge, the formation is laid up to it, the ground under it stays as the model has it + double constexpr kBridged{1.0}; // m + double constexpr kAbutment{100.0}; // per mille + // spans a few metres apart are one bridge on its piers; what is shorter than that is a culvert under the embankment + double constexpr kPier{5.0}; // m + double constexpr kCulvert{3.0}; // m + double constexpr kFewest{0.03}; // m, how far a path just laid may part from the line before it's cut + std::vector heights(count); + for (std::size_t i = 0; i < count; ++i) + heights[i] = profile::elevation(fitted_line, sampled[i]); + std::vector bridges; + for (auto const &stretch : Laid ? std::vector{} : profile::bridged(sampled, heights, model, kBridged, kAbutment)) + if (false == bridges.empty() && stretch.from - bridges.back().to < kPier) + { + bridges.back().to = stretch.to; + bridges.back().depth = std::min(bridges.back().depth, stretch.depth); + } + else + bridges.push_back(stretch); + bridges.erase(std::remove_if(bridges.begin(), bridges.end(), [&](profile::departure const &Bridge) { return Bridge.to - Bridge.from < kCulvert; }), bridges.end()); + profile.fitting = true; + profile_apply(false, bridges, Laid ? kFewest : 0.0); + profile.fitting = false; + auto const applied{profile.error.empty()}; + // where the line parts from the model: under it a gap, a bridge or a viaduct, over it a wall or a structure above the track + auto const parted{profile::departures(fitted_line, sampled, model, 2.0 * kModel)}; + if (false == parted.empty()) + ++m_nmt_state.departures; + std::size_t agreeing{0}; + std::size_t modelled{0}; + for (std::size_t i = 0; i < count; ++i) + if (std::isfinite(model[i])) + { + ++modelled; + agreeing += std::abs(profile::elevation(fitted_line, sampled[i]) - model[i]) <= kModel ? 1 : 0; + } + // how soon past a switch or its shared timbers the grade changes, the nearest break or start of a curve of the line + if (applied) + { + auto const breaks{profile::breaks(profile.line)}; + double nearest{std::numeric_limits::max()}; + std::string where; + for (auto const &zone : profile.context.switches) + for (auto const at : breaks) + { + auto const gap{at >= zone.to ? at - zone.to : at <= zone.from ? zone.from - at : -1.0}; + if (gap >= 0.0 && gap < nearest) + { + nearest = gap; + where = format("%.1f m %s %s (%.1f..%.1f), the break at %.1f", gap, at >= zone.to ? "past" : "before", zone.name.c_str(), zone.from, zone.to, at); + } + } + if (false == where.empty()) + WriteLog(format("Editor: NMT line %s .. %s: the grade changes %s", from->name().c_str(), to->name().c_str(), where.c_str()), logtype::generic); + } + // where the paths didn't take the line + double off{0.0}; + std::size_t off_at{0}; + if (applied) + for (std::size_t i = 0; i < profile.samples.size(); ++i) + if (auto const departure{std::abs(profile.samples[i].position.y - profile::elevation(profile.line, profile.samples[i].chainage))}; departure > off) + { + off = departure; + off_at = i; + } + if (off > 0.05) + { + auto const &sample{profile.samples[off_at]}; + auto const *track{profile.route.spans[sample.span].track}; + WriteLog(format("Editor: NMT line %s: the path %s (%s, %.0f m) is off the line by %.3f m at %.0f m", Track.name().c_str(), track->name().c_str(), track->eType == tt_Switch ? "switch" : "track", track->Length(), off, sample.chainage), logtype::generic); + } + if (applied) + for (auto const &hump : options.humps) + for (auto const &span : profile.route.spans) + if (span.from < hump.to && span.to > hump.from) + m_nmt_state.on_hump.insert(span.track); + if (applied) + for (auto const &sample : profile.samples) + { + auto const *track{sample.span < profile.route.spans.size() ? profile.route.spans[sample.span].track : nullptr}; + m_nmt_state.laid[{static_cast(std::floor(sample.position.x / kPlanCell)), static_cast(std::floor(sample.position.z / kPlanCell))}].push_back( + {sample.position, sample.direction, sample.grade, editor_track::sampled_elevation(authored, sample.chainage), track != nullptr ? static_cast(track->rail_height()) : 0.0, track}); + } + auto const spans{applied ? bridges : std::vector{}}; + for (auto const &stretch : spans) + for (std::size_t i = 0; i < count; ++i) + if (sampled[i] >= stretch.from && sampled[i] <= stretch.to) + m_nmt_state.bridged[{static_cast(std::floor(plan[i].x / kPlanCell)), static_cast(std::floor(plan[i].y / kPlanCell))}].push_back({plan[i].x, heights[i], plan[i].y}); + // told in the panel too: the line refused and why, the path which didn't take it, the worst place where it parts from the model + // other than over a bridge found + auto const place_at = [&](double const Chainage) { + return std::min_element(profile.samples.begin(), profile.samples.end(), [&](auto const &A, auto const &B) { return std::abs(A.chainage - Chainage) < std::abs(B.chainage - Chainage); })->position; + }; + if (false == applied) + { + auto why{profile.error}; + for (auto const &issue : profile.issues) + if (issue.error) + { + why += (why.empty() ? "" : ": ") + issue.text; + break; + } + nmt_note(nmt_state::finding::kind::refused, from, to, profile.route.length, place_at(0.5 * profile.route.length), why); + } + else if (off > 0.05) + { + auto const &sample{profile.samples[off_at]}; + nmt_note(nmt_state::finding::kind::off, from, to, profile.route.length, sample.position, format(STR_C("The path %s keeps off the line by %.2f m"), profile.route.spans[sample.span].track->name().c_str(), off), off); + } + if (applied) + { + // a ditch or a culvert of a few metres under the line, a few decimetres of the model, is no news: what's long and deep is + double constexpr kTold{0.5}; // m + double constexpr kToldLength{10.0}; // m + profile::departure const *worst{nullptr}; + for (auto const &stretch : parted) + if (std::abs(stretch.depth) >= kTold && stretch.to - stretch.from >= kToldLength && + false == std::any_of(spans.begin(), spans.end(), [&](profile::departure const &Bridge) { return stretch.depth < 0.0 && stretch.from < Bridge.to && stretch.to > Bridge.from; }) && + (worst == nullptr || std::abs(stretch.depth) > std::abs(worst->depth))) + worst = &stretch; + if (worst != nullptr) + nmt_note(nmt_state::finding::kind::parted, from, to, profile.route.length, place_at(0.5 * (worst->from + worst->to)), + worst->depth < 0.0 ? format(STR_C("Over a dip of the model %.1f m deep along %.0f m: a bridge, a culvert or the model off"), -worst->depth, worst->to - worst->from) + : format(STR_C("Under the model by %.1f m along %.0f m: a cutting, a wall or the model off"), worst->depth, worst->to - worst->from), + std::abs(worst->depth)); + } + // the line in the log: how much of it lies on the model, where it parts from it, its grades, why it wasn't applied, its + // course in the plan + std::string text{format("Editor: NMT line %s: %s .. %s, %.0f m, on the model within %.2f m over %.1f%%, parts from it", applied ? "applied" : "refused", from->name().c_str(), to->name().c_str(), profile.route.length, kModel, + 100.0 * static_cast(agreeing) / static_cast(std::max(1, modelled)))}; + for (auto const &stretch : parted) + text += format(" %s %.0f..%.0f %.1f m", stretch.depth < 0.0 ? "under" : "over", stretch.from, stretch.to, std::abs(stretch.depth)); + if (false == spans.empty()) + { + text += ", bridged"; + for (auto const &stretch : spans) + text += format(" %.0f..%.0f", stretch.from, stretch.to); + } + for (auto const &hump : options.humps) + text += format(", a hump %.0f..%.0f, its crest at %.0f %.1f m high", hump.from, hump.to, hump.crest, hump.height); + text += ", grades"; + for (std::size_t i = 1; i < fitted_line.points.size(); ++i) + { + auto const &a{fitted_line.points[i - 1]}; + auto const &b{fitted_line.points[i]}; + text += format(" %+.2f/%.0f", 1000.0 * (b.elevation - a.elevation) / std::max(1e-6, b.chainage - a.chainage), b.chainage - a.chainage); + } + if (false == applied) + { + text += "; " + profile.error; + for (auto const &issue : profile.issues) + if (issue.error) + text += " | " + issue.text; + } + text += "; plan"; + for (std::size_t i = 0; i < profile.samples.size(); i += 10) + text += format(" %.1f,%.1f", profile.samples[i].position.x, profile.samples[i].position.z); + text += format(" %.1f,%.1f", profile.samples.back().position.x, profile.samples.back().position.z); + WriteLog(text, logtype::generic); + return applied; +} + +void editor_mode::nmt_sample_paths(TTrack const &Track, std::map, std::vector> &Points) +{ + // the bridge of a turntable turns: it crosses no line nor lies beside one + if (Track.eType == tt_Table) + return; + for (auto const &path : Track.m_paths) + { + geometry::bezier const curve{path}; + auto const chord{glm::distance(path.points[segment_data::point::start], path.points[segment_data::point::end])}; + auto const count{std::max(1, static_cast(std::ceil(chord * 1.1)))}; + for (int i = 0; i <= count; ++i) + { + auto const t{static_cast(i) / count}; + auto const at{curve.point(t)}; + auto const tangent{curve.first(t)}; + auto const run{glm::length(glm::dvec2{tangent.x, tangent.z})}; + if (run > 1e-9) + Points[{static_cast(std::floor(at.x / kPlanCell)), static_cast(std::floor(at.z / kPlanCell))}].push_back( + {at, glm::dvec2{tangent.x, tangent.z} / run, tangent.y / run, at.y, static_cast(Track.rail_height()), &Track}); + } + } +} + +void editor_mode::nmt_merge_laid(std::unordered_set &Laid) +{ + auto const direction = [](segment_data const &Path) { + auto const control{geometry::plan_of(Path.points[segment_data::point::control1])}; + auto const chord{geometry::plan_of(Path.points[segment_data::point::end] - Path.points[segment_data::point::start])}; + auto const along{glm::length(control) > 1e-6 ? control : chord}; + return along / std::max(1e-12, glm::length(along)); + }; + auto const straight = [&](segment_data const &Path) { + if (std::abs(Path.radius) > 1e-3f) + return false; + auto const along{direction(Path)}; + return std::abs(geometry::cross(along, geometry::plan_of(Path.points[segment_data::point::end] - Path.points[segment_data::point::start]))) < 1e-3 + && std::abs(geometry::cross(along, geometry::plan_of(Path.points[segment_data::point::control2]))) < 1e-3; + }; + struct circle + { + glm::dvec2 centre{0.0}; + double radius{0.0}; + int side{0}; + double angle{0.0}; + }; + auto const arc = [&](segment_data const &Path) -> std::optional { + auto const radius{std::abs(static_cast(Path.radius))}; + if (radius < 1e-3 || glm::length(geometry::plan_of(Path.points[segment_data::point::control1])) < 1e-6) + return std::nullopt; + auto const start{geometry::plan_of(Path.points[segment_data::point::start])}; + auto const end{geometry::plan_of(Path.points[segment_data::point::end])}; + auto const along{direction(Path)}; + auto const side{geometry::cross(along, end - start) > 0.0 ? 1 : -1}; + circle result{start + glm::dvec2{-along.y, along.x} * (side * radius), radius, side, 0.0}; + if (std::abs(glm::distance(result.centre, end) - radius) > 0.01) + return std::nullopt; + result.angle = std::abs(geometry::signed_angle(start - result.centre, end - result.centre)); + return result; + }; + auto const alike = [](TTrack const &A, TTrack const &B) { + return editor_track::velocity(A) == editor_track::velocity(B) && A.eEnvironment == B.eEnvironment && A.iCategoryFlag == B.iCategoryFlag && A.iDamageFlag == B.iDamageFlag; + }; + editor_track::edit edit; + for (bool merged{true}; merged;) + { + merged = false; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || false == Laid.contains(track) || track->eType != tt_Normal || track->m_paths.size() != 1) + continue; + auto *next{track->trNext}; + if (next == nullptr || next == track || next->m_editorremoved || false == Laid.contains(next) || next->eType != tt_Normal || next->m_paths.size() != 1 || next->trPrev != track || false == alike(*track, *next)) + continue; + auto const &first{track->m_paths.front()}; + auto const &second{next->m_paths.front()}; + if (glm::distance(first.points[segment_data::point::end], second.points[segment_data::point::start]) > 1e-3) + continue; + auto const length{geometry::bezier(first).plan_length() + geometry::bezier(second).plan_length()}; + if (length > geometry::longest_path) + continue; + auto path{first}; + path.pieces.clear(); + if (straight(first) && straight(second) && std::abs(geometry::cross(direction(first), direction(second))) < 1e-5 && glm::dot(direction(first), direction(second)) > 0.0) + { + path.points[segment_data::point::control1] = {}; + path.points[segment_data::point::control2] = {}; + path.radius = 0.f; + } + else if (auto const a{arc(first)}, b{arc(second)}; + a && b && a->side == b->side && std::abs(a->radius - b->radius) < 1e-3 * a->radius && glm::distance(a->centre, b->centre) < 0.01 && a->angle + b->angle <= glm::radians(90.0)) + { + auto const pieces{geometry::arc_pieces(first.points[segment_data::point::start], direction(first), 0.0, a->radius, a->angle + b->angle, a->side)}; + if (pieces.size() != 1) + continue; + path.points[segment_data::point::control1] = pieces.front().points[segment_data::point::control1]; + path.points[segment_data::point::control2] = pieces.front().points[segment_data::point::control2]; + } + else + continue; + path.points[segment_data::point::end] = second.points[segment_data::point::end]; + path.rolls[1] = second.rolls[1]; + edit.capture(*track); + editor_track::retire(*next); + Laid.erase(next); + edit.removed.push_back(next); + track->m_paths.front() = path; + editor_track::commit({track}); + merged = true; + } + } + if (false == edit.removed.empty()) + push_track_snapshot(std::move(edit.states), {}, std::move(edit.removed)); +} + +bool editor_mode::nmt_fit_laid(std::size_t const From, glm::dvec3 const End) +{ + auto &state{m_nmt_state}; + if (EditorSettings.heights() != editorSettings::lay_heights::fitted || state.stage != nmt_state::automatic::idle || false == m_nmt.placed() || From >= m_history.size()) + return false; + std::unordered_set laid; + for (auto step{From}; step < m_history.size(); ++step) + for (auto const *track : m_history[step].created) + if (track != nullptr && false == track->m_editorremoved && rail(*track)) + laid.insert(track); + auto const at_end = [&]() -> TTrack * { + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && laid.contains(track) && track->eType == tt_Normal && geometry::plan_distance(track->m_paths.front().points[segment_data::point::end], End) < 0.01) + return track; + return nullptr; + }; + auto const steps{m_history.size()}; + nmt_merge_laid(laid); + auto *last{at_end()}; + if (last == nullptr) + return false; + // the tracks around stay as they are, as lines fitted already: the line keeps level with the ones beside it, the more closely + // the nearer they are, and crosses the ones it crosses at their height + double constexpr kAround{60.0}; // m + glm::dvec2 low{std::numeric_limits::max()}; + glm::dvec2 high{std::numeric_limits::lowest()}; + for (auto const *track : laid) + for (auto const &path : track->m_paths) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + { + low = glm::min(low, geometry::plan_of(path.points[end])); + high = glm::max(high, geometry::plan_of(path.points[end])); + } + low -= kAround; + high += kAround; + std::map, std::vector> around; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || false == rail(*track) || laid.contains(track)) + continue; + auto const &points{track->m_paths.front().points}; + auto const a{geometry::plan_of(points[segment_data::point::start])}; + auto const b{geometry::plan_of(points[segment_data::point::end])}; + if (std::max(a.x, b.x) < low.x || std::min(a.x, b.x) > high.x || std::max(a.y, b.y) < low.y || std::min(a.y, b.y) > high.y) + continue; + nmt_sample_paths(*track, around); + } + // the state of the tracks going onto the terrain lent to the one line, the profile tool left as it was + auto const profile{m_profile}; + auto fitted_lines{std::exchange(state.laid, around)}; + auto paths{std::exchange(state.paths, std::move(around))}; + auto loose{std::exchange(state.loose, {})}; + auto turntables{std::exchange(state.turntables, nmt_turntables())}; + auto const departures{state.departures}; + auto const applied{nmt_fit_line(*last, [&](TTrack const *Other) { return false == laid.contains(Other); }, true)}; + auto const error{m_profile.error}; + state.laid = std::move(fitted_lines); + state.paths = std::move(paths); + state.loose = std::move(loose); + state.turntables = std::move(turntables); + state.departures = departures; + m_profile = profile; + // taken back with the laying + for (auto step{steps}; step < m_history.size(); ++step) + m_history[step].joined = true; + if (applied) + { + laid.clear(); + for (auto step{From}; step < m_history.size(); ++step) + for (auto const *track : m_history[step].created) + if (track != nullptr && false == track->m_editorremoved) + laid.insert(track); + if (auto *track{at_end()}; track != nullptr) + { + m_node = track; + ui()->set_node(m_node); + } + } + else if (false == error.empty()) + WriteLog("Editor: the track laid not put onto the terrain model - " + error, logtype::generic); + return applied; +} + +namespace +{ + +// things joined one to another in sets, each set told by its root +template > +class joined_sets +{ +public: + Thing root(Thing Of) const + { + for (auto found{m_parent.find(Of)}; found != m_parent.end() && found->second != Of; found = m_parent.find(Of)) + Of = found->second; + return Of; + } + // the set of the first root goes into the set of the second + void join_roots(Thing const &A, Thing const &B) + { + m_parent[A] = B; + m_parent.try_emplace(B, B); + } + void join(Thing const &A, Thing const &B) + { + if (auto const a{root(A)}, b{root(B)}; a != b) + join_roots(a, b); + } + // joined to anything at all + bool joined(Thing const &Of) const + { + return m_parent.contains(Of); + } + +private: + Map m_parent; +}; + +// of the least squares the moves of the grade lines shared are: the sum of the unknowns at, each by its factor, is to come to the value, +// as closely as the weight tells; an unknown under 0 ends the ones taken +struct grade_term +{ + std::array at; + std::array by; + double value; + double weight; +}; + +// the unknowns of the least squares of the terms, by conjugate gradients on the normal equations, with the iterations it took +std::vector grade_moves(std::vector const &Terms, int const Unknowns, int &Iterations) +{ + auto const multiply = [&](std::vector const &In, std::vector &Out) { + std::fill(Out.begin(), Out.end(), 0.0); + for (auto const &one : Terms) + { + auto sum{0.0}; + for (int k = 0; k < 5 && one.at[k] >= 0; ++k) + sum += one.by[k] * In[one.at[k]]; + sum *= one.weight; + for (int k = 0; k < 5 && one.at[k] >= 0; ++k) + Out[one.at[k]] += one.by[k] * sum; + } + }; + std::vector moves(Unknowns, 0.0), residual(Unknowns, 0.0), diagonal(Unknowns, 0.0); + for (auto const &one : Terms) + for (int k = 0; k < 5 && one.at[k] >= 0; ++k) + { + residual[one.at[k]] += one.weight * one.by[k] * one.value; + diagonal[one.at[k]] += one.weight * one.by[k] * one.by[k]; + } + std::vector direction(Unknowns), product(Unknowns); + auto rho{0.0}; + for (int i = 0; i < Unknowns; ++i) + { + direction[i] = residual[i] / diagonal[i]; + rho += residual[i] * direction[i]; + } + auto const first_rho{std::max(rho, 1e-30)}; + for (Iterations = 0; Iterations < 30000 && rho > 1e-14 * first_rho; ++Iterations) + { + multiply(direction, product); + auto bottom{0.0}; + for (int i = 0; i < Unknowns; ++i) + bottom += direction[i] * product[i]; + if (bottom <= 0.0) + break; + auto const step{rho / bottom}; + auto next{0.0}; + for (int i = 0; i < Unknowns; ++i) + { + moves[i] += step * direction[i]; + residual[i] -= step * product[i]; + next += residual[i] * residual[i] / diagonal[i]; + } + auto const beta{next / rho}; + rho = next; + for (int i = 0; i < Unknowns; ++i) + direction[i] = residual[i] / diagonal[i] + beta * direction[i]; + } + return moves; +} + +// the grade a path rises out of an end with, by its control there: a path on a vertical curve rises otherwise than along its chord, a +// long one with the whole curve on it by 16 permille +double rise_out(segment_data const &Path, bool const Atend) +{ + auto const &points{Path.points}; + auto const control{points[Atend ? segment_data::point::control2 : segment_data::point::control1]}; + auto const along{glm::length(geometry::plan_of(control))}; + if (along > 1e-6) + return control.y / along; + auto const length{geometry::plan_distance(points[segment_data::point::start], points[segment_data::point::end])}; + return (points[segment_data::point::end].y - points[segment_data::point::start].y) * (Atend ? -1.0 : 1.0) / std::max(1e-9, length); +} + +// a path going out of a joint: of which track, the way and the grade it leaves the joint with +struct leaving +{ + TTrack const *track; + glm::dvec2 way; + double grade; // rising out of the joint +}; + +leaving leaving_of(TTrack const *Track, segment_data const &Path, bool const Atend) +{ + auto const &points{Path.points}; + auto const control{geometry::plan_of(points[Atend ? segment_data::point::control2 : segment_data::point::control1])}; + auto const chord{geometry::plan_of(points[segment_data::point::end] - points[segment_data::point::start]) * (Atend ? -1.0 : 1.0)}; + auto const rise{(points[segment_data::point::end].y - points[segment_data::point::start].y) * (Atend ? -1.0 : 1.0)}; + if (glm::length(control) > 1e-6) + return leaving{Track, glm::normalize(control), points[Atend ? segment_data::point::control2 : segment_data::point::control1].y / glm::length(control)}; + return leaving{Track, chord / std::max(1e-9, glm::length(chord)), rise / std::max(1e-9, glm::length(chord))}; +} + +// the path on the cubic of these grades along it from end to end, its pieces too +void on_vertical_curve(segment_data &Path, double const First, double const Last) +{ + auto const origin{Path.points[segment_data::point::start]}; + auto const chord{geometry::plan_of(Path.points[segment_data::point::end] - origin)}; + auto const square{std::max(1e-9, glm::dot(chord, chord))}; + auto const length{std::sqrt(square)}; + auto const rise{Path.points[segment_data::point::end].y - origin.y}; + auto const second{3.0 * rise - (2.0 * First + Last) * length}; + auto const third{(First + Last) * length - 2.0 * rise}; + auto const height = [&](double const U) { return origin.y + U * (First * length + U * (second + U * third)); }; + auto const slope = [&](double const U) { return (First * length + U * (2.0 * second + U * 3.0 * third)) / length; }; + auto const lay = [&](segment_data &Part) { + auto &points{Part.points}; + if (points[segment_data::point::control1] == glm::dvec3{} && points[segment_data::point::control2] == glm::dvec3{}) + { + points[segment_data::point::control1] = (points[segment_data::point::end] - points[segment_data::point::start]) / 3.0; + points[segment_data::point::control2] = (points[segment_data::point::start] - points[segment_data::point::end]) / 3.0; + } + auto const along = [&](glm::dvec3 const &Point) { return std::clamp(glm::dot(geometry::plan_of(Point - origin), chord) / square, 0.0, 1.0); }; + auto const from{along(points[segment_data::point::start])}; + auto const to{along(points[segment_data::point::end])}; + points[segment_data::point::control1].y = slope(from) * glm::length(geometry::plan_of(points[segment_data::point::control1])); + points[segment_data::point::control2].y = -slope(to) * glm::length(geometry::plan_of(points[segment_data::point::control2])); + points[segment_data::point::start].y = height(from); + points[segment_data::point::end].y = height(to); + }; + for (auto &piece : Path.pieces) + lay(piece); + lay(Path); +} + +} // namespace + +void editor_mode::nmt_share_grades() +{ + // one grade line for the tracks side by side: over the grade lines fitted one by one, what each joint moves by is worked out for all + // of them at once. Tracks nearly parallel under 5.1 m apart come to one height, the moves change evenly along a line, so what was fitted stays + // smooth, and each joint keeps to where it was as far as these let it: a track going away from the others is on its own again. + // Tracks over 1 m apart in height lie on another level; a long steep one, a hump, stays as it is and tells nothing to those beside it. + // It's told for a whole run of tracks from switch to switch: one with nothing beside it over 15 m and a quarter of its length has a grade line of its own. + // The tracks and switches on common timbers lie on one surface whatever else is told of them, a plane tilting along and across as the + // ground goes, each such group its own; on it they come to one grade line as far as tracks side by side do. A switch lies in its plane + auto &state{m_nmt_state}; + // nothing fitted now, nothing to share: what stays lies as it was + if (false == state.common || (false == state.stayed.empty() && state.lines == 0)) + return; + double constexpr kApart{5.1}; // m between the axes + double constexpr kParallel{0.985}; // the cosine of the angle of tracks nearly parallel, 10 degrees: the links of a crossover are, a track crossing isn't + double constexpr kLevel{1.0}; // m, as the lines keep to tracks on another level + double constexpr kSteep{0.025}; + double constexpr kSteepLength{15.0}; // m, shorter ones are the links of a crossover between tracks at two heights + double constexpr kSpacing{5.0}; // m between the places looked at on a track + double constexpr kMoved{0.00001}; // m, any less stays: what a joint moves by goes on all the tracks at it, a millimetre left on a short one is a grade of its own + // how closely each is kept to, the weights being one over the square + double constexpr kKeep{0.5}; // m, a joint to where it was + double constexpr kBeside{0.01}; // m, tracks side by side + double constexpr kEven{0.0005}; // the change of grade the moves make at a joint + double constexpr kTimbers{2.65}; // m between the axes, about the length of a sleeper + double constexpr kOnTimbers{0.001}; // m, how closely tracks on common timbers keep to the surface of their group + double constexpr kPlane{0.005}; // m, how closely the second path of a switch keeps to the plane of the first + double constexpr kAway{15.0}; // m of a run with no track beside it, as much as its ends at the switches may part from the others + double constexpr kBroken{0.015}; // a grade breaking more than this at a joint is to go, a smaller one is the vertical curve fitted + using key = std::pair; + auto const key_of = [](glm::dvec3 const &Point) { return key{static_cast(std::round(Point.x * 20.0)), static_cast(std::round(Point.z * 20.0))}; }; + std::vector tracks; + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && rail(*track) && track->eType != tt_Table) + tracks.push_back(track); + auto const steep = [&](TTrack const &Track) { + if (state.on_hump.contains(&Track)) + return true; + return std::any_of(Track.m_paths.begin(), Track.m_paths.end(), [&](segment_data const &Path) { + auto const &start{Path.points[segment_data::point::start]}; + auto const &end{Path.points[segment_data::point::end]}; + auto const length{geometry::plan_distance(start, end)}; + return length >= kSteepLength && std::abs(end.y - start.y) > kSteep * length; + }); + }; + struct link + { + int to; + double length; + glm::dvec2 out; + double rise; // the grade rising out of the joint along the path, by its control there + }; + std::map indices; + std::vector> links; + std::vector fixed; + std::vector heights; + auto const index_of = [&](glm::dvec3 const &Point) { + auto const [found, added]{indices.try_emplace(key_of(Point), static_cast(links.size()))}; + if (added) + { + links.emplace_back(); + fixed.push_back(0); + heights.push_back(Point.y); + } + return found->second; + }; + struct place + { + glm::dvec3 position; + glm::dvec2 along; + double share; + int first; + int second; + TTrack const *track; + int path{0}; + std::size_t index{0}; + double length{0.0}; // m of the track it stands for, half a step at an end: a joint is shared by the tracks meeting at it + }; + std::vector all; + std::vector timber_all; // of all the tracks, the ones held apart too + std::unordered_set hump_nodes; + std::unordered_set stayed_nodes; + for (auto const *track : tracks) + { + auto const held{steep(*track)}; + for (auto const &path : track->m_paths) + { + auto const &start{path.points[segment_data::point::start]}; + auto const &end{path.points[segment_data::point::end]}; + auto const a{index_of(start)}; + auto const b{index_of(end)}; + auto const chord{geometry::plan_of(end - start)}; + auto const length{glm::length(chord)}; + if (a == b || length < 1e-3) + continue; + links[a].push_back({b, length, chord / length, rise_out(path, false)}); + links[b].push_back({a, length, -chord / length, rise_out(path, true)}); + // the joints of a switch keep its heights: a track ending there meets it + if (track->eType == tt_Switch) + { + heights[a] = start.y; + heights[b] = end.y; + } + if (held) + fixed[a] = fixed[b] = 1; + if (state.on_hump.contains(track)) + hump_nodes.insert({a, b}); + // what stays where it is holds its ends whatever comes up to them; nothing else moves it + if (state.stayed.contains(track)) + { + heights[a] = start.y; + heights[b] = end.y; + fixed[a] = fixed[b] = 1; + stayed_nodes.insert({a, b}); + } + geometry::bezier const curve{path}; + // no farther apart than the spacing: a track beside is looked for within 0.6 of it along, sparser places leave it unseen + auto const count{std::max(1, static_cast(std::ceil(length / kSpacing)))}; + for (int i = 0; i <= count; ++i) + { + auto const share{static_cast(i) / count}; + auto const tangent{geometry::plan_of(curve.first(share))}; + place const here{curve.point(share), glm::length(tangent) > 1e-9 ? glm::normalize(tangent) : chord / length, share, a, b, track, static_cast(&path - track->m_paths.data()), timber_all.size(), length / count * (i == 0 || i == count ? 0.5 : 1.0)}; + timber_all.push_back(here); + if (held) + continue; + all.push_back(here); + } + } + } + // the places in squares of a size, the ones around a place looked through for what's beside it + using cells = std::map>; + auto const cell_at = [](glm::dvec3 const &Point, double const Size) { return key{static_cast(std::floor(Point.x / Size)), static_cast(std::floor(Point.z / Size))}; }; + auto const cells_of = [&](std::vector const &Places, double const Size, auto const &Taken) { + cells result; + for (auto const &here : Places) + if (Taken(here)) + result[cell_at(here.position, Size)].push_back(&here); + return result; + }; + auto const around = [&](cells const &Cells, glm::dvec3 const &Point, double const Size, auto const &Each) { + auto const cell{cell_at(Point, Size)}; + for (int dx = -1; dx <= 1; ++dx) + for (int dz = -1; dz <= 1; ++dz) + if (auto const found{Cells.find({cell.first + dx, cell.second + dz})}; found != Cells.end()) + for (auto const *other : found->second) + Each(*other); + }; + auto const every = [](place const &) { return true; }; + auto const places{cells_of(all, kApart, every)}; + auto const timber_places{cells_of(timber_all, kApart, every)}; + std::vector terms; + auto const nodes{static_cast(links.size())}; + // a dead end holds firmer: nothing past it, the even moves would carry the tilt of the station on along the run as on a lever, the + // end of a line at the edge of the scenery going up by metres + double constexpr kDeadEnd{0.05}; // m + for (int i = 0; i < nodes; ++i) + terms.push_back({{i, -1, -1, -1}, {1.0, 0.0, 0.0, 0.0}, 0.0, fixed[i] != 0 ? 1e8 : links[i].size() == 1 ? 1.0 / (kDeadEnd * kDeadEnd) : 1.0 / (kKeep * kKeep)}); + for (int i = 0; i < nodes; ++i) + for (std::size_t a = 0; a < links[i].size(); ++a) + for (std::size_t b = a + 1; b < links[i].size(); ++b) + if (glm::dot(links[i][a].out, links[i][b].out) < -0.7) + { + auto const in{1.0 / links[i][a].length}; + auto const on{1.0 / links[i][b].length}; + // the grade the joint breaks by, of the paths at it, not of their chords: the chords of a curve on few paths break where + // the paths don't, and taking that out would break them + auto const change{links[i][b].rise + links[i][a].rise}; + // by the true lengths, an even move breaks no grade on a short track either; what a track under 0.5 m has of it goes by height, the numbers staying of a size + auto const scale{std::min(1.0, std::min(links[i][a].length, links[i][b].length) / 0.5)}; + terms.push_back({{links[i][b].to, i, links[i][a].to, -1}, {scale * on, -scale * (on + in), scale * in, 0.0}, std::abs(change) > kBroken ? -scale * change : 0.0, 1.0 / (kEven * kEven)}); + } + // the runs from switch to switch: plain tracks meeting at a joint nothing else meets at + std::vector> at_node(nodes); + for (auto const *track : tracks) + for (auto const &path : track->m_paths) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + at_node[indices.at(key_of(path.points[end]))].push_back(track); + joined_sets runs; + for (auto const &meeting : at_node) + if (meeting.size() == 2 && meeting[0] != meeting[1] && meeting[0]->eType == tt_Normal && meeting[1]->eType == tt_Normal) + runs.join(meeting[0], meeting[1]); + // who was put on a grade line by hand stays on it, with the others put on it wherever they lie, never on another one so put + grade_lines_load(); + std::unordered_map held; + for (auto const *track : tracks) + { + auto const key{grade_line_key(*track)}; + if (auto const found{state.grade_lines.find(key)}; found != state.grade_lines.end() && found->second >= 0 && state.grade_lines_hand.contains(key)) + held[track] = found->second; + } + // the nearest place of another track on each side of one, of those taken, under the reach from it: nearly parallel to it, on its + // level and across the track, not past its end - the next piece of a line isn't beside it + auto const nearest_of = [&](place const &Here, cells const &Cells, double const Reach, auto const &Taken) { + std::array, 2> sides{std::pair{Reach, nullptr}, std::pair{Reach, nullptr}}; + around(Cells, Here.position, Reach, [&](place const &Other) { + if (Other.track == Here.track || Other.first == Here.first || Other.first == Here.second || Other.second == Here.first || Other.second == Here.second || false == Taken(Other)) + return; + glm::dvec2 const offset{Other.position.x - Here.position.x, Other.position.z - Here.position.z}; + if (std::abs(glm::dot(offset, Here.along)) > 0.6 * kSpacing || std::abs(Other.position.y - Here.position.y) > kLevel || std::abs(glm::dot(Here.along, Other.along)) < kParallel) + return; + auto const across{Here.along.x * offset.y - Here.along.y * offset.x}; + auto &side{sides[across > 0.0 ? 0 : 1]}; + if (std::abs(across) < side.first) + side = {std::abs(across), &Other}; + }); + return sides; + }; + std::unordered_set apart; + // the nearest track on each side, of the ones not held apart + auto const nearest_sides = [&](place const &Here) { + return nearest_of(Here, places, kApart, [&](place const &Other) { return false == apart.contains(runs.root(Other.track)) || held.contains(Other.track); }); + }; + // two places side by side at one height: the joints of each move as the places lie between them + auto const side_by_side = [&](place const &Here, place const &Other) { + terms.push_back({{Here.first, Here.second, Other.first, Other.second}, {1.0 - Here.share, Here.share, -(1.0 - Other.share), -Other.share}, Other.position.y - Here.position.y, 1.0 / (kBeside * kBeside)}); + }; + // the run of a track named by a selftest: how long, the places of it with nothing beside, whether it went on its own and on which line + auto const explain = [&](char const *Stage) { + for (auto const *track : tracks) + { + if (std::string::npos == state.explain.find(" " + track->name() + " ")) + continue; + auto const *run{runs.root(track)}; + std::size_t members{0}; + auto length{0.0}; + for (auto const *other : tracks) + if (runs.root(other) == run) + { + ++members; + for (auto const &path : other->m_paths) + length += geometry::plan_distance(path.points[segment_data::point::start], path.points[segment_data::point::end]); + } + std::size_t lonely{0}; + std::string where; + for (auto const &here : all) + if (runs.root(here.track) == run && here.track->eType == tt_Normal) + if (auto const sides{nearest_sides(here)}; sides[0].second == nullptr && sides[1].second == nullptr) + { + ++lonely; + if (lonely <= 40) + where += format(" %s(%.0f,%.0f,%.2f)", here.track->name().c_str(), here.position.x, here.position.z, here.position.y); + } + auto const found{state.grade_lines.find(grade_line_key(*track))}; + WriteLog(format("Editor: NMT share, %s: %s in a run of %zu tracks over %.0f m from %s, apart %d, line %d, %zu places with nothing beside:%s", Stage, track->name().c_str(), members, length, + run->name().c_str(), apart.contains(run) ? 1 : 0, found != state.grade_lines.end() ? found->second : -100, lonely, where.c_str()), + logtype::generic); + } + }; + { + // a run beside the others nearly all along stays with them: the switches at its ends often lie a few tens of metres off theirs + double constexpr kAwayShare{0.25}; + std::unordered_map alone, whole; + for (auto const &here : all) + if (here.track->eType == tt_Normal) + { + whole[runs.root(here.track)] += here.length; + if (auto const sides{nearest_sides(here)}; sides[0].second == nullptr && sides[1].second == nullptr) + alone[runs.root(here.track)] += here.length; + } + explain("alone"); + for (auto const &[run, length] : alone) + if (length > kAway && length > kAwayShare * whole[run]) + apart.insert(run); + } + // who was taken off a grade line by hand stays off them + auto const taken_off = [&](TTrack const &Track) { + auto const found{state.grade_lines.find(grade_line_key(Track))}; + return found != state.grade_lines.end() && (found->second == nmt_state::grade_line_off || found->second <= nmt_state::grade_line_off_number); + }; + std::unordered_set off; + for (auto const *track : tracks) + if (taken_off(*track)) + { + off.insert(track); + apart.insert(runs.root(track)); + } + std::size_t pairs{0}; + // the tracks on one grade line together, as they're tied side by side and along the runs + joined_sets tied; + // of a group tied, the grade line one of it was put on by hand: two groups of two such lines don't tie + std::unordered_map tied_held(held.begin(), held.end()); + auto const held_of = [&](TTrack const *Root) { + auto const found{tied_held.find(Root)}; + return found != tied_held.end() ? found->second : -1; + }; + auto const tie = [&](TTrack const *A, TTrack const *B) { + auto const *a{tied.root(A)}; + auto const *b{tied.root(B)}; + if (a == b) + return true; + auto const of_a{held_of(a)}; + auto const of_b{held_of(b)}; + if (of_a >= 0 && of_b >= 0 && of_a != of_b) + return false; + tied.join_roots(a, b); + if (of_b < 0 && of_a >= 0) + tied_held[b] = of_a; + return true; + }; + { + std::unordered_map first; + for (auto const &[track, line] : held) + if (auto const [found, added]{first.try_emplace(line, track)}; false == added) + tie(track, found->second); + } + for (auto const &here : all) + { + auto const inapart{apart.contains(runs.root(here.track))}; + if (inapart && false == held.contains(here.track)) + continue; + for (auto const &[distance, other] : nearest_sides(here)) + if (other != nullptr) + { + if (false == tie(here.track, other->track)) + continue; + ++pairs; + if (false == inapart) + tie(here.track, runs.root(here.track)); + side_by_side(here, *other); + } + } + // the tracks put on one line by hand further apart than the ones side by side, across a platform say, go up and down together too: + // each place of them with the nearest place of another track of that line on each side + double constexpr kHandApart{40.0}; // m between the axes + std::size_t hand_pairs{0}; + if (false == held.empty()) + { + auto const held_places{cells_of(all, kHandApart, [&](place const &Here) { return held.contains(Here.track); })}; + for (auto const &[cell, those] : held_places) + for (auto const *here : those) + { + auto const line{held.at(here->track)}; + for (auto const &[distance, other] : nearest_of(*here, held_places, kHandApart, [&](place const &Other) { return held.at(Other.track) == line; })) + { + // the ones side by side are tied already + if (other == nullptr || distance < kApart) + continue; + ++hand_pairs; + side_by_side(*here, *other); + } + } + } + // the groups on common timbers: tracks and switches tied by the places under a sleeper's length apart, each group on a plane of its + // own, whose three numbers are worked out with the moves + std::size_t on_timbers{0}; + // of a plain track only the stretch under the timbers counts: a long one with switches at both ends doesn't make one group of them + double constexpr kStretch{40.0}; // m + using stretch = std::tuple; + auto const stretch_of = [&](place const &Here) { + auto const &points{Here.track->m_paths[Here.path].points}; + auto const along{Here.share * geometry::plan_distance(points[segment_data::point::start], points[segment_data::point::end])}; + return stretch{Here.track, Here.track->eType == tt_Switch ? 0 : Here.path, Here.track->eType == tt_Switch ? 0 : static_cast(along / kStretch)}; + }; + joined_sets> timbered; + std::vector on_surface(timber_all.size(), 0); + for (auto const &here : timber_all) + around(timber_places, here.position, kApart, [&](place const &Other) { + if (Other.track <= here.track || (here.track->eType != tt_Switch && Other.track->eType != tt_Switch)) + return; + glm::dvec2 const offset{Other.position.x - here.position.x, Other.position.z - here.position.z}; + if (glm::length(offset) >= kTimbers || std::abs(glm::dot(offset, here.along)) > 0.6 * kSpacing || std::abs(Other.position.y - here.position.y) > kLevel) + return; + ++on_timbers; + on_surface[here.index] = on_surface[Other.index] = 1; + timbered.join(stretch_of(here), stretch_of(Other)); + }); + state.surface_places.clear(); + std::map surfaces; + struct surface_sum + { + double count{0.0}; + glm::dvec3 sum{0.0}; + }; + std::vector sums; + for (auto const &here : timber_all) + if (on_surface[here.index] != 0) + { + auto const [found, added]{surfaces.try_emplace(timbered.root(stretch_of(here)), static_cast(sums.size()))}; + if (added) + sums.emplace_back(); + sums[found->second].count += 1.0; + sums[found->second].sum += here.position; + } + double constexpr kSurfaceScale{100.0}; // m, of the tilts worked out, for numbers of a size with the others + std::unordered_set timbered_tracks; + for (auto const &here : timber_all) + if (on_surface[here.index] != 0) + { + // a steep track holds its heights, but not against the timbers it shares; a hump gives way to them as little as they let it + double constexpr kHumpKeep{0.05}; // m + for (auto const node : {here.first, here.second}) + if (false == stayed_nodes.contains(node)) + terms[node].weight = 1.0 / (hump_nodes.contains(node) ? kHumpKeep * kHumpKeep : kKeep * kKeep); + timbered_tracks.insert(here.track); + auto const surface{surfaces.at(timbered.root(stretch_of(here)))}; + auto const middle{sums[surface].sum / sums[surface].count}; + auto const level{nodes + 3 * surface}; + terms.push_back({{here.first, here.second, level, level + 1, level + 2}, {1.0 - here.share, here.share, -1.0, -(here.position.x - middle.x) / kSurfaceScale, -(here.position.z - middle.z) / kSurfaceScale}, middle.y - here.position.y, 1.0 / (kOnTimbers * kOnTimbers)}); + state.surface_places.push_back({here.track, here.path, here.share, surface}); + } + for (std::size_t surface = 0; surface < sums.size(); ++surface) + for (int k = 0; k < 3; ++k) + terms.push_back({{nodes + 3 * static_cast(surface) + k, -1, -1, -1, -1}, {1.0, 0.0, 0.0, 0.0, 0.0}, 0.0, 1.0}); + auto const unknowns{nodes + 3 * static_cast(sums.size())}; + // the end of the second path of a switch on the plane of the first + for (auto const *track : tracks) + { + if (track->eType != tt_Switch || track->m_paths.size() < 2) + continue; + auto const &main{track->m_paths[0].points}; + auto const &branch{track->m_paths[1].points}; + auto const start{indices.at(key_of(main[segment_data::point::start]))}; + auto const finish{indices.at(key_of(main[segment_data::point::end]))}; + auto const tip{indices.at(key_of(branch[segment_data::point::end]))}; + auto const chord{geometry::plan_of(main[segment_data::point::end] - main[segment_data::point::start])}; + auto const square{glm::dot(chord, chord)}; + if (start == tip || finish == tip || start != indices.at(key_of(branch[segment_data::point::start])) || square < 1e-6) + continue; + auto const share{glm::dot(geometry::plan_of(branch[segment_data::point::end] - main[segment_data::point::start]), chord) / square}; + auto const off{heights[tip] - (heights[start] + share * (heights[finish] - heights[start]))}; + terms.push_back({{tip, start, finish, -1}, {1.0, -(1.0 - share), -share, 0.0}, -off, 1.0 / (kPlane * kPlane)}); + } + // who lies on which, for the map of them: a number of each grade line shared, those on their own and the ones held apart + state.grade_lines.clear(); + { + std::unordered_map numbers; + std::unordered_map sizes; + for (auto const &here : all) + if (false == apart.contains(runs.root(here.track)) && tied.joined(here.track)) + ++sizes[tied.root(here.track)]; + // the lines put by hand keep their numbers, the others worked out get ones besides them + std::set kept; + for (auto const &[track, line] : held) + kept.insert(line); + int next{0}; + for (auto const *track : tracks) + { + auto line{nmt_state::grade_line_own}; + if (off.contains(track)) + line = nmt_state::grade_line_off; + else if (auto const found{held.find(track)}; found != held.end()) + line = found->second; + else if (steep(*track)) + line = nmt_state::grade_line_steep; + else if (false == apart.contains(runs.root(track))) + { + // by the run: a track of it with nothing beside itself lies on the line the rest of the run does + auto const root{tied.root(runs.root(track))}; + if (auto const by_hand{held_of(root)}; by_hand >= 0) + line = by_hand; + else if (sizes.contains(root)) + { + auto const [number, added]{numbers.try_emplace(root, 0)}; + if (added) + { + while (kept.contains(next)) + ++next; + number->second = next++; + } + line = number->second; + } + } + state.grade_lines[grade_line_key(*track)] = line; + } + WriteLog(format("Editor: NMT - %zu grade lines shared, %zu of them put by hand, their tracks further apart tied at %zu places", numbers.size() + kept.size(), kept.size(), hand_pairs), logtype::generic); + explain("lines"); + ++state.grade_lines_changes; + grade_lines_store(); + } + // the least squares of all of it + int iterations{0}; + auto const moves{grade_moves(terms, unknowns, iterations)}; + // the joints of the runs of the tracks named by a selftest: the height before and the move, held or not + for (auto const *track : tracks) + if (std::string::npos != state.explain.find(" " + track->name() + " ")) + { + std::string joints; + for (auto const *other : tracks) + if (runs.root(other) == runs.root(track)) + for (auto const &path : other->m_paths) + { + auto const at{indices.at(key_of(path.points[segment_data::point::end]))}; + joints += format(" %s %.2f%+.2f%s", other->name().c_str(), heights[at], moves[at], fixed[at] != 0 ? " held" : ""); + } + WriteLog(format("Editor: NMT share, moved: %s, the ends of the run:%s", track->name().c_str(), joints.c_str()), logtype::generic); + } + // what the end moves by, with what it's off the others at its joint, the switch there first + auto const move_of = [&](glm::dvec3 const &Point) { + auto const at{indices.at(key_of(Point))}; + auto const off{heights[at] - Point.y}; + return moves[at] + (std::abs(off) <= 1.0 ? off : 0.0); + }; + editor_track::edit edit; + std::vector moved; + auto largest{0.0}; + TTrack const *largest_at{nullptr}; + double constexpr kTilted{0.005}; // how far the mean grade at the ends of a path may be from its grade from end to end + double constexpr kTiltedShortest{5.0}; // m, a shorter one tells little by the grades at its ends + std::size_t straightened{0}; + for (auto *track : tracks) + { + if (state.stayed.contains(track)) + continue; + auto changed{false}; + for (auto const &path : track->m_paths) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + { + if (std::abs(move_of(path.points[end])) > largest) + { + largest = std::abs(move_of(path.points[end])); + largest_at = track; + } + changed = changed || std::abs(move_of(path.points[end])) >= kMoved; + } + if (false == changed) + continue; + edit.capture(*track); + moved.push_back(track); + // a switch on common timbers lies straight between its ends, no vertical curve taking it off their surface; the other paths where + // the grades at their ends, which average to the grade from end to end on a vertical curve, are far from it: the ends were brought + // to the tracks adjoining with the grades left as they were, and the path waves between them + auto const settle = [&](segment_data &Part) { + auto &points{Part.points}; + if (points[segment_data::point::control1] == glm::dvec3{} && points[segment_data::point::control2] == glm::dvec3{}) + return; + auto const span{geometry::plan_of(points[segment_data::point::end] - points[segment_data::point::start])}; + auto const rise{points[segment_data::point::end].y - points[segment_data::point::start].y}; + auto const tilted = [&] { + auto const length{glm::length(span)}; + auto const before{glm::length(geometry::plan_of(points[segment_data::point::control1]))}; + auto const after{glm::length(geometry::plan_of(points[segment_data::point::control2]))}; + if (length < kTiltedShortest || before < 1e-3 || after < 1e-3) + return false; + return std::abs((points[segment_data::point::control1].y / before - points[segment_data::point::control2].y / after) * 0.5 - rise / length) > kTilted; + }; + if (track->eType == tt_Switch ? timbered_tracks.contains(track) : tilted()) + { + auto const grade{rise / std::max(1e-9, glm::dot(span, span))}; + points[segment_data::point::control1].y = grade * glm::dot(geometry::plan_of(points[segment_data::point::control1]), span); + points[segment_data::point::control2].y = grade * glm::dot(geometry::plan_of(points[segment_data::point::control2]), span); + straightened += track->eType == tt_Switch ? 0 : 1; + } + }; + for (auto &path : track->m_paths) + move_path_heights(path, move_of(path.points[segment_data::point::start]), move_of(path.points[segment_data::point::end]), settle); + } + // a switch lies straight, but a change of grade that needs a curve isn't left bare at its joints: it goes on a vertical curve over the + // whole of the switch, the ends of the paths taking the grades of the tracks going on from them and staying where they are + double constexpr kBare{0.002}; // the change of grade which needs a vertical curve + double constexpr kCrest{2000.0}; // m, the sharpest convex curve a switch may lie on + std::vector> leaving_at(nodes); + for (auto const *track : tracks) + for (auto const &path : track->m_paths) + { + leaving_at[indices.at(key_of(path.points[segment_data::point::start]))].push_back(leaving_of(track, path, false)); + leaving_at[indices.at(key_of(path.points[segment_data::point::end]))].push_back(leaving_of(track, path, true)); + } + // the grade the end of a path of a switch is to rise out of the joint with, two switches meeting sharing the difference, and how much + // the grade breaks there now + struct onward + { + double grade; + double broken; + }; + auto const going_on = [&](TTrack const *Track, segment_data const &Path, bool const Atend) -> std::optional { + auto const own{leaving_of(Track, Path, Atend)}; + leaving const *best{nullptr}; + for (auto const &other : leaving_at[indices.at(key_of(Path.points[Atend ? segment_data::point::end : segment_data::point::start]))]) + if (other.track != Track && glm::dot(own.way, other.way) < -0.9 && (best == nullptr || glm::dot(own.way, other.way) < glm::dot(own.way, best->way))) + best = &other; + if (best == nullptr) + return std::nullopt; + return onward{best->track->eType == tt_Switch && false == state.stayed.contains(best->track) ? (own.grade - best->grade) * 0.5 : -best->grade, std::abs(own.grade + best->grade)}; + }; + std::size_t curved{0}; + for (auto *track : tracks) + { + if (track->eType != tt_Switch || state.stayed.contains(track) || track->m_paths.empty()) + continue; + auto const before{going_on(track, track->m_paths.front(), false)}; + auto bare{before && before->broken > kBare}; + std::vector> after; + for (auto const &path : track->m_paths) + { + after.push_back(going_on(track, path, true)); + bare = bare || (after.back() && after.back()->broken > kBare); + } + if (false == bare) + continue; + edit.capture(*track); + if (std::find(moved.begin(), moved.end(), track) == moved.end()) + moved.push_back(track); + ++curved; + std::optional blades; // the paths leave the blades with one grade, the first path tells it + for (std::size_t i = 0; i < track->m_paths.size(); ++i) + { + auto &path{track->m_paths[i]}; + auto const length{glm::length(geometry::plan_of(path.points[segment_data::point::end] - path.points[segment_data::point::start]))}; + if (length < 1e-3) + continue; + auto const chord{(path.points[segment_data::point::end].y - path.points[segment_data::point::start].y) / length}; + // the grades along the path; an end with no track going on from it makes the curve even + auto first{before ? before->grade : after[i] ? 2.0 * chord + after[i]->grade : chord}; + auto last{after[i] ? -after[i]->grade : before ? 2.0 * chord - before->grade : chord}; + auto const least_bare = [&](double const Grade) { return Grade + std::clamp(chord - Grade, -kBare, kBare); }; + if (blades) + { + // from the grade at the blades one bend reaches only so far by the far end + first = *blades; + auto const a{-2.0 * (first - chord)}; + auto const b{-0.5 * (first - chord)}; + auto const bent{chord + std::clamp(last - chord, std::min(a, b), std::max(a, b))}; + last = std::abs(bent - last) <= kBare ? bent : least_bare(last); + } + else + { + auto const bend_first{(6.0 * chord - 4.0 * first - 2.0 * last) / length}; + auto const bend_last{(-6.0 * chord + 2.0 * first + 4.0 * last) / length}; + // the ends can't be met by one bend: only what a curve is needed for is taken off them, the rest stays at the joints + if (bend_first * bend_last < 0.0 || std::min(bend_first, bend_last) < -1.0 / kCrest) + { + first = least_bare(first); + last = least_bare(last); + } + blades = first; + } + on_vertical_curve(path, first, last); + } + } + WriteLog(format("Editor: NMT - one grade line for tracks under %.1f m apart: %zu runs of tracks on their own, %zu places side by side, %zu on common timbers in %zu groups, %d joints, %d iterations, %zu tracks moved, by %.2f m at most (%s), %zu paths straightened, %zu switches on a vertical curve", kApart, apart.size(), pairs, on_timbers, sums.size(), nodes, iterations, moved.size(), largest, largest_at != nullptr ? largest_at->name().c_str() : "-", straightened, curved), logtype::generic); + if (moved.empty()) + return; + profile_library_load(); + auto library{m_profiles}; + editor_track::commit(moved); + push_track_snapshot(std::move(edit.states), {}); + fitted_set(moved); + // the designs of the lines fitted one by one go with the tracks they moved + auto const [refitted, failed]{profile_refit_stored({moved.begin(), moved.end()})}; + if (refitted > 0) + profiles_to_history(std::move(library)); + WriteLog(format("Editor: NMT - %zu designs laid anew onto the tracks moved, %zu left as they were", refitted, failed), logtype::generic); +} + +void editor_mode::nmt_auto_step() +{ + auto &state{m_nmt_state}; + if (state.stage == nmt_state::automatic::fetching) + { + bool all{true}; + for (auto const &place : state.probes) + all = nmt_ready(glm::dvec2{place.position.x, place.position.z} - glm::dvec2{1.0}, glm::dvec2{place.position.x, place.position.z} + glm::dvec2{1.0}) && all; + auto const waiting{m_nmt.waiting()}; + state.status = format(STR_P("Fetching the terrain model under the tracks: %zu square left", "Fetching the terrain model under the tracks: %zu squares left", waiting), waiting); + if (false == all) + return; + // the scenery stays at its own heights, the terrain model meets it: offset by how far the tracks lie from it, so the lines + // fitted one after another meet at heights near their own; the grade lines then follow the model so offset + // the places of the tracks fitted already, the last ones, apart + std::vector differences, kept; + auto const first_kept{state.probes.size() - std::min(state.probes_kept, state.probes.size())}; + for (std::size_t i = 0; i < state.probes.size(); ++i) + if (double height; m_nmt.height(state.probes[i].position.x, state.probes[i].position.z, height)) + (i < first_kept ? differences : kept).push_back(height - state.probes[i].crown); + if (differences.empty()) + { + state.stage = nmt_state::automatic::idle; + state.status = STR("The terrain model has no data under the tracks: is the scenery placed where it is?"); + return; + } + std::nth_element(differences.begin(), differences.begin() + differences.size() / 2, differences.end()); + auto const lift{differences[differences.size() / 2]}; + if (state.unfitted && false == kept.empty()) + { + // the tracks fitted already stay where they are, and the model keeps the offset they were fitted to, told by them + std::nth_element(kept.begin(), kept.begin() + kept.size() / 2, kept.end()); + auto const offset{-kept[kept.size() / 2]}; + if (std::abs(offset - state.offset) > 0.05) + state.offset = offset; + WriteLog(format("Editor: NMT - the tracks fitted already lie on the terrain model offset %+.2f m, kept; the ones not fitted yet lie %+.2f m against it", state.offset, -lift - state.offset), logtype::generic); + } + else + { + // the offset of the run before kept where the tracks fitted to it lie within 5 cm of it: they don't creep a centimetre a run + auto const offset{std::abs(lift) > 0.05 ? -lift : 0.0}; + if (std::abs(offset - state.offset) > 0.05) + state.offset = offset; + WriteLog(format("Editor: NMT - the terrain model offset %+.2f m to the scenery", state.offset), logtype::generic); + } + state.fitted = true; + nmt_join_ends(); + state.levelled = nmt_level_turntables(); + // the longest tracks first: the main lines lead, the sidings join them + state.left.clear(); + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && rail(*track) && track->eType != tt_Table && false == nmt_stays(*track)) + state.left.push_back(track); + std::sort(state.left.begin(), state.left.end(), [](TTrack *Left, TTrack *Right) { return Left->Length() > Right->Length(); }); + state.tracks = state.left.size(); + state.split = 0; + state.done.clear(); + // the tracks fitted before are lines fitted already: the new ones run up to them and meet them as they are + state.stayed.clear(); + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && rail(*track) && nmt_stays(*track)) + { + state.done.push_back(track); + state.stayed.insert(track); + } + state.laid.clear(); + state.bridged.clear(); + state.on_hump.clear(); + // every path sampled as laid, for the crossings of the lines + state.paths.clear(); + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && rail(*track)) + nmt_sample_paths(*track, state.paths); + state.stage = nmt_state::automatic::fitting; + return; + } + // a few lines a frame: the longest track next to the lines fitted already, so that a line meets the ones it leads into as + // it's fitted, not when the lines between them come; the longest of all where none is next to them + for (int line = 0; line < 2 && false == state.left.empty(); ++line) + { + std::unordered_set const fitted(state.done.begin(), state.done.end()); + auto const touches = [&](TTrack *Track) { + for (int path = 0; path < static_cast(Track->m_paths.size()); ++path) + for (auto const forward : {true, false}) + { + auto const onward{editor_track::continuations({Track, path, forward})}; + if (std::any_of(onward.begin(), onward.end(), [&](editor_track::continuation const &Next) { return fitted.contains(Next.span.track); })) + return true; + if (auto const loose{state.loose.find({Track, path, forward})}; loose != state.loose.end() && fitted.contains(std::get<0>(loose->second))) + return true; + } + return false; + }; + auto const next{std::find_if(state.left.begin(), state.left.end(), touches)}; + if (next != state.left.end()) + std::rotate(state.left.begin(), next, next + 1); + auto *track{state.left.front()}; + auto const name{track->name()}; + auto const known{simulation::Paths.sequence().size()}; + if (nmt_fit_line(*track, [&](TTrack const *Other) { return fitted.contains(Other); }, false)) + ++state.lines; + else + ++state.refused; + // the tracks of the line are done, whether it went or not; so is every path made meanwhile, split off by the grade line or + // by the lines following it over the crossovers: the next line over them would lay them again, and split them again + std::set done{track}; + state.done.push_back(track); + for (auto const &span : m_profile.route.spans) + if (done.insert(span.track).second) + state.done.push_back(span.track); + auto const &sequence{simulation::Paths.sequence()}; + std::string made; + for (auto i{known}; i < sequence.size(); ++i) + if (auto *piece{sequence[i]}; piece != nullptr && done.insert(piece).second) + { + state.done.push_back(piece); + if (made.size() < 300) + made += ' ' + piece->name(); + } + auto const added{sequence.size() - known}; + state.split += added; + if (added > 20) + WriteLog(format("Editor: NMT line %s made %zu paths:%s", name.c_str(), added, made.c_str()), logtype::generic); + if (state.split > state.tracks / 2 + 200) + { + // something lays the same tracks over and over: stopped before it takes all the memory + state.left.clear(); + state.error = format(STR_P("Stopped: the grade lines split off %zu path from %zu tracks, more than they should; Ctrl+Z takes the changes back", "Stopped: the grade lines split off %zu paths from %zu tracks, more than they should; Ctrl+Z takes the changes back", state.split), state.split, state.tracks); + WriteLog("Editor: NMT - " + state.error, logtype::generic); + break; + } + state.left.erase(std::remove_if(state.left.begin(), state.left.end(), [&](TTrack *Track) { return done.contains(Track); }), state.left.end()); + } + state.status = format(STR_C("Terrain model offset %+.2f m to the scenery; grade lines fitted to the terrain: %zu, refused by the checks: %zu, tracks left: %zu"), state.offset, state.lines, state.refused, state.left.size()); + if (state.departures > 0) + state.status += format(STR_P("\n%zu line parts from the terrain model by over 0.5 m: the model or the track is off there, the terrain follows the tracks (the log names it)", "\n%zu lines part from the terrain model by over 0.5 m: the model or the track is off there, the terrain follows the tracks (the log names them)", state.departures), state.departures); + if (state.levelled > 0) + state.status += format(STR_P("\n%zu turntable set level at the height of the tracks running up to it, which reach it level", "\n%zu turntables set level at the height of the tracks running up to them, which reach them level", state.levelled), state.levelled); + if (false == state.left.empty()) + return; + state.result = true; + // the last line fitted isn't left in the profile, its tracks may be gone: the profile opens on what's selected + m_profile.open = false; + m_profile.route = {}; + m_profile.samples.clear(); + m_profile.followed.clear(); + nmt_share_grades(); + state.done.clear(); + state.laid.clear(); + state.paths.clear(); + state.loose.clear(); + state.turntables.clear(); + state.stage = nmt_state::automatic::idle; + WriteLog("Editor: NMT - " + state.status, logtype::generic); + nmt_make(nmt_keys_along_tracks(), true); +} diff --git a/application/editormodeparallel.cpp b/application/editormodeparallel.cpp new file mode 100644 index 000000000..28861b93f --- /dev/null +++ b/application/editormodeparallel.cpp @@ -0,0 +1,505 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormodeparallel.h" +#include "application/editorprojection.h" +#include "application/editormodeshared.h" +#include "editor/editorFormat.hpp" +#include "editor/editorGeometry.hpp" + +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "world/Track.h" + +#include "imgui/imgui.h" +#include "utilities/translation.h" +#include +#include +#include + +namespace +{ + +using geometry::bezier; +using geometry::cross; +using geometry::plan_of; +using geometry::signed_angle; + +double const kParallelReach{5000.0}; // m each way along the line +double const kSpacings[] = {3.5, 4.0, 4.5, 4.75, 5.0, 6.0}; + +// the side of the new track as a picture: three rows, the new track on the left of the line, the line with its direction, +// the new track on the right; the side chosen drawn with the spacing marked, the other faint. a click on a row chooses its side +bool side_picker(int &Side, double const Spacing) +{ + auto const font{ImGui::GetFontSize()}; + auto const width{ImGui::GetContentRegionAvail().x}; + auto const row{std::round(font * 1.7f)}; + auto const height{row * 3.0f}; + auto const top{ImGui::GetCursorScreenPos()}; + ImGui::InvisibleButton("##side", ImVec2(width, height)); + auto const hovered{ImGui::IsItemHovered()}; + auto const mouse{ImGui::GetIO().MousePos}; + auto const middle{std::round(top.y + row * 1.5f)}; + auto const pointed{hovered ? (mouse.y < top.y + row ? -1 : mouse.y >= top.y + row * 2.0f ? 1 : 0) : 0}; + bool changed{false}; + if (ImGui::IsItemClicked() && pointed != 0 && pointed != Side) + { + Side = pointed; + changed = true; + } + auto *list{ImGui::GetWindowDrawList()}; + ImVec2 const bottom{top.x + width, top.y + height}; + auto const rounding{std::round(font * 0.35f)}; + list->AddRectFilled(top, bottom, ImGui::GetColorU32(ImGuiCol_FrameBg), rounding); + if (pointed != 0 && pointed != Side) + list->AddRectFilled(ImVec2(top.x, pointed < 0 ? top.y : top.y + row * 2.0f), ImVec2(bottom.x, pointed < 0 ? top.y + row : bottom.y), ImGui::GetColorU32(ImGuiCol_FrameBgHovered), rounding); + auto const pad{std::round(font * 0.6f)}; + char const *const labels[]{STR_C("Left"), STR_C("selected"), STR_C("Right")}; + float column{0.0f}; + for (auto const *label : labels) + column = std::max(column, ImGui::CalcTextSize(label).x); + auto const left{top.x + pad + column + pad}; + auto const right{bottom.x - pad * 2.0f}; + auto const gauge{std::round(font * 0.36f)}; + // a track as two rails, sleepers under the solid ones + auto const track = [&](float const Y, ImU32 const Colour, bool const Dashed) { + // the sleepers a whole number of pixels apart, never less than one + auto const sleeper{std::max(1.0f, std::round(font * 0.9f))}; + if (false == Dashed) + for (int k = 0; left + font * 0.3f + sleeper * static_cast(k) < right; ++k) + { + auto const x{left + font * 0.3f + sleeper * static_cast(k)}; + list->AddLine(ImVec2(x, Y - gauge * 0.95f), ImVec2(x, Y + gauge * 0.95f), (Colour & ~IM_COL32_A_MASK) | IM_COL32(0, 0, 0, 90), 2.0f); + } + for (auto const rail : {Y - gauge * 0.5f, Y + gauge * 0.5f}) + { + if (false == Dashed) + { + list->AddLine(ImVec2(left, rail), ImVec2(right, rail), Colour, 1.5f); + continue; + } + for (int k = 0; left + font * static_cast(k) < right; ++k) + { + auto const x{left + font * static_cast(k)}; + list->AddLine(ImVec2(x, rail), ImVec2(std::min(right, x + font * 0.55f), rail), Colour, 1.0f); + } + } + }; + auto const line{ImGui::GetColorU32(ImGuiCol_Text, 0.85f)}; + track(middle, line, false); + auto const arrow{std::round(font * 0.45f)}; + list->AddTriangleFilled(ImVec2(right + pad * 1.2f, middle), ImVec2(right + pad * 0.2f - arrow * 0.4f, middle - arrow), ImVec2(right + pad * 0.2f - arrow * 0.4f, middle + arrow), line); + auto const label_at = [&](int const Row, char const *Label, bool const Lit) { + auto const size{ImGui::CalcTextSize(Label)}; + list->AddText(ImVec2(top.x + pad + column - size.x, std::round(top.y + row * (Row + 0.5f) - size.y * 0.5f)), ImGui::GetColorU32(Lit ? ImGuiCol_Text : ImGuiCol_TextDisabled), Label); + }; + label_at(1, labels[1], false); + auto const accent{family_colour(0)}; + for (auto const side : {-1, 1}) + { + auto const y{middle + side * row}; + auto const chosen{side == Side}; + track(y, chosen ? accent : ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.6f), false == chosen); + label_at(side < 0 ? 0 : 2, labels[side < 0 ? 0 : 2], chosen); + if (false == chosen) + continue; + // the spacing, axis to axis + auto const x{std::round(left + (right - left) * 0.62f)}; + ImU32 const dimension{IM_COL32(255, 210, 60, 255)}; + list->AddLine(ImVec2(x, middle), ImVec2(x, y), dimension, 1.5f); + list->AddTriangleFilled(ImVec2(x, middle), ImVec2(x - 3.0f, middle + side * 6.0f), ImVec2(x + 3.0f, middle + side * 6.0f), dimension); + list->AddTriangleFilled(ImVec2(x, y), ImVec2(x - 3.0f, y - side * 6.0f), ImVec2(x + 3.0f, y - side * 6.0f), dimension); + char text[32]; + std::snprintf(text, sizeof(text), "%.2f m", Spacing); + auto const size{ImGui::CalcTextSize(text)}; + ImVec2 const at{x + 6.0f, std::round((middle + y) * 0.5f - size.y * 0.5f)}; + list->AddRectFilled(ImVec2(at.x - 3.0f, at.y), ImVec2(at.x + size.x + 3.0f, at.y + size.y), ImGui::GetColorU32(ImGuiCol_FrameBg), 3.0f); + list->AddText(at, dimension, text); + } + if (hovered) + ImGui::SetTooltip("%s", pointed != 0 && pointed != Side ? STR_C("A click: the new track on this side") : STR_C("Left and right as seen along the line, the way the arrow points")); + return changed; +} + +segment_data reversed(segment_data const &Path) +{ + segment_data result{Path}; + result.points[segment_data::point::start] = Path.points[segment_data::point::end]; + result.points[segment_data::point::end] = Path.points[segment_data::point::start]; + result.points[segment_data::point::control1] = Path.points[segment_data::point::control2]; + result.points[segment_data::point::control2] = Path.points[segment_data::point::control1]; + result.rolls = {-Path.rolls[1], -Path.rolls[0]}; + return result; +} + +// the control vectors as they're drawn, also for a straight given without them +std::pair controls(segment_data const &Path) +{ + auto const &start{Path.points[segment_data::point::start]}; + auto const &end{Path.points[segment_data::point::end]}; + auto const &control1{Path.points[segment_data::point::control1]}; + auto const &control2{Path.points[segment_data::point::control2]}; + if (control1 == glm::dvec3{} && control2 == glm::dvec3{}) + return {(end - start) / 3.0, (start - end) / 3.0}; + return {control1, control2}; +} + +// curvature in the plan at the start (false) or the end (true) of the path, 1/m, positive turning left +double curvature(segment_data const &Path, bool const Atend) +{ + auto const [control1, control2] = controls(Path); + auto const p0{plan_of(Path.points[segment_data::point::start])}; + auto const p3{plan_of(Path.points[segment_data::point::end])}; + auto const p1{p0 + plan_of(control1)}; + auto const p2{p3 + plan_of(control2)}; + auto const first{Atend ? 3.0 * (p3 - p2) : 3.0 * (p1 - p0)}; + auto const second{Atend ? 6.0 * (p1 - 2.0 * p2 + p3) : 6.0 * (p0 - 2.0 * p1 + p2)}; + auto const speed{glm::length(first)}; + return speed > 1e-9 ? cross(first, second) / (speed * speed * speed) : 0.0; +} + +std::optional arc_curvature(segment_data const &Path) +{ + auto const [control1, control2] = controls(Path); + auto const along{plan_of(control1)}; + auto const back{-plan_of(control2)}; + if (glm::length(along) < 1e-9 || glm::length(back) < 1e-9) + return std::nullopt; + auto const turn{signed_angle(glm::normalize(along), glm::normalize(back))}; + if (std::abs(turn) < 1e-6) + return std::nullopt; + auto const radius{glm::length(plan_of(Path.points[segment_data::point::end] - Path.points[segment_data::point::start])) / (2.0 * std::sin(std::abs(turn) * 0.5))}; + auto const control{4.0 / 3.0 * std::tan(std::abs(turn) * 0.25) * radius}; + if (std::abs(glm::length(along) - control) > 1e-4 * control || std::abs(glm::length(back) - control) > 1e-4 * control) + return std::nullopt; + return std::copysign(1.0 / radius, turn); +} + +glm::dvec2 direction(segment_data const &Path, bool const Atend) +{ + auto const [control1, control2] = controls(Path); + auto const along{Atend ? -plan_of(control2) : plan_of(control1)}; + return glm::length(along) > 1e-9 ? glm::normalize(along) : glm::dvec2{0.0, 1.0}; +} + +glm::dvec3 midpoint(TTrack const &Track) +{ + if (Track.m_paths.empty()) + return Track.location(); + bezier const curve{Track.m_paths.front()}; + return curve.point(0.5); +} + +// signed offset of Dst from Src, along Src's left normal; positive is the Left radio +double lateral_of(TTrack const &Src, TTrack const &Dst) +{ + if (Src.m_paths.empty()) + return 0.0; + auto const heading{direction(Src.m_paths.front(), false)}; + glm::dvec2 const left{-heading.y, heading.x}; + return glm::dot(plan_of(midpoint(Dst)) - plan_of(Src.m_paths.front().points[segment_data::point::start]), left); +} + +} // namespace + +TTrack *parallel_tool::parallel_source() const +{ + auto const &set{m_selection.track_set()}; + if (set.size() >= 2) + return set.front(); + return m_selection.selected_track(); +} + +TTrack *parallel_tool::parallel_target() const +{ + auto const &set{m_selection.track_set()}; + if (set.size() != 2) + return nullptr; + return set.back() != set.front() ? set.back() : nullptr; +} + +void parallel_tool::parallel_update() +{ + auto &tool{m_parallel}; + auto *track{parallel_source()}; + auto *target{parallel_target()}; + if (track != tool.pair_src || target != tool.pair_dst) + { + tool.pair_src = track; + tool.pair_dst = target; + if (track != nullptr && target != nullptr) + { + auto const lateral{lateral_of(*track, *target)}; + tool.side = lateral >= 0.0 ? 1 : -1; + tool.measured = std::abs(lateral); + } + else + tool.measured = 0.0; + } + else if (track != nullptr && target != nullptr) + tool.measured = std::abs(lateral_of(*track, *target)); + + if (track == tool.built_for && tool.spacing == tool.built_spacing && tool.side == tool.built_side && tool.scope == tool.built_scope && m_history.history_revision() == tool.built_history) + return; + tool.built_for = track; + tool.built_spacing = tool.spacing; + tool.built_side = tool.side; + tool.built_scope = tool.scope; + tool.built_history = m_history.history_revision(); + tool.pieces.clear(); + tool.styles.clear(); + tool.length = 0.0; + tool.error.clear(); + if (track == nullptr) + return; + if (track->eType != tt_Normal || false == editor_track::is_supported(*track)) + { + tool.error = STR_C("A switch has no line of its own: select a plain path"); + return; + } + std::vector> sources; + if (tool.scope == 1) + { + editor_track::chain run; + std::string error; + if (editor_track::find_run(*track, kParallelReach, run, error)) + for (std::size_t i = 0; i < run.tracks.size(); ++i) + sources.emplace_back(run.tracks[i], run.forward[i] ? run.tracks[i]->m_paths.front() : reversed(run.tracks[i]->m_paths.front())); + } + if (sources.empty()) + sources.emplace_back(track, track->m_paths.front()); + auto const offset{tool.spacing * tool.side}; + // the joints are moved once, along the mean direction of the paths meeting there, so the new paths meet too + std::vector joints; + for (std::size_t k = 0; k <= sources.size(); ++k) + { + bool const first{k == 0}; + bool const last{k == sources.size()}; + auto const &before{sources[last ? k - 1 : (first ? 0 : k - 1)].second}; + auto const &after{sources[last ? k - 1 : k].second}; + auto const point{first ? after.points[segment_data::point::start] : before.points[segment_data::point::end]}; + glm::dvec2 heading{first ? direction(after, false) : last ? direction(before, true) : direction(before, true) + direction(after, false)}; + heading = glm::length(heading) > 1e-9 ? glm::normalize(heading) : glm::dvec2{0.0, 1.0}; + auto const roll{first ? after.rolls[0] : last ? before.rolls[1] : 0.5f * (before.rolls[1] + after.rolls[0])}; + glm::dvec2 const left{-heading.y, heading.x}; + auto const planar{plan_of(point) + left * offset}; + joints.emplace_back(planar.x, point.y - offset * std::tan(glm::radians(static_cast(roll))), planar.y); + } + for (std::size_t i = 0; i < sources.size(); ++i) + { + auto const &source{sources[i].second}; + auto const [control1, control2] = controls(source); + auto const arc{arc_curvature(source)}; + auto const startscale{1.0 - (arc.has_value() ? *arc : curvature(source, false)) * offset}; + auto const endscale{1.0 - (arc.has_value() ? *arc : curvature(source, true)) * offset}; + if (startscale < 0.05 || endscale < 0.05) + { + tool.pieces.clear(); + tool.styles.clear(); + tool.error = format(STR_C("The spacing is larger than the radius of %s"), sources[i].first->name().c_str()); + return; + } + segment_data piece; + piece.points[segment_data::point::start] = joints[i]; + piece.points[segment_data::point::end] = joints[i + 1]; + piece.points[segment_data::point::control1] = control1 * startscale; + piece.points[segment_data::point::control2] = control2 * endscale; + piece.rolls = source.rolls; + auto const middle{0.5 * (curvature(source, false) + curvature(source, true))}; + if (source.radius != 0.0f && std::abs(middle) > 1e-7) + piece.radius = static_cast(std::copysign(std::abs(std::abs(static_cast(source.radius)) - std::copysign(offset, middle)), static_cast(source.radius))); + tool.length += bezier{piece}.plan_length(); + tool.pieces.push_back(piece); + tool.styles.push_back(sources[i].first); + } +} + +void parallel_tool::parallel_build() +{ + auto &tool{m_parallel}; + parallel_update(); + if (tool.pieces.empty()) + return; + std::vector created; + for (std::size_t i = 0; i < tool.pieces.size(); ++i) + created.push_back(editor_track::create_path(*tool.styles[i], tool.pieces[i])); + editor_track::commit(created); + m_design.digitize_drawn(created); + m_history.push_track_snapshot({}, created); + tool.status = format(STR_C("Parallel track of %zu paths, %.1f m, %.2f m away; Ctrl+Z takes it back"), created.size(), tool.length, tool.spacing); + if (scene::Layers.active() == null_handle) + tool.status += "\n" + std::string{STR_C("The scenery isn't opened for editing, the new track won't be saved")}; + WriteLog("Editor: " + tool.status, logtype::generic); + tool.built_for = nullptr; +} + +void parallel_tool::parallel_apply() +{ + auto &tool{m_parallel}; + auto *target{parallel_target()}; + parallel_update(); + if (target == nullptr || tool.pieces.empty()) + return; + if (tool.pieces.size() != 1) + { + tool.error = STR_C("Two selected paths: set the scope to this path, so the other takes its shape at the spacing"); + return; + } + std::string reason; + if (false == editor_track::can_edit_geometry(*target, reason)) + { + tool.error = reason; + return; + } + auto const joints{editor_track::joints(*target)}; + std::vector> states; + auto const remember = [&](TTrack *Track) { + if (Track == nullptr) + return; + if (std::any_of(states.begin(), states.end(), [&](auto const &Entry) { return Entry.first == Track; })) + return; + states.emplace_back(Track, editor_track::capture(*Track)); + }; + remember(target); + for (auto const &joint : joints) + remember(joint.other); + target->m_paths.front() = tool.pieces.front(); + editor_track::follow(*target, joints); + std::vector committed{target}; + for (auto const &joint : joints) + if (joint.other != nullptr) + committed.push_back(joint.other); + editor_track::commit(committed); + m_history.push_track_snapshot(std::move(states)); + tool.status = format(STR_C("%s set parallel to %s, %.2f m away; Ctrl+Z takes it back"), name_of(*target).c_str(), name_of(*parallel_source()).c_str(), tool.spacing); + WriteLog("Editor: " + tool.status, logtype::generic); + tool.built_for = nullptr; + m_design.straight_refresh(); +} + +void parallel_tool::render_parallel_controls(bool const Scope) +{ + auto &tool{m_parallel}; + if (Scope) + segmented("scope", tool.scope, {{0, STR_C("This path"), "Only beside the selected path"}, {1, STR_C("The line, up to the switches"), "Beside the whole line of the selected path, up to the switches: its curves go along with R minus or plus the spacing"}}); + side_picker(tool.side, tool.spacing); + ImGui::SetNextItemWidth(std::round(ImGui::GetFontSize() * 6.0f)); + ImGui::InputDouble("##spacing", &tool.spacing, 0.0, 0.0, STR_C("%.2f m")); + item_tooltip("Spacing of the axes of the tracks; the usual ones beside it"); + tool.spacing = std::clamp(tool.spacing, 1.5, 100.0); + ImGui::SameLine(); + value_chips("spacings", tool.spacing, {kSpacings[0], kSpacings[1], kSpacings[2], kSpacings[3], kSpacings[4], kSpacings[5]}, "%.2f"); +} + +void parallel_tool::render_options() +{ + auto &tool{m_parallel}; + ImGui::PushTextWrapPos(0.0f); + if (parallel_target() != nullptr) + ImGui::TextDisabled("%s", STR_C("Two tracks selected: set the spacing of the other in the Select tool")); + else if (parallel_source() == nullptr) + ImGui::TextColored(ImVec4(1.0f, 0.8f, 0.3f, 1.0f), "%s", STR_C("Click a track in the view: the new one goes beside it.")); + ImGui::PopTextWrapPos(); + render_parallel_controls(); + parallel_update(); + if (false == tool.error.empty()) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", tool.error.c_str()); + ImGui::PopTextWrapPos(); + } + else if (false == tool.pieces.empty()) + { + if (main_button(format(STR_P("Lay %zu track, %.1f m", "Lay %zu tracks, %.1f m", static_cast(tool.pieces.size())), tool.pieces.size(), tool.length).c_str(), ImVec2(-1.0f, tall_button_height()))) + parallel_build(); + item_tooltip("A new track beside the one selected, as in the preview; the selected stays as it is. Ctrl+Z takes it back"); + } + if (false == tool.status.empty()) + ImGui::TextWrapped("%s", tool.status.c_str()); +} + +void parallel_tool::render_set_options() +{ + auto &tool{m_parallel}; + auto *source{parallel_source()}; + auto *target{parallel_target()}; + if (source == nullptr || target == nullptr) + return; + if (false == ImGui::CollapsingHeader(STR_C("Make parallel"), ImGuiTreeNodeFlags_DefaultOpen)) + return; + ImGui::TextWrapped("%s", STR_C("The first selected track must be a straight")); + ImGui::TextWrapped("%s", format(STR_C("%s stays, %s moves to this spacing with its curves"), name_of(*source).c_str(), name_of(*target).c_str()).c_str()); + if (tool.measured > 0.05) + ImGui::TextDisabled("%s", format(lateral_of(*source, *target) >= 0.0 ? STR_C("Now %.2f m on the right") : STR_C("Now %.2f m on the left"), tool.measured).c_str()); + tool.scope = 0; + render_parallel_controls(false); + parallel_update(); + if (false == tool.error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", tool.error.c_str()); + else if (false == tool.pieces.empty() && ImGui::Button(format(STR_C("Set %s to %.2f m"), name_of(*target).c_str(), tool.spacing).c_str())) + parallel_apply(); + if (false == tool.status.empty()) + ImGui::TextWrapped("%s", tool.status.c_str()); +} + +bool parallel_tool::parallel_preview_visible() const +{ + if (m_parallel.pieces.empty() || parallel_source() != m_parallel.built_for) + return false; + if (m_view.current_track_tab() == editor_track_tab::parallel) + return true; + return m_view.current_track_tab() == editor_track_tab::path && parallel_target() != nullptr; +} + +void parallel_tool::draw_overlay() const +{ + if (false == parallel_preview_visible()) + return; + auto const &tool{m_parallel}; + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + for (auto const &piece : tool.pieces) + { + bezier const curve{piece}; + auto const count{std::clamp(static_cast(curve.plan_length() / 2.0), 4, 128)}; + auto previous{curve.point(0.0)}; + for (int k = 1; k <= count; ++k) + { + auto const next{curve.point(static_cast(k) / count)}; + projection.line(drawlist, previous, next, k % 2 ? IM_COL32(90, 255, 120, 230) : IM_COL32(90, 255, 120, 90), 3.0f); + previous = next; + } + } + ImVec2 screen; + if (projection.project(tool.pieces.front().points[segment_data::point::start], screen)) + { + drawlist->AddCircleFilled(screen, 5.0f, IM_COL32(90, 255, 120, 230)); + auto const label{format("%.2f m", tool.spacing)}; + auto const size{ImGui::CalcTextSize(label.c_str())}; + drawlist->AddRectFilled(ImVec2(screen.x + 8.0f, screen.y - 8.0f), ImVec2(screen.x + 16.0f + size.x, screen.y + 8.0f), IM_COL32(0, 0, 0, 180), 3.0f); + drawlist->AddText(ImVec2(screen.x + 12.0f, screen.y - 8.0f), IM_COL32(90, 255, 120, 255), label.c_str()); + } +} + +editor_selftest_result parallel_tool::selftest(std::string const &Command, std::istringstream &Words) +{ + if (Command == "parallel") + { + Words >> m_parallel.spacing >> m_parallel.side; + m_parallel.scope = 1; + m_parallel.built_for = nullptr; + parallel_build(); + WriteLog("SELFTEST parallel: " + m_parallel.status + " " + m_parallel.error); + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} diff --git a/application/editormodeparallel.h b/application/editormodeparallel.h new file mode 100644 index 000000000..d10ef41b2 --- /dev/null +++ b/application/editormodeparallel.h @@ -0,0 +1,61 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "application/editortool.h" + +#include +#include + +// second track alongside the selected path or the line through it, at a spacing, curves included +class parallel_tool final : public editor_tool +{ + public: + parallel_tool(editor_selection &Selection, editor_view &View, editor_history &History, editor_track_design &Design) : m_selection{Selection}, m_view{View}, m_history{History}, m_design{Design} {} + void draw_overlay() const override; + void render_options() override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + tool_tab &tab() { return m_tab; } + void render_set_options(); + + private: + editor_selection &m_selection; + editor_view &m_view; + editor_history &m_history; + editor_track_design &m_design; + tool_tab m_tab; + struct parallel_state + { + double spacing{4.0}; + int side{1}; // 1: to the right, -1: to the left, of the direction of the line + int scope{1}; // 0: the selected path, 1: the line through it, up to the switches + TTrack *built_for{nullptr}; + double built_spacing{0.0}; + int built_side{0}; + int built_scope{-1}; + std::size_t built_history{0}; + TTrack *pair_src{nullptr}; + TTrack *pair_dst{nullptr}; + double measured{0.0}; + std::vector pieces; + std::vector styles; + double length{0.0}; + std::string error; + std::string status; + }; + parallel_state m_parallel; + TTrack *parallel_source() const; + TTrack *parallel_target() const; + void parallel_update(); + void render_parallel_controls(bool const Scope = true); + void parallel_build(); + void parallel_apply(); + bool parallel_preview_visible() const; +}; diff --git a/application/editormodeprofile.cpp b/application/editormodeprofile.cpp new file mode 100644 index 000000000..2b7956f97 --- /dev/null +++ b/application/editormodeprofile.cpp @@ -0,0 +1,3195 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editorprojection.h" +#include "application/editorgestures.h" +#include "application/editormodeshared.h" +#include "application/editoruilayer.h" +#include "editor/editorFormat.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorSwitchStore.hpp" + +#include "world/Track.h" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "utilities/Globals.h" +#include "utilities/glmHelpers.h" +#include "world/TrackSleepers.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" + +#include "imgui/imgui.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using geometry::plan_distance; + +ImU32 const kGradeLine{IM_COL32(90, 230, 110, 255)}; +ImU32 const kTangents{IM_COL32(255, 210, 60, 130)}; +ImU32 const kTrack{IM_COL32(190, 190, 190, 255)}; +ImU32 const kTerrain{IM_COL32(170, 120, 70, 255)}; +ImU32 const kFormation{IM_COL32(215, 185, 140, 200)}; +ImU32 const kModel{IM_COL32(70, 200, 190, 230)}; // the ground of the terrain model, as measured +double constexpr kNoBed{0.05}; // m, a trackbed shallower is none +// a design the track lay on when it was kept, within kApplied, was applied; where the track parts from it by more than kStale since, +// it was changed by other tools, and the line is read from the track there, over the stretch and kStaleMargin around it +double constexpr kApplied{0.01}; +double constexpr kStale{0.02}; +double constexpr kStaleMargin{15.0}; +double constexpr kDesignOff{0.25}; // m, of a line put together or read that says little of the track +ImU32 const kGrid{IM_COL32(255, 255, 255, 22)}; +ImU32 const kLabel{IM_COL32(200, 200, 200, 200)}; +ImU32 const kSwitch{IM_COL32(160, 100, 220, 45)}; +ImU32 const kError{IM_COL32(255, 80, 70, 255)}; +ImU32 const kWarning{IM_COL32(255, 200, 60, 255)}; +ImU32 const kPlan{IM_COL32(120, 190, 255, 255)}; +ImU32 const kSwitchLabel{IM_COL32(200, 160, 255, 220)}; +ImU32 const kShared{IM_COL32(160, 100, 220, 110)}; // hatching, the colour of the switches +ImU32 const kSharedEdge{IM_COL32(200, 160, 255, 220)}; +ImU32 const kChip{IM_COL32(14, 15, 19, 210)}; + +// text on a dark plate, readable over the lines of the plot +void plot_label(ImDrawList &Draw, ImVec2 const At, ImU32 const Colour, std::string const &Text) +{ + auto const size{ImGui::CalcTextSize(Text.c_str())}; + Draw.AddRectFilled(ImVec2(At.x - 3.0f, At.y - 1.0f), ImVec2(At.x + size.x + 3.0f, At.y + size.y + 1.0f), kChip, 3.0f); + Draw.AddText(At, Colour, Text.c_str()); +} + +double nice_step(double const Approximate) +{ + auto const power{std::pow(10.0, std::floor(std::log10(std::max(Approximate, 1e-6))))}; + for (auto const factor : {1.0, 2.0, 5.0, 10.0}) + if (power * factor >= Approximate) + return power * factor; + return power * 10.0; +} + +std::string const kProfileMark{"//$p"}; +std::string const kFittedMark{"//$t"}; + +profile::line reversed_line(profile::line Line, double const Length) +{ + std::reverse(Line.points.begin(), Line.points.end()); + for (auto &point : Line.points) + point.chainage = Length - point.chainage; + std::swap(Line.join_start, Line.join_end); + return Line; +} + +bool end_locked(profile::line const &Line, profile::context const &Context, int const Index) +{ + if (Index == 0) + return Line.join_start && Context.start_joined; + if (Index + 1 == static_cast(Line.points.size())) + return Line.join_end && Context.end_joined; + return false; +} + +// an error of the line where the edit changes nothing holds nothing up: a long route read from the track has some, fitted to the terrain +// model at last, and a change elsewhere on it doesn't make them worse +bool errors_in_change(std::vector const &Issues, profile::line const &Line, profile::line const &Read, std::vector const &Samples) +{ + double constexpr kAround{60.0}; // m on both sides of the error + for (auto const &issue : Issues) + { + if (false == issue.error) + continue; + if (Samples.empty()) + return true; + for (auto const &sample : Samples) + if (std::abs(sample.chainage - issue.chainage) <= kAround && std::abs(profile::elevation(Line, sample.chainage) - profile::elevation(Read, sample.chainage)) > kStale) + { + WriteLog(format("Editor: vertical profile - held up at %.1f m, the line changed by %.3f m there: %s", sample.chainage, profile::elevation(Line, sample.chainage) - profile::elevation(Read, sample.chainage), issue.text.c_str()), logtype::generic); + return true; + } + } + return false; +} + +bool has_errors(std::vector const &Issues) +{ + return std::any_of(Issues.begin(), Issues.end(), [](profile::issue const &Issue) { return Issue.error; }); +} + +// the chainage of the point on the route sampled, projected onto the stretch between the samples; false off the route +bool sampled_chainage(std::vector const &Samples, glm::dvec3 const &Point, double &Chainage) +{ + double best{0.3}; + bool found{false}; + for (std::size_t i = 0; i + 1 < Samples.size(); ++i) + { + glm::dvec2 const a{Samples[i].position.x, Samples[i].position.z}; + glm::dvec2 const b{Samples[i + 1].position.x, Samples[i + 1].position.z}; + glm::dvec2 const p{Point.x, Point.z}; + auto const run{b - a}; + auto const t{std::clamp(glm::dot(p - a, run) / std::max(1e-12, glm::dot(run, run)), 0.0, 1.0)}; + if (auto const distance{glm::length(p - (a + run * t))}; distance < best) + { + best = distance; + Chainage = Samples[i].chainage + (Samples[i + 1].chainage - Samples[i].chainage) * t; + found = true; + } + } + return found; +} + +} + +// format of the lines, coordinates in the space of the file: +// profile +// speed origin join +// norms = k*V^2> +// point +// end +void editor_mode::profile_library_load() +{ + if (m_profiles_loaded) + return; + m_profiles_loaded = true; + m_profiles.clear(); + for (auto const layer : scene::Layers.marked_layers(kProfileMark)) + { + auto const &context{scene::Layers.layer(layer).context_insert()}; + auto const height = [&](double const Local) { return context.to_world({0.0, Local, 0.0}).y; }; + std::optional current; + for (auto const &text : scene::Layers.marked(layer, kProfileMark)) + { + std::istringstream line{text}; + std::string keyword; + line >> keyword; + if (keyword == "profile") + { + stored_profile entry; + entry.layer = layer; + glm::dvec3 start; + glm::dvec3 end; + glm::dvec3 middle; + line >> entry.length >> start.x >> start.y >> start.z >> end.x >> end.y >> end.z >> middle.x >> middle.y >> middle.z; + if (line.fail()) + { + current.reset(); + continue; + } + entry.start = context.to_world(start); + entry.end = context.to_world(end); + entry.middle = context.to_world(middle); + current = entry; + continue; + } + if (false == current.has_value()) + continue; + auto &entry{*current}; + std::string word; + if (keyword == "speed") + { + int start{1}; + int end{1}; + line >> entry.line.speed >> word >> entry.origin >> word >> start >> end; + entry.line.join_start = (start != 0); + entry.line.join_end = (end != 0); + } + else if (keyword == "norms") + { + auto &norms{entry.line.norms}; + line >> norms.grade_max >> norms.grade_switch_max >> norms.radius_factor >> norms.radius_min >> norms.curve_threshold >> norms.element_min >> norms.fixed_tolerance; + } + else if (keyword == "departure") + line >> entry.departure; + else if (keyword == "point") + { + profile::pvi point; + int automatic{0}; + line >> point.chainage >> point.elevation >> point.radius >> automatic; + if (line.fail()) + continue; + point.elevation = height(point.elevation); + point.automatic = (automatic != 0); + entry.line.points.push_back(point); + } + else if (keyword == "end") + { + if (entry.line.points.size() >= 2 && entry.length > 0.0) + m_profiles.push_back(entry); + current.reset(); + } + } + } + if (false == m_profiles.empty()) + WriteLog("Editor: " + std::to_string(m_profiles.size()) + " vertical profile design(s) read from the scenery", logtype::generic); +} + +void editor_mode::profile_library_mark(std::vector Layers) +{ + std::sort(Layers.begin(), Layers.end()); + Layers.erase(std::unique(Layers.begin(), Layers.end()), Layers.end()); + for (auto const layer : Layers) + { + if (false == scene::Layers.valid(layer)) + continue; + auto const &context{scene::Layers.layer(layer).context_insert()}; + auto const local = [&](glm::dvec3 const &Point) { + auto const point{context.to_local(Point)}; + return format("%.4f %.4f %.4f", point.x, point.y, point.z); + }; + std::vector lines; + for (auto const &entry : m_profiles) + { + if (entry.layer != layer) + continue; + if (lines.empty()) + lines.emplace_back("# vertical profiles (grade lines) designed in the track editor, the simulation skips these lines"); + lines.push_back(format("profile %.4f ", entry.length) + local(entry.start) + ' ' + local(entry.end) + ' ' + local(entry.middle)); + lines.push_back(format("speed %.1f origin %.4f join %d %d", entry.line.speed, entry.origin, entry.line.join_start ? 1 : 0, entry.line.join_end ? 1 : 0)); + auto const &norms{entry.line.norms}; + lines.push_back(format("norms %.4f %.4f %.4f %.1f %.4f %.2f %.4f", norms.grade_max, norms.grade_switch_max, norms.radius_factor, norms.radius_min, norms.curve_threshold, norms.element_min, norms.fixed_tolerance)); + if (entry.departure >= 0.0) + lines.push_back(format("departure %.4f", entry.departure)); + for (auto const &point : entry.line.points) + lines.push_back(format("point %.4f %.4f %.1f %d", point.chainage, context.to_local({0.0, point.elevation, 0.0}).y, point.radius, point.automatic ? 1 : 0)); + lines.emplace_back("end"); + } + scene::Layers.mark(layer, kProfileMark, std::move(lines)); + } +} + +void editor_mode::profiles_to_history(std::vector Library) +{ + if (m_history.empty() || m_history.back().action != EditorSnapshot::Action::TrackEdit || m_history.back().profiles) + return; + m_history.back().profiles = true; + m_history.back().profile_library = std::move(Library); +} + +void editor_mode::profiles_restore(std::vector Library) +{ + std::vector layers; + for (auto const *library : {&std::as_const(m_profiles), &std::as_const(Library)}) + for (auto const &entry : *library) + layers.push_back(entry.layer); + m_profiles = std::move(Library); + profile_library_mark(std::move(layers)); +} + +std::uint64_t editor_mode::fitted_shape(TTrack const &Track) +{ + // the points of the paths to a centimetre: what's read back from the files is the same shape + std::uint64_t hash{1469598103934665603ull}; + auto const add = [&](std::int64_t const Value) { + for (int i = 0; i < 8; ++i) + hash = (hash ^ static_cast((Value >> (8 * i)) & 0xff)) * 1099511628211ull; + }; + for (auto const &path : Track.m_paths) + for (auto const &point : path.points) + for (int axis = 0; axis < 3; ++axis) + // through the precision of the files first: what's read back from one has the shape it had when it was written + add(std::llround(std::round(point[axis] * 10000.0) / 100.0)); + return hash; +} + +void editor_mode::fitted_load() +{ + if (m_fitted_loaded) + return; + m_fitted_loaded = true; + m_fitted.clear(); + for (auto const layer : scene::Layers.marked_layers(kFittedMark)) + for (auto const &text : scene::Layers.marked(layer, kFittedMark)) + { + std::istringstream line{text}; + std::string keyword, name, shape, kind; + line >> keyword >> name >> shape; + if (keyword == "fitted" && false == line.fail()) + { + line >> kind; + auto const value{std::strtoull(shape.c_str(), nullptr, 16)}; + m_fitted[{name, value}] = {layer, value, kind == "hand"}; + } + } +} + +void editor_mode::fitted_set(std::vector const &Tracks, bool const Hand) +{ + fitted_load(); + std::vector layers; + for (auto const *track : Tracks) + { + if (track == nullptr || track->m_editorremoved || track->name().empty()) + continue; + scene::layer_handle layer{null_handle}; + if (false == scene::Layers.empty()) + { + layer = scene::Layers.resolve(track->layer()); + if (false == scene::Layers.valid(layer) || false == scene::Layers.accepts(layer)) + layer = scene::Layers.active(); + } + // a mark of the name in another layer leaves it when it's written again + for (auto found{m_fitted.lower_bound({track->name(), 0})}; found != m_fitted.end() && found->first.first == track->name(); ++found) + if (found->second.layer != layer) + layers.push_back(found->second.layer); + auto const shape{fitted_shape(*track)}; + m_fitted[{track->name(), shape}] = {layer, shape, Hand}; + layers.push_back(layer); + } + if (scene::Layers.empty()) + return; + std::sort(layers.begin(), layers.end()); + layers.erase(std::unique(layers.begin(), layers.end()), layers.end()); + // the marks of the tracks there are no more, or changed since, aren't written again + std::set> standing; + for (auto const *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && false == track->name().empty()) + standing.emplace(track->name(), fitted_shape(*track)); + for (auto const layer : layers) + { + if (false == scene::Layers.valid(layer)) + continue; + std::vector lines; + for (auto const &[key, mark] : m_fitted) + { + if (mark.layer != layer || false == standing.contains(key)) + continue; + if (lines.empty()) + lines.emplace_back("# the tracks whose grade line was fitted in the track editor, with their shape then; the simulation skips these lines"); + lines.push_back(format("fitted %s %016llx%s", key.first.c_str(), static_cast(mark.shape), mark.hand ? " hand" : "")); + } + scene::Layers.mark(layer, kFittedMark, std::move(lines)); + } +} + +bool editor_mode::grade_hand(TTrack const &Track) +{ + fitted_load(); + auto const found{m_fitted.find({Track.name(), fitted_shape(Track)})}; + return found != m_fitted.end() && found->second.hand; +} + +bool editor_mode::grade_fitted(TTrack const &Track) +{ + fitted_load(); + return m_fitted.contains({Track.name(), fitted_shape(Track)}); +} + +int editor_mode::profile_find(bool &Reversed) const +{ + auto const &state{m_profile}; + Reversed = false; + if (state.samples.empty()) + return -1; + auto const start{state.samples.front().position}; + auto const end{state.samples.back().position}; + auto const middle{editor_track::sampled_position(state.samples, state.route.length * 0.5)}; + for (std::size_t i = 0; i < m_profiles.size(); ++i) + { + auto const &entry{m_profiles[i]}; + if (std::abs(entry.length - state.route.length) > 0.5 || plan_distance(entry.middle, middle) > 0.5) + continue; + if (plan_distance(entry.start, start) <= 0.1 && plan_distance(entry.end, end) <= 0.1) + return static_cast(i); + if (plan_distance(entry.start, end) <= 0.1 && plan_distance(entry.end, start) <= 0.1) + { + Reversed = true; + return static_cast(i); + } + } + return -1; +} + +bool editor_mode::profile_restore() +{ + profile_library_load(); + auto &state{m_profile}; + bool reversed; + auto const index{profile_find(reversed)}; + if (index < 0) + return profile_restore_parts(); + auto const &entry{m_profiles[index]}; + state.line = reversed ? reversed_line(entry.line, entry.length) : entry.line; + state.origin = entry.origin; + state.selected = -1; + state.changed = false; + profile_check(); + if (entry.departure >= 0.0 && entry.departure <= kApplied && state.departure > kStale) + return profile_restore_parts(); + state.status = format(STR_C("Design read from the scenery file %s, largest departure from the track %.3f m"), scene::Layers.layer(entry.layer).name.c_str(), state.departure); + return true; +} + +// the designs kept for routes lying along this one, as the lines the tracks were fitted with one by one: their points carried +// over to the chainage of this route, straight between them where none lies, as over a switch none of them runs through +bool editor_mode::profile_restore_parts() +{ + auto &state{m_profile}; + auto const &samples{state.samples}; + if (samples.size() < 2) + return false; + auto const locate = [&](glm::dvec3 const &Point, double &Chainage) { return sampled_chainage(samples, Point, Chainage); }; + auto const length{state.route.length}; + // the direction of the route at the chainage, in the plan + auto const heading = [&](double const Chainage) { + auto const a{editor_track::sampled_position(samples, std::max(0.0, Chainage - 1.0))}; + auto const b{editor_track::sampled_position(samples, std::min(length, Chainage + 1.0))}; + return glm::dvec2{b.x - a.x, b.z - a.z}; + }; + std::vector points; + std::size_t parts{0}; + std::size_t retaken{0}; + // the ends of this route inside a kept design take their heights from it + std::optional start, end; + // the newer designs first: where two lie over the same stretch, the one kept later is the one meant + std::vector> covered; + auto const taken = [&](double const Chainage) { return std::any_of(covered.begin(), covered.end(), [&](auto const &Stretch) { return Chainage > Stretch.first + 0.25 && Chainage < Stretch.second - 0.25; }); }; + for (auto entries{m_profiles.rbegin()}; entries != m_profiles.rend(); ++entries) + { + auto const &entry{*entries}; + // the design laid over this route at least in part: one of its ends on it, the route running on towards the other + double a{0.0}, b{0.0}; + auto const first{locate(entry.start, a)}; + auto const last{locate(entry.end, b)}; + if (false == first && false == last) + continue; + double origin, direction; + double scale{1.0}; + if (first && last) + { + // the route between the ends of the design got longer or shorter, as when a track of it was moved: the points go along + scale = std::abs(b - a) / std::max(1.0, entry.length); + if (scale < 0.8 || scale > 1.25) + continue; + direction = b >= a ? 1.0 : -1.0; + origin = a; + } + else + { + auto const anchor{first ? a : b}; + auto const towards{first ? entry.end - entry.start : entry.start - entry.end}; + auto const along{glm::dot(heading(anchor), glm::dvec2{towards.x, towards.z})}; + if (std::abs(along) < 1e-9) + continue; + // the chainage of the design grows along the route or against it + direction = (along > 0.0) == first ? 1.0 : -1.0; + origin = first ? a : b - direction * entry.length; + } + auto const local = [&](double const Chainage) { return (Chainage - origin) * direction / scale; }; + // the stretch of this route over the paths of the design, from where it meets it: off it, as past the switch where this + // route turns away, the design says nothing + auto const extent_low{std::min(origin, origin + direction * entry.length * scale)}; + auto const extent_high{std::max(origin, origin + direction * entry.length * scale)}; + auto low{extent_low}; + auto high{extent_high}; + if (auto const own{profile_stored_route(entry)}) + { + std::set> paths; + for (auto const &span : own->spans) + paths.emplace(span.track, span.path); + auto const &spans{state.route.spans}; + auto const on = [&](std::size_t const Index) { return paths.count({spans[Index].track, spans[Index].path}) > 0; }; + auto const anchor{first ? a : b}; + std::optional at; + for (std::size_t i = 0; i < spans.size(); ++i) + if (on(i) && anchor >= spans[i].from - 0.3 && anchor <= spans[i].to + 0.3) + { + at = i; + break; + } + if (false == at.has_value()) + continue; + auto left{*at}; + auto right{*at}; + while (left > 0 && on(left - 1)) + --left; + while (right + 1 < spans.size() && on(right + 1)) + ++right; + low = std::max(low, spans[left].from); + high = std::min(high, spans[right].to); + } + auto const inside = [&](double const Chainage) { return Chainage > 0.25 && Chainage < length - 0.25 && Chainage >= low - 0.25 && Chainage <= high + 0.25; }; + // where the track was changed since the design was applied to it, by the gizmo or by dragging its points, the track holds: + // the design gives way there to the line read from the track + std::vector> stale; + if (entry.departure >= 0.0 && entry.departure <= kApplied) + { + for (auto const &sample : samples) + { + if (sample.chainage < low - 0.25 || sample.chainage > high + 0.25) + continue; + auto const designed{profile::elevation(entry.line, std::clamp(local(sample.chainage), 0.0, entry.length))}; + if (std::abs(designed - sample.position.y) <= kStale) + continue; + if (false == stale.empty() && sample.chainage - stale.back().second <= kStaleMargin) + stale.back().second = sample.chainage; + else + stale.emplace_back(sample.chainage, sample.chainage); + } + for (auto &stretch : stale) + { + stretch.first = std::max(low, stretch.first - kStaleMargin); + stretch.second = std::min(high, stretch.second + kStaleMargin); + } + } + auto const changed = [&](double const Chainage) { return std::any_of(stale.begin(), stale.end(), [&](auto const &Stretch) { return Chainage >= Stretch.first - 0.25 && Chainage <= Stretch.second + 0.25; }); }; + for (auto point : entry.line.points) + { + point.chainage = origin + direction * point.chainage * scale; + point.joint = false; + if (inside(point.chainage) && false == taken(point.chainage) && false == changed(point.chainage)) + points.push_back(point); + } + for (auto const &stretch : stale) + { + std::vector chainages, elevations, grades; + for (auto const &sample : samples) + if (sample.chainage >= stretch.first - 1e-6 && sample.chainage <= stretch.second + 1e-6) + { + chainages.push_back(sample.chainage); + elevations.push_back(sample.position.y); + grades.push_back(sample.grade); + } + if (chainages.size() < 2) + continue; + profile::recognition options; + options.minimum_length = 5.0; + options.detail = kStale; + for (auto point : profile::recognize(chainages, elevations, grades, options).points) + { + point.joint = false; + if (point.chainage >= 0.0 && point.chainage <= length && false == taken(point.chainage)) + points.push_back(point); + } + ++retaken; + } + // where this route turns off the design, its height there: between two designs the line goes straight, over the switches. + // where it runs on past the end of the design, onto track laid since, the break gets the vertical curve of the limits + for (auto const edge : {low, high}) + if (edge > 0.5 && edge < length - 0.5 && false == taken(edge) && false == changed(edge)) + { + profile::pvi point; + point.chainage = edge; + point.elevation = profile::elevation(entry.line, std::clamp(local(edge), 0.0, entry.length)); + point.automatic = std::abs(edge - (edge == low ? extent_low : extent_high)) < 0.5; + points.push_back(point); + } + if (false == start.has_value() && false == changed(0.0) && local(0.0) >= -0.25 && local(0.0) <= entry.length + 0.25) + start = profile::elevation(entry.line, std::clamp(local(0.0), 0.0, entry.length)); + if (false == end.has_value() && false == changed(length) && local(length) >= -0.25 && local(length) <= entry.length + 0.25) + end = profile::elevation(entry.line, std::clamp(local(length), 0.0, entry.length)); + covered.emplace_back(low, high); + ++parts; + } + if (parts == 0) + return false; + std::sort(points.begin(), points.end(), [](auto const &Left, auto const &Right) { return Left.chainage < Right.chainage; }); + std::vector line; + for (auto point : points) + { + point.chainage = std::clamp(point.chainage, 0.0, length); + if (false == line.empty() && point.chainage - line.back().chainage < 0.5) + continue; + line.push_back(point); + } + if (line.empty() || line.front().chainage > 0.5) + line.insert(line.begin(), profile::pvi{0.0, start.value_or(samples.front().position.y)}); + else + line.front().chainage = 0.0; + if (line.back().chainage < length - 0.5) + line.push_back(profile::pvi{length, end.value_or(samples.back().position.y)}); + else + line.back().chainage = length; + line.front().radius = 0.0; + line.back().radius = 0.0; + state.line.points = std::move(line); + state.selected = -1; + state.changed = false; + profile_check(); + // designs that don't come together along the track, its heights changed since by more than they tell: the track is what stands + if (state.departure > kDesignOff) + { + profile_recognize(); + return true; + } + state.status = format(STR_C("Design put together from %zu designs kept for the routes along this one, largest departure from the track %.3f m"), parts, state.departure); + if (retaken > 0) + state.status += format(STR_C("; %zu stretches changed on the track since read from it again"), retaken); + return true; +} + +void editor_mode::profile_store() +{ + auto &state{m_profile}; + if (state.route.spans.empty() || state.samples.empty() || state.line.points.size() < 2) + return; + if (scene::Layers.empty()) + { + state.error = STR_C("The scenery wasn't opened for editing, the design can't be kept in its files"); + return; + } + profile_library_load(); + stored_profile entry; + entry.length = state.route.length; + entry.start = state.samples.front().position; + entry.end = state.samples.back().position; + entry.middle = editor_track::sampled_position(state.samples, state.route.length * 0.5); + entry.origin = state.origin; + entry.line = state.line; + entry.departure = state.departure; + // the joints are kept as points of their own: read back over a longer route, where the end is no longer joined, the line + // keeps the curve it was laid with + for (auto &point : entry.line.points) + if (point.joint) + { + point.joint = false; + point.automatic = false; + } + + // the designs of shorter routes this one runs all along are taken over by it: kept, they'd be put together with it again + std::vector layers; + for (auto i{m_profiles.size()}; i-- > 0;) + { + auto const &old{m_profiles[i]}; + double a{0.0}, b{0.0}; + if (old.length + 0.5 < entry.length && sampled_chainage(state.samples, old.start, a) && sampled_chainage(state.samples, old.end, b) && std::abs(std::abs(b - a) - old.length) <= 1.5) + { + layers.push_back(old.layer); + m_profiles.erase(m_profiles.begin() + static_cast(i)); + } + } + bool reversed; + auto const index{profile_find(reversed)}; + if (index >= 0) + { + entry.layer = m_profiles[index].layer; + m_profiles[index] = entry; + } + else + { + auto layer{scene::Layers.resolve(state.route.spans.front().track->layer())}; + if (false == scene::Layers.valid(layer) || false == scene::Layers.accepts(layer)) + layer = scene::Layers.active(); + if (false == scene::Layers.valid(layer)) + layer = 1; + entry.layer = layer; + m_profiles.push_back(entry); + } + layers.push_back(entry.layer); + profile_library_mark(layers); + state.changed = false; +} + +void editor_mode::profile_forget() +{ + auto &state{m_profile}; + profile_library_load(); + bool reversed; + auto const index{profile_find(reversed)}; + if (index < 0) + return; + auto const layer{m_profiles[index].layer}; + m_profiles.erase(m_profiles.begin() + index); + profile_library_mark({layer}); + state.status = format(STR_C("The design will be removed from %s on save"), scene::Layers.layer(layer).name.c_str()); +} + +std::optional editor_mode::profile_stored_route(stored_profile const &Entry, TTrack **From, TTrack **To) const +{ + auto const touching = [](glm::dvec3 const &Point) { + std::vector result; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || false == editor_track::is_supported(*track)) + continue; + for (auto const &path : track->m_paths) + for (auto const index : {segment_data::point::start, segment_data::point::end}) + if (plan_distance(path.points[index], Point) <= 0.1 && std::abs(path.points[index].y - Point.y) < 3.0) + { + if (std::find(result.begin(), result.end(), track) == result.end()) + result.push_back(track); + } + } + return result; + }; + for (auto *from : touching(Entry.start)) + for (auto *to : touching(Entry.end)) + { + // the route of the fewest paths, or where the design was laid along another, the one as long through its middle; the length of + // a route comes with its samples + auto const fits = [&](editor_track::route &Route) { + auto const samples{editor_track::sample_route(Route, 1.0)}; + return false == samples.empty() && std::abs(Route.length - Entry.length) <= 0.5 && plan_distance(samples.front().position, Entry.start) <= 0.1 && plan_distance(editor_track::sampled_position(samples, Route.length * 0.5), Entry.middle) <= 0.5; + }; + editor_track::route route; + std::string error; + if ((false == editor_track::find_route(from, to, route, error) || false == fits(route)) && (false == editor_track::find_route_along(from, to, Entry.length, Entry.middle, route) || false == fits(route))) + continue; + if (From != nullptr) + *From = from; + if (To != nullptr) + *To = to; + return route; + } + return std::nullopt; +} + +std::pair editor_mode::profile_refit_stored(std::unordered_set const &Moved) +{ + // the designs were applied to the tracks one line at a time, the grade lines shared moved the tracks after them: a design left as + // it was parts from them, and a profile opened over them reads the stretches changed from the track again, a polyline bending + // wherever it falls, on the switches too. Each is laid anew onto the tracks as they lie now, as a line is onto the ground, within a + // centimetre and to the norms; one which can't be without an error stays as it was + double constexpr kTolerance{0.01}; // m + double constexpr kReach{100.0}; // m, however far a track is, it's what the line keeps to + double constexpr kSteepest{50.0}; // per mille, as the lines are fitted to the terrain, past the limit of the norms + profile_library_load(); + auto &state{m_profile}; + auto const show_model{state.show_model}; + state.show_model = false; + std::size_t refitted{0}, failed{0}; + std::vector layers; + for (auto &entry : m_profiles) + { + auto route{profile_stored_route(entry)}; + if (false == route.has_value() || std::none_of(route->spans.begin(), route->spans.end(), [&](editor_track::route_span const &Span) { return Moved.contains(Span.track); })) + continue; + state.route = std::move(*route); + profile_resample(); + auto const &samples{state.samples}; + if (samples.size() < 2) + continue; + state.line = entry.line; + state.changed = false; + profile_check(); + if (state.departure <= kStale && false == has_errors(state.issues)) + continue; + auto const before{state.departure}; + // the tracks are no ground with structures to go past: the line keeps to all of them, as steep as they are, as sharply bent as + // on a hump the line was fitted to + std::vector chainages, heights; + for (auto const &sample : samples) + { + chainages.push_back(sample.chainage); + heights.push_back(sample.position.y); + } + std::vector const tolerances(samples.size(), kTolerance * 0.5); + std::vector const reaches(samples.size(), kReach); + profile::ground_fit options; + options.tolerance = kTolerance; + options.grade_max = kSteepest; + options.humps = profile::humps(chainages, heights, state.context, kTolerance); + options.hump_radius = 300.0; + auto line{profile::fit_ground(chainages, heights, state.context, entry.line, options, tolerances, reaches)}; + if (line.points.size() < 2) + continue; + state.line = std::move(line); + profile_check(); + if (has_errors(state.issues)) + { + ++failed; + std::string errors; + for (auto const &issue : state.issues) + if (issue.error) + errors += " | " + issue.text; + WriteLog(format("Editor: vertical profile - the design of %.0f m from %.1f %.1f, %.3f m off the tracks moved, can't be laid onto them anew without an error, it stays as it was%s", state.route.length, entry.start.x, entry.start.z, before, errors.c_str()), logtype::generic); + continue; + } + ++refitted; + entry.length = state.route.length; + entry.start = samples.front().position; + entry.end = samples.back().position; + entry.middle = editor_track::sampled_position(samples, state.route.length * 0.5); + entry.line = state.line; + entry.departure = state.departure; + for (auto &point : entry.line.points) + if (point.joint) + { + point.joint = false; + point.automatic = false; + } + layers.push_back(entry.layer); + } + state.show_model = show_model; + state.open = false; + state.route = {}; + state.samples.clear(); + if (false == layers.empty()) + profile_library_mark(std::move(layers)); + return {refitted, failed}; +} + +void editor_mode::profile_open_stored(std::size_t const Index) +{ + auto &state{m_profile}; + if (Index >= m_profiles.size()) + return; + auto const entry{m_profiles[Index]}; + TTrack *from{nullptr}; + TTrack *to{nullptr}; + // the route the design lies along, not the one of the fewest paths between its ends + if (auto route{profile_stored_route(entry, &from, &to)}) + { + state.open = true; + state.status.clear(); + state.error.clear(); + profile_take(std::move(*route), from, to); + return; + } + state.open = true; + state.error = STR_C("The route of the stored design isn't in the scenery any more (paths moved or removed)"); +} + +void editor_mode::profile_edited() +{ + m_profile.changed = true; + profile_check(); + first_step_done(first_step::profile_point); +} + +void editor_mode::profile_remove_point(int const Index) +{ + auto &state{m_profile}; + auto &points{state.line.points}; + if (Index <= 0 || Index + 1 >= static_cast(points.size())) + return; + points.erase(points.begin() + Index); + for (auto const neighbour : {Index - 1, Index}) + if (neighbour > 0 && neighbour + 1 < static_cast(points.size()) && false == points[neighbour].joint) + points[neighbour].automatic = true; + state.selected = -1; + profile_edited(); +} + +void editor_mode::profile_open(TTrack *From, TTrack *To) +{ + auto &state{m_profile}; + state.open = true; + state.status.clear(); + editor_track::route route; + if (false == editor_track::find_route(From, To, route, state.error)) + return; + profile_take(std::move(route), From, To); +} + +void editor_mode::profile_open_run(TTrack &Track) +{ + auto &state{m_profile}; + state.open = true; + state.status.clear(); + state.error.clear(); + auto route{editor_track::run_route(Track, state.run_length)}; + if (route.spans.empty()) + { + state.error = STR_C("The path can't carry a profile"); + return; + } + auto *from{route.spans.front().track}; + auto *to{route.spans.back().track}; + profile_take(std::move(route), from, to); +} + +// the route from one end of the selected tracks to the other: of the two of them farthest apart, through the switches between +void editor_mode::profile_open_selection(std::vector const &Tracks) +{ + auto const middle = [](TTrack const &Track) { return geometry::bezier{Track.m_paths.front()}.point(0.5); }; + TTrack *from{nullptr}; + TTrack *to{nullptr}; + double farthest{-1.0}; + for (std::size_t i = 0; i < Tracks.size(); ++i) + for (std::size_t j = i + 1; j < Tracks.size(); ++j) + if (auto const distance{plan_distance(middle(*Tracks[i]), middle(*Tracks[j]))}; distance > farthest) + { + farthest = distance; + from = Tracks[i]; + to = Tracks[j]; + } + if (from == nullptr || to == nullptr) + return; + profile_open(from, to); + auto &state{m_profile}; + if (state.route.spans.empty()) + return; + auto const off{std::count_if(Tracks.begin(), Tracks.end(), [&](TTrack const *Track) { + return std::none_of(state.route.spans.begin(), state.route.spans.end(), [&](editor_track::route_span const &Span) { return Span.track == Track; }); + })}; + if (off > 0) + state.status = format(STR_C("%d of the selected tracks are off the route from %s to %s"), static_cast(off), from->name().c_str(), to->name().c_str()); +} + +// the route follows the selection: one track gives its whole line unless it's on the route already, several give the route +// from one end of them to the other; the changes of the design left are kept for the save +void editor_mode::profile_follow_selection() +{ + auto &state{m_profile}; + auto const tracks{selected_tracks()}; + if (tracks == state.followed) + return; + state.followed = tracks; + if (tracks.empty()) + return; + auto const on_route{std::any_of(state.route.spans.begin(), state.route.spans.end(), [&](editor_track::route_span const &Span) { return Span.track == tracks.front(); })}; + if (tracks.size() == 1 && on_route) + return; + if (state.changed) + profile_store(); + if (tracks.size() == 1) + profile_open_run(*tracks.front()); + else + profile_open_selection(tracks); +} + +void editor_mode::profile_take(editor_track::route Route, TTrack *From, TTrack *To) +{ + auto &state{m_profile}; + state.picked_from = From; + state.from = state.picked_from; + state.picked_to = To; + state.to = state.picked_to; + state.route = std::move(Route); + state.selected = -1; + state.edits = m_track_edits; + first_step_done(first_step::profile); + profile_resample(); + if (false == profile_restore()) + { + profile_recognize(); + if (false == state.samples.empty()) + { + auto const km{alignment_store::chainage_at(state.samples.front().position)}; + auto const further{alignment_store::chainage_at(editor_track::sampled_position(state.samples, std::min(state.route.length, 5.0)))}; + if (km.has_value() && further.has_value() && *further > *km) + state.origin = *km; + } + } + profile_fit_view(); +} + +void editor_mode::profile_resample() +{ + auto &state{m_profile}; + state.samples = editor_track::sample_route(state.route, 1.0); + auto const &samples{state.samples}; + state.terrain.assign(samples.size(), std::numeric_limits::quiet_NaN()); + std::vector points; + points.reserve(samples.size()); + for (auto const &sample : samples) + points.push_back(sample.position); + std::vector found; + auto const heights{ground_heights(points, true, &found)}; + for (std::size_t i = 0; i < samples.size(); ++i) + if (found[i] != 0) + state.terrain[i] = heights[i]; + profile_sample_model(); + state.beds.assign(samples.size(), 0.0); + std::vector bedless(samples.size(), 0); + std::vector own; + for (std::size_t i = 0; i < samples.size(); ++i) + if (samples[i].span < state.route.spans.size()) + { + auto const &track{*state.route.spans[samples[i].span].track}; + state.beds[i] = profile_ballast(track).first; + bedless[i] = profile_own_bed(track) ? 0 : 1; + if (bedless[i] == 0) + own.push_back(state.beds[i]); + } + // a track with no trackbed of its own, as the switches of the older sceneries whose bed is an include, lies in the bed of + // the others + if (false == own.empty()) + { + std::nth_element(own.begin(), own.begin() + own.size() / 2, own.end()); + for (std::size_t i = 0; i < samples.size(); ++i) + if (bedless[i] != 0) + state.beds[i] = own[own.size() / 2]; + } + + auto &context{state.context}; + context = {}; + context.length = state.route.length; + if (samples.empty()) + return; + std::optional open; + for (auto const &span : state.route.spans) + { + if (auto const found{switch_store::named(*span.track)}) + { + if (open.has_value() && open->name == found->name && span.from - context.switches.back().to <= std::max(found->a + found->b, context.switches.back().to - context.switches.back().from)) + { + context.switches.back().to = span.to; + continue; + } + auto const label{switch_store::label(*found)}; + context.switches.push_back({span.from, span.to, found->number != "-" ? found->number + ' ' + label : label}); + open = found; + } + else if (span.track->eType != tt_Normal) + { + context.switches.push_back({span.from, span.to, span.track->name()}); + open.reset(); + } + } + // where the rails of the route lie on timbers shared with another track, at a switch, a crossover, a crossing, the grade + // doesn't break nor does a vertical curve reach: the timbers carry both tracks in one plane + { + auto const before{context.switches.size()}; + for (auto const &span : state.route.spans) + { + auto const length{span.track->eType == tt_Switch ? span.track->SwitchExtension->Segments[span.path]->GetLength() : span.track->Segment->GetLength()}; + if (length < 1e-6) + continue; + auto const scale{(span.to - span.from) / length}; + for (auto const &zone : track_sleepers::shared_zones(*span.track, span.path)) + { + auto const a{span.forward ? span.from + zone.first * scale : span.to - zone.second * scale}; + auto const b{span.forward ? span.from + zone.second * scale : span.to - zone.first * scale}; + // the stretches of a switch on the route are its own zone already + auto const inside{std::any_of(context.switches.begin(), context.switches.begin() + static_cast(before), [&](auto const &Zone) { return a >= Zone.from - 0.5 && b <= Zone.to + 0.5; })}; + if (false == inside && b - a > 0.1) + context.switches.push_back({a, b, STR("shared timbers")}); + } + } + std::sort(context.switches.begin(), context.switches.end(), [](auto const &Left, auto const &Right) { return Left.from < Right.from; }); + } + context.start_elevation = samples.front().position.y; + context.end_elevation = samples.back().position.y; + TTrack *adjoining{nullptr}; + int path{0}; + bool entered{false}; + // a joined end on a switch inherits its height and grade from the switch, which lies in one plane + auto const inherits = [&](bool const Joined, double const Elevation, double const Grade) { + if (false == Joined || adjoining == nullptr || adjoining->eType != tt_Switch) + return std::string{}; + auto const found{switch_store::named(*adjoining)}; + auto const point{entered ? "P1" : path == 0 ? "P2" : "P4"}; + return format(STR_C("Grade line from the switch %s (%s): %.2f m, %+.2f per mille"), (found ? switch_store::label(*found) : adjoining->name()).c_str(), point, Elevation, Grade * 1000.0); + }; + context.start_joined = editor_track::adjoining_grade(state.route, false, context.start_grade, &adjoining, &path, &entered); + state.start_inherits = inherits(context.start_joined, context.start_elevation, context.start_grade); + adjoining = nullptr; + context.end_joined = editor_track::adjoining_grade(state.route, true, context.end_grade, &adjoining, &path, &entered); + state.end_inherits = inherits(context.end_joined, context.end_elevation, context.end_grade); + profile_check(); +} + +void editor_mode::profile_sample_model() +{ + auto &state{m_profile}; + auto const &samples{state.samples}; + state.model.assign(samples.size(), std::numeric_limits::quiet_NaN()); + state.model_waiting = false; + state.model_polled = ImGui::GetTime(); + if (samples.empty() || false == state.show_model) + return; + nmt_locate(); + if (false == m_nmt.placed()) + return; + // the squares along the route, not all those under the rectangle around it: a long line crosses the grid + std::size_t constexpr run{200}; + for (std::size_t first = 0; first < samples.size(); first += run) + { + glm::dvec2 low{samples[first].position.x, samples[first].position.z}; + auto high{low}; + for (auto i = first; i < std::min(samples.size(), first + run + 1); ++i) + { + low = glm::min(low, glm::dvec2{samples[i].position.x, samples[i].position.z}); + high = glm::max(high, glm::dvec2{samples[i].position.x, samples[i].position.z}); + } + if (false == m_nmt.request(low - glm::dvec2{2.0}, high + glm::dvec2{2.0})) + state.model_waiting = true; + } + std::vector differences; + for (std::size_t i = 0; i < samples.size(); ++i) + if (double height; m_nmt.height(samples[i].position.x, samples[i].position.z, height)) + { + state.model[i] = height; + differences.push_back(samples[i].position.y - height); + } + // a scenery put onto the model lies at its heights, or as far from them as the model was found to lie from it; one built at + // heights of its own, never put onto it, is compared by the shape: the model goes as far as the route lies from it + auto offset{m_nmt_state.offset}; + if (false == m_nmt_state.fitted && false == differences.empty()) + { + std::nth_element(differences.begin(), differences.begin() + differences.size() / 2, differences.end()); + if (auto const median{differences[differences.size() / 2]}; std::abs(median) > 30.0) + offset = median; + } + for (auto &height : state.model) + height += offset; +} + +void editor_mode::profile_recognize() +{ + auto &state{m_profile}; + std::vector chainages, elevations, grades; + for (auto const &sample : state.samples) + { + chainages.push_back(sample.chainage); + elevations.push_back(sample.position.y); + grades.push_back(sample.grade); + } + auto const norms{state.line.norms}; + auto const read = [&](profile::recognition const &Options) { + state.line = profile::recognize(chainages, elevations, grades, Options); + state.line.norms = norms; + state.line.speed = editor_track::route_speed(state.route); + state.selected = -1; + profile_check(); + }; + state.changed = false; + read({}); + // the constant grades alone don't tell a line bent all along: its bends read as they lie + if (state.departure > kDesignOff) + { + profile::recognition options; + options.minimum_length = 5.0; + options.detail = kStale; + read(options); + } + state.status = format(STR_P("Grade line recognized from the track: %zu point, largest departure %.3f m", "Grade line recognized from the track: %zu points, largest departure %.3f m", state.line.points.size()), state.line.points.size(), state.departure); +} + +void editor_mode::profile_fit_ground() +{ + auto &state{m_profile}; + std::vector chainages; + for (auto const &sample : state.samples) + chainages.push_back(sample.chainage); + if (std::none_of(state.terrain.begin(), state.terrain.end(), [](double const Height) { return std::isfinite(Height); })) + { + state.error = STR_C("There's no ground under the route"); + return; + } + auto settings{state.line}; + settings.speed = editor_track::route_speed(state.route); + // the grade line is the rail top: it's fitted so the formation under it, not the rails, follows the ground + auto ground{state.terrain}; + for (std::size_t i = 0; i < ground.size() && i < state.beds.size(); ++i) + ground[i] += state.beds[i]; + auto line{profile::fit_ground(chainages, ground, state.context, settings, state.fit)}; + if (line.points.size() < 2) + return; + state.line = std::move(line); + state.selected = -1; + state.error.clear(); + profile_check(); + double fill{0.0}; + double cut{0.0}; + for (std::size_t i = 0; i < state.samples.size(); ++i) + { + if (false == std::isfinite(state.terrain[i])) + continue; + auto const difference{profile::elevation(state.line, state.samples[i].chainage) - (i < state.beds.size() ? state.beds[i] : 0.0) - state.terrain[i]}; + fill = std::max(fill, difference); + cut = std::max(cut, -difference); + } + state.status = format(STR_P("Grade line fitted to the ground: %zu point, embankment up to %.2f m, cutting up to %.2f m", "Grade line fitted to the ground: %zu points, embankment up to %.2f m, cutting up to %.2f m", state.line.points.size()), state.line.points.size(), fill, cut); +} + +std::pair editor_mode::profile_ballast(TTrack const &Track) +{ + // the ballast is laid from the foot of the rails down, the rail top being the grade line + auto const depth{std::max(0.0, static_cast(Track.fTexHeight1 - Track.fTexHeightOffset)) + Track.rail_height()}; + auto const foot{0.5 * std::abs(Track.fTrackWidth) + std::abs(Track.fTexWidth) + std::abs(Track.fTexSlope)}; + return {depth, std::max(0.5, foot)}; +} + +bool editor_mode::profile_own_bed(TTrack const &Track) +{ + return Track.fTexHeight1 - Track.fTexHeightOffset > kNoBed; +} + +std::pair editor_mode::profile_generate_ground(std::vector> const &Beds, double const Reach) +{ + auto &state{m_profile}; + auto &works{state.earthworks}; + auto const &samples{state.samples}; + if (samples.empty() || false == ensure_terrain()) + return {0, 0}; + auto const size{heightmap::chunk_size}; + std::set keys; + for (auto const &sample : samples) + { + auto const &p{sample.position}; + auto const low{heightmap::chunk_at(p.x - Reach, p.z - Reach)}; + auto const high{heightmap::chunk_at(p.x + Reach, p.z + Reach)}; + for (auto x = low.first; x <= high.first; ++x) + for (auto z = low.second; z <= high.second; ++z) + keys.insert({x, z}); + } + auto const cells{heightmap::cells_for(m_terrain_spacing)}; + auto const cellsize{size / cells}; + auto const side{static_cast(cells) + 1}; + int made{0}; + int skipped{0}; + for (auto const &key : keys) + { + if (m_streamer.exists(key)) + continue; + auto const low{heightmap::chunk_corner(key)}; + glm::dvec2 const middle{low + glm::dvec2{size * 0.5}}; + std::vector around; + for (std::size_t i = 0; i < samples.size(); ++i) + if (std::abs(samples[i].position.x - middle.x) <= size * 0.5 + Reach && std::abs(samples[i].position.z - middle.y) <= size * 0.5 + Reach) + around.push_back(i); + if (around.empty()) + continue; + // where the scenery has its own ground, the chunk isn't made: the two would cover each other + std::vector probes; + for (int iz = 1; iz < 10; ++iz) + for (int ix = 1; ix < 10; ++ix) + probes.emplace_back(low.x + ix * size / 10.0, profile::elevation(state.line, samples[around.front()].chainage), low.y + iz * size / 10.0); + std::vector found; + ground_heights(probes, true, &found); + if (std::count(found.begin(), found.end(), 1) * 20 > static_cast(probes.size())) + { + ++skipped; + continue; + } + // the ground of the chunk: the ground under the nearest point of the route, or the formation there + std::vector heights(side * side); + for (std::size_t iz = 0; iz < side; ++iz) + for (std::size_t ix = 0; ix < side; ++ix) + { + glm::dvec3 const point{low.x + ix * cellsize, 0.0, low.y + iz * cellsize}; + auto best{around.front()}; + auto distance{std::numeric_limits::max()}; + for (auto const i : around) + { + auto const d{plan_distance(point, samples[i].position)}; + if (d < distance) + { + distance = d; + best = i; + } + } + heights[iz * side + ix] = static_cast(best < state.terrain.size() && std::isfinite(state.terrain[best]) ? state.terrain[best] : profile::elevation(state.line, samples[best].chainage) - Beds[best].first); + } + auto const added{m_streamer.add_chunk(key.first, key.second, m_terrain_spacing, [&](double const X, double const Z) { + auto const ix{static_cast(std::clamp(std::lround((X - low.x) / cellsize), 0, cells))}; + auto const iz{static_cast(std::clamp(std::lround((Z - low.y) / cellsize), 0, cells))}; + return heights[iz * side + ix]; + })}; + if (false == added) + continue; + works.generated.push_back(key); + ++made; + } + return {made, skipped}; +} + +void editor_mode::profile_shape_ground() +{ + auto &state{m_profile}; + auto &works{state.earthworks}; + auto const &samples{state.samples}; + if (samples.size() < 2 || state.line.points.size() < 2) + return; + if (false == ensure_terrain()) + { + state.error = STR_C("The heightmap terrain can't be opened"); + return; + } + auto const slope{std::max(0.1, works.slope)}; + std::vector> beds(samples.size(), {works.depth, works.half_width}); + if (works.from_ballast) + for (std::size_t i = 0; i < samples.size(); ++i) + if (samples[i].span < state.route.spans.size()) + if (auto const *track{state.route.spans[samples[i].span].track}; track != nullptr) + beds[i] = profile_ballast(*track); + double widest{0.0}; + for (auto const &bed : beds) + widest = std::max(widest, bed.second); + auto const reach{widest + works.reach}; + works.generated.clear(); + auto const generated{works.generate ? profile_generate_ground(beds, reach) : std::pair{0, 0}}; + + // the shaping is a modifier of the terrain: the formation along the axis of the route, followed by the ground + // around it. shaped again, the route replaces its modifier, and the terrain follows the new grade line + heightmap::modifier modifier; + auto const name = [](TTrack const *Track) { return Track != nullptr && false == Track->name().empty() ? Track->name() : std::string{"?"}; }; + modifier.name = "route " + name(state.from) + " - " + name(state.to); + modifier.slope = slope; + modifier.reach = works.reach; + modifier.rounding = std::max(0.0, works.rounding); + std::vector points; + points.reserve(samples.size()); + for (std::size_t i = 0; i < samples.size(); ++i) + points.push_back({{samples[i].position.x, samples[i].position.z}, profile::elevation(state.line, samples[i].chainage) - beds[i].first, beds[i].second}); + // the points the line between their neighbours passes within a few millimetres of are left out + double constexpr tolerance{0.005}; + modifier.points.push_back(points.front()); + std::size_t anchor{0}; + for (std::size_t next = 2; next < points.size(); ++next) + { + auto const &a{points[anchor]}; + auto const &b{points[next]}; + auto const run{b.position - a.position}; + auto const length{glm::length(run)}; + bool straight{true}; + for (auto i = anchor + 1; i < next && straight; ++i) + { + auto const t{length > 1e-9 ? glm::dot(points[i].position - a.position, run) / (length * length) : 0.0}; + auto const offset{glm::length(points[i].position - (a.position + run * t))}; + auto const formation{a.formation + (b.formation - a.formation) * t}; + auto const width{a.half_width + (b.half_width - a.half_width) * t}; + straight = offset <= tolerance && std::abs(points[i].formation - formation) <= tolerance && std::abs(points[i].half_width - width) <= tolerance; + } + if (false == straight) + { + anchor = next - 1; + modifier.points.push_back(points[anchor]); + } + } + modifier.points.push_back(points.back()); + + double fill{0.0}; + double cut{0.0}; + for (std::size_t i = 0; i < samples.size(); ++i) + { + if (i >= state.terrain.size() || false == std::isfinite(state.terrain[i])) + continue; + fill = std::max(fill, points[i].formation - state.terrain[i]); + cut = std::max(cut, state.terrain[i] - points[i].formation); + } + if (false == works.modifier.empty() && works.modifier != modifier.name) + m_streamer.remove_modifier(works.modifier); + works.modifier = modifier.name; + auto const count{modifier.points.size()}; + m_streamer.modifier(std::move(modifier)); + forget_ground(); + + auto status{format(STR_P("Terrain shaped by the modifier \"%s\" (%zu point): embankment up to %.2f m, cutting up to %.2f m", "Terrain shaped by the modifier \"%s\" (%zu points): embankment up to %.2f m, cutting up to %.2f m", count), works.modifier.c_str(), count, fill, cut)}; + if (generated.first > 0) + status += format(STR_P("; %d chunk of terrain made under the route", "; %d chunks of terrain made under the route", generated.first), generated.first); + if (generated.second > 0) + status += format(STR_P("; %d chunk left out: the scenery has its own ground there, convert it to shape it", "; %d chunks left out: the scenery has its own ground there, convert it to shape it", generated.second), generated.second); + state.error.clear(); + profile_resample(); + state.status = status; + WriteLog("Editor: vertical profile - " + state.status, logtype::generic); +} + +void editor_mode::profile_restore_ground() +{ + auto &state{m_profile}; + auto &works{state.earthworks}; + std::size_t restored{0}; + if (false == works.modifier.empty() && m_streamer.remove_modifier(works.modifier)) + ++restored; + works.modifier.clear(); + for (auto const &key : works.generated) + { + m_streamer.remove_chunk(key.first, key.second); + ++restored; + } + works.generated.clear(); + forget_ground(); + profile_resample(); + state.status = restored > 0 ? STR_C("The terrain is back as it was before the shaping") : STR_C("The shaping of the terrain is gone already"); +} + +void editor_mode::render_ground_conversion() +{ + auto &conversion{m_ground_conversion}; + ImGui::PushID("ground_conversion"); + if (false == conversion.open) + { + if (ImGui::Button(STR_C("Convert the terrain files to heightmap terrain..."))) + { + conversion.open = true; + load_ground_files(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Replaces the triangles of the terrain files of the scenery (terrain directive, .txtf/.btf) with heightmap terrain\n" + "of the same shape, painted with their materials; the files lose these triangles on save")); + if (false == conversion.status.empty()) + ImGui::TextWrapped("%s", conversion.status.c_str()); + ImGui::PopID(); + return; + } + if (conversion.files.empty()) + ImGui::TextWrapped("%s", STR_C("The scenery has no terrain files: no terrain directive names a .txtf or .btf file")); + else + ImGui::TextUnformatted(STR_C("Terrain files of the scenery:")); + for (std::size_t index = 0; index < conversion.files.size(); ++index) + { + auto &source{conversion.files[index]}; + ImGui::PushID(static_cast(index)); + ImGui::BeginDisabled(false == source.good); + ImGui::Checkbox(source.file.c_str(), &source.chosen); + ImGui::EndDisabled(); + ImGui::SameLine(); + if (source.good) + ImGui::TextDisabled(source.text ? STR_C("(text, %zu triangles)") : STR_C("(binary, %zu triangles)"), source.count); + else + ImGui::TextDisabled("(%s)", source.message.c_str()); + ImGui::PopID(); + } + // the materials of the chosen files + std::vector counts(conversion.names.size(), 0); + for (auto const &source : conversion.files) + if (source.good && source.chosen) + for (auto index = source.first; index < source.first + source.count; ++index) + ++counts[conversion.materials[index]]; + if (false == conversion.names.empty()) + ImGui::TextUnformatted(STR_C("Materials: tick the ones which are the ground")); + for (std::size_t index = 0; index < conversion.names.size(); ++index) + { + if (counts[index] == 0) + continue; + bool chosen{conversion.chosen.count(index) != 0}; + ImGui::PushID(static_cast(index) + 0x10000); + if (ImGui::Checkbox(format(STR_C("%s (%zu triangles)"), conversion.names[index].c_str(), counts[index]).c_str(), &chosen)) + { + if (chosen) + conversion.chosen.insert(index); + else + conversion.chosen.erase(index); + } + ImGui::PopID(); + } + ImGui::TextWrapped("%s", STR_C("The chunks are painted with the materials of the triangles, up to 8 of them per chunk, added to the palette of the terrain. " + "Until saved, loading the scenery again takes it all back.")); + auto const ready{std::any_of(conversion.files.begin(), conversion.files.end(), [](auto const &Source) { return Source.good && Source.chosen; }) && false == conversion.chosen.empty()}; + ImGui::BeginDisabled(false == ready); + if (ImGui::Button(STR_C("Convert"))) + { + conversion.status = convert_ground(); + conversion.open = false; + profile_resample(); + } + ImGui::EndDisabled(); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Cancel"))) + conversion.open = false; + if (false == conversion.open) + { + // the triangles take memory, they're read again the next time + conversion.triangles = {}; + conversion.materials = {}; + } + ImGui::PopID(); +} + +void editor_mode::render_profile_earthworks() +{ + auto &state{m_profile}; + auto &works{state.earthworks}; + if (false == ImGui::TreeNode(STR_C("Shape the terrain to the grade line"))) + return; + ImGui::TextWrapped("%s", STR_C("Only the heightmap terrain changes: a formation and slopes are made, the models of the scenery stay as they are")); + render_ground_conversion(); + auto const drag = [](char const *Label, double &Value, float const Speed, char const *Format) { + field_row(Label); + ImGui::PushID(Label); + auto const edited{ImGui::DragScalar("##value", ImGuiDataType_Double, &Value, Speed, nullptr, nullptr, Format)}; + ImGui::PopID(); + return edited; + }; + toggle_chips("earthworks", {{STR_C("Make terrain where the route has none"), &works.generate, + "Chunks of heightmap terrain are made along the route where there's none, from the ground around,\nthen shaped. Where the scenery has its own ground triangles the chunk is left out: convert them instead"}, + {STR_C("Formation under the ballast of the track"), &works.from_ballast, + "The terrain goes as deep under the track as its ballast reaches and as wide as its foot,\nread from each path of the route; off: the values given below"}}); + if (works.from_ballast) + { + if (false == state.route.spans.empty() && state.route.spans.front().track != nullptr) + { + auto const bed{profile_ballast(*state.route.spans.front().track)}; + ImGui::TextDisabled(STR_C("Ballast %.2f m deep, its foot %.2f m from the axis"), bed.first, bed.second); + } + } + if (false == works.from_ballast && begin_fields("##earthworkfields", 0.55f)) + { + drag("Formation below the track (m)", works.depth, 0.01f, "%.2f"); + drag("Half width of the formation (m)", works.half_width, 0.05f, "%.2f"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("From the axis of the route to the edge of the formation;\nfor two tracks add the distance between them")); + ImGui::EndTable(); + } + ImGui::PushID("earthworkmore"); + if (ImGui::TreeNode(STR_C("More settings"))) + { + if (begin_fields("##earthworkslopes", 0.55f)) + { + drag("Slopes 1 : n, n", works.slope, 0.05f, "%.2f"); + drag("Slopes reach at most (m)", works.reach, 1.0f, "%.0f"); + drag("Rounding of the edges (m)", works.rounding, 0.1f, "%.1f"); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Length over which the slope bends into the formation and into the ground; 0: sharp edges")); + ImGui::EndTable(); + } + ImGui::TreePop(); + } + ImGui::PopID(); + works.rounding = std::clamp(works.rounding, 0.0, 20.0); + works.depth = std::clamp(works.depth, 0.0, 5.0); + works.half_width = std::clamp(works.half_width, 0.5, 30.0); + works.slope = std::clamp(works.slope, 0.1, 10.0); + works.reach = std::clamp(works.reach, 1.0, 200.0); + if (has_errors(state.issues)) + ImGui::TextDisabled("%s", STR_C("Correct the errors of the grade line first")); + else + { + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.18f, 0.42f, 0.24f, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.22f, 0.52f, 0.30f, 1.0f)); + if (ImGui::Button(STR_C("Shape the terrain"), ImVec2(-FLT_MIN, ImGui::GetFrameHeight() * 1.3f))) + profile_shape_ground(); + item_tooltip("Makes the formation and the slopes along the route in the heightmap terrain.\nThey're kept as a modifier of the terrain, which follows the grade line when you shape it again; the triangles and models of the scenery stay as they are"); + ImGui::PopStyleColor(2); + } + if (false == works.modifier.empty() || false == works.generated.empty()) + { + if (ImGui::Button(STR_C("Restore the terrain"), ImVec2(-FLT_MIN, 0.0f))) + profile_restore_ground(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Removes the modifier of the route, and takes away the terrain the shaping made")); + } + if (m_streamer.active()) + { + // the terrain tools take the tool options window over, the profile stays open under them + if (ImGui::Button(STR_C("Sculpting..."))) + terrain_workspace(true); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Opens the terrain tools: raising, lowering and smoothing with a brush")); + } + ImGui::TreePop(); +} + +void editor_mode::profile_check() +{ + auto &state{m_profile}; + auto &points{state.line.points}; + // what the edits start from + if (false == state.changed) + state.line_read = state.line; + // joint points come and go, the selection follows the point it was made on + struct mark + { + int *index; + double chainage; + bool joint; + }; + std::vector marks; + for (auto *index : {&state.selected, &state.dragging, &state.curve_grip}) + if (*index >= 0 && *index < static_cast(points.size())) + marks.push_back({index, points[*index].chainage, points[*index].joint}); + profile::complete(state.line, state.context); + for (auto const &mark : marks) + { + int best{-1}; + double distance{std::numeric_limits::max()}; + for (int i = 0; i < static_cast(points.size()); ++i) + if (points[i].joint == mark.joint && std::abs(points[i].chainage - mark.chainage) < distance) + { + distance = std::abs(points[i].chainage - mark.chainage); + best = i; + } + *mark.index = (mark.joint || distance < 1e-6) ? best : -1; + } + state.issues = profile::check(state.line, state.context); + state.departure = 0.0; + for (auto const &sample : state.samples) + state.departure = std::max(state.departure, std::abs(profile::elevation(state.line, sample.chainage) - sample.position.y)); +} + +void editor_mode::profile_fit_view() +{ + auto &state{m_profile}; + auto const length{std::max(1.0, state.route.length)}; + state.view_from = -0.02 * length; + state.view_to = length * 1.02; + state.exaggeration = 0.0f; +} + +void editor_mode::profile_to_camera() +{ + auto &state{m_profile}; + if (state.samples.empty()) + return; + // where the view looks: from above the camera itself, else the middle of the view on the level of the route + glm::dvec3 target{Camera.Pos}; + if (false == Global.EditorOrtho) + { + auto const low{editor_ui::view_min()}; + auto const high{editor_ui::view_max()}; + glm::dvec3 point; + if (screen_projection{}.on_level(ImVec2{(low.x + high.x) * 0.5f, (low.y + high.y) * 0.5f}, state.samples[state.samples.size() / 2].position.y, point)) + target = point; + } + auto best{std::numeric_limits::max()}; + double chainage{0.0}; + for (auto const &sample : state.samples) + if (auto const distance{geometry::plan_distance(sample.position, target)}; distance < best) + { + best = distance; + chainage = sample.chainage; + } + auto const span{state.view_to - state.view_from}; + state.view_from = chainage - 0.5 * span; + state.view_to = chainage + 0.5 * span; +} + +void editor_mode::profile_frame_view() +{ + auto const &state{m_profile}; + std::vector points; + for (auto const &sample : state.samples) + if (sample.chainage >= state.view_from && sample.chainage <= state.view_to) + points.push_back(sample.position); + auto const &io{ImGui::GetIO()}; + if (points.size() < 2 || io.DisplaySize.y <= 0.0f) + return; + glm::dvec3 low{points.front()}; + glm::dvec3 high{points.front()}; + for (auto const &point : points) + { + low = glm::min(low, point); + high = glm::max(high, point); + } + auto const centre{(low + high) * 0.5}; + // the room the docks and the strip of the plot leave to the view, and how far its middle lies from the middle of the screen, + // in pixels + glm::dvec2 const screen{io.DisplaySize.x, io.DisplaySize.y}; + auto const viewlow{editor_ui::view_min()}; + auto viewhigh{editor_ui::view_max()}; + if (state.strip_top > viewlow.y + 100.0f) + viewhigh.y = std::min(viewhigh.y, state.strip_top); + auto const width{std::max(50.0, static_cast(viewhigh.x - viewlow.x))}; + auto const height{std::max(50.0, static_cast(viewhigh.y - viewlow.y))}; + glm::dvec2 const shift{(viewlow.x + viewhigh.x) * 0.5 - screen.x * 0.5, (viewlow.y + viewhigh.y) * 0.5 - screen.y * 0.5}; + double constexpr margin{1.1}; + if (Global.EditorOrtho) + { + auto const yaw{static_cast(Camera.Angle.y)}; + double extent{5.0}; + for (auto const &point : points) + { + auto const local{RotateY(point - centre, -yaw)}; + extent = std::max({extent, std::abs(local.x) * margin * screen.y / width, std::abs(local.z) * margin * screen.y / height}); + } + Global.EditorOrthoExtent = std::clamp(static_cast(extent), 5.0f, 50000.0f); + auto const scale{2.0 * static_cast(Global.EditorOrthoExtent) / screen.y}; + auto const offset{RotateY(glm::dvec3{shift.x * scale, 0.0, shift.y * scale}, yaw)}; + m_ride.leave(); + Camera.Pos.x = centre.x - offset.x; + Camera.Pos.z = centre.z - offset.z; + Camera.Velocity = {}; + m_focus_active = false; + Global.pCamera = Camera; + return; + } + // seen from the side, as the plot shows it: the start on the left, from a little above + glm::dvec3 chord{points.back().x - points.front().x, 0.0, points.back().z - points.front().z}; + chord = glm::length(chord) > 1e-6 ? glm::normalize(chord) : glm::dvec3{1.0, 0.0, 0.0}; + glm::dvec3 const up{0.0, 1.0, 0.0}; + auto const look{glm::normalize(glm::cross(up, chord) + glm::dvec3{0.0, -0.4, 0.0})}; + auto const right{glm::normalize(glm::cross(look, up))}; + auto const above{glm::cross(right, look)}; + auto const tangent{std::tan(glm::radians(static_cast(Global.FieldOfView) / std::max(0.01, static_cast(Global.ZoomFactor))) * 0.5)}; + auto const across{tangent * width / screen.y}; + auto const upward{tangent * height / screen.y}; + double distance{10.0}; + for (auto const &point : points) + { + auto const offset{point - centre}; + auto const depth{glm::dot(offset, look)}; + distance = std::max({distance, std::abs(glm::dot(offset, right)) * margin / across - depth, std::abs(glm::dot(offset, above)) * margin / upward - depth}); + } + distance = std::min(distance, 8000.0); + auto const pixel{2.0 * distance * tangent / screen.y}; + fly_to(centre - right * (shift.x * pixel) + above * (shift.y * pixel), look, distance, 0.35); +} + +void editor_mode::profile_apply(bool const Terrain, std::vector const &Bridges, double const Fewest) +{ + auto &state{m_profile}; + state.status.clear(); + state.error.clear(); + if (state.route.spans.empty() || state.line.points.size() < 2) + return; + auto const edits{m_track_edits}; + if (state.changed && false == state.fitting ? errors_in_change(state.issues, state.line, state.line_read, state.samples) : has_errors(state.issues)) + { + state.error = STR_C("Correct the errors to apply the grade line"); + state.show_remarks = true; + return; + } + std::vector tracks; + for (auto const &span : state.route.spans) + tracks.push_back(span.track); + if (false == tracks_editable(tracks, state.error)) + { + state.error = STR_C("The grade line can't be applied, ") + state.error; + return; + } + auto const line{state.line}; + auto const before{state.samples}; + std::vector> states; + std::vector created; + std::vector ends; + for (auto const &span : state.route.spans) + ends.insert(ends.end(), {span.from, span.to}); + auto cuts{profile::breaks(line)}; + // an edit goes onto the track as what it changed in the line: where it changed nothing the track stays as it lies, whatever the line + // read from it is off it by, and isn't cut + bool const edit_only{state.changed && false == state.fitting}; + auto const read_line{state.line_read}; + auto const changed_at = [&](double const Chainage) { return profile::elevation(line, Chainage) - profile::elevation(read_line, Chainage); }; + if (edit_only) + std::erase_if(cuts, [&](double const Cut) { + double constexpr kCutNear{1.0}; // m + double constexpr kNoChange{0.001}; // m + return std::abs(changed_at(Cut - kCutNear)) < kNoChange && std::abs(changed_at(Cut + kCutNear)) < kNoChange; + }); + auto const height_at = [&](double const Chainage) { return edit_only ? editor_track::sampled_elevation(before, Chainage) + changed_at(Chainage) : profile::elevation(line, Chainage); }; + auto const grade_at = [&](double const Chainage) { return edit_only ? editor_track::sampled_grade(before, Chainage) + profile::grade(line, Chainage) - profile::grade(read_line, Chainage) : profile::grade(line, Chainage); }; + // the paths are cut only at the breaks they can't go over keeping to the line within a hair: one cut there, by a joint, or by + // another cut, would leave a sliver of a track, the line applied again leaving more of them by the first, the ballast mapped + // on each from its start. A path just laid keeps to it as closely as Fewest + double constexpr kFollow{0.002}; // m + cuts = profile::fewest_breaks(cuts, ends, Fewest > 0.0 ? Fewest : kFollow, height_at, grade_at); + // a bridge ends at a joint or a break of the line by its abutment rather than leave a sliver of a path there + double constexpr kBridgeSnap{1.0}; // m + auto joints{cuts}; + joints.insert(joints.end(), ends.begin(), ends.end()); + auto bridges{Bridges}; + for (auto &bridge : bridges) + for (auto *end : {&bridge.from, &bridge.to}) + if (auto const nearest{std::min_element(joints.begin(), joints.end(), [&](double const A, double const B) { return std::abs(A - *end) < std::abs(B - *end); })}; + nearest != joints.end() && std::abs(*nearest - *end) <= kBridgeSnap) + *end = *nearest; + for (auto const &bridge : bridges) + cuts.insert(cuts.end(), {bridge.from, bridge.to}); + std::sort(cuts.begin(), cuts.end()); + auto const gaps{editor_track::apply_profile( + state.route, height_at, grade_at, cuts, states, created)}; + // the paths over a bridge sound and light as on one, and get no formation; within what a cut too near an end leaves on + double constexpr kBridgeEnd{0.5}; // m + std::size_t bridged{0}; + for (auto const &span : state.route.spans) + if (span.track->eEnvironment != e_bridge && span.track->eEnvironment != e_tunnel + && std::any_of(bridges.begin(), bridges.end(), [&](profile::departure const &Bridge) { return span.from >= Bridge.from - kBridgeEnd && span.to <= Bridge.to + kBridgeEnd; })) + { + span.track->eEnvironment = e_bridge; + ++bridged; + } + auto const changed{states.size()}; + auto const added{created.size()}; + state.created = created; + { + auto marked{tracks}; + marked.insert(marked.end(), created.begin(), created.end()); + fitted_set(marked, edit_only); + } + // the stored design changes with the paths, an undo takes both back + profile_library_load(); + auto library{m_profiles}; + bool const pushed{false == states.empty() || false == created.empty()}; + push_track_snapshot(std::move(states), std::move(created)); + state.edits = m_track_edits; + first_step_done(first_step::profile_apply); + if (pushed) + { + m_history.back().profiles = true; + m_history.back().profile_library = std::move(library); + } + state.from = state.route.spans.front().track; + state.to = state.route.spans.back().track; + profile_resample(); + profile_store(); + state.status = format(STR_P("Grade line applied: %zu path changed, %zu added, largest departure %.3f m", "Grade line applied: %zu paths changed, %zu added, largest departure %.3f m", changed), changed, added, state.departure); + if (false == scene::Layers.empty()) + state.status += STR_C("\nThe paths and the design (//$p lines) go to the scenery files on save"); + if (bridged > 0) + state.status += format(STR_P("\nOver a bridge or a viaduct: %zu path", "\nOver a bridge or a viaduct: %zu paths", bridged), bridged); + auto const name = [](TTrack const *Track) { return name_of(*Track); }; + auto const closed{std::count_if(gaps.begin(), gaps.end(), [](auto const &Gap) { return Gap.closed; })}; + if (closed > 0) + state.status += STR_C("\nPaths off the route brought to its height:"); + for (auto const &gap : gaps) + if (gap.closed) + state.status += format(STR_C("\n %s at %s: %+.3f m"), name(gap.neighbour).c_str(), name(gap.track).c_str(), -gap.gap); + if (closed < static_cast(gaps.size())) + state.status += STR_C("\nSwitch ends off the adjoining paths, which can't be changed here:"); + for (auto const &gap : gaps) + if (false == gap.closed) + state.status += format("\n %s -> %s: %+.3f m", name(gap.track).c_str(), name(gap.neighbour).c_str(), gap.gap); + // the tracks on the other side of the crossovers of the route go up and down with it + auto const followed{follow_crossovers(before)}; + if (followed > 0) + state.status += format(STR_C("\nThe tracks across %zu crossover(s) followed the change"), followed); + // a line fitted to the terrain model goes by itself: the ones sharing its grade line are worked out after them all + if (auto const beside{state.fitting ? std::size_t{0} : grade_line_follow(before)}; beside > 0) + state.status += format(STR_P("\nThe common grade line: %zu track beside went with the route", "\nThe common grade line: %zu tracks beside went with the route", beside), beside); + if (Terrain) + profile_follow_terrain(static_cast(m_track_edits - edits)); + WriteLog("Editor: vertical profile - " + state.status, logtype::generic); +} + +void editor_mode::profile_follow_terrain(std::size_t const Edits) +{ + auto &state{m_profile}; + // the heightmap terrain the scenery has; the ground of a scenery without it stays as it is + if (false == m_streamer.active() || Edits == 0) + return; + std::vector tracks; + std::size_t found{0}; + for (auto step{m_history.rbegin()}; step != m_history.rend() && found < Edits; ++step) + { + if (step->action != EditorSnapshot::Action::TrackEdit) + continue; + ++found; + for (auto const &entry : step->tracks) + tracks.push_back(entry.first); + tracks.insert(tracks.end(), step->created.begin(), step->created.end()); + tracks.insert(tracks.end(), step->removed.begin(), step->removed.end()); + } + std::erase(tracks, nullptr); + std::sort(tracks.begin(), tracks.end()); + tracks.erase(std::unique(tracks.begin(), tracks.end()), tracks.end()); + if (tracks.empty()) + return; + // the route shaped by the earthworks of the profile keeps its modifier, shaped again to the new grade line; the tracks + // shaped one by one, as the terrain model lays them, get their formations anew + auto const name = [](TTrack const *Track) { return Track != nullptr && false == Track->name().empty() ? Track->name() : std::string{"?"}; }; + auto const route{"route " + name(state.from) + " - " + name(state.to)}; + auto const &modifiers{m_streamer.modifiers()}; + auto const has = [&](std::string const &Name) { return std::any_of(modifiers.begin(), modifiers.end(), [&](heightmap::modifier const &Modifier) { return Modifier.name == Name; }); }; + auto const shaped{has(route) || (false == state.earthworks.modifier.empty() && has(state.earthworks.modifier))}; + auto const own{std::any_of(tracks.begin(), tracks.end(), [&](TTrack const *Track) { + return false == Track->name().empty() && std::any_of(modifiers.begin(), modifiers.end(), [&](heightmap::modifier const &Modifier) { return Modifier.name == "nmt " + Track->name() || Modifier.name.starts_with("nmt " + Track->name() + " "); }); + })}; + auto status{state.status}; + std::size_t laid{0}; + if (false == shaped || own) + laid = nmt_shape_tracks(&tracks); + if (shaped) + { + profile_shape_ground(); + status += "\n" + state.status; + } + else + profile_resample(); + if (laid > 0) + status += format(STR_P("\nThe terrain followed the tracks: %zu formation laid anew", "\nThe terrain followed the tracks: %zu formations laid anew", laid), laid); + state.status = status; + // the terrain goes back with the grade line in one step + auto const before{m_history.empty() ? EditorSnapshot::Action::Other : m_history.back().action}; + terrain_history_step(); + if (before != EditorSnapshot::Action::Terrain && false == m_history.empty() && m_history.back().action == EditorSnapshot::Action::Terrain) + m_history.back().joined = true; +} + +void editor_mode::profile_after_undo() +{ + auto &state{m_profile}; + if (state.route.spans.empty()) + return; + auto const removed = [](TTrack const *Track) { return Track == nullptr || Track->m_editorremoved; }; + if (removed(state.from) || removed(state.to)) + { + state.from = state.picked_from; + state.to = state.picked_to; + } + std::string error; + if (removed(state.from) || removed(state.to) || false == editor_track::find_route(state.from, state.to, state.route, error)) + { + state.route = {}; + state.samples.clear(); + state.selected = -1; + state.dragging = -1; + state.curve_grip = -1; + return; + } + profile_resample(); +} + +// the tracks of the route changed by another tool or by an undo: the route read again, the design kept in the scenery read +// again over it unless it's being changed +void editor_mode::profile_follow_edits() +{ + auto &state{m_profile}; + if (state.edits == m_track_edits) + return; + state.edits = m_track_edits; + if (state.route.spans.empty() || state.dragging >= 0) + return; + auto const kept{false == state.changed}; + profile_after_undo(); + if (kept && false == state.route.spans.empty()) + profile_restore(); +} + +void editor_mode::render_profile_body() +{ + auto &state{m_profile}; + profile_follow_selection(); + step_heading(1, STR_C("Route")); + render_profile_source(); + if (state.route.spans.empty()) + { + if (false == state.error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.3f, 1.0f), "%s", state.error.c_str()); + return; + } + ImGui::TextWrapped(STR_P("%zu path, %.2f m: %s ... %s", "%zu paths, %.2f m: %s ... %s", state.route.spans.size()), state.route.spans.size(), state.route.length, state.route.spans.front().track->name().c_str(), state.route.spans.back().track->name().c_str()); + { + bool reversed; + auto const stored{profile_find(reversed)}; + if (stored >= 0) + { + ImGui::TextDisabled(STR_C("Design kept in %s%s"), scene::Layers.layer(m_profiles[stored].layer).name.c_str(), state.changed ? STR_C(", changes go there on save") : ""); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Forget the design"))) + profile_forget(); + } + else if (state.changed) + ImGui::TextDisabled(STR_C("The design goes to the scenery file of the route on save")); + } + + render_profile_grade_line(); + step_heading(2, STR_C("Grade line")); + if (render_profile_parameters()) + profile_edited(); + step_heading(3, STR_C("Terrain")); + render_profile_earthworks(); +} + +void editor_mode::render_profile_strip() +{ + profile_follow_edits(); + // the strip follows the selection by itself: the panel of the tool needn't be the one in front + profile_follow_selection(); + auto &state{m_profile}; + auto const &io{ImGui::GetIO()}; + // along the bottom of the 3d view, as wide as it; each time the profile opens, wherever it was left before + auto const low{editor_ui::view_min()}; + auto const high{editor_ui::view_max()}; + auto const width{std::max(480.0f, high.x - low.x)}; + auto const height{std::clamp((high.y - low.y) * 0.5f, 260.0f, std::max(260.0f, high.y - low.y - 80.0f))}; + ImGui::SetNextWindowPos(ImVec2(low.x, high.y - height), ImGuiCond_Appearing); + ImGui::SetNextWindowSize(ImVec2(width, height), ImGuiCond_Appearing); + auto title{std::string{STR_C("Vertical profile")}}; + if (false == state.route.spans.empty()) + title += format(STR_P(" %s > %s, %zu path, %.2f m", " %s > %s, %zu paths, %.2f m", state.route.spans.size()), state.route.spans.front().track->name().c_str(), state.route.spans.back().track->name().c_str(), state.route.spans.size(), state.route.length); + title += "###profilestrip"; + if (ImGui::Begin(title.c_str(), nullptr, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) + { + // a window left past the edge of the screen comes back into it + auto const position{ImGui::GetWindowPos()}; + auto const size{ImGui::GetWindowSize()}; + state.strip_top = ImGui::IsWindowDocked() ? -1.0f : position.y; + if (false == ImGui::IsWindowDocked() && (position.y + size.y > io.DisplaySize.y + 1.0f || position.x + 80.0f > io.DisplaySize.x || position.x + size.x < 80.0f)) + ImGui::SetWindowPos(ImVec2(std::clamp(position.x, 0.0f, std::max(0.0f, io.DisplaySize.x - size.x)), std::max(0.0f, std::min(position.y, io.DisplaySize.y - size.y)))); + if (state.route.spans.empty()) + render_profile_empty(); + else + { + render_profile_header(); + auto const side{std::clamp(ImGui::GetContentRegionAvail().x * 0.3f, 250.0f, 400.0f)}; + ImGui::BeginChild("##profileplot", ImVec2(-side, 0.0f), false, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse); + render_profile_toolbar(); + render_profile_canvas(ImGui::GetContentRegionAvail().y); + ImGui::EndChild(); + ImGui::SameLine(); + ImGui::BeginChild("##profileside", ImVec2(0.0f, 0.0f), false); + if (ImGui::BeginTabBar("##profiletabs")) + { + // a click on a point in the plot brings its tab forward, a click on the state of the grade line the remarks + bool const picked{state.selected >= 0 && state.selected != state.shown}; + state.shown = state.selected; + if (ImGui::BeginTabItem(STR_C("Point"), nullptr, picked ? ImGuiTabItemFlags_SetSelected : 0)) + { + render_profile_point(); + ImGui::EndTabItem(); + } + if (ImGui::BeginTabItem(format("%s (%zu)###profilepoints", STR_C("Points"), state.line.points.size()).c_str())) + { + ImGui::BeginChild("##profilepointlist"); + render_profile_points(); + ImGui::EndChild(); + ImGui::EndTabItem(); + } + bool const errors{has_errors(state.issues)}; + if (false == state.issues.empty()) + ImGui::PushStyleColor(ImGuiCol_Text, errors ? ImVec4(1.0f, 0.45f, 0.4f, 1.0f) : ImVec4(1.0f, 0.8f, 0.3f, 1.0f)); + bool const remarks{ImGui::BeginTabItem(format("%s (%zu)###profileremarks", STR_C("Remarks"), state.issues.size()).c_str(), nullptr, state.show_remarks ? ImGuiTabItemFlags_SetSelected : 0)}; + state.show_remarks = false; + if (false == state.issues.empty()) + ImGui::PopStyleColor(); + if (remarks) + { + render_profile_issues(); + ImGui::EndTabItem(); + } + ImGui::EndTabBar(); + } + ImGui::EndChild(); + } + } + ImGui::End(); +} + +void editor_mode::render_profile_header() +{ + auto &state{m_profile}; + auto const errors{std::count_if(state.issues.begin(), state.issues.end(), [](profile::issue const &Issue) { return Issue.error; })}; + auto const warnings{static_cast(state.issues.size()) - errors}; + if (ImGui::Button(STR_C("From the track"))) + { + profile_recognize(); + state.changed = true; + } + item_tooltip("The points of the grade line read from the track as it lies now"); + ImGui::SameLine(); + if (ImGui::Button(STR_C("To the ground"))) + { + profile_fit_ground(); + state.changed = true; + } + item_tooltip("Places the breaks of the grade line along the ground under the route,\nwithin the limits and with the least earthworks; the ground itself stays as it is"); + ImGui::SameLine(0.0f, 2.0f); + ImGui::SetNextItemWidth(ImGui::CalcTextSize("+00.00 m").x + ImGui::GetStyle().FramePadding.x * 2.0f); + ImGui::DragScalar("##fittolerance", ImGuiDataType_Double, &state.fit.tolerance, 0.05f, nullptr, nullptr, STR_C("+-%.2f m")); + state.fit.tolerance = std::clamp(state.fit.tolerance, 0.05, 50.0); + item_tooltip("How far the grade line may depart from the ground before it breaks;\nmore gives fewer breaks and higher embankments and deeper cuttings"); + ImGui::SameLine(0.0f, ImGui::GetFontSize()); + // the state of the grade line against the limits; a click lists the remarks + std::string chip; + ImVec4 colour; + if (errors > 0) + { + chip = warnings > 0 ? format(STR_C("%d errors, %d warnings"), static_cast(errors), static_cast(warnings)) : format(STR_C("%d errors"), static_cast(errors)); + colour = ImVec4(1.0f, 0.45f, 0.38f, 1.0f); + } + else if (warnings > 0) + { + chip = format(STR_C("%d warnings"), static_cast(warnings)); + colour = ImVec4(1.0f, 0.8f, 0.3f, 1.0f); + } + else + { + chip = STR_C("Within the limits"); + colour = ImVec4(0.45f, 0.9f, 0.45f, 1.0f); + } + if (state_chip((chip + "###profilestate").c_str(), colour)) + state.show_remarks = true; + item_tooltip(state.issues.empty() ? "The grade line meets the limits of the line" : "Click: the list of the remarks; a click on a remark shows its place"); + // apply at the right end, as far as there's room + auto const label{std::string{STR_C("Apply to the scenery")} + (state.departure > 0.0005 ? " *" : "")}; + auto const button{ImGui::CalcTextSize(label.c_str()).x + ImGui::GetStyle().FramePadding.x * 2.0f}; + auto const right{ImGui::GetWindowContentRegionMax().x - button}; + ImGui::SameLine(0.0f, ImGui::GetFontSize()); + if (ImGui::GetCursorPosX() < right) + ImGui::SetCursorPosX(right); + ImGui::BeginDisabled(errors > 0); + ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.2f, 0.55f, 0.25f, 1.0f)); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.25f, 0.68f, 0.3f, 1.0f)); + if (ImGui::Button((label + "###profileapply").c_str())) + profile_apply(true); + ImGui::PopStyleColor(2); + ImGui::EndDisabled(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + if (errors > 0) + ImGui::SetTooltip("%s", STR_C("Correct the errors first: the red remarks, a click on the state shows them")); + else if (state.departure > 0.0005) + ImGui::SetTooltip(STR_C("Sets the heights of the track along the route to the grade line, the track moves by up to %.3f m; Ctrl+Z takes it back"), state.departure); + else + ImGui::SetTooltip("%s", STR_C("The track lies on the grade line already")); + } + if (false == state.error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.3f, 1.0f), "%s", state.error.c_str()); +} + +void editor_mode::render_profile_empty() +{ + auto &state{m_profile}; + auto *selected{selected_track()}; + auto const available{ImGui::GetContentRegionAvail()}; + auto *draw{ImGui::GetWindowDrawList()}; + auto const line{ImGui::GetTextLineHeight()}; + auto const mouse{std::round(line * 2.6f)}; + auto const headline{std::string{STR_C("Click a track in the view")}}; + auto const detail{std::string{STR_C("The grade line of its whole line shows here; Shift+LMB on more tracks or Shift+drag a box: the route from one end of them to the other. Drag the points of the line up and down, then apply it to the scenery.")}}; + auto const wrap{std::min(available.x - 40.0f, 560.0f)}; + auto const top{ImGui::GetCursorScreenPos().y + std::max(0.0f, available.y * 0.5f - mouse - line * 2.0f)}; + auto const left{ImGui::GetCursorScreenPos().x + std::max(0.0f, (available.x - wrap) * 0.5f)}; + gesture_mouse(*draw, ImVec2(left, top), mouse, "LMB"); + auto *font{ui_layer::font_bold != nullptr ? ui_layer::font_bold : ImGui::GetFont()}; + auto const big{ui_layer::font_bold != nullptr ? ui_layer::font_bold->FontSize : ImGui::GetFontSize() * 1.2f}; + auto const textleft{left + mouse * 0.68f + line}; + draw->AddText(font, big, ImVec2(textleft, top + line * 0.2f), ImGui::GetColorU32(ImGuiCol_Text), headline.c_str()); + draw->AddText(ImGui::GetFont(), ImGui::GetFontSize(), ImVec2(textleft, top + big + line * 0.6f), ImGui::GetColorU32(ImGuiCol_TextDisabled), detail.c_str(), nullptr, wrap - (textleft - left)); + auto const detailsize{ImGui::CalcTextSize(detail.c_str(), nullptr, false, wrap - (textleft - left))}; + ImGui::SetCursorScreenPos(ImVec2(textleft, std::max(top + mouse, top + big + line * 0.6f + detailsize.y) + line)); + if (selected != nullptr) + { + if (ImGui::Button(format(STR_C("Along the line of %s"), selected->name().c_str()).c_str())) + profile_open_run(*selected); + ImGui::SameLine(); + } + profile_library_load(); + if (false == m_profiles.empty() && ImGui::Button(format(STR_C("Designs kept in the scenery (%zu)..."), m_profiles.size()).c_str())) + ImGui::OpenPopup("##profilekept"); + if (ImGui::BeginPopup("##profilekept")) + { + for (std::size_t i = 0; i < m_profiles.size(); ++i) + { + auto const &entry{m_profiles[i]}; + ImGui::PushID(static_cast(i)); + if (ImGui::Selectable(format(STR_P("%s %.1f m, %zu point", "%s %.1f m, %zu points", entry.line.points.size()), scene::Layers.layer(entry.layer).name.c_str(), entry.length, entry.line.points.size()).c_str())) + profile_open_stored(i); + ImGui::PopID(); + } + ImGui::EndPopup(); + } + if (false == state.error.empty()) + { + ImGui::SetCursorScreenPos(ImVec2(textleft, ImGui::GetCursorScreenPos().y)); + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.3f, 1.0f), "%s", state.error.c_str()); + } +} + +void editor_mode::render_profile_source() +{ + gesture_rows({{"LMB on a track", "its whole line"}, {"Shift+LMB on more tracks", "the route between the outermost ones"}, {"Shift+drag a box", "the route over the tracks in it"}}); + profile_library_load(); + if (false == m_profiles.empty() && ImGui::TreeNode("##profilestored", STR_C("Designs kept in the scenery (%zu)"), m_profiles.size())) + { + for (std::size_t i = 0; i < m_profiles.size(); ++i) + { + auto const &entry{m_profiles[i]}; + ImGui::PushID(static_cast(i)); + if (ImGui::SmallButton(STR_C("Open"))) + profile_open_stored(i); + ImGui::SameLine(); + ImGui::Text(STR_P("%s %.1f m, %zu point, from (%.1f, %.1f) to (%.1f, %.1f)", "%s %.1f m, %zu points, from (%.1f, %.1f) to (%.1f, %.1f)", entry.line.points.size()), scene::Layers.layer(entry.layer).name.c_str(), entry.length, entry.line.points.size(), entry.start.x, entry.start.z, entry.end.x, entry.end.z); + ImGui::PopID(); + } + ImGui::TreePop(); + } +} + +bool editor_mode::render_profile_parameters() +{ + auto &state{m_profile}; + auto &line{state.line}; + bool changed{false}; + auto const drag = [](char const *Label, double &Value, float const Speed, char const *Format) { + field_row(Label); + ImGui::PushID(Label); + auto const edited{ImGui::DragScalar("##value", ImGuiDataType_Double, &Value, Speed, nullptr, nullptr, Format)}; + ImGui::PopID(); + return edited; + }; + if (begin_fields("##profileline", 0.5f)) + { + drag("Chainage of the start (m)", state.origin, 1.0f, "%.2f"); + changed |= drag("Design speed (km/h)", line.speed, 1.0f, "%.0f"); + ImGui::EndTable(); + } + line.speed = std::max(1.0, line.speed); + auto const join_tooltip = [] { + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Keeps the elevation of the joint and takes over the grade of the adjoining track,\nwith a vertical curve which starts right at the joint")); + }; + if (state.context.start_joined) + { + changed |= ImGui::Checkbox(STR_C("Join the adjoining track at the start"), &line.join_start); + join_tooltip(); + } + if (state.context.end_joined) + { + changed |= ImGui::Checkbox(STR_C("Join the adjoining track at the end"), &line.join_end); + join_tooltip(); + } + if (ImGui::TreeNode(STR_C("Norms"))) + { + auto &norms{line.norms}; + auto const table{begin_fields("##profilelimits", 0.6f)}; + changed |= table && drag("Maximum grade (per mille)", norms.grade_max, 0.1f, "%.2f"); + if (table) + { + changed |= drag("Maximum grade over switches (per mille)", norms.grade_switch_max, 0.1f, norms.grade_switch_max > 0.0 ? "%.2f" : STR_C("as the line")); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("0: the limit of the line, a switch may lie on its grade.\nA lower one for the tracks of a station where the vehicles stand, e.g. 2.5")); + changed |= drag("Vertical curve R >= k*V^2, k", norms.radius_factor, 0.01f, "%.2f"); + item_tooltip("The required radius of a vertical curve grows with the square of the design speed: R = k * V^2, V in km/h"); + changed |= drag("Vertical curve R min (m)", norms.radius_min, 10.0f, "%.0f"); + item_tooltip("A vertical curve is never smaller than this, even at a low speed"); + changed |= drag("Vertical curve needed above a change of (per mille)", norms.curve_threshold, 0.1f, "%.2f"); + item_tooltip("A smaller change of grade may stay a sharp break, without a curve"); + changed |= drag("Constant grade between curves at least (m)", norms.element_min, 1.0f, "%.0f"); + item_tooltip("The shortest stretch of one grade between two vertical curves; 0: not checked"); + changed |= drag("Tolerance at fixed points (m)", norms.fixed_tolerance, 0.001f, "%.3f"); + item_tooltip("How far the grade line may pass from a fixed point, e.g. the joint with the adjoining track, before it's reported"); + ImGui::EndTable(); + } + norms.grade_switch_max = std::max(0.0, norms.grade_switch_max); + norms.radius_factor = std::max(0.0, norms.radius_factor); + norms.radius_min = std::max(10.0, norms.radius_min); + if (ImGui::SmallButton(STR_C("Automatic R at all points"))) + { + for (auto &point : line.points) + point.automatic = true; + changed = true; + } + ImGui::TextDisabled(STR_C("Required R for %.0f km/h: %.0f m"), line.speed, profile::required_radius(line)); + ImGui::TreePop(); + } + auto const errors{std::count_if(state.issues.begin(), state.issues.end(), [](profile::issue const &Issue) { return Issue.error; })}; + auto const warnings{static_cast(state.issues.size()) - errors}; + ImGui::PushTextWrapPos(0.0f); + auto const good{IM_COL32(100, 230, 100, 255)}; + ImGui::BeginGroup(); + metric_tiles({{format("%d", static_cast(errors)), STR_C("errors"), errors > 0 ? IM_COL32(255, 100, 80, 255) : good}, + {format("%d", static_cast(warnings)), STR_C("warnings"), warnings > 0 ? IM_COL32(255, 200, 80, 255) : good}, + {format("%.3f m", state.departure), STR_C("off the track"), ImGui::GetColorU32(ImGuiCol_Text)}}); + ImGui::EndGroup(); + item_tooltip("From the track, To the ground and Apply to the scenery are over the plot of the strip"); + if (errors + warnings > 0) + ImGui::TextDisabled("%s", STR_C("The list of them: Remarks in the strip under the view")); + else + ImGui::TextColored(ImVec4(0.4f, 0.9f, 0.4f, 1.0f), "%s", STR_C("The grade line meets the limits")); + ImGui::PopTextWrapPos(); + return changed; +} + +void editor_mode::render_profile_issues() +{ + auto &state{m_profile}; + ImGui::BeginChild("##profileissues", ImVec2(0.0f, 0.0f), false); + if (state.issues.empty()) + ImGui::TextColored(ImVec4(0.4f, 0.9f, 0.4f, 1.0f), "%s", STR_C("The grade line meets the limits")); + else + ImGui::TextDisabled("%s", STR_C("LMB on a remark shows its place")); + for (std::size_t i = 0; i < state.issues.size(); ++i) + { + auto const &issue{state.issues[i]}; + ImGui::PushID(static_cast(i)); + ImGui::PushStyleColor(ImGuiCol_Text, issue.error ? ImVec4(1.0f, 0.4f, 0.3f, 1.0f) : ImVec4(1.0f, 0.8f, 0.3f, 1.0f)); + auto const text{format("%s km %s %s", issue.error ? "x" : "!", profile::format_chainage(issue.chainage + state.origin).c_str(), issue.text.c_str())}; + if (ImGui::Selectable(text.c_str())) + { + if (issue.point >= 0) + state.selected = issue.point; + auto const half{(state.view_to - state.view_from) * 0.5}; + state.view_from = issue.chainage - half; + state.view_to = issue.chainage + half; + } + ImGui::PopStyleColor(); + ImGui::PopID(); + } + if (false == state.status.empty()) + ImGui::TextWrapped("%s", state.status.c_str()); + if (false == state.error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.3f, 1.0f), "%s", state.error.c_str()); + ImGui::EndChild(); +} + +void editor_mode::render_profile_point() +{ + auto &state{m_profile}; + auto &points{state.line.points}; + bool changed{false}; + auto const count{static_cast(points.size())}; + if (state.selected >= count) + state.selected = -1; + auto const drag = [](char const *Label, double &Value, float const Speed, char const *Format) { + field_row(Label); + ImGui::PushID(Label); + auto const edited{ImGui::DragScalar("##value", ImGuiDataType_Double, &Value, Speed, nullptr, nullptr, Format)}; + ImGui::PopID(); + return edited; + }; + auto const kind_of = [](double const Change) { return Change > 0.0 ? STR_C("sag") : STR_C("crest"); }; + if (state.selected < 0) + { + ImGui::TextWrapped("%s", STR_C("No point selected. Click a point of the grade line in the plot, or double click the line to add one.")); + } + else if (points[state.selected].joint) + { + auto const index{state.selected}; + auto const &point{points[index]}; + auto const change{(profile::grade_after(state.line, index) - profile::grade_after(state.line, index - 1)) * 1000.0}; + ImGui::Text(STR_C("Point %d: joint with the adjoining track"), index + 1); + ImGui::Text(STR_C("km %s H %.3f m R %.0f m"), profile::format_chainage(point.chainage + state.origin).c_str(), point.elevation, point.radius); + ImGui::Text(STR_C("Grade %+.2f -> %+.2f per mille (%s)"), profile::grade_after(state.line, index - 1) * 1000.0, profile::grade_after(state.line, index) * 1000.0, kind_of(change)); + ImGui::TextWrapped("%s", STR_C("Placed automatically, moves with the neighbouring point; untick the joining in the tool options to edit the end freely")); + } + else + { + auto const index{state.selected}; + auto &point{points[index]}; + bool const end{index == 0 || index == count - 1}; + bool const locked{end_locked(state.line, state.context, index)}; + ImGui::Text(STR_C("Point %d"), index + 1); + ImGui::SameLine(); + ImGui::TextDisabled(STR_C("km %s%s"), profile::format_chainage(point.chainage + state.origin).c_str(), locked ? STR_C(", joined to the adjoining track") : end ? STR_C(", end of the route") : ""); + if (begin_fields("##profilepoint", 0.45f)) + { + auto chainage{point.chainage + state.origin}; + if (false == end && drag("Chainage (m)", chainage, 0.5f, "%.2f")) + { + point.chainage = std::clamp(chainage - state.origin, points[index - 1].chainage + 0.5, points[index + 1].chainage - 0.5); + changed = true; + } + if (locked) + { + field_row("Elevation (m)"); + ImGui::Text("%.3f", point.elevation); + } + else + changed |= drag("Elevation (m)", point.elevation, 0.01f, "%.3f"); + if (index > 0 && false == locked) + { + auto grade{profile::grade_after(state.line, index - 1) * 1000.0}; + if (drag("Grade before (per mille)", grade, 0.05f, "%+.2f")) + { + point.elevation = points[index - 1].elevation + grade / 1000.0 * (point.chainage - points[index - 1].chainage); + changed = true; + } + } + if (index + 1 < count) + { + auto grade{profile::grade_after(state.line, index) * 1000.0}; + if (drag("Grade after (per mille)", grade, 0.05f, "%+.2f")) + { + points[index + 1].elevation = point.elevation + grade / 1000.0 * (points[index + 1].chainage - point.chainage); + changed = true; + } + } + if (false == end) + { + field_row("Vertical curve R (m)"); + auto const box{ImGui::GetFrameHeight() + ImGui::GetStyle().ItemInnerSpacing.x + ImGui::CalcTextSize(STR_C("auto")).x}; + ImGui::SetNextItemWidth(std::max(40.0f, ImGui::GetContentRegionAvail().x - box - ImGui::GetStyle().ItemSpacing.x)); + if (ImGui::DragScalar("##pointradius", ImGuiDataType_Double, &point.radius, 10.0f, nullptr, nullptr, "%.0f")) + { + point.automatic = false; + changed = true; + } + if (ImGui::IsItemHovered()) + { + auto const change{(profile::grade_after(state.line, index) - profile::grade_after(state.line, index - 1)) * 1000.0}; + auto const tangent{point.radius * std::abs(change) / 2000.0}; + auto text{std::string{STR_C("The radius of the vertical curve which rounds off the break of the grade here")} + "\n" + format(STR_C("Change of grade %+.2f per mille, %s"), change, kind_of(change))}; + if (point.radius > 0.0) + text += "\n" + format(STR_C("Tangent T %.2f m, sagitta f %.3f m"), tangent, tangent * tangent / (2.0 * point.radius)); + ImGui::SetTooltip("%s", text.c_str()); + } + point.radius = std::max(0.0, point.radius); + ImGui::SameLine(); + changed |= ImGui::Checkbox(STR_C("auto"), &point.automatic); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("R follows the limits: the required radius where the change of grade needs a curve; 0: no curve")); + } + ImGui::EndTable(); + } + if (index + 1 < count && ImGui::Button(STR_C("Add a point after"))) + { + profile::pvi inserted; + inserted.chainage = (point.chainage + points[index + 1].chainage) * 0.5; + inserted.elevation = (point.elevation + points[index + 1].elevation) * 0.5; + points.insert(points.begin() + index + 1, inserted); + state.selected = index + 1; + changed = true; + } + if (false == end) + { + ImGui::SameLine(); + if (ImGui::Button(STR_C("Remove Del"))) + { + profile_remove_point(index); + return; + } + } + } + if (changed) + profile_edited(); +} + +void editor_mode::render_profile_points() +{ + auto &state{m_profile}; + auto const &points{state.line.points}; + ImGui::Columns(4, "##profilepointcolumns", false); + for (auto const *header : {"#", "km", "H (m)", "R (m)"}) + { + ImGui::TextDisabled("%s", header); + ImGui::NextColumn(); + } + ImGui::Separator(); + for (int i = 0; i < static_cast(points.size()); ++i) + { + auto const &point{points[i]}; + if (ImGui::Selectable(format("%d##point%d", i + 1, i).c_str(), state.selected == i, ImGuiSelectableFlags_SpanAllColumns)) + { + state.selected = i; + auto const half{(state.view_to - state.view_from) * 0.5}; + if (point.chainage < state.view_from || point.chainage > state.view_to) + { + state.view_from = point.chainage - half; + state.view_to = point.chainage + half; + } + } + ImGui::NextColumn(); + ImGui::TextUnformatted(profile::format_chainage(point.chainage + state.origin).c_str()); + ImGui::NextColumn(); + ImGui::Text("%.3f", point.elevation); + ImGui::NextColumn(); + if (point.radius > 0.0) + ImGui::Text("%.0f%s", point.radius, point.joint ? STR_C(" joint") : point.automatic ? STR_C(" auto") : ""); + else + ImGui::TextDisabled("-"); + ImGui::NextColumn(); + } + ImGui::Columns(1); +} + +// screen mapping of the profile canvas, chainage across and elevation upwards +struct editor_mode::profile_view +{ + ImVec2 corner; + ImVec2 size; + float strip; + float top; + float height; + double across; + double vertical; + double from; + double centre; + + profile_view(profile_state const &State, ImVec2 const Corner, ImVec2 const Size) : + corner{Corner}, size{Size}, strip{State.show_plan ? 44.0f : 0.0f}, top{18.0f}, height{Size.y - strip - top}, + across{std::max(1.0, State.view_to - State.view_from) / Size.x}, vertical{across / State.exaggeration}, from{State.view_from}, centre{State.view_centre} + { + } + float x_of(double const Chainage) const { return corner.x + static_cast((Chainage - from) / across); } + float y_of(double const Height) const { return corner.y + top + height * 0.5f - static_cast((Height - centre) / vertical); } + double chainage_of(float const X) const { return from + (X - corner.x) * across; } + double height_of(float const Y) const { return centre - (Y - corner.y - top - height * 0.5f) * vertical; } + float plot_top() const { return corner.y + top; } + float plot_bottom() const { return corner.y + top + height; } + ImVec2 bottom_right() const { return {corner.x + size.x, corner.y + size.y}; } + float mouse_distance2(double const Chainage, double const Height) const + { + auto const &mouse{ImGui::GetIO().MousePos}; + auto const dx{x_of(Chainage) - mouse.x}; + auto const dy{y_of(Height) - mouse.y}; + return dx * dx + dy * dy; + } +}; + +void editor_mode::render_profile_toolbar() +{ + auto &state{m_profile}; + // the next item on the same line while it fits, past the edge of the plot on the next one + auto const edge{ImGui::GetWindowPos().x + ImGui::GetWindowContentRegionMax().x}; + auto const next = [&](float const Gap, float const Width) { + ImGui::SameLine(0.0f, Gap); + if (ImGui::GetCursorScreenPos().x + Width > edge) + ImGui::NewLine(); + }; + auto const pill = [](char const *Label) { return ImGui::CalcTextSize(Label).x + ImGui::GetFrameHeight() * 1.75f; }; + ImGui::AlignTextToFramePadding(); + ImGui::TextDisabled("%s", STR_C("Show:")); + next(ImGui::GetStyle().ItemSpacing.x, pill(STR_C("Track"))); + pill_toggle(STR_C("Track"), kTrack, state.show_track); + next(4.0f, pill(STR_C("Terrain"))); + pill_toggle(STR_C("Terrain"), kTerrain, state.show_terrain); + if (m_nmt.placed()) + { + next(4.0f, pill(STR_C("Terrain model"))); + if (pill_toggle(STR_C("Terrain model"), kModel, state.show_model)) + profile_sample_model(); + item_tooltip(state.model_waiting ? "The ground of the terrain model (NMT) as it was measured, before the earthworks; its squares along the route are still being fetched" + : "The ground of the terrain model (NMT) as it was measured, before the earthworks"); + } + next(4.0f, pill(STR_C("Plan curvature"))); + pill_toggle(STR_C("Plan curvature"), kPlan, state.show_plan); + next(6.0f, ImGui::CalcTextSize("(?)").x); + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::TextUnformatted(STR_C("Legend")); + ImGui::Separator(); + auto *draw{ImGui::GetWindowDrawList()}; + auto const entry = [&](ImU32 const Colour, char const *Label) { + auto const at{ImGui::GetCursorScreenPos()}; + auto const height{ImGui::GetTextLineHeight()}; + draw->AddLine(ImVec2(at.x, at.y + height * 0.5f), ImVec2(at.x + 22.0f, at.y + height * 0.5f), Colour, 3.0f); + ImGui::Dummy(ImVec2(22.0f, height)); + ImGui::SameLine(0.0f, 8.0f); + ImGui::TextUnformatted(STR_C(Label)); + }; + entry(kGradeLine, "Grade line"); + entry(kTangents, "Tangents"); + entry(kTrack, "Track"); + entry(kTerrain, "Terrain"); + entry(kFormation, "Formation"); + entry(kModel, "Terrain model"); + entry(kPlan, "Plan curvature"); + entry(kSwitchLabel, "Switches"); + entry(kSharedEdge, "Shared timbers"); + entry(kError, "Errors"); + entry(kWarning, "Warnings"); + ImGui::EndTooltip(); + } + next(14.0f, 120.0f); + ImGui::SetNextItemWidth(120.0f); + ImGui::SliderFloat("##exaggeration", &state.exaggeration, 1.0f, 500.0f, STR_C("heights x%.0f"), ImGuiSliderFlags_Logarithmic); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Exaggeration of the heights against the lengths, also Ctrl+wheel over the plot")); + next(ImGui::GetStyle().ItemSpacing.x, ImGui::CalcTextSize(STR_C("Fit")).x + ImGui::GetStyle().FramePadding.x * 2.0f); + if (ImGui::Button(STR_C("Fit"))) + profile_fit_view(); + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Shows the whole route")); + // the camera and the plot brought to one another only when asked: the camera doesn't turn as the plot is zoomed + auto const button = [](char const *Label) { return ImGui::CalcTextSize(Label).x + ImGui::GetStyle().FramePadding.x * 2.0f; }; + next(14.0f, button(STR_C("Camera to the plot"))); + if (ImGui::Button(STR_C("Camera to the plot"))) + profile_frame_view(); + item_tooltip("Moves the camera to the part of the route the plot shows"); + next(ImGui::GetStyle().ItemSpacing.x, button(STR_C("Plot to the camera"))); + if (ImGui::Button(STR_C("Plot to the camera"))) + profile_to_camera(); + item_tooltip("Moves the plot to the part of the route where the camera is, its zoom kept"); +} + +void editor_mode::render_profile_canvas(float const Height) +{ + auto &state{m_profile}; + auto const available{ImGui::GetContentRegionAvail()}; + auto const hintheight{std::round(ImGui::GetTextLineHeight() * 1.2f)}; + auto const hintrow{hintheight + 8.0f}; + ImVec2 const size{std::max(200.0f, available.x), std::max(100.0f, Height - hintrow)}; + ImVec2 const corner{ImGui::GetCursorScreenPos()}; + ImGui::InvisibleButton("##profilecanvas", size); + bool const hovered{ImGui::IsItemHovered()}; + + if (state.exaggeration <= 0.0f) + profile_fit_exaggeration(profile_view{state, corner, size}); + if (state.model_waiting && ImGui::GetTime() - state.model_polled > 0.5) + profile_sample_model(); + profile_navigate(profile_view{state, corner, size}, hovered); + profile_view const view{state, corner, size}; + if (profile_canvas_edit(view, hovered)) + profile_edited(); + state.hover = hovered ? view.chainage_of(ImGui::GetIO().MousePos.x) : -1.0; + + auto *draw{ImGui::GetWindowDrawList()}; + draw->AddRectFilled(corner, view.bottom_right(), IM_COL32(22, 24, 28, 255)); + draw->PushClipRect(corner, view.bottom_right(), true); + draw_profile_canvas(view, *draw); + if (hovered && state.hover >= 0.0 && state.hover <= state.route.length && false == state.samples.empty()) + { + auto const x{view.x_of(state.hover)}; + draw->AddLine(ImVec2(x, view.plot_top()), ImVec2(x, view.bottom_right().y), IM_COL32(255, 255, 255, 90)); + if (state.hover_point < 0 && state.hover_grip < 0 && state.curve_grip < 0) + profile_canvas_tooltip(); + } + + draw->PopClipRect(); + + // what the mouse does over the thing under it, along the bottom of the plot + std::vector> hints{{"wheel", "zoom"}, {"Ctrl+wheel", "heights"}, {"RMB move", "pan"}, {"LMB LMB", "on the line: add a point"}}; + if (state.dragging >= 0) + hints = {{"Ctrl", "only the height"}, {"Shift", "keep the grade before"}}; + else if (state.curve_grip >= 0 || state.hover_grip >= 0) + hints = {{"LMB move", "up or down: radius of the vertical curve"}}; + else if (state.hover_point >= 0) + hints = {{"LMB move", "move the point"}, {"Ctrl+LMB", "only the height"}, {"Shift+LMB", "keep the grade before"}, {"Del", "remove"}}; + else if (state.hover_line) + hints = {{"LMB LMB", "add a point here"}}; + { + auto const height{hintheight}; + auto x{corner.x + 6.0f}; + auto const y{corner.y + size.y + 4.0f}; + draw->AddRectFilled(ImVec2(corner.x, corner.y + size.y), ImVec2(corner.x + size.x, corner.y + size.y + hintrow), IM_COL32(14, 15, 19, 255)); + draw->PushClipRect(ImVec2(corner.x, corner.y + size.y), ImVec2(corner.x + size.x, corner.y + size.y + hintrow), true); + for (auto const &hint : hints) + { + auto const words{gesture_words(hint.first)}; + auto const text{STR(hint.second)}; + if (x + gesture_width(height, words) + 6.0f + ImGui::CalcTextSize(text.c_str()).x > corner.x + size.x - 6.0f) + break; + x += gesture_draw(*draw, ImVec2(x, y), height, words, kLabel) + 6.0f; + draw->AddText(ImVec2(x, std::round(y + (height - ImGui::GetTextLineHeight()) * 0.5f)), IM_COL32(235, 235, 235, 255), text.c_str()); + x += ImGui::CalcTextSize(text.c_str()).x + 18.0f; + } + draw->PopClipRect(); + } + ImGui::Dummy(ImVec2(size.x, hintrow)); + + auto const &points{state.line.points}; + if (state.dragging >= 0 && state.dragging < static_cast(points.size())) + { + auto const index{state.dragging}; + ImGui::BeginTooltip(); + ImGui::Text(STR_C("Point %d"), index + 1); + ImGui::Text(STR_C("km %s H %.3f m"), profile::format_chainage(points[index].chainage + state.origin).c_str(), points[index].elevation); + if (index > 0) + ImGui::Text(STR_C("before %+.2f per mille"), profile::grade_after(state.line, index - 1) * 1000.0); + if (index + 1 < static_cast(points.size())) + ImGui::Text(STR_C("after %+.2f per mille"), profile::grade_after(state.line, index) * 1000.0); + ImGui::EndTooltip(); + } + else if (state.curve_grip > 0 && state.curve_grip < static_cast(points.size())) + { + ImGui::BeginTooltip(); + ImGui::Text("R %.0f m", points[state.curve_grip].radius); + ImGui::EndTooltip(); + } +} + +void editor_mode::profile_fit_exaggeration(profile_view const &View) +{ + auto &state{m_profile}; + double low{std::numeric_limits::max()}; + double high{std::numeric_limits::lowest()}; + for (auto const &sample : state.samples) + { + low = std::min(low, sample.position.y); + high = std::max(high, sample.position.y); + } + for (auto const &point : state.line.points) + { + low = std::min(low, point.elevation); + high = std::max(high, point.elevation); + } + if (low > high) + { + low = 0.0; + high = 0.0; + } + auto const range{std::max(1.0, (high - low) * 1.3)}; + state.exaggeration = static_cast(std::clamp(View.across / (range / View.height), 1.0, 500.0)); + state.view_centre = (low + high) * 0.5; +} + +void editor_mode::profile_navigate(profile_view const &View, bool const Hovered) +{ + auto &state{m_profile}; + ImGuiIO const &io{ImGui::GetIO()}; + if (Hovered && io.MouseWheel != 0.0f) + { + if (io.KeyCtrl) + state.exaggeration = std::clamp(state.exaggeration * std::pow(1.2f, io.MouseWheel), 1.0f, 500.0f); + else + { + auto const anchor{View.chainage_of(io.MousePos.x)}; + auto const factor{std::pow(0.8, static_cast(io.MouseWheel))}; + state.view_from = anchor - (anchor - state.view_from) * factor; + state.view_to = anchor + (state.view_to - anchor) * factor; + } + } + if (Hovered && (ImGui::IsMouseClicked(1) || ImGui::IsMouseClicked(2))) + state.panning = true; + if (state.panning) + { + if (ImGui::IsMouseDown(1) || ImGui::IsMouseDown(2)) + { + state.view_from -= io.MouseDelta.x * View.across; + state.view_to -= io.MouseDelta.x * View.across; + state.view_centre += io.MouseDelta.y * View.vertical; + } + else + state.panning = false; + } +} + +bool editor_mode::profile_canvas_edit(profile_view const &View, bool const Hovered) +{ + auto &state{m_profile}; + auto &line{state.line}; + auto &points{line.points}; + ImGuiIO const &io{ImGui::GetIO()}; + ImVec2 const mouse{io.MousePos}; + + auto const hit_point = [&]() { + int hit{-1}; + float best{64.0f}; + for (int i = 0; i < static_cast(points.size()); ++i) + { + if (points[i].joint) + continue; + if (auto const distance{View.mouse_distance2(points[i].chainage, points[i].elevation)}; distance < best) + { + best = distance; + hit = i; + } + } + return hit; + }; + auto const hit_grip = [&]() { + for (auto const &c : profile::curves(line)) + { + if (points[c.point].joint) + continue; + auto const chainage{points[c.point].chainage}; + if (View.mouse_distance2(chainage, profile::elevation(line, chainage)) < 64.0f) + return static_cast(c.point); + } + return -1; + }; + bool changed{false}; + bool const busy{state.dragging >= 0 || state.curve_grip >= 0 || state.panning}; + state.hover_point = Hovered && false == busy ? hit_point() : -1; + state.hover_grip = Hovered && false == busy && state.hover_point < 0 ? hit_grip() : -1; + state.hover_line = false; + if (Hovered && false == busy && state.hover_point < 0 && state.hover_grip < 0 && points.size() >= 2) + { + auto const chainage{View.chainage_of(mouse.x)}; + state.hover_line = chainage > points.front().chainage && chainage < points.back().chainage && std::abs(View.y_of(profile::elevation(line, chainage)) - mouse.y) < 12.0f; + } + if (state.dragging >= 0 || state.panning) + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeAll); + else if (state.curve_grip >= 0 || state.hover_grip >= 0) + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS); + else if (state.hover_point >= 0 || state.hover_line) + ImGui::SetMouseCursor(ImGuiMouseCursor_Hand); + if (Hovered && ImGui::IsMouseClicked(0)) + { + auto const point{hit_point()}; + auto const grip{point < 0 ? hit_grip() : -1}; + if (point >= 0) + { + state.dragging = point; + state.selected = state.dragging; + state.drag_press = mouse; + state.drag_grab = {points[point].chainage - View.chainage_of(mouse.x), points[point].elevation - View.height_of(mouse.y)}; + state.drag_moved = false; + } + else if (grip >= 0) + { + state.curve_grip = grip; + state.selected = state.curve_grip; + state.drag_press = mouse; + state.drag_moved = false; + } + else + state.selected = -1; + } + if (Hovered && ImGui::IsMouseDoubleClicked(0) && state.dragging < 0 && state.curve_grip < 0 && points.size() >= 2) + { + auto const chainage{View.chainage_of(mouse.x)}; + if (chainage > points.front().chainage + 0.5 && chainage < points.back().chainage - 0.5 && std::abs(View.y_of(profile::elevation(line, chainage)) - mouse.y) < 12.0f) + { + std::size_t index{0}; + while (index + 2 < points.size() && points[index + 1].chainage < chainage) + ++index; + profile::pvi inserted; + inserted.chainage = std::round(chainage * 100.0) / 100.0; + inserted.elevation = points[index].elevation + profile::grade_after(line, index) * (inserted.chainage - points[index].chainage); + points.insert(points.begin() + index + 1, inserted); + state.selected = static_cast(index) + 1; + changed = true; + } + } + if (state.dragging >= 0 && state.dragging < static_cast(points.size())) + { + // a click selects the point, it moves only when dragged, by as much as the mouse went + state.drag_moved = state.drag_moved || std::abs(mouse.x - state.drag_press.x) > 3.0f || std::abs(mouse.y - state.drag_press.y) > 3.0f; + if (false == ImGui::IsMouseDown(0)) + state.dragging = -1; + else if (state.drag_moved) + { + auto const index{state.dragging}; + auto &point{points[index]}; + bool const end{index == 0 || index + 1 == static_cast(points.size())}; + auto const incoming{index > 0 ? profile::grade_after(line, index - 1) : 0.0}; + if (false == end && false == io.KeyCtrl) + point.chainage = std::clamp(std::round((View.chainage_of(mouse.x) + state.drag_grab.x) * 100.0) / 100.0, points[index - 1].chainage + 0.5, points[index + 1].chainage - 0.5); + if (end_locked(line, state.context, index)) + ; + else if (io.KeyShift && index > 0) + point.elevation = points[index - 1].elevation + incoming * (point.chainage - points[index - 1].chainage); + else + point.elevation = std::round((View.height_of(mouse.y) + state.drag_grab.y) * 1000.0) / 1000.0; + changed = true; + } + } + else + state.dragging = -1; + if (state.curve_grip > 0 && state.curve_grip + 1 < static_cast(points.size())) + { + // a click on the grip leaves the radius as it is + state.drag_moved = state.drag_moved || std::abs(mouse.y - state.drag_press.y) > 3.0f; + if (false == ImGui::IsMouseDown(0)) + state.curve_grip = -1; + else if (state.drag_moved) + { + auto const sagitta{View.height_of(mouse.y) - points[state.curve_grip].elevation}; + points[state.curve_grip].radius = std::max(10.0, std::round(profile::radius_for_sagitta(line, state.curve_grip, sagitta) / 10.0) * 10.0); + points[state.curve_grip].automatic = false; + changed = true; + } + } + else + state.curve_grip = -1; + if ((Hovered || ImGui::IsWindowFocused()) && state.selected > 0 && state.selected + 1 < static_cast(points.size()) && false == points[state.selected].joint && ImGui::IsKeyPressed(ImGuiKey_Delete)) + profile_remove_point(state.selected); + return changed; +} + +void editor_mode::draw_profile_canvas(profile_view const &View, ImDrawList &Draw) const +{ + auto const &state{m_profile}; + auto const &line{state.line}; + auto const &points{line.points}; + auto const &samples{state.samples}; + auto const bottomright{View.bottom_right()}; + auto const plottop{View.plot_top()}; + auto const plotbottom{View.plot_bottom()}; + + auto const step{nice_step(View.across * 110.0)}; + auto const firsts{std::ceil((state.view_from + state.origin) / step) * step - state.origin}; + for (int i = 0; firsts + i * step <= state.view_to; ++i) + { + auto const s{firsts + i * step}; + auto const x{View.x_of(s)}; + Draw.AddLine(ImVec2(x, plottop), ImVec2(x, plotbottom), kGrid); + Draw.AddText(ImVec2(x + 3.0f, View.corner.y + 2.0f), kLabel, profile::format_chainage(s + state.origin).c_str()); + } + auto const heightstep{nice_step(View.vertical * 45.0)}; + auto const firsth{std::floor(View.height_of(plotbottom) / heightstep) * heightstep}; + for (int i = 0; firsth + i * heightstep <= View.height_of(plottop); ++i) + { + auto const y{View.y_of(firsth + i * heightstep)}; + Draw.AddLine(ImVec2(View.corner.x, y), ImVec2(bottomright.x, y), kGrid); + } + for (auto const &zone : state.context.switches) + { + auto const left{View.x_of(zone.from)}; + auto const right{std::max(View.x_of(zone.to), left + 2.0f)}; + if (zone.name == STR("shared timbers")) + { + // the timbers shared with another track, past a switch or at a crossing: drawn with their bounds, nothing + // breaks the grade over them + Draw.PushClipRect(ImVec2(left, plottop), ImVec2(right, plotbottom), true); + auto const height{plotbottom - plottop}; + for (int k = 0; left - height + 8.0f * static_cast(k) < right; ++k) + { + auto const x{left - height + 8.0f * static_cast(k)}; + Draw.AddLine(ImVec2(x, plotbottom), ImVec2(x + height, plottop), kShared, 1.5f); + } + Draw.PopClipRect(); + Draw.AddLine(ImVec2(left, plottop), ImVec2(left, plotbottom), kSharedEdge, 1.0f); + Draw.AddLine(ImVec2(right, plottop), ImVec2(right, plotbottom), kSharedEdge, 1.0f); + if (right - left > 4.0f) + Draw.AddText(ImVec2(left + 2.0f, plotbottom - 32.0f), kSharedEdge, zone.name.c_str()); + continue; + } + Draw.AddRectFilled(ImVec2(left, plottop), ImVec2(right, plotbottom), kSwitch); + if (right - left > 20.0f || View.across < 0.5) + Draw.AddText(ImVec2(left + 2.0f, plotbottom - 16.0f), kSwitchLabel, zone.name.c_str()); + } + // the ends which inherit the grade line from a switch, said where they are + if (false == state.start_inherits.empty()) + { + auto const x{View.x_of(0.0)}; + Draw.AddLine(ImVec2(x, plottop), ImVec2(x, plotbottom), kSwitchLabel, 2.0f); + Draw.AddText(ImVec2(x + 4.0f, plottop + 18.0f), kSwitchLabel, ("<- " + state.start_inherits).c_str()); + } + if (false == state.end_inherits.empty()) + { + auto const x{View.x_of(state.route.length)}; + auto const text{state.end_inherits + " ->"}; + Draw.AddLine(ImVec2(x, plottop), ImVec2(x, plotbottom), kSwitchLabel, 2.0f); + Draw.AddText(ImVec2(x - 4.0f - ImGui::CalcTextSize(text.c_str()).x, plottop + 34.0f), kSwitchLabel, text.c_str()); + } + + auto const polyline = [&](auto const &Height, ImU32 const Colour, float const Thickness) { + ImVec2 previous{}; + bool open{false}; + float lastx{-1e9f}; + for (std::size_t i = 0; i < samples.size(); ++i) + { + auto const x{View.x_of(samples[i].chainage)}; + auto const h{Height(i)}; + if (std::isnan(h) || x < View.corner.x - 50.0f || x > bottomright.x + 50.0f) + { + open = false; + continue; + } + if (open && x - lastx < 1.0f && i + 1 < samples.size()) + continue; + ImVec2 const next{x, View.y_of(h)}; + if (open) + Draw.AddLine(previous, next, Colour, Thickness); + previous = next; + lastx = x; + open = true; + } + }; + if (state.show_terrain) + { + auto const fill{(kTerrain & 0x00FFFFFFu) | 0x30000000u}; + float lastx{-1e9f}; + ImVec2 previous{}; + bool open{false}; + for (std::size_t i = 0; i < samples.size(); ++i) + { + auto const x{View.x_of(samples[i].chainage)}; + auto const h{state.terrain[i]}; + if (std::isnan(h) || x < View.corner.x - 50.0f || x > bottomright.x + 50.0f) + { + open = false; + continue; + } + if (open && x - lastx < 2.0f && i + 1 < samples.size()) + continue; + ImVec2 const next{x, std::min(View.y_of(h), plotbottom)}; + if (open) + Draw.AddQuadFilled(previous, next, ImVec2(next.x, plotbottom), ImVec2(previous.x, plotbottom), fill); + previous = next; + lastx = x; + open = true; + } + polyline([&](std::size_t const I) { return state.terrain[I]; }, kTerrain, 1.5f); + // the formation under the grade line, which is what meets the ground + polyline([&](std::size_t const I) { return profile::elevation(state.line, samples[I].chainage) - (I < state.beds.size() ? state.beds[I] : 0.0); }, kFormation, 1.0f); + } + if (state.show_model && state.model.size() == samples.size()) + polyline([&](std::size_t const I) { return state.model[I]; }, kModel, 1.5f); + if (state.show_track) + polyline([&](std::size_t const I) { return samples[I].position.y; }, kTrack, 1.5f); + + for (std::size_t i = 0; i + 1 < points.size(); ++i) + Draw.AddLine(ImVec2(View.x_of(points[i].chainage), View.y_of(points[i].elevation)), ImVec2(View.x_of(points[i + 1].chainage), View.y_of(points[i + 1].elevation)), kTangents, 1.0f); + { + auto const from{std::max(points.front().chainage, View.chainage_of(View.corner.x))}; + auto const to{std::min(points.back().chainage, View.chainage_of(bottomright.x))}; + ImVec2 previous{View.x_of(from), View.y_of(profile::elevation(line, from))}; + auto const firstx{previous.x}; + for (int i = 1; firstx + 2.0f * i <= View.x_of(to) + 2.0f; ++i) + { + auto const x{firstx + 2.0f * i}; + auto const chainage{std::min(to, View.chainage_of(x))}; + ImVec2 const next{View.x_of(chainage), View.y_of(profile::elevation(line, chainage))}; + Draw.AddLine(previous, next, kGradeLine, 2.5f); + previous = next; + } + } + for (std::size_t i = 0; i + 1 < points.size(); ++i) + { + auto const middle{(points[i].chainage + points[i + 1].chainage) * 0.5}; + auto const x{View.x_of(middle)}; + if (View.x_of(points[i + 1].chainage) - View.x_of(points[i].chainage) < 70.0f) + continue; + auto const text{format("%+.2f o/oo L %.0f m", profile::grade_after(line, i) * 1000.0, points[i + 1].chainage - points[i].chainage)}; + auto const size{ImGui::CalcTextSize(text.c_str())}; + if (View.x_of(points[i + 1].chainage) - View.x_of(points[i].chainage) < size.x + 30.0f) + continue; + plot_label(Draw, ImVec2(x - size.x * 0.5f, View.y_of(profile::elevation(line, middle)) - size.y - 10.0f), kGradeLine, text); + } + for (auto const &c : profile::curves(line)) + { + for (auto const at : {c.start, c.end}) + { + auto const y{View.y_of(profile::elevation(line, at))}; + Draw.AddLine(ImVec2(View.x_of(at), y - 7.0f), ImVec2(View.x_of(at), y + 7.0f), kGradeLine, 1.5f); + } + auto const chainage{points[c.point].chainage}; + ImVec2 const grip{View.x_of(chainage), View.y_of(profile::elevation(line, chainage))}; + bool const lit{static_cast(c.point) == state.curve_grip || static_cast(c.point) == state.hover_grip}; + Draw.AddCircleFilled(grip, lit ? 6.5f : 4.5f, overlay_color::grip, 4); + if (lit) + Draw.AddCircle(grip, 10.0f, overlay_color::highlight, 12, 2.0f); + plot_label(Draw, ImVec2(grip.x + 8.0f, grip.y + 6.0f), overlay_color::grip, format("R %.0f", points[c.point].radius)); + } + for (int i = 0; i < static_cast(points.size()); ++i) + { + ImVec2 const at{View.x_of(points[i].chainage), View.y_of(points[i].elevation)}; + bool const lit{i == state.hover_point || i == state.dragging}; + auto const radius{lit ? 7.0f : 5.5f}; + if (i == 0 || i + 1 == static_cast(points.size())) + Draw.AddRectFilled(ImVec2(at.x - radius, at.y - radius), ImVec2(at.x + radius, at.y + radius), IM_COL32(70, 140, 255, 255)); + else if (points[i].joint) + Draw.AddQuadFilled(ImVec2(at.x, at.y - radius), ImVec2(at.x + radius, at.y), ImVec2(at.x, at.y + radius), ImVec2(at.x - radius, at.y), IM_COL32(90, 210, 230, 255)); + else + Draw.AddCircleFilled(at, radius, overlay_color::marked); + if (i == state.selected) + Draw.AddCircle(at, 11.0f, overlay_color::highlight, 16, 2.5f); + else if (lit) + Draw.AddCircle(at, 11.0f, IM_COL32(255, 255, 255, 160), 16, 1.5f); + // the heights only where they're asked for, the numbers of the points always + auto const text{i == state.selected || lit ? format("%d H %.3f", i + 1, points[i].elevation) : std::to_string(i + 1)}; + plot_label(Draw, ImVec2(at.x + 8.0f, at.y - 22.0f), overlay_color::marked, text); + } + // heights along the left edge, over everything else + for (int i = 0; firsth + i * heightstep <= View.height_of(plottop); ++i) + plot_label(Draw, ImVec2(View.corner.x + 4.0f, View.y_of(firsth + i * heightstep) - 8.0f), kLabel, format("%.1f", firsth + i * heightstep)); + for (auto const &issue : state.issues) + { + auto const x{View.x_of(issue.chainage)}; + Draw.AddTriangleFilled(ImVec2(x - 5.0f, plottop), ImVec2(x + 5.0f, plottop), ImVec2(x, plottop + 8.0f), issue.error ? kError : kWarning); + } + if (state.show_plan && false == samples.empty()) + { + auto const middle{plotbottom + View.strip * 0.5f}; + Draw.AddLine(ImVec2(View.corner.x, plotbottom), ImVec2(bottomright.x, plotbottom), IM_COL32(255, 255, 255, 60)); + Draw.AddLine(ImVec2(View.corner.x, middle), ImVec2(bottomright.x, middle), IM_COL32(255, 255, 255, 40)); + ImVec2 previous{}; + bool open{false}; + float lastx{-1e9f}; + for (std::size_t i = 0; i < samples.size(); ++i) + { + auto const x{View.x_of(samples[i].chainage)}; + if (x < View.corner.x - 50.0f || x > bottomright.x + 50.0f || (open && x - lastx < 1.0f)) + continue; + ImVec2 const next{x, middle - std::clamp(static_cast(samples[i].curvature * 300.0 * View.strip * 0.4), -View.strip * 0.45f, View.strip * 0.45f)}; + if (open) + Draw.AddLine(previous, next, IM_COL32(120, 190, 255, 255), 1.5f); + previous = next; + lastx = x; + open = true; + } + Draw.AddText(ImVec2(View.corner.x + 4.0f, plotbottom + 1.0f), kLabel, STR_C("plan: curvature (up: left)")); + } +} + +void editor_mode::profile_canvas_tooltip() const +{ + auto const &state{m_profile}; + auto const &samples{state.samples}; + auto const designed{profile::elevation(state.line, state.hover)}; + auto const existing{editor_track::sampled_elevation(samples, state.hover)}; + ImGui::BeginTooltip(); + ImGui::Text(STR_C("km %s"), profile::format_chainage(state.hover + state.origin).c_str()); + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(kGradeLine), STR_C("Grade line %.3f m, %+.2f per mille"), designed, profile::grade(state.line, state.hover) * 1000.0); + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(kTrack), STR_C("Track %.3f m (%+.3f), %+.2f per mille"), existing, existing - designed, editor_track::sampled_grade(samples, state.hover) * 1000.0); + auto const next{std::lower_bound(samples.begin(), samples.end(), state.hover, [](editor_track::route_sample const &Sample, double const Value) { return Sample.chainage < Value; })}; + auto const index{static_cast(std::distance(samples.begin(), std::min(next, std::prev(samples.end()))))}; + if (index < state.terrain.size() && false == std::isnan(state.terrain[index])) + { + auto const formation{designed - (index < state.beds.size() ? state.beds[index] : 0.0)}; + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(kFormation), STR_C("Formation %.3f m, %.2f m under the rail top"), formation, designed - formation); + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(kTerrain), STR_C("Terrain %.3f m, %s %.2f m"), state.terrain[index], formation > state.terrain[index] ? STR_C("fill") : STR_C("cut"), std::abs(formation - state.terrain[index])); + } + if (state.show_model && index < state.model.size() && false == std::isnan(state.model[index])) + ImGui::TextColored(ImGui::ColorConvertU32ToFloat4(kModel), STR_C("Terrain model %.3f m, the grade line %+.2f m from it"), state.model[index], designed - state.model[index]); + auto const &span{state.route.spans[samples[index].span]}; + ImGui::TextDisabled("%s%s", span.track->name().c_str(), span.track->eType != tt_Normal ? STR_C(" (switch, tilted as a whole with its branch)") : ""); + ImGui::EndTooltip(); +} + +void editor_mode::draw_profile_overlay() const +{ + auto const &state{m_profile}; + if (false == state.open || state.samples.size() < 2) + return; + screen_projection const projection; + ImDrawList *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const &samples{state.samples}; + glm::dvec3 previous{samples.front().position}; + glm::dvec3 designedprevious{previous.x, profile::elevation(state.line, 0.0), previous.z}; + for (std::size_t i = 1; i < samples.size(); ++i) + { + if (glm::distance(samples[i].position, previous) < 2.0 && i + 1 < samples.size()) + continue; + auto const &next{samples[i].position}; + projection.line(drawlist, previous, next, IM_COL32(255, 150, 40, 200), 2.5f); + glm::dvec3 const designed{next.x, profile::elevation(state.line, samples[i].chainage), next.z}; + if (std::abs(designed.y - next.y) > 0.01 || std::abs(designedprevious.y - previous.y) > 0.01) + projection.line(drawlist, designedprevious, designed, kGradeLine, 2.0f); + previous = next; + designedprevious = designed; + } + // the tracks sharing the grade line that go with the route + if (state.whole_grade_line) + for (auto const *track : state.beside) + for (auto const &path : track->m_paths) + projection.line(drawlist, path.points[segment_data::point::start], path.points[segment_data::point::end], IM_COL32(70, 170, 255, 200), 2.0f); + // the grade line told in the view: the grades of its straight stretches, the ranges of its vertical curves, its points + glm::dvec3 const eye{Global.pCamera.Pos}; + double constexpr labels_range{1500.0}; + auto const on_line = [&](double const Chainage) { + auto position{editor_track::sampled_position(samples, Chainage)}; + position.y = profile::elevation(state.line, Chainage); + return position; + }; + auto const label = [&](glm::dvec3 const &At, std::string const &Text, ImU32 const Colour) { + ImVec2 screen; + if (glm::distance(At, eye) > labels_range || false == projection.project(At + glm::dvec3{0.0, 1.5, 0.0}, screen)) + return; + auto const size{ImGui::CalcTextSize(Text.c_str())}; + ImVec2 const corner{screen.x - size.x * 0.5f - 4.0f, screen.y - size.y - 4.0f}; + drawlist->AddRectFilled(corner, ImVec2(corner.x + size.x + 8.0f, corner.y + size.y + 4.0f), IM_COL32(20, 20, 24, 190), 3.0f); + drawlist->AddText(ImVec2(corner.x + 4.0f, corner.y + 2.0f), Colour, Text.c_str()); + }; + auto const &points{state.line.points}; + auto const curves{profile::curves(state.line)}; + // the straight stretches between the curves + for (std::size_t k = 0; k + 1 < points.size(); ++k) + { + auto from{points[k].chainage}; + auto to{points[k + 1].chainage}; + for (auto const &curve : curves) + { + if (curve.point == k) + from = std::max(from, curve.end); + if (curve.point == k + 1) + to = std::min(to, curve.start); + } + if (to - from < 5.0) + continue; + auto const grade{(points[k + 1].elevation - points[k].elevation) / std::max(1e-6, points[k + 1].chainage - points[k].chainage) * 1000.0}; + label(on_line((from + to) * 0.5), format("%+.2f o/oo L %.0f m", grade, points[k + 1].chainage - points[k].chainage), kGradeLine); + } + // the vertical curves: their range along the track, the ends marked, the radius at the point + for (auto const &curve : curves) + { + glm::dvec3 previouscurve{on_line(curve.start)}; + auto const steps{std::max(2, static_cast((curve.end - curve.start) / 2.0))}; + for (int s = 1; s <= steps; ++s) + { + auto const next{on_line(curve.start + (curve.end - curve.start) * s / steps)}; + projection.line(drawlist, previouscurve, next, kTangents, 5.0f); + previouscurve = next; + } + for (auto const end : {curve.start, curve.end}) + { + auto const at{on_line(end)}; + auto const sample{editor_track::sampled_position(samples, std::min(state.route.length, end + 0.5)) - editor_track::sampled_position(samples, std::max(0.0, end - 0.5))}; + glm::dvec2 across{-sample.z, sample.x}; + across = glm::length(across) > 1e-9 ? glm::normalize(across) * 2.0 : glm::dvec2{2.0, 0.0}; + projection.line(drawlist, at - glm::dvec3{across.x, 0.0, across.y}, at + glm::dvec3{across.x, 0.0, across.y}, kTangents, 2.0f); + } + label(on_line(points[curve.point].chainage) + glm::dvec3{0.0, 1.2, 0.0}, format("R %.0f T %.1f m", points[curve.point].radius, curve.tangent), kTangents); + } + for (int i = 0; i < static_cast(points.size()); ++i) + { + auto const position{on_line(points[i].chainage)}; + ImVec2 screen; + if (false == projection.project(position, screen)) + continue; + drawlist->AddCircleFilled(screen, i == state.selected ? 7.0f : 5.0f, overlay_color::marked); + drawlist->AddText(ImVec2(screen.x + 8.0f, screen.y - 16.0f), overlay_color::marked, format("%d", i + 1).c_str()); + if (glm::distance(position, eye) <= labels_range * 0.5) + drawlist->AddText(ImVec2(screen.x + 8.0f, screen.y - 2.0f), overlay_color::marked, format("km %s, %.2f m", profile::format_chainage(points[i].chainage + state.origin).c_str(), points[i].elevation).c_str()); + } + if (state.hover >= 0.0 && state.hover <= state.route.length) + { + ImVec2 screen; + if (projection.project(editor_track::sampled_position(samples, state.hover), screen)) + drawlist->AddCircle(screen, 12.0f, IM_COL32(255, 255, 255, 230), 16, 2.5f); + } +} diff --git a/application/editormoderecords.cpp b/application/editormoderecords.cpp new file mode 100644 index 000000000..67498ba73 --- /dev/null +++ b/application/editormoderecords.cpp @@ -0,0 +1,576 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editoruilayer.h" +#include "application/editormodeshared.h" +#include "editor/editorFormat.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorSwitchStore.hpp" +#include "editor/editorGeometry.hpp" + +#include "world/Track.h" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" + +#include "imgui/imgui.h" +#include +#include +#include +#include + +namespace +{ + +using geometry::bezier; +using geometry::plan_of; +using geometry::signed_angle; +using geometry::turned; +using path_ends = std::pair; + +struct record_drift +{ + int followed{0}; + int departed{0}; + double departure{0.0}; + double cant{0.0}; + std::string layer; +}; + +glm::dvec2 chord_direction(glm::dvec3 const &Start, glm::dvec3 const &End) +{ + auto const direction{plan_of(End - Start)}; + return glm::length(direction) > 1e-9 ? glm::normalize(direction) : glm::dvec2{0.0, 1.0}; +} + +path_ends const &ends_before(std::vector const &Moving, std::vector const &Before, TTrack const *Track) +{ + return Before[static_cast(std::find(Moving.begin(), Moving.end(), Track) - Moving.begin())]; +} + +bool lies_on(int const Record, TTrack const &Track) +{ + bezier const curve{Track.m_paths.front()}; + std::array constexpr samples{0.0, 0.5, 1.0}; + return std::ranges::all_of(samples, [&](double const T) { return alignment_store::on_record(Record, curve.point(T), alignment_store::tolerance).has_value(); }); +} + +bool covers_record(int const Record, std::vector const &Moving) +{ + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && track->eType == tt_Normal && false == track->m_paths.empty() && std::find(Moving.begin(), Moving.end(), track) == Moving.end() && lies_on(Record, *track)) + return false; + return true; +} + +bool carried_rigidly(int const Record, std::vector const &Tracks, std::vector const &Moving, std::vector const &Before, record_drift &Drift) +{ + auto const &first{ends_before(Moving, Before, Tracks.front())}; + auto const &path{Tracks.front()->m_paths.front()}; + auto const &start{path.points[segment_data::point::start]}; + auto const from{chord_direction(first.first, first.second)}; + auto const to{chord_direction(start, path.points[segment_data::point::end])}; + auto const angle{signed_angle(from, to)}; + auto const carried = [&](glm::dvec3 const &Old, glm::dvec3 const &Current) { return glm::distance(plan_of(start) + turned(plan_of(Old) - plan_of(first.first), angle), plan_of(Current)) <= 0.01; }; + for (auto const *track : Tracks) + { + auto const &was{ends_before(Moving, Before, track)}; + auto const &now{track->m_paths.front()}; + if (false == carried(was.first, now.points[segment_data::point::start]) || false == carried(was.second, now.points[segment_data::point::end])) + return false; + } + if (glm::distance(first.first, start) > 1e-4 || std::abs(angle) > 1e-7) + { + alignment_store::transform(Record, first.first, from, start, to); + ++Drift.followed; + } + return true; +} + +void measure_departure(int const Record, std::vector const &Tracks, record_drift &Drift) +{ + auto const &records{alignment_store::records()}; + auto const gauge{records[Record].design.norms.gauge}; + for (auto const *track : Tracks) + { + if (track->m_editorremoved) + continue; + auto const &path{track->m_paths.front()}; + bezier const curve{path}; + double largest{0.0}; + for (auto const t : {0.0, 0.5, 1.0}) + { + auto const found{alignment_store::on_record(Record, curve.point(t), 1000.0)}; + largest = std::max(largest, found.has_value() ? found->offset : 1000.0); + } + if (largest > alignment_store::tolerance) + { + ++Drift.departed; + Drift.departure = std::max(Drift.departure, largest); + Drift.layer = scene::Layers.layer(records[Record].layer).name; + continue; + } + for (auto const end : {0, 1}) + if (auto const found{alignment_store::on_record(Record, curve.point(end), alignment_store::tolerance)}) + { + auto const actual{gauge * std::sin(std::abs(glm::radians(static_cast(path.rolls[end]))))}; + Drift.cant = std::max(Drift.cant, std::abs(actual - alignment_store::cant_at(Record, found->chainage))); + } + } +} + +std::vector drift_notes(record_drift const &Drift) +{ + std::vector notes; + if (Drift.followed > 0) + notes.push_back(STR("The kept design of the line went along with its paths")); + if (Drift.departed > 0) + notes.push_back(format(STR_P("%d path left the design kept in %s, by up to %.2f m: Ctrl+Z takes it back, the Plan tool (G) lays it by the design again or forgets the design", + "%d paths left the design kept in %s, by up to %.2f m: Ctrl+Z takes it back, the Plan tool (G) lays them by the design again or forgets it", Drift.departed), + Drift.departed, Drift.layer.c_str(), Drift.departure)); + if (Drift.cant > 5.0) + notes.push_back(format(STR_C("The cant differs from the kept design by up to %.0f mm"), Drift.cant)); + return notes; +} + +switch_store::record switch_entry(editor_track::switch_template const &Shape) +{ + switch_store::record entry; + if (Shape.source == nullptr) + { + entry.type = Shape.type; + entry.rail = Shape.rail; + entry.radius = Shape.radius; + entry.ratio = Shape.ratio; + entry.a = Shape.a; + entry.b = Shape.b; + entry.source = "designed"; + } + else if (auto const known{switch_store::of(*Shape.source)}; known.has_value() && known->kind == "switch") + { + entry = *known; + entry.number = "-"; + } + else + { + // Rz, Rlj or Rld, as classify finds it by the shape + entry.type = "Rz"; + entry.radius = Shape.radius; + entry.ratio = Shape.ratio; + entry.source = "measured"; + } + return entry; +} + +template +bool edit_dashed(char const *Label, std::string &Value) +{ + std::array text{}; + std::snprintf(text.data(), text.size(), "%s", Value == "-" ? "" : Value.c_str()); + if (false == ImGui::InputText(Label, text.data(), text.size(), ImGuiInputTextFlags_EnterReturnsTrue) && false == ImGui::IsItemDeactivatedAfterEdit()) + return false; + Value = text[0] != '\0' ? text.data() : "-"; + return true; +} + +} // namespace + +void editor_mode::records_watch_begin() +{ + auto &watch{m_record_watch}; + watch = {}; + watch.active = true; + watch.moving = m_track_drag; + for (auto const &link : m_track_gizmo_drag.switches) + for (auto const &member : link.cluster) + if (std::find(watch.moving.begin(), watch.moving.end(), member.first) == watch.moving.end()) + watch.moving.push_back(member.first); + for (auto *track : watch.moving) + { + auto const &path{track->m_paths.front()}; + watch.before.emplace_back(path.points[segment_data::point::start], path.points[segment_data::point::end]); + if (track->eType != tt_Normal) + continue; + if (auto const found{alignment_store::on_track(*track)}) + watch.on[found->record].push_back(track); + } + for (auto const &[record, tracks] : watch.on) + if (covers_record(record, watch.moving)) + watch.whole.insert(record); +} + +// what the drag of the gizmo did to the kept alignments and switches: an alignment all of whose paths were moved or turned as a +// whole goes along with them, paths pulled out of an alignment or given another cant are told about, as are switches bent out +// of the shape of their type; switches moved as a whole take their records along +void editor_mode::records_watch_end() +{ + auto &watch{m_record_watch}; + if (false == watch.active) + return; + watch.active = false; + record_drift drift; + for (auto const &[record, tracks] : watch.on) + if (watch.whole.count(record) == 0 || false == carried_rigidly(record, tracks, watch.moving, watch.before, drift)) + measure_departure(record, tracks, drift); + auto notes{drift_notes(drift)}; + switch_store::follow(); + for (auto const *track : watch.moving) + if (track->eType == tt_Switch && false == track->m_editorremoved) + if (auto const known{switch_store::named(*track)}; known.has_value() && false == switch_store::of(*track).has_value()) + notes.push_back(format(STR_C("Switch %s lost the shape of its type %s: Ctrl+Z takes it back"), track->name().c_str(), switch_store::label(*known).c_str())); + records_to_history(); + if (false == notes.empty()) + { + std::string text; + for (auto const ¬e : notes) + text += (text.empty() ? "" : "\n") + note; + ui()->set_status(text, drift.departed > 0 || drift.cant > 5.0 || notes.size() > static_cast(drift.followed > 0 ? 1 : 0)); + WriteLog("Editor: " + text, logtype::generic); + } + watch = {}; +} + +void editor_mode::records_to_history() +{ + auto alignments{alignment_store::take_changes()}; + auto switches{switch_store::take_changes()}; + if (m_history.empty() || m_history.back().action != EditorSnapshot::Action::TrackEdit) + return; + auto &last{m_history.back()}; + if (alignments.has_value() && false == last.alignments.has_value()) + last.alignments = std::move(alignments); + if (switches.has_value() && false == last.switch_records.has_value()) + last.switch_records = std::move(switches); +} + +// the switch is kept in the scenery with its type: of the catalogue template, of the switch of the scenery it was copied +// from, or measured; on a curve it is an arc switch, one-sided when it diverges to the side the curve turns to +void editor_mode::record_switch(TTrack &Track, editor_track::switch_template const &Shape) +{ + if (Track.eType != tt_Switch || Track.m_paths.size() < 2 || Track.name().empty() || scene::Layers.empty()) + return; + auto entry{switch_entry(Shape)}; + entry.kind = "switch"; + entry.name = Track.name(); + entry.parts = {entry.name}; + switch_store::place(entry, Track); + switch_store::classify(entry, Track); + switch_store::put(entry, alignment_store::layer_of(Track)); +} + +// a double switch is kept as one record of its two switches, with the type, the size and the side of the first one +void editor_mode::record_double(TTrack &First, TTrack &Second, editor_track::switch_template const &Shape) +{ + if (First.eType != tt_Switch || Second.eType != tt_Switch || First.m_paths.size() < 2 || First.name().empty() || Second.name().empty() || scene::Layers.empty()) + return; + auto entry{switch_entry(Shape)}; + entry.kind = "double"; + entry.name = First.name(); + entry.parts = {First.name(), Second.name()}; + switch_store::place(entry, First); + switch_store::classify(entry, First); + switch_store::put(entry, alignment_store::layer_of(First)); +} + +void editor_mode::record_connection(connection::kind const Kind, std::vector const &Switches, connection::result const &Plan, editor_track::switch_template const &Shape) +{ + if (Switches.empty() || Switches.front()->eType != tt_Switch || Switches.front()->m_paths.size() < 2 || scene::Layers.empty()) + return; + auto entry{switch_entry(Shape)}; + entry.kind = "connection"; + entry.name = Switches.front()->name(); + for (auto const *track : Switches) + if (track->name().empty()) + return; + else + entry.parts.push_back(track->name()); + switch_store::place(entry, *Switches.front()); + switch_store::classify(entry, *Switches.front()); + entry.type = connection::word(Kind); + entry.a = Plan.spacing; + entry.b = Plan.straights.empty() ? 0.0 : Plan.straights.front(); + switch_store::put(entry, alignment_store::layer_of(*Switches.front())); +} + +std::optional editor_mode::double_of(TTrack const &Track) const +{ + auto const of_switch = [](TTrack const &Switch) -> std::optional { + if (Switch.eType != tt_Switch || Switch.m_editorremoved) + return std::nullopt; + auto const known{switch_store::named(Switch)}; + if (false == known.has_value() || known->kind != "double" || known->parts.size() != 2) + return std::nullopt; + auto *first{simulation::Paths.find(known->parts[0])}; + auto *second{simulation::Paths.find(known->parts[1])}; + for (auto const *part : {first, second}) + if (part == nullptr || part->m_editorremoved || part->eType != tt_Switch || part->m_paths.size() != 2) + return std::nullopt; + if (first == second) + return std::nullopt; + auto const start{second->m_paths.front().points[segment_data::point::start]}; + for (auto const &[other, point] : editor_track::connected_points(*first, first->m_paths.front().points[segment_data::point::end])) + { + if (other->m_editorremoved || other->eType != tt_Normal || other->m_paths.size() != 1) + continue; + auto const &path{other->m_paths.front()}; + auto const opposite{path.points[point.kind == editor_track::point_kind::start ? segment_data::point::end : segment_data::point::start]}; + if (glm::distance(opposite, start) < geometry::same_point) + return double_switch{first, other, second}; + } + return std::nullopt; + }; + if (Track.eType == tt_Switch) + return of_switch(Track); + if (Track.eType != tt_Normal || Track.m_editorremoved || Track.m_paths.size() != 1) + return std::nullopt; + for (auto const index : {segment_data::point::start, segment_data::point::end}) + for (auto const &[other, point] : editor_track::connected_points(Track, Track.m_paths.front().points[index])) + if (other->eType == tt_Switch) + if (auto const found{of_switch(*other)}; found.has_value() && found->link == &Track) + return found; + return std::nullopt; +} + +std::optional editor_mode::slip_of(TTrack const &Track) const +{ + if (Track.m_editorremoved) + return std::nullopt; + auto const record_of = [](TTrack const &Each) -> std::optional { + if (Each.eType != tt_Switch || Each.m_editorremoved) + return std::nullopt; + auto found{switch_store::named(Each)}; + return found.has_value() && found->kind == "slip" ? found : std::nullopt; + }; + // the record of the switch, or of a switch of the slip the track between them is joined to + auto known{record_of(Track)}; + if (false == known.has_value() && Track.eType == tt_Normal && Track.m_paths.size() == 1) + for (auto const index : {segment_data::point::start, segment_data::point::end}) + for (auto const &[other, point] : editor_track::connected_points(Track, Track.m_paths.front().points[index])) + if (false == known.has_value()) + known = record_of(*other); + if (false == known.has_value()) + return std::nullopt; + slip_set slip; + slip.record = *known; + for (auto const &name : known->parts) + { + auto *part{simulation::Paths.find(name)}; + if (part == nullptr || part->m_editorremoved || part->eType != tt_Switch || part->m_paths.size() < 2) + return std::nullopt; + slip.switches.push_back(part); + } + if (slip.switches.size() < 2) + return std::nullopt; + // where the straights of its first and its last switch meet: the joints of its tracks near it are inside the slip, its ends far off + auto const &first{slip.switches.front()->m_paths.front()}; + auto const &last{slip.switches.back()->m_paths.front()}; + auto const a{plan_of(first.points[segment_data::point::start])}; + auto const d{plan_of(last.points[segment_data::point::start])}; + auto const da{editor_track::end_direction(first, editor_track::point_kind::start)}; + auto const dd{editor_track::end_direction(last, editor_track::point_kind::start)}; + double alongfirst, alonglast; + if (false == geometry::lines_cross(a, da, d, dd, alongfirst, alonglast)) + return std::nullopt; + auto const crossing{a + da * alongfirst}; + auto const inside{0.5 * glm::distance(a, crossing)}; + slip.parts = slip.switches; + for (std::size_t i = 0; i < slip.parts.size(); ++i) + for (auto const &path : slip.parts[i]->m_paths) + for (auto const index : {segment_data::point::start, segment_data::point::end}) + { + auto const &position{path.points[index]}; + if (glm::distance(plan_of(position), crossing) > inside) + continue; + for (auto const &[other, point] : editor_track::connected_points(*slip.parts[i], position)) + if (false == other->m_editorremoved && std::find(slip.parts.begin(), slip.parts.end(), other) == slip.parts.end()) + slip.parts.push_back(other); + } + // its ends, each with the way into the slip there + std::vector> ends; + for (auto const *part : slip.parts) + for (auto const &path : part->m_paths) + for (auto const atend : {false, true}) + { + auto const &position{path.points[atend ? segment_data::point::end : segment_data::point::start]}; + if (glm::distance(plan_of(position), crossing) <= inside || + std::any_of(ends.begin(), ends.end(), [&](auto const &End) { return glm::distance(End.first, position) < geometry::same_point; })) + continue; + auto const &control{path.points[atend ? segment_data::point::control2 : segment_data::point::control1]}; + auto const into{plan_of(control != glm::dvec3{} ? control : path.points[atend ? segment_data::point::start : segment_data::point::end] - position)}; + if (glm::length(into) < 1e-9) + return std::nullopt; + ends.emplace_back(position, glm::normalize(into)); + } + if (ends.size() != 4) + return std::nullopt; + // A where its first switch starts, B on along its first track, D where its last switch starts, C the other one + auto const at = [&](glm::dvec2 const &Point) { + return static_cast(std::min_element(ends.begin(), ends.end(), [&](auto const &One, auto const &Other) { return glm::distance(plan_of(One.first), Point) < glm::distance(plan_of(Other.first), Point); }) - + ends.begin()); + }; + auto const ia{at(a)}; + auto const id{at(d)}; + if (ia == id) + return std::nullopt; + std::vector others; + for (std::size_t i = 0; i < 4; ++i) + if (i != ia && i != id) + others.push_back(i); + if (others.size() != 2) + return std::nullopt; + // of the other two the one farther on along the first track + auto const ahead = [&](std::size_t const Index) { return glm::dot(plan_of(ends[Index].first) - crossing, da); }; + auto const ib{ahead(others[0]) >= ahead(others[1]) ? others[0] : others[1]}; + auto const ic{ib == others[0] ? others[1] : others[0]}; + std::size_t const order[]{ia, ib, ic, id}; + for (std::size_t i = 0; i < 4; ++i) + { + slip.ends[i] = ends[order[i]].first; + slip.into[i] = ends[order[i]].second; + } + return slip; +} + +std::vector editor_mode::slip_taken_out(slip_set const &Slip, bool const Throughs) +{ + switch_store::forget(Slip.record.name); + auto &style{*Slip.switches.front()}; + auto const velocity{speed_check::path_velocity(style, 0)}; + for (auto *part : Slip.parts) + editor_track::retire(*part); + std::vector laid; + if (false == Throughs) + return laid; + for (auto const &path : slip_throughs(Slip)) + if (auto *through{editor_track::create_path(style, path)}) + { + editor_track::velocity(*through, velocity); + laid.push_back(through); + } + editor_track::commit(laid); + return laid; +} + +std::optional editor_mode::crossing_record(TTrack const &Track) const +{ + if (Track.eType != tt_Normal || Track.m_editorremoved) + return std::nullopt; + auto const known{switch_store::named(Track)}; + if (false == known.has_value() || known->kind != "crossing" || known->parts.size() != 2) + return std::nullopt; + for (auto const &name : known->parts) + if (auto const *part{simulation::Paths.find(name)}; part == nullptr || part->m_editorremoved || part->eType != tt_Normal || part->m_paths.size() != 1) + return std::nullopt; + return known; +} + +std::array editor_mode::slip_throughs(slip_set const &Slip) +{ + // from end to end, a straight where the slip is one, else heading out of the ends as the slip does + auto const through = [&](std::size_t const From, std::size_t const To) { + segment_data path; + path.points[segment_data::point::start] = Slip.ends[From]; + path.points[segment_data::point::end] = Slip.ends[To]; + auto const chord{plan_of(Slip.ends[To] - Slip.ends[From])}; + auto const length{glm::length(chord)}; + if (length > 1e-6 && std::abs(geometry::cross(Slip.into[From], chord / length)) + std::abs(geometry::cross(Slip.into[To], chord / length)) > 1e-5) + { + auto const handle{length / 3.0}; + auto const rise{Slip.ends[To].y - Slip.ends[From].y}; + path.points[segment_data::point::control1] = {Slip.into[From].x * handle, rise / 3.0, Slip.into[From].y * handle}; + path.points[segment_data::point::control2] = {Slip.into[To].x * handle, -rise / 3.0, Slip.into[To].y * handle}; + path.radius = static_cast(Slip.record.main_radius); + } + return path; + }; + return {through(0, 1), through(2, 3)}; +} + +std::vector editor_mode::double_paths(double_switch const &Set) +{ + auto link{Set.link->m_paths.front()}; + auto const joint{Set.first->m_paths.front().points[segment_data::point::end]}; + if (glm::distance(link.points[segment_data::point::start], joint) > glm::distance(link.points[segment_data::point::end], joint)) + link = geometry::reversed(link); + return {Set.first->m_paths[0], Set.first->m_paths[1], Set.second->m_paths[0], Set.second->m_paths[1], link}; +} + +void editor_mode::record_slip(std::vector const &Parts, std::string const &Kind, std::string const &Type, double const Radius, double const Angle, std::string const &Base, double const Middle) +{ + if (Parts.empty() || scene::Layers.empty()) + return; + switch_store::record entry; + entry.kind = Kind; + entry.name = Base; + entry.type = Type; + entry.radius = Radius; + entry.middle = Middle; + entry.ratio = Angle > 1e-9 ? 1.0 / std::tan(Angle) : 0.0; + for (auto const *part : Parts) + if (part != nullptr && false == part->name().empty() && (Kind == "crossing" || part->eType == tt_Switch)) + entry.parts.push_back(part->name()); + if (entry.parts.empty()) + return; + auto const *first{simulation::Paths.find(entry.parts.front())}; + if (first == nullptr || first->m_paths.empty()) + return; + switch_store::place(entry, *first); + // a slip bent into a curve, as a switch is + entry.main_radius = switch_store::main_radius_of(*first); + switch_store::put(entry, alignment_store::layer_of(*first)); +} + +void editor_mode::render_switch_record(TTrack const &Track) const +{ + auto const known{switch_store::of(Track)}; + if (false == known.has_value()) + { + ImGui::TextDisabled("%s", STR_C("The scenery keeps no type for this switch, it's read from its shape")); + return; + } + auto entry{*known}; + ImGui::Text(STR_C("Type kept in the scenery: %s"), switch_store::label(entry).c_str()); + if (ImGui::IsItemHovered()) + { + std::string text; + if (entry.kind == "switch" && entry.main_radius != 0.0) + text = format(STR_C("Diverging track R %.0f m: the R %.0f m of the type bent with the main track"), switch_store::branch_radius(entry), entry.radius); + if (entry.source == "measured") + text += (text.empty() ? "" : "\n") + std::string{STR_C("The size is measured from the shape of the switch, it's of no template of the catalogue")}; + if (false == text.empty()) + ImGui::SetTooltip("%s", text.c_str()); + } + bool changed{false}; + if (begin_fields("##switchrecord", 0.4f)) + { + field_row("Number##switchnumber"); + changed |= edit_dashed<32>("##switchnumber", entry.number); + item_tooltip("Number of the switch in the station, as the plans of the station give it"); + field_row("Rail##switchrail"); + changed |= edit_dashed<16>("##switchrail", entry.rail); + item_tooltip("Rail of the switch: 60E1, 49E1..."); + auto km{entry.km.has_value() ? *entry.km / 1000.0 : 0.0}; + field_row("Km of the start##switchkm"); + if (ImGui::InputDouble("##switchkm", &km, 0.0, 0.0, "%.3f", ImGuiInputTextFlags_EnterReturnsTrue)) + { + entry.km = km * 1000.0; + changed = true; + } + item_tooltip("Chainage of the start of the switch; taken from the horizontal alignment kept in the scenery when the switch lies on one"); + ImGui::EndTable(); + } + if (changed) + { + switch_store::put(entry, entry.layer); + switch_store::settle(); + } +} diff --git a/application/editormoderide.cpp b/application/editormoderide.cpp new file mode 100644 index 000000000..6e74bffd4 --- /dev/null +++ b/application/editormoderide.cpp @@ -0,0 +1,684 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormoderide.h" +#include "application/editoruilayer.h" +#include "editor/editorFormat.hpp" +#include "editor/editorKilometrage.hpp" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" +#include "vehicle/Camera.h" +#include "world/Segment.h" +#include "world/Track.h" +#include "imgui/imgui.h" +#include +#include +#include +#include +#include + +namespace track_ride_walk +{ + +namespace +{ + +double plan_length(glm::dvec3 const &Vector) +{ + return std::hypot(Vector.x, Vector.z); +} + +glm::dvec3 plan_unit(glm::dvec3 const &Vector) +{ + auto const length{plan_length(Vector)}; + return length > 1e-9 ? glm::dvec3{Vector.x / length, 0.0, Vector.z / length} : glm::dvec3{0.0}; +} + +glm::dvec3 point_of(TSegment const &Segment, double const Distance) +{ + glm::dvec3 point{0.0}; + glm::vec3 rotation{0.0f}; + Segment.RaPositionGet(std::clamp(Distance, 0.0, Segment.GetLength()), point, rotation); + return point; +} + +// the track goes on there for the camera: there is one, it wasn't removed, it isn't a crossroads of roads +bool passable(TTrack const *Track) +{ + return Track != nullptr && false == Track->m_editorremoved && Track->eType != tt_Cross && segment({const_cast(Track), Track->eType == tt_Switch ? 0 : -1, 0.0}) != nullptr; +} + +// the path of a switch entered from its frog: the one whose end at Point2 is nearest to where the camera came from +int path_from_frog(TTrack const &Switch, glm::dvec3 const &From) +{ + auto best{0}; + auto nearest{std::numeric_limits::max()}; + for (int path = 0; path < Switch.path_count(); ++path) + { + auto const *segment{Switch.path_segment(path)}; + if (segment == nullptr) + continue; + if (auto const distance{glm::distance(point_of(*segment, segment->GetLength()), From)}; distance < nearest) + { + nearest = distance; + best = path; + } + } + return best; +} + +// the next track over the joint at the end the place is moving to (Direction 1: Point2, -1: Point1); Place becomes the +// start of it and Direction the way along it. False where the track ends +bool cross_joint(place &Place, int &Direction, int const Choice, bool &Facing) +{ + auto const *segment{track_ride_walk::segment(Place)}; + if (segment == nullptr) + return false; + auto const exit{point_of(*segment, Direction > 0 ? segment->GetLength() : 0.0)}; + double way{static_cast(Direction)}; + auto *next{Place.track->Connected(Direction, way, Place.track->eType == tt_Switch ? Place.path : -1)}; + if (false == passable(next)) + return false; + auto const direction{way > 0.0 ? 1 : -1}; + auto path{-1}; + if (next->eType == tt_Switch) + { + // both paths of a switch start at its Point1, at the blades + if (direction > 0) + { + path = switch_path(*next, Choice); + Facing = true; + } + else + path = path_from_frog(*next, exit); + } + Place.track = next; + Place.path = path; + Direction = direction; + auto const *entered{track_ride_walk::segment(Place)}; + Place.s = direction > 0 ? 0.0 : entered->GetLength(); + return true; +} + +} // namespace + +TSegment *segment(place const &Place) +{ + if (Place.track == nullptr) + return nullptr; + if (Place.track->eType == tt_Switch) + return Place.track->SwitchExtension != nullptr ? Place.track->path_segment(std::clamp(Place.path, 0, 1)) : nullptr; + return Place.track->Segment.get(); +} + +bool frame(place const &Place, glm::dvec3 &Point, glm::dvec3 &Forward) +{ + auto const *path{segment(Place)}; + if (path == nullptr) + return false; + auto const length{path->GetLength()}; + Point = point_of(*path, Place.s); + // the direction from two points around the place, the same on any kind of path + auto const step{std::min(0.5, std::max(length * 0.5, 1e-3))}; + auto const from{std::max(0.0, Place.s - step)}; + auto const to{std::min(length, Place.s + step)}; + Forward = to > from ? point_of(*path, to) - point_of(*path, from) : glm::dvec3{0.0, 0.0, 1.0}; + auto const size{glm::length(Forward)}; + Forward = size > 1e-9 ? Forward / size : glm::dvec3{0.0, 0.0, 1.0}; + return true; +} + +int switch_path(TTrack const &Switch, int const Choice) +{ + if (Switch.eType != tt_Switch || Switch.SwitchExtension == nullptr) + return -1; + // how much each path turns away from the way in at the blades + double turn[2]{0.0, 0.0}; + for (int path = 0; path < 2; ++path) + { + auto const *segment{Switch.path_segment(path)}; + if (segment == nullptr || segment->GetLength() <= 0.0) + { + turn[path] = std::numeric_limits::max(); + continue; + } + auto const length{segment->GetLength()}; + auto const in{plan_unit(point_of(*segment, std::min(1.0, length * 0.5)) - point_of(*segment, 0.0))}; + auto const out{plan_unit(point_of(*segment, length) - point_of(*segment, std::max(0.0, length - 1.0)))}; + turn[path] = std::acos(std::clamp(glm::dot(in, out), -1.0, 1.0)); + } + auto const straighter{turn[1] < turn[0] ? 1 : 0}; + return (Choice % 2) == 0 ? straighter : 1 - straighter; +} + +halt walk(place &Place, double const Distance, int const Choice, int &Flips, bool &Facing) +{ + Flips = 0; + Facing = false; + if (segment(Place) == nullptr) + return halt::end; + Place.s = std::clamp(Place.s, 0.0, segment(Place)->GetLength()); + auto direction{Distance >= 0.0 ? 1 : -1}; + auto left{std::abs(Distance)}; + // the joints passed in one step; a ring of tracks of no length would hold it here for ever + for (int joint = 0; joint < 10000; ++joint) + { + auto const length{segment(Place)->GetLength()}; + auto const target{Place.s + direction * left}; + if (target >= 0.0 && target <= length) + { + Place.s = target; + return halt::none; + } + left = std::max(0.0, left - (direction > 0 ? length - Place.s : Place.s)); + auto const before{direction}; + if (false == cross_joint(Place, direction, Choice, Facing)) + { + Place.s = direction > 0 ? length : 0.0; + return halt::end; + } + if (direction != before) + ++Flips; + } + return halt::end; +} + +TTrack *facing_switch_ahead(place Place, int Direction, double const Reach, double &Distance) +{ + auto travelled{0.0}; + for (int joint = 0; joint < 1000; ++joint) + { + auto const *path{segment(Place)}; + if (path == nullptr) + return nullptr; + travelled += Direction > 0 ? path->GetLength() - Place.s : Place.s; + if (travelled > Reach) + return nullptr; + auto facing{false}; + if (false == cross_joint(Place, Direction, 0, facing)) + return nullptr; + if (facing) + { + Distance = travelled; + return Place.track; + } + } + return nullptr; +} + +double nearest_distance(TSegment const &Segment, glm::dvec3 const &Point) +{ + auto const length{Segment.GetLength()}; + if (length <= 0.0) + return 0.0; + auto const off = [&](double const Distance) { return plan_length(point_of(Segment, Distance) - Point); }; + auto const steps{std::clamp(static_cast(std::ceil(length / 2.0)), 8, 4000)}; + auto const step{length / steps}; + auto best{0.0}; + auto nearest{std::numeric_limits::max()}; + for (int i = 0; i <= steps; ++i) + { + if (auto const distance{off(i * step)}; distance < nearest) + { + nearest = distance; + best = i * step; + } + } + // golden section within a step on either side + auto low{std::max(0.0, best - step)}; + auto high{std::min(length, best + step)}; + constexpr double ratio{0.6180339887498949}; + for (int i = 0; i < 40 && high - low > 1e-4; ++i) + { + auto const a{high - ratio * (high - low)}; + auto const b{low + ratio * (high - low)}; + if (off(a) < off(b)) + high = b; + else + low = a; + } + return 0.5 * (low + high); +} + +} // namespace track_ride_walk + +namespace +{ + +constexpr double glide_time{0.35}; // s +constexpr double side_reach{20.0}; // m to the track alongside +constexpr double switch_reach{400.0}; // m ahead the switch is shown + +glm::dvec3 plan_right(glm::dvec3 const &Forward) +{ + auto const length{std::hypot(Forward.x, Forward.z)}; + return length > 1e-9 ? glm::dvec3{-Forward.z / length, 0.0, Forward.x / length} : glm::dvec3{1.0, 0.0, 0.0}; +} + +// which way a path of a switch turns away from the other one, seen from the blades +char const *turn_name(TTrack const &Switch, int const Path) +{ + auto const *path{Switch.path_segment(Path)}; + auto const *other{Switch.path_segment(1 - Path)}; + if (path == nullptr || other == nullptr) + return STR_C("straight on"); + glm::dvec3 start, forward; + track_ride_walk::frame({const_cast(&Switch), Path, 0.0}, start, forward); + glm::dvec3 end, ignored; + track_ride_walk::frame({const_cast(&Switch), Path, path->GetLength()}, end, ignored); + glm::dvec3 otherend; + track_ride_walk::frame({const_cast(&Switch), 1 - Path, other->GetLength()}, otherend, ignored); + if (track_ride_walk::switch_path(Switch, 0) == Path) + return STR_C("straight on"); + auto const right{plan_right(forward)}; + return glm::dot(end - otherend, right) > 0.0 ? STR_C("to the right") : STR_C("to the left"); +} + +} // namespace + +bool track_ride::enter(TTrack *Track, int const Path, glm::dvec3 const &Near, glm::dvec3 const &Look, bool const Orient) +{ + if (Track == nullptr || Track->m_editorremoved || Track->eType == tt_Cross) + return false; + track_ride_walk::place place{Track, Track->eType == tt_Switch ? std::clamp(Path, 0, 1) : -1, 0.0}; + auto const *path{track_ride_walk::segment(place)}; + if (path == nullptr) + return false; + place.s = track_ride_walk::nearest_distance(*path, Near); + m_place = place; + m_direction = 1; + m_direction = look_direction(Look); + m_speed = 0.0; + m_choice = 0; + m_forward = m_back = m_up = m_down = false; + m_glide_pending = true; + m_orient_pending = Orient; + m_km.clear(); + m_km_age = 1e9; + m_switch = nullptr; + return true; +} + +void track_ride::leave() +{ + m_place = {}; + m_speed = 0.0; + m_switch = nullptr; + m_forward = m_back = m_up = m_down = false; +} + +int track_ride::look_direction(glm::dvec3 const &Look) const +{ + glm::dvec3 point, forward; + if (false == track_ride_walk::frame(m_place, point, forward)) + return m_direction; + auto const along{forward.x * Look.x + forward.z * Look.z}; + // looking across the track keeps the way it was + if (std::abs(along) < 0.15 * std::hypot(Look.x, Look.z)) + return m_direction; + return along >= 0.0 ? 1 : -1; +} + +glm::dvec3 track_ride::rail_point() const +{ + glm::dvec3 point{0.0}, forward; + track_ride_walk::frame(m_place, point, forward); + return point; +} + +void track_ride::cycle_choice() +{ + m_choice = (m_choice + 1) % 2; +} + +bool track_ride::key(int const Key, int const Action, int const Mods, glm::dvec3 const &Look, bool const Driving, std::string &Status) +{ + m_shift = (Mods & GLFW_MOD_SHIFT) != 0; + m_ctrl = (Mods & GLFW_MOD_CONTROL) != 0; + if (Key == GLFW_KEY_LEFT_SHIFT || Key == GLFW_KEY_RIGHT_SHIFT) + m_shift = Action != GLFW_RELEASE; + if (Key == GLFW_KEY_LEFT_CONTROL || Key == GLFW_KEY_RIGHT_CONTROL) + m_ctrl = Action != GLFW_RELEASE; + if (false == active()) + return false; + auto const held{Action != GLFW_RELEASE}; + auto const press{Action == GLFW_PRESS}; + // with Ctrl or Alt the ride keeps only Ctrl+W and Ctrl+arrows, the much faster drive; the shortcuts of the editor get the + // rest (Ctrl+S saves, Ctrl+Z and Ctrl+Y undo and redo). Releases go on to the editor too, it may have seen the key go down + // before the ride + auto const shortcut{(Mods & GLFW_MOD_ALT) != 0 || (m_ctrl && Key != GLFW_KEY_W && Key != GLFW_KEY_UP && Key != GLFW_KEY_DOWN)}; + auto const hold = [&](bool &Flag) { + Flag = held && Driving && false == shortcut; + return Flag; + }; + switch (Key) + { + case GLFW_KEY_W: + case GLFW_KEY_UP: return hold(m_forward); + case GLFW_KEY_S: + case GLFW_KEY_DOWN: return hold(m_back); + case GLFW_KEY_E: + case GLFW_KEY_PAGE_UP: return hold(m_up); + case GLFW_KEY_Q: + case GLFW_KEY_PAGE_DOWN: return hold(m_down); + case GLFW_KEY_A: + case GLFW_KEY_LEFT: + case GLFW_KEY_D: + case GLFW_KEY_RIGHT: + if (shortcut || false == Driving) + return false; + if (press && false == jump_side(Key == GLFW_KEY_A || Key == GLFW_KEY_LEFT ? -1 : 1, Look)) + Status = STR("No track alongside"); + return held; + case GLFW_KEY_Z: + if (shortcut) + return false; + if (press) + cycle_choice(); + return held; + case GLFW_KEY_Y: + if (shortcut) + return false; + if (press) + leave(); + return held; + default: return false; + } +} + +void track_ride::wheel(double const Notches) +{ + m_height = std::clamp(m_height * std::pow(0.85, -Notches), 0.5, 500.0); +} + +void track_ride::advance(TCamera &Camera, double const Deltatime, bool const Driving) +{ + if (false == active()) + return; + if (m_place.track->m_editorremoved || track_ride_walk::segment(m_place) == nullptr) + { + leave(); + return; + } + auto const dt{std::clamp(Deltatime, 0.0, 0.1)}; + // the window takes the keys, their releases among them, and the right button let go leaves them to the editor: none is held + // for the ride then + if (ImGui::GetIO().WantCaptureKeyboard || false == Driving) + m_forward = m_back = m_up = m_down = false; + // the path may have got shorter, an undo or a change of the track under the ride + m_place.s = std::clamp(m_place.s, 0.0, track_ride_walk::segment(m_place)->GetLength()); + glm::dvec3 const look{-std::sin(Camera.Angle.y), 0.0, -std::cos(Camera.Angle.y)}; + // standing, the way ahead is the one the camera looks; a camera about to be turned along the track looks there already + if (std::abs(m_speed) < 0.5 && false == m_orient_pending) + m_direction = look_direction(look); + + auto const top{m_ctrl ? 250.0 : m_shift ? 60.0 : 20.0}; + auto const wanted{static_cast((m_forward ? 1 : 0) - (m_back ? 1 : 0)) * top}; + auto const rate{(wanted == 0.0 || wanted * m_speed < 0.0 ? 2.5 : 1.2) * std::max(top, std::abs(m_speed))}; + m_speed = m_speed < wanted ? std::min(wanted, m_speed + rate * dt) : std::max(wanted, m_speed - rate * dt); + + if (m_speed != 0.0) + { + int flips{0}; + bool facing{false}; + auto const halted{track_ride_walk::walk(m_place, m_direction * m_speed * dt, m_choice, flips, facing)}; + if (flips % 2 != 0) + m_direction = -m_direction; + if (facing) + m_choice = 0; + if (halted == track_ride_walk::halt::end) + m_speed = 0.0; + } + if (m_up != m_down) + m_height = std::clamp(m_height + (m_up ? 1.0 : -1.0) * std::clamp(m_height, 2.0, 50.0) * (m_shift ? 3.0 : 1.0) * dt, 0.5, 500.0); + + // the switch ahead + m_switch = track_ride_walk::facing_switch_ahead(m_place, m_speed < 0.0 ? -m_direction : m_direction, switch_reach, m_switch_distance); + m_km_age += dt; + if (m_km_age > 0.5) + { + m_km_age = 0.0; + auto const at{rail_point()}; + double km{0.0}; + auto const line{kilometrage::line_at(at)}; + m_km = false == line.empty() && kilometrage::km_at(line, at, km) ? kilometrage::text(km) : std::string{}; + } + + if (m_orient_pending) + { + // along the way ahead, a little down to the rails + m_orient_pending = false; + glm::dvec3 point, forward; + track_ride_walk::frame(m_place, point, forward); + auto const ahead{forward * static_cast(m_direction)}; + Camera.Angle.y = static_cast(std::atan2(-ahead.x, -ahead.z)); + Camera.Angle.x = -0.12f; + Camera.Angle.z = 0.0f; + } + auto const target{rail_point() + glm::dvec3{0.0, m_height, 0.0}}; + if (m_glide_pending) + { + m_glide_from = Camera.Pos; + m_glide = 0.0; + m_glide_pending = false; + } + if (m_glide < 1.0) + { + m_glide = std::min(1.0, m_glide + dt / glide_time); + auto const eased{m_glide * m_glide * (3.0 - 2.0 * m_glide)}; + Camera.Pos = glm::mix(m_glide_from, target, eased); + } + else + Camera.Pos = target; + Camera.Velocity = glm::dvec3{0.0}; +} + +bool track_ride::jump_side(int const Side, glm::dvec3 const &Look) +{ + glm::dvec3 here, forward; + if (false == track_ride_walk::frame(m_place, here, forward)) + return false; + auto const ahead{forward * static_cast(look_direction(Look))}; + auto const right{plan_right(ahead)}; + auto const category{m_place.track->iCategoryFlag & 15}; + auto const parallel{std::cos(30.0 * M_PI / 180.0)}; + track_ride_walk::place best; + auto nearest{side_reach}; + auto bestforward{forward}; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track == m_place.track || track->m_editorremoved || track->eType == tt_Cross || (track->iCategoryFlag & 15) != category) + continue; + for (int path = 0; path < track->path_count(); ++path) + { + track_ride_walk::place candidate{track, track->eType == tt_Switch ? path : -1, 0.0}; + auto const *segment{track_ride_walk::segment(candidate)}; + if (segment == nullptr) + continue; + // far off tracks out at once: no point of the path nearer than the reach + auto const length{segment->GetLength()}; + auto const first{segment->FastGetPoint_0()}; + auto const last{segment->FastGetPoint_1()}; + if (std::min(std::hypot(first.x - here.x, first.z - here.z), std::hypot(last.x - here.x, last.z - here.z)) > 0.6 * length + side_reach + 1.0) + continue; + candidate.s = track_ride_walk::nearest_distance(*segment, here); + glm::dvec3 point, along; + track_ride_walk::frame(candidate, point, along); + auto const offset{point - here}; + auto const across{(offset.x * right.x + offset.z * right.z) * Side}; + auto const lengthwise{offset.x * ahead.x + offset.z * ahead.z}; + // alongside on that side, about across from the camera, running the same way + if (across < 1.5 || across >= nearest || std::abs(lengthwise) > 2.0 + 0.25 * across || std::abs(along.x * ahead.x + along.z * ahead.z) < parallel) + continue; + nearest = across; + best = candidate; + bestforward = along; + } + } + if (best.track == nullptr) + return false; + auto const speed{m_speed}; + auto const goingahead{m_direction == look_direction(Look)}; + m_place = best; + // the way ahead stays the same on the new track + auto const aheadnow{bestforward.x * ahead.x + bestforward.z * ahead.z >= 0.0 ? 1 : -1}; + m_direction = goingahead ? aheadnow : -aheadnow; + m_speed = speed; + m_glide_pending = true; + m_choice = 0; + return true; +} + +void track_ride::forget(scene::basic_node const *Node) +{ + if (Node != nullptr && Node == m_place.track) + leave(); +} + +void track_ride::draw_hud() const +{ + if (false == active()) + return; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const pad{6.0f}; + auto const height{ImGui::GetTextLineHeight()}; + + std::string line{m_place.track->name().empty() ? std::string{"?"} : m_place.track->name()}; + if (false == m_km.empty()) + line += " km " + m_km; + line += format(" %.0f km/h %s %.1f m", std::abs(m_speed) * 3.6, STR_C("height"), m_height); + std::string ahead; + if (m_switch != nullptr) + ahead = format(STR_C("Switch in %.0f m: %s (Z changes)"), m_switch_distance, turn_name(*m_switch, track_ride_walk::switch_path(*m_switch, m_choice))); + // the keys only standing, out of the way while driving + std::string keys; + if (std::abs(m_speed) < 0.5) + keys = STR("RMB held: W/S drive, A/D next track, Q/E height Y leave"); + + // over the bottom of the view, above the bar of the keys of the tools; the rows keep their places as the others come and go + auto const centre{0.5f * (editor_ui::view_min().x + editor_ui::view_max().x)}; + auto y{editor_ui::view_max().y - 12.0f - height * 2.5f - 3.0f * (height + pad * 1.5f)}; + auto const row = [&](std::string const &Text, ImU32 const Background, ImU32 const Foreground) { + if (false == Text.empty()) + { + auto const size{ImGui::CalcTextSize(Text.c_str())}; + ImVec2 const from{centre - 0.5f * size.x - pad, y - pad * 0.5f}; + ImVec2 const to{centre + 0.5f * size.x + pad, y + size.y + pad * 0.5f}; + drawlist->AddRectFilled(from, to, Background, 4.0f); + drawlist->AddText(ImVec2(from.x + pad, y), Foreground, Text.c_str()); + } + y += height + pad * 1.5f; + }; + row(line, IM_COL32(20, 60, 110, 215), IM_COL32(255, 255, 255, 255)); + row(ahead, m_choice != 0 ? IM_COL32(150, 100, 10, 225) : IM_COL32(0, 0, 0, 170), IM_COL32(255, 255, 255, 240)); + row(keys, IM_COL32(0, 0, 0, 120), IM_COL32(220, 220, 220, 210)); +} + +editor_selftest_result track_ride::selftest(std::string const &Command, std::istringstream &Words) +{ + auto const report = [this](char const *What) { + if (false == active()) + { + WriteLog(format("SELFTEST %s: not riding", What)); + return; + } + auto const at{rail_point()}; + WriteLog(format("SELFTEST %s: %s path %d s %.3f direction %d speed %.2f choice %d at %.3f %.3f %.3f", What, m_place.track->name().c_str(), m_place.path, m_place.s, m_direction, m_speed, m_choice, at.x, at.y, at.z)); + }; + if (Command == "ride") + { + // ride [path] [s]: onto the track at the distance, looking towards the growing distance + std::string name; + int path{0}; + double s{0.0}; + Words >> name >> path >> s; + auto *track{simulation::Paths.find(name)}; + track_ride_walk::place place{track, track != nullptr && track->eType == tt_Switch ? path : -1, 0.0}; + auto const *segment{track_ride_walk::segment(place)}; + if (segment == nullptr || false == enter(track, path, glm::dvec3{0.0}, glm::dvec3{0.0, 0.0, 1.0}, true)) + { + WriteLog("SELFTEST ride " + name + ": no such track"); + return editor_selftest_result::handled; + } + m_place.s = std::clamp(s, 0.0, segment->GetLength()); + m_direction = 1; + report("ride"); + return editor_selftest_result::handled; + } + if (Command == "ridewalk") + { + // ridewalk [choice]: the place moved ahead by the distance (negative: back), the switches and tracks logged + // before and after, they mustn't change + double metres{0.0}; + int choice{0}; + Words >> metres >> choice; + if (false == active()) + { + report("ridewalk"); + return editor_selftest_result::handled; + } + auto const states = [] { + std::string text; + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && track->eType == tt_Switch && track->SwitchExtension != nullptr) + text += std::to_string(track->SwitchExtension->CurrentIndex); + return text; + }; + auto const before{states()}; + int flips{0}; + bool facing{false}; + auto const halted{track_ride_walk::walk(m_place, m_direction * metres, choice, flips, facing)}; + if (flips % 2 != 0) + m_direction = -m_direction; + WriteLog(format("SELFTEST ridewalk %.3f choice %d: flips %d facing %d %s, switches %s", metres, choice, flips, facing ? 1 : 0, halted == track_ride_walk::halt::end ? "halted at an end" : "on the way", before == states() ? "kept" : "THROWN")); + report("ridewalk"); + return editor_selftest_result::handled; + } + if (Command == "ridejump") + { + // ridejump <-1|1>: to the track alongside on the left or the right of the way ahead + int side{1}; + Words >> side; + glm::dvec3 point, forward; + if (false == track_ride_walk::frame(m_place, point, forward)) + { + report("ridejump"); + return editor_selftest_result::handled; + } + auto const jumped{jump_side(side, forward * static_cast(m_direction))}; + WriteLog(format("SELFTEST ridejump %d: %s", side, jumped ? "jumped" : "no track alongside")); + report("ridejump"); + return editor_selftest_result::handled; + } + if (Command == "rideahead") + { + // rideahead: the switch ahead entered from its blades and the path the camera would take there + double distance{0.0}; + auto *ahead{active() ? track_ride_walk::facing_switch_ahead(m_place, m_direction, switch_reach, distance) : nullptr}; + if (ahead == nullptr) + WriteLog("SELFTEST rideahead: no switch ahead"); + else + WriteLog(format("SELFTEST rideahead: %s in %.2f m, straight path %d", ahead->name().c_str(), distance, track_ride_walk::switch_path(*ahead, 0))); + return editor_selftest_result::handled; + } + if (Command == "rideprobe") + { + report("rideprobe"); + return editor_selftest_result::handled; + } + if (Command == "rideleave") + { + leave(); + WriteLog("SELFTEST rideleave"); + return editor_selftest_result::handled; + } + return editor_selftest_result::unhandled; +} diff --git a/application/editormoderide.h b/application/editormoderide.h new file mode 100644 index 000000000..62b190f66 --- /dev/null +++ b/application/editormoderide.h @@ -0,0 +1,113 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.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 "application/editortool.h" + +#include + +class TTrack; +class TSegment; +class TCamera; + +// the place of the camera riding along the tracks +namespace track_ride_walk +{ + +struct place +{ + TTrack *track{nullptr}; + int path{-1}; // of a switch, -1 on other tracks + double s{0.0}; // m from Point1 of the path +}; + +// how the walk ended +enum class halt +{ + none, + end, // the track ends there, or goes on into a crossroads of roads +}; + +// the path the place is on +TSegment *segment(place const &Place); +// the point of the path and its unit direction towards the growing distance +bool frame(place const &Place, glm::dvec3 &Point, glm::dvec3 &Forward); +// the path of a switch taken from the blades: 0 the one going on straighter, 1 the other one +int switch_path(TTrack const &Switch, int const Choice); +// moves the place by Distance along the path (negative: towards Point1), over the joints to the next tracks; a switch +// entered from its blades is left by the path Choice gives (switch_path), one entered from the frog by the path it came on; +// the switches aren't thrown and nothing on the tracks learns of it. Flips is how many times the counting of the distance +// turned round on the way, at the joints of tracks running the other way. Facing is set to true when a switch was +// entered from the blades +halt walk(place &Place, double const Distance, int const Choice, int &Flips, bool &Facing); +// the nearest switch ahead to be entered from its blades, moving towards the growing distance (Direction 1) or the other +// way (-1), within Reach; null when there's none +TTrack *facing_switch_ahead(place Place, int Direction, double const Reach, double &Distance); +// the distance along the path nearest to the point, in the plan +double nearest_distance(TSegment const &Segment, glm::dvec3 const &Point); + +} // namespace track_ride_walk + +// the camera riding along the tracks as a vehicle: the keys drive it over the joints and switches and jump it over to the +// tracks alongside, the mouse looks around as it does when flying +class track_ride final : public editor_tool +{ + public: + bool active() const { return m_place.track != nullptr; } + // onto the path at the point nearest to Near, the way ahead the one nearer to Look; Orient: the camera turns to look + // along the track, else it keeps looking where it did. False where it can't + bool enter(TTrack *Track, int const Path, glm::dvec3 const &Near, glm::dvec3 const &Look, bool const Orient); + void leave(); + TTrack const *track() const { return m_place.track; } + // a key while riding; true when it was taken. Status is a message to show. The keys driving the ride are taken only with + // Driving, the right button held as it is to fly the camera; without it they're the editor's + bool key(int const Key, int const Action, int const Mods, glm::dvec3 const &Look, bool const Driving, std::string &Status); + void wheel(double const Notches); + // the keys held moved the place by the time passed, the camera is put above the rails there; none is held without Driving + void advance(TCamera &Camera, double const Deltatime, bool const Driving); + // to the track nearest the place on the side (-1 left, 1 right) of the way the camera looks; false with none within reach + bool jump_side(int const Side, glm::dvec3 const &Look); + // the bar of the ride over the view + void draw_hud() const; + void forget(scene::basic_node const *Node) override; + editor_selftest_result selftest(std::string const &Command, std::istringstream &Words) override; + + static constexpr double default_height{3.0}; // m over the rails + + private: + // the direction of the growing distance the camera looks + int look_direction(glm::dvec3 const &Look) const; + void cycle_choice(); + glm::dvec3 rail_point() const; + + track_ride_walk::place m_place; + int m_direction{1}; // the growing distance (1) or the other way (-1), which is ahead + double m_speed{0.0}; // m/s ahead, negative backwards + double m_height{default_height}; + int m_choice{0}; // at the next switch from its blades + // keys held + bool m_forward{false}; + bool m_back{false}; + bool m_up{false}; + bool m_down{false}; + bool m_shift{false}; + bool m_ctrl{false}; + // the camera glides over from where it was, as it enters or jumps over + glm::dvec3 m_glide_from{0.0}; + double m_glide{1.0}; // 0..1, done at 1 + bool m_glide_pending{false}; // starts from where the camera is on the next step + bool m_orient_pending{false}; // the camera turns along the track on the next step + // the switch ahead, for the bar + TTrack *m_switch{nullptr}; + double m_switch_distance{0.0}; + // kilometrage of the place, worked out now and then + std::string m_km; + double m_km_age{1e9}; +}; diff --git a/application/editormoderoad.cpp b/application/editormoderoad.cpp new file mode 100644 index 000000000..9c44c0550 --- /dev/null +++ b/application/editormoderoad.cpp @@ -0,0 +1,2908 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editoruilayer.h" +#include "application/editormodeshared.h" +#include "application/editorgestures.h" +#include "editor/editorFormat.hpp" + +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "rendering/renderer.h" +#include "world/Track.h" +#include "world/Road.h" +#include "world/RoadPoint.h" +#include "simulation/simulation.h" + +#include "imgui/imgui.h" +#include +#include +#include +#include +#include +#include + +namespace +{ + +// the same helper the track tools use to draw over the viewport +class screen_projection +{ + public: + screen_projection() + { + ImGuiIO const &io = ImGui::GetIO(); + m_size = io.DisplaySize; + m_camera = GfxRenderer->Camera_Position(); + float const aspect = m_size.y > 0.0f ? m_size.x / m_size.y : 1.0f; + m_viewprojection = editor_mode::projection_matrix(aspect) * GfxRenderer->Camera_View_Matrix(); + } + + glm::vec4 clip(glm::dvec3 const &Point) const + { + return m_viewprojection * glm::vec4(glm::vec3(Point - m_camera), 1.0f); + } + ImVec2 screen(glm::vec4 const &Clip) const + { + return ImVec2((Clip.x / Clip.w * 0.5f + 0.5f) * m_size.x, (0.5f - Clip.y / Clip.w * 0.5f) * m_size.y); + } + bool project(glm::dvec3 const &Point, ImVec2 &Screen) const + { + auto const c = clip(Point); + if (c.w < kNear) + return false; + Screen = screen(c); + return true; + } + // true while there's room in the draw list for more. the user interface is drawn with 16 bit indices, so a list + // can't hold more than 65536 vertices; past that the lines come out as triangles strewn all over the screen, + // which takes the frame rate down with it. the limit doesn't apply if the renderer can deal with larger lists + bool room(ImDrawList const *Drawlist) const + { + return (Drawlist->Flags & ImDrawListFlags_AllowVtxOffset) != 0 || Drawlist->VtxBuffer.Size < limit; + } + // true if a line between two points on the screen can't be seen + bool outside(ImVec2 const &A, ImVec2 const &B) const + { + return (A.x < 0.0f && B.x < 0.0f) || (A.y < 0.0f && B.y < 0.0f) || (A.x > m_size.x && B.x > m_size.x) || (A.y > m_size.y && B.y > m_size.y); + } + void line(ImDrawList *Drawlist, glm::dvec3 const &A, glm::dvec3 const &B, ImU32 const Color, float const Thickness) const + { + if (false == room(Drawlist)) + return; + glm::vec4 a = clip(A); + glm::vec4 b = clip(B); + if (a.w < kNear && b.w < kNear) + return; + if (a.w < kNear) + a = glm::mix(a, b, (kNear - a.w) / (b.w - a.w)); + else if (b.w < kNear) + b = glm::mix(b, a, (kNear - b.w) / (a.w - b.w)); + auto const from{screen(a)}; + auto const to{screen(b)}; + if (outside(from, to)) + return; + Drawlist->AddLine(from, to, Color, Thickness); + } + // members + int limit{kVertexLimit}; // vertices the draw list can hold before the drawing stops + + static constexpr int kVertexLimit{56000}; // leaves room for what's drawn after the overlay + static constexpr int kLaneVertexLimit{36000}; // the lanes give way to the tools, which are drawn after them + + private: + static constexpr float kNear{0.1f}; + ImVec2 m_size; + glm::dvec3 m_camera; + glm::mat4 m_viewprojection; +}; + +glm::dvec3 path_point(segment_data const &Path, double const T) +{ + auto const &p0 = Path.points[segment_data::point::start]; + auto const &p3 = Path.points[segment_data::point::end]; + auto const &cp1 = Path.points[segment_data::point::control1]; + auto const &cp2 = Path.points[segment_data::point::control2]; + if (cp1 == glm::dvec3{0.0} && cp2 == glm::dvec3{0.0}) + return glm::mix(p0, p3, T); + auto const p1 = p0 + cp1; + auto const p2 = p3 + cp2; + double const u = 1.0 - T; + return u * u * u * p0 + 3.0 * u * u * T * p1 + 3.0 * u * T * T * p2 + T * T * T * p3; +} + +bool is_curved(segment_data const &Path) +{ + return Path.points[segment_data::point::control1] != glm::dvec3{0.0} || Path.points[segment_data::point::control2] != glm::dvec3{0.0}; +} + +std::string lower_case(std::string Text) +{ + std::transform(Text.begin(), Text.end(), Text.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); + return Text; +} + +double const kSnapRadius{4.0}; // an end of a road this close to the cursor is what the click is taken to mean +double const kPointRadius{2.5}; // a point where pieces meet this close to the click is what gets selected, instead of the piece +double const kPointRange{400.0}; // the points are drawn for the roads this close to the camera +double const kSideMargin{1.0}; // how far past the edge of a road the cursor still counts as being on it +double const kMarkerRadius{2.0}; // a level crossing or a traffic point this close to the click is what gets selected +double const kRailReach{40.0}; // rails crossing the road this close to the cursor are taken for a single level crossing +double const kLaneReach{2.5}; // a lane with its middle this close to the cursor is the one a traffic point is put on +double const kFullTurn{6.283185307179586}; +double const kJoinClearance{15.0}; // a road isn't led into the side of another this close to the point it's led from +double const kReach{3000.0}; // clicks landing further than this are taken for misses +double const kLaneRange{600.0}; // lanes are drawn for the roads this close to the camera +double const kLongestStretch{2000.0}; // a single click doesn't lead a road further than this +// lengths of the pieces a road following the ground is tried with, from the longest; the first one to fit the ground is taken +double const kProfileSteps[]{50.0, 25.0, 12.5}; +double const kSunkTolerance{0.05}; // how far under the height it's built at the road can get between the points it's led through +double const kRaisedTolerance{0.5}; // and how far over it + +ImU32 const kForwardColor{IM_COL32(70, 230, 110, 230)}; +ImU32 const kBackwardColor{IM_COL32(255, 170, 50, 230)}; +ImU32 const kTurnColor{IM_COL32(210, 210, 210, 150)}; +ImU32 const kWayColor{IM_COL32(120, 200, 255, 170)}; +ImU32 const kPointColor{IM_COL32(255, 255, 255, 200)}; +ImU32 const kSelectedColor{IM_COL32(40, 220, 255, 230)}; +ImU32 const kPreviewColor{IM_COL32(255, 210, 60, 255)}; +ImU32 const kRefusedColor{IM_COL32(240, 60, 60, 255)}; +ImU32 const kSnapColor{IM_COL32(255, 60, 255, 255)}; +ImU32 const kCrossingColor{IM_COL32(255, 220, 60, 230)}; +ImU32 const kSpawnColor{IM_COL32(90, 230, 120, 230)}; +ImU32 const kDespawnColor{IM_COL32(255, 110, 110, 230)}; +ImU32 const kCrosswalkColor{IM_COL32(235, 235, 235, 230)}; +double const kBankReach{30.0}; // how far from the road the ground is looked for, for a bank to be led to it +double const kBankStep{0.5}; + +roadpoint_node::kind_type point_kind(int const Index) +{ + return Index == 1 ? roadpoint_node::kind_type::spawn : Index == 2 ? roadpoint_node::kind_type::despawn : Index == 3 ? roadpoint_node::kind_type::crosswalk : roadpoint_node::kind_type::crossing; +} + +char const *point_label(roadpoint_node::kind_type const Kind) +{ + return Kind == roadpoint_node::kind_type::spawn ? STR_C("spawn point") : + Kind == roadpoint_node::kind_type::despawn ? STR_C("removal point") : + Kind == roadpoint_node::kind_type::crosswalk ? STR_C("pedestrian crossing") : + STR_C("level crossing"); +} + +std::string cannot_change(std::string const &Name, std::string const &Reason) +{ + return format(STR_C("\"%s\" can't be changed: %s"), Name.c_str(), STR(Reason).c_str()); +} + +// gathers new definitions for the pieces which meet or end at provided points. +// Change: receives a definition, which end of it is at the point, and the number of the point +template +std::vector> point_changes(std::vector const &Points, Change_ Change) +{ + std::vector> changes; + for (std::size_t index = 0; index < Points.size(); ++index) + { + for (auto const &end : editor_road::ends_at(Points[index])) + { + // a piece with both its ends among the points gets both changed + auto entry{std::find_if(changes.begin(), changes.end(), [&end](std::pair const &Listed) { return Listed.first == end.road; })}; + if (entry == changes.end()) + { + changes.emplace_back(end.road, end.road->definition()); + entry = std::prev(changes.end()); + } + Change(entry->second, end.atend, index); + } + } + return changes; +} + +// direction of a path for specified value of its curve parameter. like path_point() it's cheap enough to be asked for a lot each frame +glm::dvec3 path_direction(segment_data const &Path, double const T) +{ + auto const &p0 = Path.points[segment_data::point::start]; + auto const &p3 = Path.points[segment_data::point::end]; + auto const &cp1 = Path.points[segment_data::point::control1]; + auto const &cp2 = Path.points[segment_data::point::control2]; + if (cp1 == glm::dvec3{0.0} && cp2 == glm::dvec3{0.0}) + return p3 - p0; + auto const p1 = p0 + cp1; + auto const p2 = p3 + cp2; + double const u = 1.0 - T; + return 3.0 * u * u * (p1 - p0) + 6.0 * u * T * (p2 - p1) + 3.0 * T * T * (p3 - p2); +} + +} + +void editor_mode::update_road_tool() +{ + { + // an Alt+drag of the heights is dropped once the window, the tool or the work area isn't its own any more, or its + // release went elsewhere + auto &lift{m_roadtool}; + if (lift.lifting && (false == lift.window || lift.tool != 0 || ui()->mode() == nodebank_panel::TRACK || false == ImGui::IsMouseDown(ImGuiMouseButton_Left))) + lift.lifting = false; + } + auto &tool{m_roadtool}; + if (tool.selected != nullptr && tool.selected->m_editorremoved) + tool.selected = nullptr; + if (tool.junction != nullptr && tool.junction->m_editorremoved) + tool.junction = nullptr; + if (tool.marker != nullptr && tool.marker->m_editorremoved) + tool.marker = nullptr; + if ((tool.branchroad != nullptr && tool.branchroad->m_editorremoved) || (tool.branchjunction != nullptr && tool.branchjunction->m_editorremoved)) + { + // what the road was to be led out of is gone + tool.branchroad = nullptr; + tool.branchjunction = nullptr; + tool.chain = false; + } + // so are the points whose pieces were removed or changed behind the back of the selection + tool.points.erase(std::remove_if(tool.points.begin(), tool.points.end(), [](glm::dvec3 const &Point) { return editor_road::ends_at(Point).empty(); }), tool.points.end()); + tool.plan = road_plan{}; + tool.hashover = false; + if (false == tool.window || tool.tool != 2) + { + tool.hastarget = false; + tool.aimedkind = -1; + } + if (false == tool.window) + { + tool.chain = false; + return; + } + glm::dvec3 const camera{Global.pCamera.Pos}; + tool.mouse = camera + GfxRenderer->Mouse_Position(); + if (glm::distance(tool.mouse, camera) > kReach) + { + tool.plan.error = STR_C("The cursor isn't over anything near enough"); + tool.hastarget = false; + tool.aimedkind = -1; + return; + } + if (tool.tool == 2) + { + // the point a click would make at the moment, to be drawn over the view + roadpoint_aim(false); + return; + } + if (tool.tool != 1) + return; + if (tool.ring) + { + // a click puts a roundabout around the cursor, there's nothing to lead from a point to another + tool.chain = false; + return; + } + if (tool.chain) + { + // what a click would make at the moment, to be drawn over the view + tool.plan = road_preview(false); + return; + } + // where a click would lead a road out of the side of a road, or out of a junction + if (editor_road::find_end(tool.mouse, kSnapRadius).valid()) + return; + if (auto const *road{editor_road::nearest(tool.mouse, kSideMargin)}; road != nullptr) + { + tool.hover = road->definition().point(editor_road::nearest_parameter(road->definition(), tool.mouse)); + tool.hashover = true; + } + else if (auto const *junction{editor_road::nearest_junction(tool.mouse)}; junction != nullptr) + { + tool.hover = junction->definition().centre; + tool.hashover = true; + } +} + +void editor_mode::road_select(road_node *Road) +{ + auto &tool{m_roadtool}; + tool.selected = Road; + if (Road != nullptr) + { + tool.junction = nullptr; + tool.settings = Road->definition(); + std::string reason; + tool.status = format(STR_C("Selected: %s"), Road->name().empty() ? STR_C("(unnamed road)") : Road->name().c_str()); + if (false == editor_road::can_edit(*Road, &reason)) + tool.status += ". " + format(STR_C("It can't be changed: %s"), STR(reason).c_str()); + } + else + { + // the layout stays for the build tool, which makes pieces with the same lanes all the way + tool.settings.missing = {}; + } + tool.varied = tool.settings.changing(); +} + +void editor_mode::junction_select(junction_node *Junction) +{ + auto &tool{m_roadtool}; + tool.junction = Junction; + if (Junction == nullptr) + return; + tool.selected = nullptr; + std::string reason; + tool.status = format(STR_C("Selected: %s"), Junction->name().c_str()); + if (false == editor_road::can_edit(*Junction, &reason)) + tool.status += ". " + format(STR_C("It can't be changed: %s"), STR(reason).c_str()); +} + +void editor_mode::roadpoint_select(roadpoint_node *Point) +{ + auto &tool{m_roadtool}; + tool.marker = Point; + if (Point == nullptr) + return; + std::string reason; + tool.status = format(STR_C("Selected: %s"), Point->name().c_str()); + if (false == editor_road::can_edit(*Point, &reason)) + tool.status += ". " + format(STR_C("It can't be changed: %s"), STR(reason).c_str()); +} + +// works out the point a click of the place tool would make with the cursor where it is +void editor_mode::roadpoint_aim(bool const Fresh) +{ + auto &tool{m_roadtool}; + if (false == Fresh && tool.aimedkind == tool.placekind && glm::distance(tool.aimed, tool.mouse) < 0.1) + { + // the cursor didn't move, so neither did what it points at + return; + } + tool.aimed = tool.mouse; + tool.aimedkind = tool.placekind; + auto const kind{point_kind(tool.placekind)}; + tool.target = tool.placing[tool.placekind]; + tool.target.kind = kind; + tool.hastarget = false; + tool.targetnote.clear(); + tool.targetdirection = glm::dvec3{0.0}; + if (kind == roadpoint_node::kind_type::crosswalk) + { + auto const *road{editor_road::nearest(tool.mouse, kSideMargin)}; + if (road == nullptr) + { + tool.targetnote = STR_C("Point at a road"); + return; + } + // the stripes go across the road, whichever part of it the cursor is over + auto const t{editor_road::nearest_parameter(road->definition(), tool.mouse)}; + tool.target.position = road->definition().point(t); + tool.targetdirection = road->definition().tangent(t); + tool.hastarget = true; + return; + } + if (kind == roadpoint_node::kind_type::crossing) + { + auto const *road{editor_road::nearest(tool.mouse, kSideMargin)}; + if (road == nullptr) + { + tool.targetnote = STR_C("Point at the place a road crosses the rails"); + return; + } + if (road->definition().changing()) + { + tool.targetnote = STR_C("The road gains or loses lanes on this piece; a level crossing goes on a piece which keeps its lanes"); + return; + } + glm::dvec3 middle{0.0}; + double halfspan{0.0}; + if (editor_road::rails_across(*road, tool.mouse, kRailReach, middle, halfspan)) + { + // the crossing goes halfway between the outermost tracks. the distance is rounded up, so it reads well in the scenery file + tool.target.position = middle; + tool.target.clearance = static_cast(std::ceil((halfspan + tool.stopmargin) * 2.0) * 0.5); + } + else + { + tool.target.position = road->definition().point(editor_road::nearest_parameter(road->definition(), tool.mouse)); + tool.target.clearance = std::max(tool.stopmargin, 2.0f); + tool.targetnote = STR_C("No rails cross the road here; a crossing put here won't close until some do"); + } + tool.hastarget = true; + return; + } + if (false == editor_road::nearest_lane(tool.mouse, kLaneReach, tool.target.position, tool.targetdirection)) + { + tool.targetnote = STR_C("Point at a lane of a road"); + return; + } + tool.hastarget = true; +} + +// puts down the point the place tool is set for, as a step which can be taken back +void editor_mode::roadpoint_place() +{ + auto &tool{m_roadtool}; + roadpoint_aim(true); + if (false == tool.hastarget) + { + tool.status = tool.targetnote; + return; + } + auto const created{editor_road::create(std::vector{tool.target})}; + if (created.empty()) + { + tool.status = STR_C("No scenery is loaded"); + return; + } + auto const *point{created.front()}; + auto const &state{point->definition()}; + editor_road::record record; + record.points_created = created; + push_road_snapshot(std::move(record)); + switch (state.kind) + { + case roadpoint_node::kind_type::crossing: + { + tool.status = format(STR_C("Level crossing made, Ctrl+Z takes it back. Lanes stopping %.1f m from its middle: %d, tracks watched for trains: %d"), static_cast(state.clearance), + static_cast(point->stops().size()), static_cast(point->rails())); + break; + } + case roadpoint_node::kind_type::spawn: + { + tool.status = (state.vehicles.empty() ? std::string{STR_C("Spawn point made, with no vehicles: nothing appears there until it's given some (Select, click the point)")} : + format(STR_C("Spawn point made, Ctrl+Z takes it back. Vehicles on the roads at a time: up to %d. They appear while the simulation runs"), state.count)); + break; + } + case roadpoint_node::kind_type::despawn: + { + tool.status = format(STR_C("Removal point made, Ctrl+Z takes it back. Lanes it takes vehicles from: %d"), static_cast(point->lanes().size())); + break; + } + case roadpoint_node::kind_type::crosswalk: + { + tool.status = STR_C("Pedestrian crossing painted, Ctrl+Z takes it back"); + break; + } + } + if (false == tool.targetnote.empty()) + tool.status += ". " + tool.targetnote; +} + +// replaces the definition of a level crossing or a traffic point, as a step which can be taken back +void editor_mode::roadpoint_apply(roadpoint_node &Point, roadpoint_node::state const &State) +{ + auto &tool{m_roadtool}; + std::string reason; + if (false == editor_road::can_edit(Point, &reason)) + { + tool.status = cannot_change(Point.name(), reason); + return; + } + editor_road::record record; + record.points.emplace_back(&Point, Point.definition()); + editor_road::apply(std::vector>{{&Point, State}}); + push_road_snapshot(std::move(record)); + tool.status = STR_C("Changed, Ctrl+Z takes it back"); +} + +// draws controls for a level crossing or a traffic point. returns: true if something was changed +bool editor_mode::render_roadpoint_layout(roadpoint_node::state &State, roadpoint_node const *Point) +{ + auto &tool{m_roadtool}; + bool changed{false}; + // values typed for a point which is there already are taken when confirmed, so the point isn't made anew with each digit + auto const flags{Point != nullptr ? ImGuiInputTextFlags_EnterReturnsTrue : ImGuiInputTextFlags_None}; + auto const number = [flags](char const *Label, float &Value, float const Step, char const *Format) { + ImGui::SetNextItemWidth(120.0f); + return ImGui::InputFloat(Label, &Value, Step, Step * 4.0f, Format, flags); + }; + ImVec4 const warning{1.0f, 0.6f, 0.3f, 1.0f}; + switch (State.kind) + { + case roadpoint_node::kind_type::crossing: + { + if (Point != nullptr) + { + ImGui::Text(STR_C("Lanes stopping here: %d, tracks watched for trains: %d"), static_cast(Point->stops().size()), static_cast(Point->rails())); + if (Point->rails() == 0) + ImGui::TextColored(warning, "%s", STR_C("No rails pass through it, so it never closes")); + // the crossing is tied to what's there when it's made or changed, and when the roads change + if (ImGui::Button(STR_C("Look for the rails again"))) + changed = true; + item_tooltip("For when the tracks were laid or changed after the crossing was made"); + if (number(STR_C("Stop distance from the middle [m]"), State.clearance, 0.5f, "%.1f")) + changed = true; + item_tooltip("Where the vehicles stop, measured along the road from the middle of the crossing.\n" + "The crossing closes for the tracks passing within that distance from the middle"); + } + else + { + if (number(STR_C("Stop distance from the track [m]"), tool.stopmargin, 0.5f, "%.1f")) + tool.stopmargin = std::clamp(tool.stopmargin, 2.0f, 50.0f); + item_tooltip("Where the vehicles stop, measured along the road from the axis of the first track they'd get to"); + } + if (number(STR_C("Closing distance [m]"), State.warning, 50.0f, "%.0f")) + changed = true; + item_tooltip("How far a train is when the crossing closes. Measured along the tracks, both ways, with both ways of each switch counted.\n" + "A rail vehicle within that distance which gets nearer closes the crossing, and so does one right at it.\n" + "It opens a few seconds after the last one is gone"); + if (ImGui::Checkbox(STR_C("Paint the stop lines"), &State.stoplines)) + changed = true; + break; + } + case roadpoint_node::kind_type::spawn: + { + if (Point != nullptr) + { + if (Point->lanes().empty()) + ImGui::TextColored(warning, "%s", STR_C("It isn't on a lane, so nothing appears here")); + else if (Point->vehicles() == 0) + ImGui::TextDisabled("%s", STR_C("The vehicles are made when the simulation runs")); + else + ImGui::Text(STR_C("Vehicles made: %d, waiting for their turn: %d"), static_cast(Point->vehicles()), static_cast(Point->waiting())); + } + if (number(STR_C("A vehicle every [s]"), State.interval, 1.0f, "%.0f")) + changed = true; + if (number(STR_C("Randomness [0-1]"), State.variation, 0.1f, "%.2f")) + changed = true; + item_tooltip("Part of the time between vehicles which is drawn at random each time.\n" + "0: they come like clockwork, 1: anything from one right after another to twice the time"); + if (number(STR_C("Speed [km/h]"), State.velocity, 5.0f, "%.0f")) + changed = true; + item_tooltip("The speed the vehicles appear with. From there on the drivers go by the speed limits of the lanes"); + ImGui::SetNextItemWidth(120.0f); + if (ImGui::InputInt(STR_C("Vehicles at a time"), &State.count, 1, 5, flags)) + changed = true; + item_tooltip("How many vehicles of this point can be on the scenery at once. That many are made along with the scenery,\n" + "drawn from the listed ones in turn; one of those which wait is put on the road each time its turn comes,\n" + "until all of them are out. A vehicle taken by a removal point goes back to wait for its next turn,\n" + "and so does one which stood still for 15 seconds, other than at a closed level crossing, or went backwards"); + // the set + ImGui::Separator(); + ImGui::Text(STR_C("Vehicles of the set: %d"), static_cast(State.vehicles.size())); + int removed{-1}; + for (std::size_t index = 0; index < State.vehicles.size(); ++index) + { + auto const &vehicle{State.vehicles[index]}; + ImGui::PushID(static_cast(index)); + if (ImGui::SmallButton("x")) + removed = static_cast(index); + item_tooltip("Remove from the set"); + ImGui::SameLine(); + if (vehicle.load > 0) + ImGui::Text("%s / %s, %s, %d %s", vehicle.folder.c_str(), vehicle.type.c_str(), vehicle.skin.c_str(), vehicle.load, vehicle.loadtype.c_str()); + else + ImGui::Text("%s / %s, %s", vehicle.folder.c_str(), vehicle.type.c_str(), vehicle.skin.c_str()); + ImGui::PopID(); + } + if (removed >= 0) + { + State.vehicles.erase(State.vehicles.begin() + removed); + changed = true; + } + if (State.vehicles.empty()) + ImGui::TextColored(warning, "%s", STR_C("No vehicles, so nothing appears here")); + ImGui::InputTextMultiline("##vehicles", tool.vehicles, sizeof(tool.vehicles), ImVec2(-1.0f, ImGui::GetTextLineHeight() * 5.0f)); + item_tooltip("node -1 0 none dynamic \n" + " enddynamic\n" + "or , one vehicle a line.\n" + "The path, the offset, the driver and the velocity don't matter"); + if (ImGui::Button(STR_C("Add to the set"))) + { + auto const parsed{roadpoint_node::parse_vehicles(tool.vehicles)}; + if (parsed.empty()) + { + tool.status = STR_C("No vehicle found in the text"); + } + else + { + State.vehicles.insert(State.vehicles.end(), parsed.begin(), parsed.end()); + tool.vehicles[0] = 0; + changed = true; + } + } + ImGui::SameLine(); + if (ImGui::Button(STR_C("Empty the set")) && false == State.vehicles.empty()) + { + State.vehicles.clear(); + changed = true; + } + ImGui::TextDisabled("%s", STR_C("Paste the vehicles above the way a scenery lists them")); + item_tooltip("node -1 0 none dynamic \n" + " enddynamic\n" + "or , one vehicle a line.\n" + "The path, the offset, the driver and the velocity don't matter"); + break; + } + case roadpoint_node::kind_type::despawn: + { + if (Point != nullptr) + ImGui::Text(STR_C("Lanes it takes vehicles from: %d"), static_cast(Point->lanes().size())); + if (number(STR_C("Reach [m]"), State.radius, 0.5f, "%.1f")) + changed = true; + item_tooltip("Road vehicles on the lanes passing within this distance from the point are taken off the road when they get here,\n" + "except for the one the user drives. Vehicles which came from a spawn point go back to wait for their next turn.\n" + "The distance it starts with takes in a single lane"); + break; + } + case roadpoint_node::kind_type::crosswalk: + { + if (number(STR_C("Length along the road [m]"), State.length, 0.5f, "%.1f")) + changed = true; + ImGui::TextDisabled("%s", STR_C("Stripes across the whole road")); + item_tooltip("The drivers don't stop for it: there's nobody to cross"); + break; + } + } + if (changed && Point != nullptr) + State.normalize(); + return changed; +} + +// replaces the definition of a junction, as a step which can be taken back +void editor_mode::junction_apply(junction_node &Junction, junction_node::state const &State) +{ + auto &tool{m_roadtool}; + std::string reason; + if (false == editor_road::can_edit(Junction, &reason)) + { + tool.status = cannot_change(Junction.name(), reason); + // what the window shows goes back to what the junction is like + junction_select(&Junction); + tool.status = cannot_change(Junction.name(), reason); + return; + } + editor_road::record record; + record.junctions.emplace_back(&Junction, Junction.definition()); + editor_road::apply(std::vector>{{&Junction, State}}); + push_road_snapshot(std::move(record)); + tool.status = STR_C("Changed, Ctrl+Z takes it back"); +} + +// draws controls for what a junction is like, and makes the changes as they're made +void editor_mode::render_junction_layout(junction_node &Junction) +{ + auto &tool{m_roadtool}; + auto state{Junction.definition()}; + bool changed{false}; + // typed values are taken when confirmed, so the junction isn't made anew with each digit + auto const number = [](char const *Label, float &Value, float const Step, char const *Format) { + ImGui::SetNextItemWidth(120.0f); + return ImGui::InputFloat(Label, &Value, Step, Step * 4.0f, Format, ImGuiInputTextFlags_EnterReturnsTrue); + }; + + auto limit{state.velocity > 0.f ? state.velocity : 0.f}; + if (number(STR_C("Speed limit [km/h]"), limit, 5.0f, "%.0f")) + { + state.velocity = (limit > 0.f ? limit : -1.f); + changed = true; + } + item_tooltip("0: no limit"); + auto centre{static_cast(state.centre.y)}; + if (number(STR_C("Height of the middle [m]"), centre, 0.1f, "%.2f")) + { + state.centre.y = centre; + changed = true; + } + item_tooltip("The surface is spanned between the ends of the roads and this point.\nThe ends of the roads are raised or lowered as points: select the white dot at the end of a road"); + + // appearance + ImGui::Separator(); + char const *colours[]{STR_C("no markings"), STR_C("white"), STR_C("orange")}; + int colour{state.markings == road_node::marking_colour::white ? 1 : state.markings == road_node::marking_colour::orange ? 2 : 0}; + ImGui::SetNextItemWidth(120.0f); + if (ImGui::Combo(STR_C("Markings"), &colour, colours, 3)) + { + state.markings = (colour == 1 ? road_node::marking_colour::white : colour == 2 ? road_node::marking_colour::orange : road_node::marking_colour::none); + changed = true; + } + if (render_road_material("Surface", state.surface)) + changed = true; + if (number(STR_C("Texture length [m]"), state.texturelength, 0.5f, "%.2f")) + { + state.texturelength = std::max(0.1f, state.texturelength); + changed = true; + } + item_tooltip("How many metres of the surface one copy of the texture covers"); + // what the corners between the roads are lined with + if (ImGui::Checkbox(STR_C("Kerb around the corners"), &state.kerbs)) + changed = true; + if (state.kerbs) + { + ImGui::Indent(); + if (number(STR_C("Kerb width [m]"), state.kerbwidth, 0.05f, "%.2f")) + { + state.kerbwidth = std::clamp(state.kerbwidth, 0.05f, 2.0f); + changed = true; + } + if (render_road_material("Kerb material", state.kerbmaterial)) + changed = true; + if (state.side.type != road_node::side_type::sidewalk && number(STR_C("Kerb height [m]"), state.kerbheight, 0.01f, "%.2f")) + { + state.kerbheight = std::clamp(state.kerbheight, 0.0f, 1.0f); + changed = true; + } + ImGui::Unindent(); + } + char const *sidetypes[]{STR_C("no side"), STR_C("shoulder"), STR_C("sidewalk")}; + int type{state.side.type == road_node::side_type::shoulder ? 1 : state.side.type == road_node::side_type::sidewalk ? 2 : 0}; + ImGui::SetNextItemWidth(120.0f); + if (ImGui::Combo(STR_C("Beside the corners"), &type, sidetypes, 3)) + { + state.side.type = (type == 1 ? road_node::side_type::shoulder : type == 2 ? road_node::side_type::sidewalk : road_node::side_type::none); + if (state.side.type != road_node::side_type::none && state.side.width <= 0.0f) + state.side.width = 1.5f; + changed = true; + } + if (state.side.type != road_node::side_type::none) + { + ImGui::Indent(); + if (number(STR_C("Width [m]"), state.side.width, 0.25f, "%.2f")) + { + state.side.width = std::clamp(state.side.width, 0.1f, 20.0f); + changed = true; + } + if (render_road_material("Material", state.side.material)) + changed = true; + if (state.side.material.empty() || state.side.material == "none") + ImGui::TextDisabled("%s", STR_C("Pick a material to have the sides drawn")); + if (state.side.type == road_node::side_type::sidewalk) + { + if (number(STR_C("Kerb height [m]"), state.kerbheight, 0.01f, "%.2f")) + { + state.kerbheight = std::clamp(state.kerbheight, 0.0f, 1.0f); + changed = true; + } + } + else + { + if (number(STR_C("Bank width [m]"), state.slope.x, 0.25f, "%.2f")) + { + state.slope.x = std::clamp(state.slope.x, 0.0f, 20.0f); + changed = true; + } + if (number(STR_C("Bank height [m]"), state.slope.y, 0.1f, "%.2f")) + { + state.slope.y = std::clamp(state.slope.y, 0.0f, 20.0f); + changed = true; + } + } + ImGui::Unindent(); + } + + // banks leading from the corners to the ground + if (ImGui::CollapsingHeader(STR_C("Banks to the ground##banks"))) + { + if (render_road_material("Bank material", state.bankmaterial)) + changed = true; + item_tooltip("What the banks are covered with next to a sidewalk, a kerb or the bare edge.\nA bank of a shoulder is covered with the material of the shoulder"); + ImGui::SetNextItemWidth(120.0f); + if (ImGui::InputFloat(STR_C("Bank slope 1:n"), &tool.bankgrade, 0.25f, 0.5f, "%.2f")) + tool.bankgrade = std::clamp(tool.bankgrade, 0.25f, 10.0f); + item_tooltip("n: metres across for a metre of height; 1.5 is a usual embankment"); + if (ImGui::Button(STR_C("Lead the banks to the ground"))) + { + if (changed) + junction_apply(Junction, state); + junction_bank_to_ground(Junction); + return; + } + item_tooltip("Looks for the ground past each corner, at both roads the corner runs between,\n" + "and sets the bank of the corner to reach it. Done for the roads too, the banks meet at the ends of the roads"); + auto banked{false}; + for (auto const &arm : state.arms) + banked = banked || arm.bank.set; + if (banked) + { + ImGui::SameLine(); + if (ImGui::Button(STR_C("Remove the banks"))) + { + for (auto &arm : state.arms) + arm.bank = road_node::bank_data{}; + changed = true; + } + } + } + if (state.arms.size() == 2) + { + // where a road changes its lanes: what's between its two directions, if the roads keep them apart + ImGui::Separator(); + char const *mediantypes[]{STR_C("nothing, the ground shows"), STR_C("surface closed to the traffic"), STR_C("island")}; + int median{state.median == road_node::median_type::gap ? 0 : state.median == road_node::median_type::island ? 2 : 1}; + ImGui::SetNextItemWidth(220.0f); + if (ImGui::Combo(STR_C("Between the directions"), &median, mediantypes, 3)) + { + state.median = (median == 0 ? road_node::median_type::gap : median == 2 ? road_node::median_type::island : road_node::median_type::painted); + changed = true; + } + item_tooltip("Shows where a road which keeps its two directions apart meets this stretch:\n" + "what's between the directions is led on to the other road, where it closes or carries on"); + if (state.median == road_node::median_type::island && render_road_material("Island material", state.medianmaterial)) + changed = true; + } + + // the roads + if (ImGui::CollapsingHeader(STR_C("Roads of the junction##arms"), ImGuiTreeNodeFlags_DefaultOpen)) + { + ImGui::TextDisabled("%s", STR_C("Lanes come from the roads: change them on the road")); + item_tooltip("The junction follows the roads. The roads are numbered in the view. Lanes are counted from the middle of the road;\n" + "automatic: the inner lane turns left, the outer one right, all go straight on"); + for (std::size_t arm = 0; arm < state.arms.size(); ++arm) + { + ImGui::PushID(static_cast(arm)); + auto &data{state.arms[arm]}; + ImGui::Text(STR_C("%d: %d in, %d out, lanes %.2f m wide"), static_cast(arm) + 1, data.incoming, data.outgoing, data.width); + if (state.arms.size() > 2) + { + ImGui::SameLine(); + if (ImGui::Checkbox(STR_C("Stop line"), &data.stopline)) + changed = true; + // stripes for the pedestrians, across the whole road where it meets the junction + ImGui::SameLine(); + bool zebra{data.crosswalk > 0.f}; + if (ImGui::Checkbox(STR_C("Pedestrian crossing"), &zebra)) + { + data.crosswalk = (zebra ? 4.f : 0.f); + changed = true; + } + if (zebra) + { + ImGui::SameLine(); + ImGui::SetNextItemWidth(90.0f); + if (ImGui::InputFloat("m##crosswalk", &data.crosswalk, 0.5f, 1.0f, "%.1f", ImGuiInputTextFlags_EnterReturnsTrue)) + { + data.crosswalk = std::clamp(data.crosswalk, 1.0f, 20.0f); + changed = true; + } + item_tooltip("Length of the pedestrian crossing along the road"); + } + } + if (data.incoming > 0 && state.arms.size() > 2) + { + ImGui::Indent(); + // the entries are in the order of the stored values + char const *priorities[]{STR_C("no sign: gives way to the right"), STR_C("has the right of way"), STR_C("gives way"), STR_C("stops, then gives way")}; + int priority{static_cast(data.priority)}; + ImGui::SetNextItemWidth(220.0f); + if (ImGui::Combo("##priority", &priority, priorities, 4)) + { + data.priority = static_cast(std::clamp(priority, 0, 3)); + changed = true; + } + item_tooltip("Right of way of the traffic coming in from this road"); + // ways each lane can be left by + char const *ways[]{STR_C("automatic"), STR_C("left"), STR_C("straight on"), STR_C("left, straight on"), STR_C("right"), STR_C("left, right"), STR_C("straight on, right"), STR_C("any way")}; + for (int lane = 0; lane < data.incoming; ++lane) + { + ImGui::PushID(100 + lane); + int turns{static_cast(lane) < data.turns.size() ? data.turns[lane] & 7 : 0}; + auto const label{format(STR_C("Lane %d goes"), lane + 1)}; + ImGui::SetNextItemWidth(140.0f); + if (ImGui::Combo(label.c_str(), &turns, ways, 8)) + { + data.turns.resize(std::max(data.turns.size(), static_cast(lane) + 1), 0); + data.turns[lane] = turns; + changed = true; + } + ImGui::PopID(); + } + ImGui::Unindent(); + } + ImGui::PopID(); + } + } + if (changed) + junction_apply(Junction, state); +} + +void editor_mode::road_cancel() +{ + auto &tool{m_roadtool}; + // Esc in the middle of Alt+drag: the heights stay as they were + tool.lifting = false; + tool.chain = false; + tool.branchroad = nullptr; + tool.branchjunction = nullptr; +} + +// works out what a click of the build tool would make with the cursor where it is +editor_mode::road_plan editor_mode::road_preview(bool const Fresh) +{ + auto const &tool{m_roadtool}; + auto const &layout{tool.settings}; + road_plan plan; + // lanes of the road being built which lead to its far end, and the ones leading back from there + auto const arriving{tool.reversed ? layout.backward : layout.forward}; + auto const leaving{tool.reversed ? layout.forward : layout.backward}; + float lanewidth{0.f}; + auto const evenlanes{editor_road::lane_width(layout, 0.0, lanewidth)}; + char const *unevenlanes{STR_C("Lanes of the road being built differ in width, and a junction takes roads with lanes of the same width")}; + + // where the road is led to. a loose end of a road or an arm of a junction near the cursor comes first + plan.snap = editor_road::find_end(tool.mouse, kSnapRadius); + // the end the road is being drawn from isn't somewhere to lead it to + if (plan.snap.valid() && glm::distance(plan.snap.position, tool.point) < 0.5) + plan.snap = {}; + auto target{tool.mouse + glm::dvec3{0.0, tool.offset, 0.0}}; + glm::dvec2 enddirection{0.0, 1.0}; + double endgrade{0.0}; + bool tied{false}; // the road has to arrive at the target in set direction, with set slope + if (plan.snap.valid()) + { + glm::dvec2 const outwards{plan.snap.outwards.x, plan.snap.outwards.z}; + if (glm::length(outwards) > 1e-6) + { + target = plan.snap.position; + enddirection = -glm::normalize(outwards); + endgrade = -plan.snap.outwards.y / glm::length(outwards); + tied = true; + } + else + { + plan.snap = {}; + } + } + if (plan.snap.junction != nullptr || plan.snap.half != 0) + { + // the junction has its ways through made for a set of lanes at each arm; a single roadway of a road takes the lanes it has + if (false == evenlanes || arriving != plan.snap.backward || leaving != plan.snap.forward || std::abs(lanewidth - plan.snap.width) > 0.01f) + { + plan.error = format(plan.snap.junction != nullptr ? STR_C("This arm of the junction takes a road with lanes: %d leading to it and %d away from it, %.2f m wide each") : + STR_C("This roadway takes a road with lanes: %d leading to it and %d away from it, %.2f m wide each"), + plan.snap.backward, plan.snap.forward, static_cast(plan.snap.width)); + return plan; + } + } + else if (false == plan.snap.valid() && glm::distance(tool.mouse, tool.point) > kJoinClearance) + { + // then the side of a road, or a junction between its roads: the road is taken in with a junction made there, or with another arm of the one which is there + auto *road{editor_road::nearest(tool.mouse, kSideMargin)}; + auto *junction{road == nullptr ? editor_road::nearest_junction(tool.mouse) : nullptr}; + if (road != nullptr && road == tool.branchroad) + road = nullptr; + if (junction != nullptr && junction == tool.branchjunction) + junction = nullptr; + if (road != nullptr || junction != nullptr) + { + if (false == evenlanes) + { + plan.error = unevenlanes; + return plan; + } + auto const t{road != nullptr ? editor_road::nearest_parameter(road->definition(), tool.mouse) : 0.0}; + auto const centre{road != nullptr ? road->definition().point(t) : junction->definition().centre}; + // seen from the junction the road comes from where it's being led from + glm::dvec2 const from{tool.point.x - centre.x, tool.point.z - centre.z}; + if (false == (road != nullptr ? editor_road::branch_from(*road, t, from, arriving, leaving, lanewidth, plan.end, plan.error) : editor_road::branch_from(*junction, from, arriving, leaving, lanewidth, plan.end, plan.error))) + return plan; + plan.hasend = true; + auto const &arm{plan.end.layout.arms[plan.end.arm]}; + target = arm.position; + enddirection = -arm.direction; + tied = true; + } + } + + // where the road starts + auto start{tool.point}; + auto direction{tool.direction}; + auto hasdirection{tool.hasdirection}; + auto startgrade{tool.grade}; + auto hasgrade{tool.hasgrade}; + if (tool.branchroad != nullptr || tool.branchjunction != nullptr) + { + // out of the side of a road, or out of a junction, in the direction of where it's led to + if (false == evenlanes) + { + plan.error = unevenlanes; + return plan; + } + glm::dvec2 const away{target.x - tool.point.x, target.z - tool.point.z}; + if (glm::length(away) < 1.0) + { + plan.error = STR_C("Move the cursor to where the road is to go"); + return plan; + } + // the axis of the road goes away from the junction, so the lanes going against it are the ones leading into the junction + if (false == (tool.branchroad != nullptr ? editor_road::branch_from(*tool.branchroad, tool.branchat, away, layout.backward, layout.forward, lanewidth, plan.start, plan.error) : + editor_road::branch_from(*tool.branchjunction, away, layout.backward, layout.forward, lanewidth, plan.start, plan.error))) + return plan; + plan.hasstart = true; + auto const &arm{plan.start.layout.arms[plan.start.arm]}; + start = arm.position; + direction = arm.direction; + hasdirection = true; + startgrade = 0.0; + hasgrade = true; + } + if (plan.hasstart && plan.hasend) + { + // the two junctions are laid out for the roads as they are now, which stops being true for the second once the first is made + bool shared{plan.start.junction != nullptr && plan.start.junction == plan.end.junction}; + auto const touches = [](editor_road::branch const &Branch, road_node const *Road) { + return std::any_of(Branch.changes.begin(), Branch.changes.end(), [Road](std::pair const &Change) { return Change.first == Road; }) || + std::find(Branch.removed.begin(), Branch.removed.end(), Road) != Branch.removed.end(); + }; + for (auto const &change : plan.start.changes) + shared = shared || touches(plan.end, change.first); + for (auto const *road : plan.start.removed) + shared = shared || touches(plan.end, road); + if (shared) + { + plan.error = STR_C("The junctions at both ends would take the same piece of road; lead the road somewhere else first"); + return plan; + } + } + if (glm::distance(start, target) > kLongestStretch) + { + plan.error = STR_C("Too far from the last point"); + return plan; + } + plan.pieces = editor_road::plan(start, hasdirection ? &direction : nullptr, target, tied ? &enddirection : nullptr, Global.ctrlState, plan.error); + road_profile(plan.pieces, hasgrade ? &startgrade : nullptr, tied ? &endgrade : nullptr, Fresh); + return plan; +} + +// gives the pieces laid out by the planner their heights: over the ground if the road is to follow it, with the slopes +// of the pieces matched where they meet, and with what the road is attached to +void editor_mode::road_profile(std::vector &Pieces, double const *Firstgrade, double const *Lastgrade, bool const Fresh) +{ + auto const &tool{m_roadtool}; + if (Pieces.empty()) + return; + if (false == tool.follow) + { + // straight from a point to the next one, the way a ramp or a viaduct goes + std::vector heights; + for (auto const &piece : Pieces) + heights.emplace_back(piece.points[segment_data::point::start].y); + heights.emplace_back(Pieces.back().points[segment_data::point::end].y); + editor_road::profile(Pieces, heights, Firstgrade, Lastgrade); + return; + } + auto const planned{Pieces}; + for (auto const step : kProfileSteps) + { + Pieces = editor_road::refine(planned, step); + auto const count{Pieces.size()}; + // the ground is looked up where the pieces meet, and in the middle of each to see how the result fits it + std::vector points; + points.reserve(2 * count + 1); + for (auto const &piece : Pieces) + points.emplace_back(piece.points[segment_data::point::start]); + points.emplace_back(Pieces.back().points[segment_data::point::end]); + for (auto const &piece : Pieces) + points.emplace_back(path_point(piece, 0.5)); + // the planner leads the road between its ends, which are over the ground already + for (auto &point : points) + point.y -= tool.offset; + auto ground{ground_heights(points, Fresh)}; + for (auto &height : ground) + height += tool.offset; + std::vector heights(ground.begin(), ground.begin() + count + 1); + // the ends are where they were put + heights.front() = Pieces.front().points[segment_data::point::start].y; + heights.back() = Pieces.back().points[segment_data::point::end].y; + editor_road::profile(Pieces, heights, Firstgrade, Lastgrade); + // shorter pieces are called for if the ground shows through the road, or the road hangs over it. + // the pieces attached to something are let off, as they have to get to its height one way or another + bool fits{true}; + for (std::size_t i = 0; i < count; ++i) + { + if ((i == 0 && Firstgrade != nullptr) || (i + 1 == count && Lastgrade != nullptr)) + continue; + auto const over{path_point(Pieces[i], 0.5).y - ground[count + 1 + i]}; + if (over < -kSunkTolerance || over > kRaisedTolerance) + { + fits = false; + break; + } + } + if (fits) + break; + } +} + +bool editor_mode::road_joint_on_screen(glm::dvec3 &Joint) const +{ + screen_projection const projection; + auto const mouse{ImGui::GetIO().MousePos}; + glm::dvec3 const camera{Global.pCamera.Pos}; + // no farther than what is under the cursor and a bit beyond it (a point in a cutting, under an embankment), so nothing far + // behind the ground or a model shown there is picked through it + auto reach{kReach}; + if (GfxRenderer->Mouse_Hit()) + reach = std::min(reach, glm::length(GfxRenderer->Mouse_Position()) * 1.1 + 15.0); + // the nearest on the screen, by whole pixels; of those as near, the one nearer to the camera + auto best_pixels{std::numeric_limits::max()}; + auto best_range{std::numeric_limits::max()}; + bool found{false}; + editor_road::each_joint([&](glm::dvec3 const &Point) { + auto const range{glm::distance(Point, camera)}; + ImVec2 screen; + if (range > reach || false == projection.project(Point, screen)) + return; + auto const dx{screen.x - mouse.x}; + auto const dy{screen.y - mouse.y}; + auto const pixels{static_cast(std::sqrt(dx * dx + dy * dy))}; + if (pixels > 12 || pixels > best_pixels || (pixels == best_pixels && range >= best_range)) + return; + best_pixels = pixels; + best_range = range; + Joint = Point; + found = true; + }); + return found; +} + +bool editor_mode::road_lift_start() +{ + auto &tool{m_roadtool}; + glm::dvec3 joint; + if (tool.tool != 0 || false == road_joint_on_screen(joint)) + return false; + auto const listed{std::find_if(tool.points.begin(), tool.points.end(), [&joint](glm::dvec3 const &Point) { return glm::distance(Point, joint) < 0.25; })}; + if (listed == tool.points.end()) + tool.points.assign(1, joint); + tool.selected = nullptr; + tool.junction = nullptr; + tool.marker = nullptr; + auto const &io{ImGui::GetIO()}; + auto const height{std::max(1.0f, io.DisplaySize.y)}; + if (Global.EditorOrtho) + tool.lift_scale = 2.0 * static_cast(Global.EditorOrthoExtent) / height; + else + tool.lift_scale = glm::distance(joint, glm::dvec3{Global.pCamera.Pos}) * 2.0 * std::tan(glm::radians(Global.FieldOfView / Global.ZoomFactor) * 0.5) / height; + tool.lift_mouse = io.MousePos.y; + tool.lift_from.clear(); + for (auto const &point : tool.points) + tool.lift_from.push_back(point.y); + tool.lifting = true; + tool.status = STR_C("Drag up or down, let go to set the heights. Ctrl while dragging: by centimetres"); + return true; +} + +double editor_mode::road_lift_offset() const +{ + auto const &tool{m_roadtool}; + auto offset{(tool.lift_mouse - ImGui::GetIO().MousePos.y) * tool.lift_scale}; + // with Ctrl it's slower, for the fine part + if (Global.ctrlState) + offset *= 0.1; + return std::round(offset * 100.0) / 100.0; +} + +void editor_mode::road_lift_finish() +{ + auto &tool{m_roadtool}; + if (false == tool.lifting) + return; + tool.lifting = false; + auto const offset{road_lift_offset()}; + if (std::abs(offset) < 0.005 || tool.lift_from.size() != tool.points.size()) + return; + std::vector heights; + for (auto const height : tool.lift_from) + heights.push_back(height + offset); + road_point_heights(heights); +} + +void editor_mode::road_click() +{ + auto &tool{m_roadtool}; + glm::dvec3 const camera{Global.pCamera.Pos}; + glm::dvec3 const ground{camera + GfxRenderer->Mouse_Position()}; + if (glm::distance(ground, camera) > kReach) + { + tool.status = STR_C("The click didn't land on anything near enough"); + return; + } + tool.mouse = ground; + if (tool.tool == 2) + { + roadpoint_place(); + return; + } + if (tool.tool == 0) + { + if (auto *marker{editor_road::nearest_point(ground, kMarkerRadius)}; marker != nullptr) + { + // a level crossing or a traffic point + tool.points.clear(); + tool.junction = nullptr; + road_select(nullptr); + roadpoint_select(marker); + return; + } + tool.marker = nullptr; + glm::dvec3 joint; + // the point by the ground clicked first, then the piece or the junction under the cursor; the point nearest on the screen + // only when there's none of them (a point under the terrain, in a cutting, can't be got near by the ground clicked) + auto *under{editor_road::nearest(ground, 1.5)}; + auto *junction_under{under == nullptr ? editor_road::nearest_junction(ground) : nullptr}; + if (editor_road::nearest_joint(ground, kPointRadius, joint) || (under == nullptr && junction_under == nullptr && road_joint_on_screen(joint))) + { + // a point where pieces meet or end. with Shift it's added to the selected ones, or taken out of them + auto const listed{std::find_if(tool.points.begin(), tool.points.end(), [&joint](glm::dvec3 const &Point) { return glm::distance(Point, joint) < 0.25; })}; + if (false == Global.shiftState) + tool.points.assign(1, joint); + else if (listed != tool.points.end()) + tool.points.erase(listed); + else + tool.points.emplace_back(joint); + tool.selected = nullptr; + tool.junction = nullptr; + tool.status = format(STR_C("Points selected: %d"), static_cast(tool.points.size())); + return; + } + tool.points.clear(); + if (under == nullptr && junction_under == nullptr) + tool.status = STR_C("No road here"); + road_select(under); + junction_select(junction_under); + return; + } + + std::string reason; + if (false == editor_road::available(&reason)) + { + tool.status = STR(reason); + return; + } + if (tool.ring) + { + road_roundabout(ground); + return; + } + if (false == tool.chain) + { + // first click sets where the road starts + tool.branchroad = nullptr; + tool.branchjunction = nullptr; + tool.selected = nullptr; + tool.junction = nullptr; + tool.points.clear(); + auto const end{editor_road::find_end(ground, kSnapRadius)}; + glm::dvec2 const outwards{end.outwards.x, end.outwards.z}; + if (end.valid() && glm::length(outwards) > 1e-6) + { + // started from a loose end of a road it carries that road on, started from an arm of a junction it's the road the junction is made for there + if (false == editor_road::can_join(end, &reason)) + { + tool.status = format(STR_C("Can't build from here: %s"), STR(reason).c_str()); + return; + } + tool.point = end.position; + tool.direction = glm::normalize(outwards); + tool.hasdirection = true; + tool.grade = end.outwards.y / glm::length(outwards); + tool.hasgrade = true; + if (end.road != nullptr && end.half == 0) + { + // carried on from its start the road keeps the direction of its axis, so the lanes stay what they were + tool.reversed = (false == end.atend); + // with the lanes it has at that end + tool.settings = end.road->definition().section(end.atend ? 1 : 0); + // and it stays as wide as it is at that end, with its directions as far apart + auto const scale{tool.settings.taper[end.atend ? 1 : 0]}; + tool.settings.taper = {scale, scale}; + auto const gap{tool.settings.median.width[end.atend ? 1 : 0]}; + tool.settings.median.width = {gap, gap}; + // the banks were made for the ground where they are + tool.settings.banks = {}; + tool.status = format(STR_C("Carrying on \"%s\" with its layout"), end.road->name().c_str()); + } + else + { + tool.reversed = false; + if (end.road != nullptr) + { + // one of the roadways of a road which keeps its directions apart is carried on as a road of its own, which looks like the road it leaves + tool.settings = end.road->definition(); + tool.settings.sides[end.half > 0 ? 0 : 1] = road_node::side_data{}; + tool.settings.banks = {}; + tool.settings.missing = {}; + } + tool.settings.forward = end.forward; + tool.settings.backward = end.backward; + tool.settings.lanewidth = end.width; + tool.settings.taper = {1.f, 1.f}; + tool.settings.median.width = {0.f, 0.f}; + tool.settings.lanes.clear(); + tool.settings.changes.clear(); + tool.settings.normalize(); + tool.status = (end.junction != nullptr ? format(STR_C("Leading a road out of \"%s\", with the lanes the junction has there"), end.junction->name().c_str()) : + format(STR_C("Carrying on one of the roadways of \"%s\" as a one-way road"), end.road->name().c_str())); + } + road_select(nullptr); + } + else + { + tool.hasdirection = false; + tool.hasgrade = false; + tool.reversed = false; + tool.settings.taper = {1.f, 1.f}; + if (auto *road{editor_road::nearest(ground, kSideMargin)}; road != nullptr) + { + // started from the side of a road it leaves that road at a junction, made along with its first piece + tool.branchroad = road; + tool.branchat = editor_road::nearest_parameter(road->definition(), ground); + tool.point = road->definition().point(tool.branchat); + tool.status = format(STR_C("Leading a road out of the side of \"%s\": click where it goes"), road->name().c_str()); + } + else if (auto *junction{editor_road::nearest_junction(ground)}; junction != nullptr) + { + // started from a junction it's another road of that junction + if (junction->definition().arms.size() >= 4) + { + tool.status = format(STR_C("\"%s\" has four roads already"), junction->name().c_str()); + return; + } + tool.branchjunction = junction; + tool.point = junction->definition().centre; + tool.status = format(STR_C("Leading another road out of \"%s\": click where it goes"), junction->name().c_str()); + } + else + { + tool.point = ground + glm::dvec3{0.0, tool.offset, 0.0}; + tool.status = STR_C("Start set: click the next points, Esc finishes"); + } + } + tool.chain = true; + return; + } + + auto plan{road_preview(true)}; + if (plan.pieces.empty()) + { + tool.status = format(STR_C("Can't build this: %s"), STR(plan.error).c_str()); + return; + } + if (plan.snap.valid() && false == editor_road::can_join(plan.snap, &reason)) + { + tool.status = format(STR_C("Can't join here: %s"), STR(reason).c_str()); + return; + } + auto pieces{plan.pieces}; + // where the next piece is going to carry on from + auto const &last{pieces.back()}; + auto const endpoint{last.points[segment_data::point::end]}; + auto const tangent{last.points[segment_data::point::control2] != glm::dvec3{0.0} ? -last.points[segment_data::point::control2] : last.points[segment_data::point::end] - last.points[segment_data::point::start]}; + auto const grade{editor_road::end_grade(last)}; + if (tool.reversed) + { + for (auto &piece : pieces) + { + std::swap(piece.points[segment_data::point::start], piece.points[segment_data::point::end]); + std::swap(piece.points[segment_data::point::control1], piece.points[segment_data::point::control2]); + } + std::reverse(pieces.begin(), pieces.end()); + } + // the junctions the road starts or ends with are made first, so the road finds them when it's made + editor_road::record record; + if (plan.hasstart) + { + if (plan.start.junction == nullptr) + plan.start.layout.velocity = tool.crossingspeed; + editor_road::carry_out(plan.start, record); + } + if (plan.hasend) + { + if (plan.end.junction == nullptr) + plan.end.layout.velocity = tool.crossingspeed; + editor_road::carry_out(plan.end, record); + } + std::vector states; + // what changes from the start of a piece to its end is spread over the whole stretch being built, + // so the pieces don't each go through all of it + std::vector stations{0.0}; + for (auto const &piece : pieces) + stations.emplace_back(stations.back() + editor_road::planar_length(piece)); + auto const along = [&stations](std::size_t const Index) { + auto const fraction{stations.back() > 0.0 ? stations[Index] / stations.back() : 0.0}; + return static_cast(fraction * fraction * (3.0 - 2.0 * fraction)); + }; + for (std::size_t index = 0; index < pieces.size(); ++index) + { + auto state{tool.settings}; + state.axis = pieces[index]; + state.missing = {}; + auto const from{along(index)}; + auto const to{along(index + 1)}; + auto const &median{tool.settings.median}; + state.median.width = {glm::mix(median.width[0], median.width[1], from), glm::mix(median.width[0], median.width[1], to)}; + // an island is rounded where the stretch starts and ends + state.median.round = {index == 0 ? median.round[0] : 0.f, index + 1 == pieces.size() ? median.round[1] : 0.f}; + for (std::size_t side = 0; side < state.banks.size(); ++side) + { + auto const &bank{tool.settings.banks[side]}; + state.banks[side].width = {glm::mix(bank.width[0], bank.width[1], from), glm::mix(bank.width[0], bank.width[1], to)}; + state.banks[side].drop = {glm::mix(bank.drop[0], bank.drop[1], from), glm::mix(bank.drop[0], bank.drop[1], to)}; + } + states.emplace_back(state); + } + auto const created{editor_road::create(states)}; + record.roads_created.insert(record.roads_created.end(), created.begin(), created.end()); + push_road_snapshot(std::move(record)); + tool.branchroad = nullptr; + tool.branchjunction = nullptr; + if (created.empty()) + { + tool.chain = false; + tool.status = STR_C("The road wasn't created"); + return; + } + if (plan.snap.valid() || plan.hasend) + { + tool.chain = false; + tool.status = (plan.snap.valid() ? format(STR_C("Joined with \"%s\", Ctrl+Z takes it back"), (plan.snap.road != nullptr ? plan.snap.road->name() : plan.snap.junction->name()).c_str()) : + plan.end.junction != nullptr ? format(STR_C("Led into \"%s\" as another of its roads, Ctrl+Z takes it back"), plan.end.junction->name().c_str()) : + std::string{STR_C("Led into the side of the road, with a junction made there, Ctrl+Z takes it back")}); + return; + } + glm::dvec2 const planar{tangent.x, tangent.z}; + tool.point = endpoint; + if (glm::length(planar) > 1e-6) + { + tool.direction = glm::normalize(planar); + tool.hasdirection = true; + } + tool.grade = grade; + tool.hasgrade = true; + tool.status = format(STR_C("Pieces added: %d"), static_cast(created.size())); + if (plan.hasstart) + tool.status += (plan.start.junction != nullptr ? STR_C(", as another road of the junction") : STR_C(", with a junction where the road leaves")); + tool.status += STR_C(", Ctrl+Z takes them back"); +} + +void editor_mode::road_apply() +{ + auto &tool{m_roadtool}; + if (tool.selected == nullptr) + return; + tool.settings.normalize(); + // other lanes at the end are something the selected piece has for itself; the rest of the road keeps the lanes it has + auto const pieces{tool.whole && false == tool.settings.changing() ? editor_road::chain(*tool.selected) : std::vector{tool.selected}}; + editor_road::record record; + std::vector> changes; + // the banks are kept for each piece as they are, unless it's the banks which were just changed + auto const banked{tool.settings.banks != tool.selected->definition().banks}; + for (auto *road : pieces) + { + std::string reason; + if (false == editor_road::can_edit(*road, &reason)) + { + // what the window shows goes back to what the road is like + road_select(tool.selected); + tool.status = cannot_change(road->name(), reason); + return; + } + auto state{tool.settings}; + state.axis = road->definition().axis; + // how wide the road is at its points is set at these points, for each piece on its own + state.taper = road->definition().taper; + if (road != tool.selected) + { + // and so is how far apart the two directions are led, and the rounded ends of what's between them + state.median.width = road->definition().median.width; + state.median.round = road->definition().median.round; + // banks led to the ground differ from piece to piece, so a change of something else leaves them alone + if (false == banked) + state.banks = road->definition().banks; + } + if (road != tool.selected && road->definition().changes.size() == state.changes.size()) + { + // where the lanes can be changed is set for each piece on its own + state.changes = road->definition().changes; + } + record.roads.emplace_back(road, road->definition()); + changes.emplace_back(road, state); + } + editor_road::apply(changes); + // what's next to the changed pieces is fitted to them: junctions take the lanes they have now, the pieces of the road + // which stay as they were get wider or narrower towards them, or give up their ends for the lanes to change + std::string notes; + for (auto *road : pieces) + editor_road::settle(*road, record, notes); + auto const fitted{record.roads.size() + record.roads_removed.size() + record.junctions.size() + record.junctions_created.size() - pieces.size()}; + push_road_snapshot(std::move(record)); + tool.settings = tool.selected->definition(); + tool.status = (pieces.size() == 1 ? std::string{STR_C("Changed, Ctrl+Z takes it back")} : format(STR_C("Pieces changed: %d, Ctrl+Z takes it back"), static_cast(pieces.size()))); + if (fitted > 0) + tool.status += std::string{". "} + STR_C("What's next to it was fitted to it"); + if (false == notes.empty()) + tool.status += ". " + notes; +} + +bool editor_mode::road_delete() +{ + auto &tool{m_roadtool}; + if (false == tool.window) + return false; + std::string reason; + editor_road::record record; + if (tool.marker != nullptr) + { + auto *point{tool.marker}; + if (false == editor_road::can_edit(*point, &reason)) + { + tool.status = format(STR_C("Can't delete: %s"), STR(reason).c_str()); + return true; + } + editor_road::remove(std::vector{point}); + record.points_removed.emplace_back(point); + push_road_snapshot(std::move(record)); + tool.marker = nullptr; + tool.status = format(STR_C("\"%s\" deleted, Ctrl+Z brings it back"), point->name().c_str()); + return true; + } + if (false == tool.points.empty()) + return road_points_delete(); + if (tool.selected == nullptr && tool.junction == nullptr) + return false; + if (tool.junction != nullptr) + { + auto *junction{tool.junction}; + if (false == editor_road::can_edit(*junction, &reason)) + { + tool.status = format(STR_C("Can't delete: %s"), STR(reason).c_str()); + return true; + } + editor_road::remove(std::vector{junction}); + record.junctions_removed.emplace_back(junction); + push_road_snapshot(std::move(record)); + tool.junction = nullptr; + tool.status = format(STR_C("\"%s\" deleted, Ctrl+Z brings it back"), junction->name().c_str()); + return true; + } + auto *road{tool.selected}; + if (false == editor_road::can_edit(*road, &reason)) + { + tool.status = format(STR_C("Can't delete: %s"), STR(reason).c_str()); + return true; + } + editor_road::remove(std::vector{road}); + record.roads_removed.emplace_back(road); + push_road_snapshot(std::move(record)); + tool.selected = nullptr; + tool.status = format(STR_C("\"%s\" deleted, Ctrl+Z brings it back"), road->name().c_str()); + return true; +} + +// puts a roundabout around specified point +void editor_mode::road_roundabout(glm::dvec3 const &Ground) +{ + auto &tool{m_roadtool}; + std::string reason; + if (false == editor_road::available(&reason)) + { + tool.status = STR(reason); + return; + } + auto const states{editor_road::roundabout(Ground + glm::dvec3{0.0, tool.offset, 0.0}, tool.ringradius, tool.settings, tool.island)}; + if (states.empty()) + { + tool.status = STR_C("The roundabout is too small for its lanes: give it a larger radius"); + return; + } + for (auto const &state : states) + { + for (auto const t : {0.0, 0.5}) + { + if (editor_road::nearest(state.point(t), 0.0) != nullptr || editor_road::nearest_junction(state.point(t)) != nullptr) + { + tool.status = STR_C("There's a road in the way. Make the roundabout next to it, then lead the road into its side"); + return; + } + } + } + auto const created{editor_road::create(states)}; + if (created.empty()) + { + tool.status = STR_C("The roundabout wasn't created"); + return; + } + editor_road::record record; + record.roads_created = created; + push_road_snapshot(std::move(record)); + tool.status = STR_C("Roundabout made, Ctrl+Z takes it back. Untick Roundabout and lead roads out of its side, or into it: the traffic joining it gives way to the traffic going around"); +} + +// how far from specified point, and how far down, a slope of the grade set for the banks gets to the ground +std::pair editor_mode::bank_reach(glm::dvec3 const &Edge, glm::dvec3 const &Outwards) +{ + auto const grade{std::clamp(static_cast(m_roadtool.bankgrade), 0.25, 10.0)}; + auto const steps{static_cast(kBankReach / kBankStep)}; + // the ground further and further from the edge, without the roads themselves + std::vector probes; + for (int step = 1; step <= steps; ++step) + probes.emplace_back(Edge + Outwards * (step * kBankStep)); + auto const ground{ground_heights(probes, true)}; + // the bank ends where a slope of the set grade, going down or up, gets to the ground + auto const rising{ground.front() > Edge.y}; + auto width{kBankReach}; + auto drop{Edge.y - ground.back()}; + for (int step = 1; step <= steps; ++step) + { + auto const reach{step * kBankStep}; + auto const height{ground[step - 1]}; + if (rising ? height <= Edge.y + reach / grade : height >= Edge.y - reach / grade) + { + width = reach; + drop = Edge.y - height; + break; + } + } + return {static_cast(width), static_cast(drop)}; +} + +// leads the banks of the corners of a junction to the ground beside it +void editor_mode::junction_bank_to_ground(junction_node &Junction) +{ + auto state{Junction.definition()}; + auto const order{state.arm_order()}; + auto const sided{state.side.type != road_node::side_type::none && state.side.width > 0.f}; + // where the banks start: past the kerb and whatever lines the corners + auto const lining{(state.kerbs ? state.kerbwidth : 0.f) + (sided ? state.side.width : 0.f)}; + auto const raised{sided && state.side.type == road_node::side_type::sidewalk ? state.kerbheight : 0.f}; + for (std::size_t idx = 0; idx < order.size(); ++idx) + { + // a corner starts at the left edge of a road, seen from the junction, and ends at the right edge of the next one + auto &arm{state.arms[order[idx]]}; + auto const &next{state.arms[order[(idx + 1) % order.size()]]}; + glm::dvec3 const outwards[2]{glm::dvec3{arm.direction.y, 0.0, -arm.direction.x}, -glm::dvec3{next.direction.y, 0.0, -next.direction.x}}; + glm::dvec3 const edges[2]{arm.position + outwards[0] * (0.5 * state.arm_width(order[idx]) + lining) + glm::dvec3{0.0, raised, 0.0}, + next.position + outwards[1] * (0.5 * state.arm_width(order[(idx + 1) % order.size()]) + lining) + glm::dvec3{0.0, raised, 0.0}}; + arm.bank.set = true; + for (int end = 0; end < 2; ++end) + { + auto const reach{bank_reach(edges[end], outwards[end])}; + arm.bank.width[end] = reach.first; + arm.bank.drop[end] = reach.second; + } + } + junction_apply(Junction, state); + auto &tool{m_roadtool}; + if (tool.status == STR_C("Changed, Ctrl+Z takes it back")) + { + tool.status = STR_C("Banks of the junction led to the ground, Ctrl+Z takes it back"); + if ((false == sided || state.side.type != road_node::side_type::shoulder) && (state.bankmaterial.empty() || state.bankmaterial == "none")) + tool.status += std::string{". "} + STR_C("Pick a bank material to have them drawn"); + } +} + +// leads the banks of the selected piece, or of the whole road, to the ground beside it +void editor_mode::road_bank_to_ground() +{ + auto &tool{m_roadtool}; + if (tool.selected == nullptr) + return; + auto const pieces{tool.whole ? editor_road::chain(*tool.selected) : std::vector{tool.selected}}; + std::string reason; + for (auto const *road : pieces) + { + if (false == editor_road::can_edit(*road, &reason)) + { + tool.status = cannot_change(road->name(), reason); + return; + } + } + std::vector> changes; + for (auto *road : pieces) + { + auto state{road->definition()}; + for (int side = 0; side < 2; ++side) + { + auto const &data{state.sides[side]}; + auto const sided{data.type != road_node::side_type::none && data.width > 0.f}; + for (int end = 0; end < 2; ++end) + { + auto const t{static_cast(end)}; + // where the bank starts: past the roadway, the kerb and whatever lies beside it + auto const tangent{state.tangent(t)}; + glm::dvec3 across{tangent.z, 0.0, -tangent.x}; + if (glm::length(across) < 1e-9) + continue; + across = glm::normalize(across) * (side == 0 ? 1.0 : -1.0); + auto edge{state.point(t) + across * (0.5 * state.span(t) + (state.kerbs[side] ? state.kerbwidth : 0.f) + (sided ? data.width : 0.f))}; + if (sided && data.type == road_node::side_type::sidewalk) + edge.y += state.kerbheight; + auto const reach{bank_reach(edge, across)}; + state.banks[side].set = true; + state.banks[side].width[end] = reach.first; + state.banks[side].drop[end] = reach.second; + } + } + changes.emplace_back(road, state); + } + editor_road::record record; + for (auto const &change : changes) + record.roads.emplace_back(change.first, change.first->definition()); + editor_road::apply(changes); + push_road_snapshot(std::move(record)); + road_select(tool.selected); + tool.status = format(STR_C("Banks led to the ground, pieces: %d, Ctrl+Z takes it back"), static_cast(changes.size())); + auto const &layout{tool.selected->definition()}; + if ((layout.sides[0].type != road_node::side_type::shoulder || layout.sides[1].type != road_node::side_type::shoulder) && (layout.bankmaterial.empty() || layout.bankmaterial == "none")) + tool.status += std::string{". "} + STR_C("Pick a bank material to have them drawn where the road has no shoulder"); +} + +// takes the selected points out of their roads +bool editor_mode::road_points_delete() +{ + auto &tool{m_roadtool}; + editor_road::record record; + std::string notes; + int taken{0}; + for (auto const &point : tool.points) + { + std::string error; + if (editor_road::dissolve(point, record, error)) + ++taken; + else if (auto const note{". " + format(STR_C("A point was left: %s"), STR(error).c_str())}; notes.find(note) == std::string::npos) + notes += note; + } + push_road_snapshot(std::move(record)); + // the points which stayed are still selected, so it's clear which ones these are + tool.points.erase(std::remove_if(tool.points.begin(), tool.points.end(), [](glm::dvec3 const &Point) { return editor_road::ends_at(Point).empty(); }), tool.points.end()); + tool.status = (taken == 0 ? std::string{STR_C("Nothing deleted")} : taken == 1 ? std::string{STR_C("Point deleted, Ctrl+Z brings it back")} : + format(STR_C("Points deleted: %d, Ctrl+Z brings them back"), taken)); + tool.status += notes; + return true; +} + +bool editor_mode::road_split() +{ + auto &tool{m_roadtool}; + if (false == tool.window || tool.selected == nullptr) + return false; + auto *road{tool.selected}; + std::string reason; + if (false == editor_road::can_edit(*road, &reason)) + { + tool.status = format(STR_C("Can't split: %s"), STR(reason).c_str()); + return true; + } + if (road->definition().changing()) + { + tool.status = STR_C("Can't split a piece which gains or loses lanes; give it the same lanes at both ends first"); + return true; + } + editor_road::record record; + record.roads.emplace_back(road, road->definition()); + auto *created{editor_road::split(*road, editor_road::nearest_parameter(road->definition(), tool.mouse))}; + if (created == nullptr) + { + tool.status = STR_C("Can't split this close to the end"); + return true; + } + record.roads_created.emplace_back(created); + push_road_snapshot(std::move(record)); + road_select(road); + tool.status = format(STR_C("Split in two: \"%s\" and \"%s\", Ctrl+Z takes it back. Click the point between them to set the width or the height of the road there"), road->name().c_str(), + created->name().c_str()); + return true; +} + +// makes the changes gathered for the selected points. returns: true if they were made +bool editor_mode::road_points_apply(std::vector> const &Changes, std::vector> const &Junctions) +{ + auto &tool{m_roadtool}; + if (Changes.empty() && Junctions.empty()) + { + tool.status = STR_C("There's nothing to change at the selected points"); + return false; + } + editor_road::record record; + std::string reason; + for (auto const &change : Changes) + { + if (false == editor_road::can_edit(*change.first, &reason)) + { + tool.status = cannot_change(change.first->name(), reason); + return false; + } + record.roads.emplace_back(change.first, change.first->definition()); + } + for (auto const &change : Junctions) + { + if (false == editor_road::can_edit(*change.first, &reason)) + { + tool.status = cannot_change(change.first->name(), reason); + return false; + } + record.junctions.emplace_back(change.first, change.first->definition()); + } + editor_road::apply(Changes); + editor_road::apply(Junctions); + // junctions the changed pieces lead to are made for the roads as they are now + std::string notes; + for (auto const &change : Changes) + editor_road::settle(*change.first, record, notes); + push_road_snapshot(std::move(record)); + tool.status = format(STR_C("Pieces changed: %d, Ctrl+Z takes it back"), static_cast(Changes.size())); + if (false == notes.empty()) + tool.status += ". " + notes; + return true; +} + +void editor_mode::road_point_width(float const Width) +{ + // the pieces on both sides of a point get to that width there, and from there go back to their own along their length + auto const changes{point_changes(m_roadtool.points, [Width](road_node::state &State, bool const Atend, std::size_t const) { + auto const width{State.width(Atend ? 1 : 0)}; + if (width > 0.0) + State.taper[Atend ? 1 : 0] = std::clamp(static_cast(Width / width), 0.25f, 4.f); + })}; + road_points_apply(changes, {}); +} + +// Heights: one for each of the selected points +void editor_mode::road_point_heights(std::vector const &Heights) +{ + auto &tool{m_roadtool}; + if (Heights.size() != tool.points.size()) + return; + // the control points are kept relative to the ends, so the slopes the pieces have at a point stay what they are + auto const changes{point_changes(tool.points, [&Heights](road_node::state &State, bool const Atend, std::size_t const Point) { State.axis.points[Atend ? segment_data::point::end : segment_data::point::start].y = Heights[Point]; })}; + // an arm of a junction goes up or down with the end of the road it's made for + std::vector> junctions; + for (std::size_t index = 0; index < tool.points.size(); ++index) + { + for (auto const &arm : editor_road::arms_at(tool.points[index])) + { + auto entry{std::find_if(junctions.begin(), junctions.end(), [&arm](std::pair const &Listed) { return Listed.first == arm.first; })}; + if (entry == junctions.end()) + { + junctions.emplace_back(arm.first, arm.first->definition()); + entry = std::prev(junctions.end()); + } + entry->second.arms[arm.second].position.y = Heights[index]; + } + } + if (false == road_points_apply(changes, junctions)) + return; + // the selection follows what it's made of + for (std::size_t index = 0; index < tool.points.size(); ++index) + tool.points[index].y = Heights[index]; +} + +void editor_mode::push_road_snapshot(editor_road::record Record) +{ + if (Record.empty()) + return; + + if (m_max_history_size >= 0 && (int)m_history.size() >= m_max_history_size) + m_history.erase(m_history.begin(), m_history.begin() + ((int)m_history.size() - m_max_history_size + 1)); + + // the entry is listed under the name of the first thing it's about + scene::basic_node const *node{nullptr}; + if (false == Record.roads.empty()) + node = Record.roads.front().first; + else if (false == Record.roads_created.empty()) + node = Record.roads_created.front(); + else if (false == Record.roads_removed.empty()) + node = Record.roads_removed.front(); + else if (false == Record.junctions.empty()) + node = Record.junctions.front().first; + else if (false == Record.junctions_created.empty()) + node = Record.junctions_created.front(); + else if (false == Record.junctions_removed.empty()) + node = Record.junctions_removed.front(); + else if (false == Record.points.empty()) + node = Record.points.front().first; + else if (false == Record.points_created.empty()) + node = Record.points_created.front(); + else + node = Record.points_removed.front(); + EditorSnapshot snap; + snap.action = EditorSnapshot::Action::RoadEdit; + snap.node_name = node->name(); + snap.position = node->location(); + snap.roads = std::move(Record); + m_history.push_back(std::move(snap)); + g_redo.clear(); +} + +void editor_mode::restore_road_snapshot(EditorSnapshot const &Snapshot, std::vector &Opposite, bool const Undo) +{ + auto const &record{Snapshot.roads}; + if (record.empty()) + return; + + // what the roads are like now is what the opposite operation brings back + EditorSnapshot current{Snapshot}; + for (auto &entry : current.roads.roads) + entry.second = entry.first->definition(); + for (auto &entry : current.roads.junctions) + entry.second = entry.first->definition(); + for (auto &entry : current.roads.points) + entry.second = entry.first->definition(); + Opposite.push_back(std::move(current)); + + // things are taken out before the rest is changed and put in after it, so nothing gets joined with what's on its way out + if (Undo) + { + editor_road::remove(record.roads_created); + editor_road::remove(record.junctions_created); + editor_road::remove(record.points_created); + } + else + { + editor_road::remove(record.roads_removed); + editor_road::remove(record.junctions_removed); + editor_road::remove(record.points_removed); + } + editor_road::apply(record.roads); + editor_road::apply(record.junctions); + editor_road::apply(record.points); + if (Undo) + { + editor_road::revive(record.roads_removed); + editor_road::revive(record.junctions_removed); + editor_road::revive(record.points_removed); + } + else + { + editor_road::revive(record.roads_created); + editor_road::revive(record.junctions_created); + editor_road::revive(record.points_created); + } + + auto &tool{m_roadtool}; + road_cancel(); + if (tool.selected != nullptr) + road_select(tool.selected->m_editorremoved ? nullptr : tool.selected); + if (tool.junction != nullptr) + junction_select(tool.junction->m_editorremoved ? nullptr : tool.junction); + if (tool.marker != nullptr && tool.marker->m_editorremoved) + tool.marker = nullptr; + tool.aimedkind = -1; +} + +// a field of the material of a part of a road or of a junction. returns: true if the material was changed +bool editor_mode::render_road_material(char const *Label, std::string &Value) +{ + ImGui::PushID(Label); + auto const picked{texture_field(STR_C(Label), 200.0f, Value, {STR_C("On the roads of this scenery:"), [this]() { return road_textures_used(); }, STR_C("No texture"), "none"})}; + ImGui::PopID(); + if (picked) + Value = lower_case(Value); + return picked; +} + +std::vector editor_mode::road_textures_used() const +{ + std::map counted; + auto const count = [&](std::set const &Names) { + for (auto const &name : Names) + if (false == name.empty() && name != "none") + ++counted[name]; + }; + for (auto const *road : simulation::Roads.sequence()) + if (road != nullptr && false == road->m_editorremoved) + { + auto const &state{road->definition()}; + count({state.surface, state.sides[0].material, state.sides[1].material, state.kerbmaterial, state.bankmaterial, state.median.material}); + } + for (auto const *junction : simulation::Junctions.sequence()) + if (junction != nullptr && false == junction->m_editorremoved) + { + auto const &state{junction->definition()}; + count({state.surface, state.side.material, state.kerbmaterial, state.bankmaterial, state.medianmaterial}); + } + std::vector list; + for (auto const &[name, number] : counted) + list.push_back({null_handle, name, number, format(STR_P("On %d road or junction", "On %d roads or junctions", static_cast(number)), number)}); + std::stable_sort(list.begin(), list.end(), [](auto const &Left, auto const &Right) { return Left.count > Right.count; }); + return list; +} + +// draws controls for the layout of a road. returns: true if the layout was changed in a way which calls for the road to be made anew +bool editor_mode::render_road_layout(road_node::state &State) +{ + auto &tool{m_roadtool}; + bool changed{false}; + // typed values are taken when confirmed, so the road isn't made anew with each digit + auto const number = [](char const *Label, float &Value, float const Step, char const *Format) { + ImGui::SetNextItemWidth(120.0f); + return ImGui::InputFloat(Label, &Value, Step, Step * 4.0f, Format, ImGuiInputTextFlags_EnterReturnsTrue); + }; + + // lanes. a piece of a road which is there already can end with other lanes than it starts with + { + auto const selecting{tool.tool == 0 && tool.selected != nullptr}; + int counts[2][2]{{State.lanes_at(0, true), State.lanes_at(0, false)}, {State.lanes_at(1, true), State.lanes_at(1, false)}}; + bool relaned{false}; + ImGui::SetNextItemWidth(120.0f); + if (ImGui::InputInt(selecting && tool.varied ? STR_C("Lanes along the axis, at the start") : STR_C("Lanes along the axis"), &counts[0][0])) + relaned = true; + item_tooltip("Lanes going the way the road was built, from its start to its end; drawn green with Show lanes"); + ImGui::SetNextItemWidth(120.0f); + if (ImGui::InputInt(selecting && tool.varied ? STR_C("Lanes against the axis, at the start") : STR_C("Lanes against the axis"), &counts[0][1])) + relaned = true; + item_tooltip("Lanes going back, from the end of the road to its start; drawn orange with Show lanes"); + if (selecting) + { + // ticked it only shows the lanes of the end to be set; unticked it gives the end the lanes of the start + if (ImGui::Checkbox(STR_C("Other lanes at the end of the piece"), &tool.varied) && false == tool.varied && State.changing()) + relaned = true; + item_tooltip("The road gains or loses lanes along this piece: it gets wider or narrower, a lane it gains branches off the outermost lane\n" + "of its direction (two at most), a lane it loses joins the outermost one left.\n" + "What's next to the piece is fitted to the lanes the piece has at that end.\n" + "The axis goes the way the lanes drawn in green do: the start of the piece is where these come from.\n" + "Split the piece (K) first to have the lanes change over a part of it"); + if (tool.varied) + { + ImGui::SetNextItemWidth(120.0f); + if (ImGui::InputInt(STR_C("Lanes along the axis, at the end"), &counts[1][0])) + relaned = true; + ImGui::SetNextItemWidth(120.0f); + if (ImGui::InputInt(STR_C("Lanes against the axis, at the end"), &counts[1][1])) + relaned = true; + } + } + // the traffic going along the axis gets on the piece at its start, the one going against it at its end + if (State.lanes_at(1, true) - State.lanes_at(0, true) > 2 || State.lanes_at(0, false) - State.lanes_at(1, false) > 2) + ImGui::TextColored(ImVec4(1.0f, 0.5f, 0.3f, 1.0f), "%s", STR_C("A lane forks into three at most: lanes past the second one gained can't be got on")); + if (relaned) + { + if (false == selecting || false == tool.varied) + { + counts[1][0] = counts[0][0]; + counts[1][1] = counts[0][1]; + } + // a different set of lanes starts with the common width and speed limit, and the default rules for changing lanes + State.lanes_between(counts[0][0], counts[0][1], counts[1][0], counts[1][1]); + changed = true; + } + } + if (number(STR_C("Lane width [m]"), State.lanewidth, 0.25f, "%.2f")) + { + State.lanewidth = std::clamp(State.lanewidth, 1.0f, 10.0f); + for (auto &lane : State.lanes) + lane.width = State.lanewidth; + changed = true; + } + float limit{State.velocity > 0.0f ? State.velocity : 0.0f}; + if (number(STR_C("Speed limit [km/h]"), limit, 10.0f, "%.0f")) + { + State.velocity = (limit > 0.0f ? limit : -1.0f); + for (auto &lane : State.lanes) + lane.velocity = State.velocity; + changed = true; + } + item_tooltip("0: no limit"); + + // appearance + ImGui::Separator(); + char const *colours[]{STR_C("no markings"), STR_C("white"), STR_C("orange")}; + int colour{State.markings == road_node::marking_colour::white ? 1 : State.markings == road_node::marking_colour::orange ? 2 : 0}; + ImGui::SetNextItemWidth(120.0f); + if (ImGui::Combo(STR_C("Markings"), &colour, colours, 3)) + { + State.markings = (colour == 1 ? road_node::marking_colour::white : colour == 2 ? road_node::marking_colour::orange : road_node::marking_colour::none); + changed = true; + } + if (render_road_material("Surface", State.surface)) + changed = true; + char const *sidenames[]{STR_C("Left side"), STR_C("Right side")}; + char const *sidetypes[]{STR_C("no side"), STR_C("shoulder"), STR_C("sidewalk")}; + for (int side = 0; side < 2; ++side) + { + ImGui::PushID(side); + auto &data{State.sides[side]}; + int type{data.type == road_node::side_type::shoulder ? 1 : data.type == road_node::side_type::sidewalk ? 2 : 0}; + ImGui::SetNextItemWidth(120.0f); + if (ImGui::Combo(sidenames[side], &type, sidetypes, 3)) + { + data.type = (type == 1 ? road_node::side_type::shoulder : type == 2 ? road_node::side_type::sidewalk : road_node::side_type::none); + if (data.type != road_node::side_type::none && data.width <= 0.0f) + data.width = 1.5f; + changed = true; + } + if (data.type != road_node::side_type::none) + { + ImGui::Indent(); + if (number(STR_C("Width [m]"), data.width, 0.25f, "%.2f")) + { + data.width = std::clamp(data.width, 0.1f, 20.0f); + changed = true; + } + if (render_road_material("Material", data.material)) + changed = true; + if (data.material.empty() || data.material == "none") + ImGui::TextDisabled("%s", STR_C("Pick a material to have the side drawn")); + ImGui::Unindent(); + } + ImGui::PopID(); + } + // kerbs + if (ImGui::Checkbox(STR_C("Kerb on the left"), &State.kerbs[0])) + changed = true; + ImGui::SameLine(); + if (ImGui::Checkbox(STR_C("on the right##kerb"), &State.kerbs[1])) + changed = true; + auto const island{State.divided() && State.median.type == road_node::median_type::island}; + if (State.kerbs[0] || State.kerbs[1] || island) + { + ImGui::Indent(); + if (render_road_material("Kerb material", State.kerbmaterial)) + changed = true; + if ((State.kerbs[0] || State.kerbs[1]) && (State.kerbmaterial.empty() || State.kerbmaterial == "none")) + ImGui::TextDisabled("%s", STR_C("Pick a material to have the kerbs drawn")); + ImGui::Unindent(); + } + if (State.sides[0].type == road_node::side_type::shoulder || State.sides[1].type == road_node::side_type::shoulder) + { + if (number(STR_C("Bank width [m]"), State.slope.x, 0.25f, "%.2f")) + { + State.slope.x = std::clamp(State.slope.x, 0.0f, 20.0f); + changed = true; + } + item_tooltip("The bank every shoulder of the road is closed with, unless the side has a bank of its own set below"); + if (number(STR_C("Bank height [m]"), State.slope.y, 0.1f, "%.2f")) + { + State.slope.y = std::clamp(State.slope.y, 0.0f, 20.0f); + changed = true; + } + } + + // banks leading to the ground + if (ImGui::CollapsingHeader(STR_C("Banks to the ground##banks"))) + { + ImGui::TextDisabled("%s", STR_C("A slope from the edge of the road to the ground")); + item_tooltip("It goes down, or up, to the ground. Set here it goes to every piece the changes go to;\nthe button below works out each piece on its own"); + char const *banknames[]{STR_C("Bank on the left"), STR_C("Bank on the right")}; + for (int side = 0; side < 2; ++side) + { + ImGui::PushID(100 + side); + auto &bank{State.banks[side]}; + if (ImGui::Checkbox(banknames[side], &bank.set)) + { + if (bank.set && bank.width[0] <= 0.f && bank.width[1] <= 0.f) + { + bank.width = {State.slope.x, State.slope.x}; + bank.drop = {State.slope.y, State.slope.y}; + } + changed = true; + } + if (bank.set) + { + ImGui::Indent(); + if (number(STR_C("Width at the start [m]"), bank.width[0], 0.5f, "%.2f")) + changed = true; + if (number(STR_C("Height at the start [m]"), bank.drop[0], 0.25f, "%.2f")) + changed = true; + if (number(STR_C("Width at the end [m]"), bank.width[1], 0.5f, "%.2f")) + changed = true; + if (number(STR_C("Height at the end [m]"), bank.drop[1], 0.25f, "%.2f")) + changed = true; + ImGui::Unindent(); + } + ImGui::PopID(); + } + if (render_road_material("Bank material", State.bankmaterial)) + changed = true; + item_tooltip("What a bank is covered with next to a sidewalk, a kerb or the bare edge of the road.\nA bank of a shoulder is covered with the material of the shoulder"); + if (tool.selected != nullptr) + { + ImGui::SetNextItemWidth(120.0f); + if (ImGui::InputFloat(STR_C("Bank slope 1:n"), &tool.bankgrade, 0.25f, 0.5f, "%.2f")) + tool.bankgrade = std::clamp(tool.bankgrade, 0.25f, 10.0f); + item_tooltip("n: metres across for a metre of height; 1.5 is a usual embankment"); + if (ImGui::Button(STR_C("Lead the banks to the ground"))) + { + road_bank_to_ground(); + // the layout shown was replaced with what the road is like now + return false; + } + item_tooltip("Looks for the ground on both sides of the road, at the start and at the end of each piece,\n" + "and sets the banks to reach it with the slope given above: down where the road is over the ground, up where it's cut into it.\n" + "Done for the selected piece, or for every piece of the road if the changes go to the whole road"); + } + } + + // the two directions kept apart + if (State.forward > 0 && State.backward > 0 && ImGui::CollapsingHeader(STR_C("Between the directions##median"))) + { + char const *mediantypes[]{STR_C("nothing, the ground shows"), STR_C("surface closed to the traffic"), STR_C("island")}; + int type{State.median.type == road_node::median_type::gap ? 0 : State.median.type == road_node::median_type::island ? 2 : 1}; + ImGui::SetNextItemWidth(220.0f); + if (ImGui::Combo("##median", &type, mediantypes, 3)) + { + State.median.type = (type == 0 ? road_node::median_type::gap : type == 2 ? road_node::median_type::island : road_node::median_type::painted); + changed = true; + } + char const *apart{"How far apart the two directions are led at each end of the piece; 0 at one end and more at the other makes them part along it.\n" + "Set for each piece on its own. The pieces next to it follow it where they meet, and so do the junctions.\n" + "A road with its directions apart can be carried on as two one-way roads: start the Build tool\n" + "on the middle of one of its roadways, at an end of the road with nothing attached"}; + if (number(STR_C("Apart at the start [m]"), State.median.width[0], 0.5f, "%.2f")) + changed = true; + item_tooltip(apart); + if (number(STR_C("Apart at the end [m]"), State.median.width[1], 0.5f, "%.2f")) + changed = true; + item_tooltip(apart); + if (State.median.type == road_node::median_type::island) + { + if (render_road_material("Island material", State.median.material)) + changed = true; + item_tooltip("The island is as high as the kerbs; with a kerb material set it gets kerbs of its own"); + char const *rounded{"Length of the rounded end of the island at that end of the piece; half of the width of the island makes it a half circle.\n" + "0: the island is cut straight, with a face. Use it where the next piece has no island"}; + if (number(STR_C("Rounded at the start [m]"), State.median.round[0], 0.5f, "%.2f")) + changed = true; + item_tooltip(rounded); + if (number(STR_C("Rounded at the end [m]"), State.median.round[1], 0.5f, "%.2f")) + changed = true; + item_tooltip(rounded); + } + } + + ImGui::PushID("layout"); + if (ImGui::TreeNode(STR_C("More settings"))) + { + if (number(STR_C("Texture length [m]"), State.texturelength, 0.5f, "%.2f")) + { + State.texturelength = std::max(0.1f, State.texturelength); + changed = true; + } + item_tooltip("How many metres of the surface one copy of the texture covers"); + if (State.kerbs[0] || State.kerbs[1] || island) + { + if (number(STR_C("Kerb width [m]"), State.kerbwidth, 0.05f, "%.2f")) + { + State.kerbwidth = std::clamp(State.kerbwidth, 0.05f, 2.0f); + changed = true; + } + } + if (State.kerbs[0] || State.kerbs[1] || island || State.sides[0].type == road_node::side_type::sidewalk || State.sides[1].type == road_node::side_type::sidewalk) + { + if (number(STR_C("Kerb height [m]"), State.kerbheight, 0.01f, "%.2f")) + { + State.kerbheight = std::clamp(State.kerbheight, 0.0f, 1.0f); + changed = true; + } + } + // traffic + if (number(STR_C("Traffic share"), State.weight, 10.0f, "%.0f")) + { + State.weight = std::clamp(State.weight, 0.0f, 10000.0f); + changed = true; + } + item_tooltip("How willing the drivers are to take this road when they leave a junction, next to the other roads they can take there.\n" + "100: like any other. With 100 for the main road and 20 for a dirt road leaving it, one vehicle in six turns into the dirt road.\n" + "0: nobody takes it, unless there's no other way"); + if (ImGui::Checkbox(STR_C("Part of a roundabout"), &State.roundabout)) + changed = true; + item_tooltip("A junction made on this road gives the right of way to the traffic going along it,\nand tells the traffic of the road joining it to give way"); + ImGui::TreePop(); + } + ImGui::PopID(); + + // single lanes, and the rules for changing between them + if (ImGui::CollapsingHeader(STR_C("Lanes and lane changes##lanes"))) + { + ImGui::TextDisabled("%s", STR_C("Left to right, facing along the axis")); + item_tooltip("f: a lane along the axis, b: against it"); + for (std::size_t lane = 0; lane < State.lanes.size(); ++lane) + { + ImGui::PushID(static_cast(lane)); + auto &data{State.lanes[lane]}; + auto const id{State.lane_id(lane)}; + ImGui::TextColored(lane >= static_cast(State.backward) ? ImVec4(0.3f, 0.9f, 0.45f, 1.0f) : ImVec4(1.0f, 0.67f, 0.2f, 1.0f), "%-3s", id.c_str()); + ImGui::SameLine(); + if (number("m##width", data.width, 0.25f, "%.2f")) + { + data.width = std::clamp(data.width, 1.0f, 10.0f); + changed = true; + } + item_tooltip("Width of the lane"); + ImGui::SameLine(); + float lanelimit{data.velocity > 0.0f ? data.velocity : 0.0f}; + if (number("km/h##velocity", lanelimit, 10.0f, "%.0f")) + { + data.velocity = (lanelimit > 0.0f ? lanelimit : -1.0f); + changed = true; + } + item_tooltip("Speed limit of the lane, 0: no limit"); + if (lane + 1 < State.lanes.size() && lane < State.changes.size()) + { + // the entries are in the order of the stored values: none, to the right, to the left, both + auto const next{State.lane_id(lane + 1)}; + auto const toright{format(STR_C("only %s to %s"), id.c_str(), next.c_str())}; + auto const toleft{format(STR_C("only %s to %s"), next.c_str(), id.c_str())}; + char const *modes[]{STR_C("no lane change"), toright.c_str(), toleft.c_str(), STR_C("lane change both ways")}; + ImGui::Indent(); + ImGui::SetNextItemWidth(200.0f); + if (ImGui::Combo("##change", &State.changes[lane], modes, 4)) + changed = true; + item_tooltip("Which way a vehicle may change between these two lanes"); + ImGui::Unindent(); + } + ImGui::PopID(); + } + } + return changed; +} + +void editor_mode::road_choose_tool(int const Tool) +{ + auto &tool{m_roadtool}; + if (Tool == tool.tool) + return; + tool.tool = Tool; + road_cancel(); + if (tool.tool != 0) + { + tool.junction = nullptr; + tool.points.clear(); + tool.marker = nullptr; + // the fields for the names of materials show the layout for the roads to be built again + road_select(nullptr); + } +} + +// the road tools and what the next pieces get, in the tool options window; the selection is drawn in the inspector by render_road_selection() +void editor_mode::render_road_tool_options() +{ + auto &tool{m_roadtool}; + std::string reason; + if (false == editor_road::available(&reason)) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "%s", STR(reason).c_str()); + + // the tools and what the place tool puts are chosen in the toolbar + + if (tool.tool == 1) + { + if (ImGui::Checkbox(STR_C("Roundabout"), &tool.ring)) + road_cancel(); + item_tooltip("A one-way road going around, with the lanes set below as the lanes along the axis.\nThen untick this and lead the roads out of its side, or into it"); + if (tool.ring) + { + gesture_rows({{"LMB", "a roundabout around the cursor"}}); + ImGui::SetNextItemWidth(120.0f); + if (ImGui::InputFloat(STR_C("Radius [m]##ring"), &tool.ringradius, 1.0f, 5.0f, "%.1f")) + tool.ringradius = std::clamp(tool.ringradius, 8.0f, 200.0f); + item_tooltip("Radius of the middle of the road going around"); + render_road_material("Island in the middle", tool.island); + item_tooltip("What the middle is covered with; it's raised on a kerb as high as the kerbs of the road.\nNo texture: the middle is left as it is"); + } + else + { + gesture_rows({{"LMB", "the start, then each next point"}, + {"Ctrl", "straight ahead"}, + {"Esc", "finish the road"}, + {"LMB on a road or a junction", "the new road is joined to it there"}}); + } + if (tool.chain) + { + if (ImGui::Button(STR_C("Finish (Esc)"))) + road_cancel(); + } + // how the road is put on the ground + ImGui::Checkbox(STR_C("Follow the ground"), &tool.follow); + item_tooltip("On: the road is led over the ground between the clicked points, in pieces as short as the ground calls for,\nwith the profile rounded so the slope doesn't change abruptly.\nOff: the road goes straight from a point to the next one, like a ramp or a viaduct"); + ImGui::PushID("build"); + if (ImGui::TreeNode(STR_C("More settings"))) + { + ImGui::SetNextItemWidth(120.0f); + if (ImGui::InputFloat(STR_C("Height above the ground [m]"), &tool.offset, 0.05f, 0.25f, "%.2f")) + tool.offset = std::clamp(tool.offset, -10.0f, 100.0f); + item_tooltip("How far over the ground under the cursor the points are put.\nA few centimetres keep the surface from flickering where it lies on the ground"); + ImGui::SetNextItemWidth(120.0f); + if (ImGui::InputFloat(STR_C("Junction speed limit [km/h]"), &tool.crossingspeed, 5.0f, 10.0f, "%.0f")) + tool.crossingspeed = std::clamp(tool.crossingspeed, 5.0f, 200.0f); + item_tooltip("The speed limit the junctions made by the new roads get"); + ImGui::TreePop(); + } + ImGui::PopID(); + ImGui::Separator(); + // what's set here is what the next pieces get + render_road_layout(tool.settings); + } + else if (tool.tool == 2) + { + tool.placekind = std::clamp(tool.placekind, 0, 3); + switch (tool.placekind) + { + case 0: gesture_rows({{"LMB on a road", "where the rails cross it; the vehicles stop ahead of the rails while a train is coming"}}); break; + case 1: gesture_rows({{"LMB on a lane", "the vehicles of the set appear there one by one and drive the way the lane goes"}}); break; + case 3: gesture_rows({{"LMB on a road", "stripes are painted across it there"}}); break; + default: gesture_rows({{"LMB on a lane", "the vehicles getting there are taken off the road; put one where the road leaves the scenery"}}); break; + } + ImGui::Separator(); + // what's set here is what the next points get + auto &placing{tool.placing[tool.placekind]}; + placing.kind = point_kind(tool.placekind); + render_roadpoint_layout(placing, nullptr); + } + else + ImGui::TextDisabled("%s", STR_C("The selected road is set up in the inspector")); + if (false == tool.status.empty()) + { + ImGui::Separator(); + ImGui::TextWrapped("%s", tool.status.c_str()); + } +} + +// what the select tool of the roads picked, in the inspector +void editor_mode::render_road_selection() +{ + auto &tool{m_roadtool}; + // typed values are taken when confirmed, so nothing is made anew with each digit + auto const number = [](char const *Label, float &Value, float const Step, char const *Format) { + ImGui::SetNextItemWidth(120.0f); + return ImGui::InputFloat(Label, &Value, Step, Step * 4.0f, Format, ImGuiInputTextFlags_EnterReturnsTrue); + }; + if (tool.tool != 0) + ImGui::TextDisabled("%s", STR_C("The Select tool shows the road picked in the view here")); + else if (tool.marker != nullptr) + { + auto &point{*tool.marker}; + auto state{point.definition()}; + ImGui::Text("%s, %s", point.name().c_str(), point_label(state.kind)); + if (render_roadpoint_layout(state, &point)) + roadpoint_apply(point, state); + if (ImGui::Button(STR_C("Delete (Del)"))) + road_delete(); + } + else if (false == tool.points.empty()) + { + // the road at the selected points + ImGui::Text(STR_C("Points selected: %d"), static_cast(tool.points.size())); + gesture_rows({{"Shift+LMB", "adds a point, or takes it out"}, {"K", "on a selected piece: a point at the cursor"}}); + auto const ends{editor_road::ends_at(tool.points.front())}; + if (false == ends.empty()) + { + auto const &layout{ends.front().road->definition()}; + auto width{static_cast(layout.width(ends.front().atend ? 1 : 0) * layout.taper[ends.front().atend ? 1 : 0])}; + if (number(STR_C("Road width here [m]"), width, 0.25f, "%.2f")) + road_point_width(std::clamp(width, 1.0f, 100.0f)); + item_tooltip("Combined width of the lanes at this point; each lane takes its share of it.\nThe pieces on both sides get wider or narrower along their length to meet it.\nSelect several points to keep the width over the pieces between them"); + // heights: set outright, moved by a step, or taken from the ground + auto height{static_cast(tool.points.front().y)}; + if (number(STR_C("Height [m]"), height, 0.1f, "%.2f")) + road_point_heights(std::vector(tool.points.size(), height)); + item_tooltip("Height of the axis of the road at the point; with several points selected all are put at this height.\nThe slopes of the pieces at the point are kept, so the road stays smooth"); + std::vector heights; + for (auto const &point : tool.points) + heights.emplace_back(point.y); + auto const moved{ImGui::Button(STR_C("Lower")) ? -1.0 : 0.0}; + ImGui::SameLine(); + auto const raised{ImGui::Button(STR_C("Raise")) ? 1.0 : 0.0}; + ImGui::SameLine(); + ImGui::SetNextItemWidth(80.0f); + if (ImGui::InputFloat(STR_C("by [m]##heightstep"), &tool.heightstep, 0.0f, 0.0f, "%.2f")) + tool.heightstep = std::clamp(tool.heightstep, 0.01f, 50.0f); + if (moved + raised != 0.0) + { + // each point moves from where it is, so the shape of the road between them is kept + for (auto &entry : heights) + entry += (moved + raised) * tool.heightstep; + road_point_heights(heights); + } + if (ImGui::Button(STR_C("Put on the ground"))) + { + // a point with nothing under it comes back with the height it has, and is left where it is + auto const ground{ground_heights(tool.points, true)}; + for (std::size_t index = 0; index < heights.size(); ++index) + if (ground[index] != tool.points[index].y) + heights[index] = ground[index] + tool.offset; + road_point_heights(heights); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip(STR_C("Puts each point %.2f m over the ground under it; the height above the ground is set in the Build tool"), tool.offset); + } + if (ImGui::Button(tool.points.size() == 1 ? STR_C("Delete the point (Del)") : STR_C("Delete the points (Del)"))) + road_points_delete(); + item_tooltip("Takes the point out of the road: the pieces on its two sides become one piece,\n" + "led from the far end of one to the far end of the other the way the road goes there.\n" + "A point the road ends at takes the last piece of the road with it"); + } + else if (tool.junction != nullptr) + { + auto &junction{*tool.junction}; + if (junction.definition().arms.size() == 2) + { + ImGui::Text(STR_C("%s, a stretch where the road changes its lanes"), junction.name().c_str()); + ImGui::TextDisabled("%s", STR_C("A part of the road, leading the lanes of one side to the other")); + } + else + { + ImGui::Text(STR_C("%s, roads: %d, ways through: %d"), junction.name().c_str(), static_cast(junction.definition().arms.size()), static_cast(junction.movements().size())); + ImGui::TextDisabled("%s", STR_C("The ways through follow the roads attached now")); + item_tooltip("Build tool, LMB on the junction: lead another road out of it"); + } + render_junction_layout(junction); + if (ImGui::Button(STR_C("Delete (Del)"))) + road_delete(); + } + else if (tool.selected != nullptr) + { + auto const &road{*tool.selected}; + auto const &layout{road.definition()}; + if (layout.changing()) + ImGui::Text(STR_C("%s, %.1f m, lanes %d + %d to %d + %d"), road.name().c_str(), layout.length(), layout.lanes_at(0, true), layout.lanes_at(0, false), layout.lanes_at(1, true), + layout.lanes_at(1, false)); + else + ImGui::Text(STR_C("%s, %.1f m, lanes %d + %d"), road.name().c_str(), layout.length(), layout.forward, layout.backward); + if (ImGui::Button(STR_C("Delete (Del)"))) + road_delete(); + ImGui::SameLine(); + ImGui::TextDisabled("%s", STR_C("K: split at the cursor")); + if (tool.settings.changing()) + ImGui::TextDisabled("%s", STR_C("This piece has lanes of its own at its end, so it's changed alone")); + else + ImGui::Checkbox(STR_C("Changes go to the whole road"), &tool.whole); + item_tooltip("A road is a string of pieces. With this on a change of the layout is made to all of them,\nexcept for the lane change rules, which are always set for the selected piece alone.\nWith this off the selected piece alone is changed, and the road next to it is fitted to it:\nmade wider or narrower towards it, or given a stretch where the lanes change if their number differs.\nSplit a piece (K) to get a piece of the length you need"); + ImGui::Separator(); + if (tool.selected != nullptr && render_road_layout(tool.settings)) + road_apply(); + } + else + { + gesture_rows({{"LMB", "a road piece, a junction, a point where pieces meet, a level crossing or a traffic point"}}); + } +} + +void editor_mode::draw_road_overlay() const +{ + auto const &tool{m_roadtool}; + if (false == tool.lanes && false == tool.window) + return; + + screen_projection projection; + ImDrawList *drawlist = ImGui::GetBackgroundDrawList(ImGui::GetMainViewport()); + glm::dvec3 const camera{Global.pCamera.Pos}; + // pieces of a line needed to draw a path: one for a straight, more the longer a bend is and the nearer it is + auto const pieces = [&camera](segment_data const &Path, glm::dvec3 const &Location) { + auto const range{glm::distance(Location, camera)}; + auto const length{glm::distance(Path.points[segment_data::point::start], Path.points[segment_data::point::end])}; + return std::clamp(static_cast(length / (range < 100.0 ? 3.0 : range < 300.0 ? 8.0 : 20.0)), 2, 12); + }; + auto const drawpath = [&](segment_data const &Path, ImU32 const Color, float const Thickness, int const Samples) { + auto previous{path_point(Path, 0.0)}; + for (int i = 1; i <= Samples; ++i) + { + auto const next{path_point(Path, static_cast(i) / Samples)}; + projection.line(drawlist, previous, next, Color, Thickness); + previous = next; + } + }; + + // lanes, as the vehicles see them: a line for each, with an arrow pointing where the traffic goes + if (tool.lanes) + { + projection.limit = screen_projection::kLaneVertexLimit; + for (auto const *road : simulation::Roads.sequence()) + { + if (road == nullptr || road->m_editorremoved) + continue; + auto const range{glm::distance(road->location(), camera)}; + if (range > kLaneRange + 0.5 * glm::distance(road->definition().axis.points[segment_data::point::start], road->definition().axis.points[segment_data::point::end])) + continue; + if (false == projection.room(drawlist)) + break; + auto const against{static_cast(road->definition().backward)}; + // a lane of a piece which gains or loses lanes is a path at each end of the piece; the ways between these are drawn below + auto const lanecount{road->definition().lanes.size()}; + for (std::size_t slot = 0; slot < 2 * lanecount; ++slot) + { + auto const lane{slot / 2}; + auto const *track{road->lane_track(lane, static_cast(slot % 2))}; + if (track == nullptr || track->m_paths.empty() || (slot % 2 == 1 && track == road->lane_track(lane, 0))) + continue; + auto const &path{track->m_paths.front()}; + auto const color{lane >= against ? kForwardColor : kBackwardColor}; + drawpath(path, color, 2.0f, is_curved(path) ? pieces(path, road->location()) : 1); + if (range > 300.0 || road->definition().changing()) + continue; + auto const middle{path_point(path, 0.5)}; + auto direction{path_point(path, 0.52) - middle}; + if (glm::length(direction) < 1e-6) + continue; + direction = glm::normalize(direction); + glm::dvec3 const across{direction.z, 0.0, -direction.x}; + auto const tip{middle + direction * 1.2}; + projection.line(drawlist, tip, middle - direction * 0.6 + across * 0.6, color, 2.0f); + projection.line(drawlist, tip, middle - direction * 0.6 - across * 0.6, color, 2.0f); + } + for (auto const *turn : road->turns()) + { + if (turn != nullptr && false == turn->m_paths.empty() && range < 300.0) + drawpath(turn->m_paths.front(), kTurnColor, 1.5f, 8); + } + // ways from the lanes at one end to the lanes at the other + for (auto const &way : road->ways()) + drawpath(way, kWayColor, 1.5f, pieces(way, road->location())); + } + // ways through the junctions + for (auto const *junction : simulation::Junctions.sequence()) + { + if (junction == nullptr || junction->m_editorremoved || glm::distance(junction->location(), camera) > kLaneRange) + continue; + for (auto const &way : junction->movements()) + drawpath(way, kWayColor, 1.5f, pieces(way, junction->location())); + } + projection.limit = screen_projection::kVertexLimit; + } + if (false == tool.window) + return; + + // outline of a road piece: its axis and the edges of its surface + auto const drawroad = [&](road_node::state const &State, ImU32 const Color) { + auto const samples{is_curved(State.axis) || State.taper[0] != State.taper[1] ? pieces(State.axis, State.axis.points[segment_data::point::start]) : 1}; + drawpath(State.axis, Color, 3.0f, samples); + glm::dvec3 previous[2]; + for (int i = 0; i <= samples; ++i) + { + auto const t{static_cast(i) / samples}; + auto const position{path_point(State.axis, t)}; + auto const tangent{path_direction(State.axis, t)}; + glm::dvec3 across{tangent.z, 0.0, -tangent.x}; + if (glm::length(across) > 1e-6) + across = glm::normalize(across); + auto const halfwidth{0.5 * State.span(t)}; + glm::dvec3 const edges[2]{position + across * halfwidth, position - across * halfwidth}; + if (i > 0) + { + projection.line(drawlist, previous[0], edges[0], Color, 1.5f); + projection.line(drawlist, previous[1], edges[1], Color, 1.5f); + } + previous[0] = edges[0]; + previous[1] = edges[1]; + } + }; + auto const drawpoint = [&](glm::dvec3 const &Point, ImU32 const Color, float const Radius, bool const Filled) { + ImVec2 screen; + if (false == projection.room(drawlist) || false == projection.project(Point, screen) || projection.outside(screen, screen)) + return; + if (Filled) + drawlist->AddCircleFilled(screen, Radius, Color); + else + drawlist->AddCircle(screen, Radius, Color, 20, 3.0f); + }; + + // outline of a junction: the edge of its surface, with the ends of the roads it's made for + auto const drawjunction = [&](junction_node::state const &State, ImU32 const Color) { + auto const outline{State.outline()}; + for (std::size_t i = 0; i < outline.size(); ++i) + projection.line(drawlist, outline[i], outline[(i + 1) % outline.size()], Color, 2.0f); + for (auto const &arm : State.arms) + drawpoint(arm.position, Color, 5.0f, true); + }; + + // a circle lying on the ground + auto const drawring = [&](glm::dvec3 const &Centre, double const Radius, ImU32 const Color) { + int const pieces{24}; + glm::dvec3 previous{Centre + glm::dvec3{Radius, 0.0, 0.0}}; + for (int i = 1; i <= pieces; ++i) + { + auto const angle{kFullTurn * i / pieces}; + glm::dvec3 const next{Centre + glm::dvec3{Radius * std::cos(angle), 0.0, Radius * std::sin(angle)}}; + projection.line(drawlist, previous, next, Color, 2.0f); + previous = next; + } + }; + auto const drawlabel = [&](glm::dvec3 const &Point, ImU32 const Color, char const *Text) { + ImVec2 screen; + if (false == projection.room(drawlist) || false == projection.project(Point, screen) || projection.outside(screen, screen)) + return; + drawlist->AddText(ImVec2(screen.x + 14.0f, screen.y - 8.0f), Color, Text); + }; + // a level crossing or a traffic point. Point: the node it's drawn for, nullptr for one which isn't made yet + auto const drawmarker = [&](roadpoint_node::state const &State, roadpoint_node const *Point, ImU32 const Color) { + drawpoint(State.position, Color, 6.0f, true); + auto const labelled{glm::distance(State.position, camera) < 200.0}; + switch (State.kind) + { + case roadpoint_node::kind_type::crossing: + { + // the tracks within the circle are the ones it's closed for, the lines are where the vehicles stop + drawring(State.position, State.clearance, Color); + auto const closed{Point != nullptr && Point->closed()}; + if (Point != nullptr) + { + for (auto const &stop : Point->stops()) + { + glm::dvec3 across{stop.direction.z, 0.0, -stop.direction.x}; + if (glm::length(across) < 1e-6) + continue; + across = glm::normalize(across) * (0.5 * stop.width); + projection.line(drawlist, stop.position - across, stop.position + across, closed ? kRefusedColor : Color, 4.0f); + } + } + if (labelled) + drawlabel(State.position, Color, closed ? STR_C("crossing, closed") : STR_C("crossing")); + break; + } + case roadpoint_node::kind_type::spawn: + { + drawpoint(State.position, Color, 11.0f, false); + if (labelled) + drawlabel(State.position, Color, STR_C("spawn")); + break; + } + case roadpoint_node::kind_type::despawn: + { + drawring(State.position, State.radius, Color); + if (labelled) + drawlabel(State.position, Color, STR_C("removal")); + break; + } + case roadpoint_node::kind_type::crosswalk: + { + drawpoint(State.position, Color, 11.0f, false); + if (labelled) + drawlabel(State.position, Color, STR_C("pedestrians")); + break; + } + } + }; + for (auto const *point : simulation::Roadpoints.sequence()) + { + if (point == nullptr || point->m_editorremoved || glm::distance(point->location(), camera) > kPointRange) + continue; + auto const kind{point->definition().kind}; + drawmarker(point->definition(), point, + point == tool.marker ? kSelectedColor : + kind == roadpoint_node::kind_type::spawn ? kSpawnColor : + kind == roadpoint_node::kind_type::despawn ? kDespawnColor : + kind == roadpoint_node::kind_type::crosswalk ? kCrosswalkColor : + kCrossingColor); + if (point == tool.marker) + drawpoint(point->definition().position, kSelectedColor, 15.0f, false); + } + + if (tool.selected != nullptr && false == tool.selected->m_editorremoved) + { + auto const &state{tool.selected->definition()}; + drawroad(state, kSelectedColor); + drawpoint(state.axis.points[segment_data::point::start], kSelectedColor, 6.0f, true); + drawpoint(state.axis.points[segment_data::point::end], kSelectedColor, 6.0f, true); + } + if (tool.junction != nullptr && false == tool.junction->m_editorremoved) + { + drawjunction(tool.junction->definition(), kSelectedColor); + // the roads are numbered the way the window lists them + auto const &arms{tool.junction->definition().arms}; + for (std::size_t arm = 0; arm < arms.size(); ++arm) + drawlabel(arms[arm].position, kSelectedColor, std::to_string(arm + 1).c_str()); + } + + std::string hint; + if (tool.tool == 1 && tool.ring) + { + // the road going around, as wide as its lanes + auto layout{tool.settings}; + layout.backward = 0; + layout.forward = std::max(1, layout.forward); + layout.lanes.clear(); + layout.normalize(); + auto const centre{tool.mouse + glm::dvec3{0.0, tool.offset, 0.0}}; + drawring(centre, tool.ringradius + 0.5 * layout.width(), kPreviewColor); + drawring(centre, std::max(0.0, tool.ringradius - 0.5 * layout.width()), kPreviewColor); + hint = STR_C("LMB: put a roundabout here"); + } + else if (tool.tool == 1) + { + if (tool.chain) + { + auto const &plan{tool.plan}; + drawpoint(tool.point, kPreviewColor, 6.0f, true); + if (plan.pieces.empty()) + { + projection.line(drawlist, tool.point, tool.mouse, kRefusedColor, 2.0f); + hint = STR(plan.error) + " "; + } + else + { + // junctions the road would start or end with + if (plan.hasstart) + drawjunction(plan.start.layout, kPreviewColor); + if (plan.hasend) + drawjunction(plan.end.layout, kPreviewColor); + } + for (auto const &piece : plan.pieces) + { + auto state{tool.settings}; + state.axis = piece; + drawroad(state, kPreviewColor); + } + if (plan.snap.valid()) + drawpoint(plan.snap.position, kSnapColor, 14.0f, false); + hint += (tool.branchroad != nullptr ? STR_C("LMB: lead the road out to the cursor, with a junction where it leaves Esc: give up") : + tool.branchjunction != nullptr ? STR_C("LMB: lead the road out to the cursor, as another road of the junction Esc: give up") : + STR_C("LMB: build up to the cursor Ctrl: straight ahead Esc: finish Ctrl+Z: undo the last piece")); + } + else + { + auto const end{editor_road::find_end(tool.mouse, kSnapRadius)}; + if (end.valid()) + { + drawpoint(end.position, kSnapColor, 14.0f, false); + hint = STR_C("LMB: carry on from this end"); + } + else if (tool.hashover) + { + drawpoint(tool.hover, kSnapColor, 5.0f, true); + drawpoint(tool.hover, kSnapColor, 14.0f, false); + hint = STR_C("LMB: lead a road out of here, with a junction"); + } + else + { + hint = STR_C("LMB: set where the road starts; on a loose end of a road to carry it on, on the side of a road or on a junction to lead a road out of it"); + } + } + } + else if (tool.tool == 2) + { + if (tool.hastarget) + { + drawmarker(tool.target, nullptr, kPreviewColor); + if (glm::length(tool.targetdirection) > 1e-6) + { + // the way the traffic goes on the lane + auto const direction{glm::normalize(tool.targetdirection)}; + glm::dvec3 const across{direction.z, 0.0, -direction.x}; + auto const tip{tool.target.position + direction * 5.0}; + projection.line(drawlist, tool.target.position, tip, kPreviewColor, 2.0f); + projection.line(drawlist, tip, tip - direction * 1.2 + across * 0.8, kPreviewColor, 2.0f); + projection.line(drawlist, tip, tip - direction * 1.2 - across * 0.8, kPreviewColor, 2.0f); + } + hint = format(STR_C("LMB: put a %s here"), point_label(tool.target.kind)); + if (false == tool.targetnote.empty()) + hint += " " + tool.targetnote; + } + else + { + hint = (tool.targetnote.empty() ? format(STR_C("LMB: put a %s on a road"), point_label(point_kind(tool.placekind))) : tool.targetnote); + } + } + else + { + // points where the pieces meet or end, to pick from + for (auto const *road : simulation::Roads.sequence()) + { + if (road == nullptr || road->m_editorremoved || glm::distance(road->location(), camera) > kPointRange) + continue; + drawpoint(road->definition().axis.points[segment_data::point::start], kPointColor, 3.5f, true); + drawpoint(road->definition().axis.points[segment_data::point::end], kPointColor, 3.5f, true); + } + for (auto const &point : tool.points) + { + drawpoint(point, kSelectedColor, 6.0f, true); + drawpoint(point, kSelectedColor, 11.0f, false); + } + if (tool.lifting) + { + // where the points go: a line up or down to each, and the change by the cursor + auto const offset{road_lift_offset()}; + ImU32 const lifted{IM_COL32(255, 210, 60, 255)}; + for (auto const &point : tool.points) + { + glm::dvec3 const target{point.x, point.y + offset, point.z}; + projection.line(drawlist, point, target, lifted, 2.0f); + drawpoint(target, lifted, 6.0f, true); + } + auto const mouse{ImGui::GetIO().MousePos}; + char label[64]; + std::snprintf(label, sizeof(label), STR_C("%+.2f m, to %.2f m"), offset, tool.points.empty() ? 0.0 : tool.points.front().y + offset); + drawlist->AddRectFilled(ImVec2(mouse.x + 14.0f, mouse.y - 4.0f), ImVec2(mouse.x + 22.0f + ImGui::CalcTextSize(label).x, mouse.y + 18.0f), IM_COL32(0, 0, 0, 170), 3.0f); + drawlist->AddText(ImVec2(mouse.x + 18.0f, mouse.y - 2.0f), lifted, label); + } + hint = tool.lifting ? STR_C("Drag up or down: the height of the selected points Ctrl: finer let go: set") : + tool.marker != nullptr ? STR_C("LMB: select a piece, a junction, a point or a marker Del: delete Ctrl+Z: undo") : + false == tool.points.empty() ? STR_C("LMB: select a point (under the terrain too) Shift+LMB: add a point or take it out Alt+LMB drag: the height Del: delete the points Ctrl+Z: undo") : + tool.selected != nullptr ? STR_C("LMB: select a piece, a junction or a point (white dot) K: split at the cursor Del: delete Ctrl+Z: undo") : + tool.junction != nullptr ? STR_C("LMB: select a piece, a junction or a point (white dot) Del: delete Ctrl+Z: undo") : + STR_C("LMB: select a piece, a junction, a point (white dot) or a marker"); + } + // shown above the place the track tools put their hints at + ImVec2 const position{editor_ui::view_min().x + 12.0f, editor_ui::view_max().y - 56.0f}; + auto const size{ImGui::CalcTextSize(hint.c_str())}; + drawlist->AddRectFilled(ImVec2(position.x - 6.0f, position.y - 4.0f), ImVec2(position.x + size.x + 6.0f, position.y + size.y + 4.0f), IM_COL32(0, 0, 0, 150), 4.0f); + drawlist->AddText(position, IM_COL32(255, 255, 255, 230), hint.c_str()); +} diff --git a/application/editormoderoute.cpp b/application/editormoderoute.cpp new file mode 100644 index 000000000..dd79147ac --- /dev/null +++ b/application/editormoderoute.cpp @@ -0,0 +1,2423 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http: +*/ + + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editoruilayer.h" +#include "application/editorprojection.h" +#include "application/editormodeshared.h" +#include "application/editorgestures.h" +#include "editor/editorFormat.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorSwitchStore.hpp" +#include "editor/editorGeometry.hpp" +#include "editor/editorIncludeInfo.hpp" + +#include "utilities/Globals.h" +#include "rendering/renderer.h" +#include "world/Track.h" +#include "world/TrackFeatures.h" +#include "scene/scene.h" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" + +#include "imgui/imgui.h" +#include "imgui/ImGuizmo.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "application/editormodetrackshared.h" + +using namespace track_mode; + +bool editor_mode::route_active() const +{ + return ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::route && false == m_route.chain.tracks.empty(); +} + +void editor_mode::route_recommend(alignment::vertex &Vertex) const +{ + auto sharpest{Vertex.radius}; + if (Vertex.compound) + for (auto const &arc : Vertex.arcs) + sharpest = std::min(sharpest, arc.radius); + auto const recommended{alignment::recommend(m_route.design.speed, sharpest, laying_norms())}; + Vertex.cant = recommended.cant; + // the cants of the arcs in proportion to their curvature, as the norms recommend them + Vertex.first_cant = -1.0; + for (auto &arc : Vertex.arcs) + arc.cant = -1.0; + Vertex.transition_in = recommended.transition; + Vertex.transition_out = recommended.transition; + alignment::recommend_between(Vertex, m_route.design.speed, laying_norms()); +} + +void editor_mode::route_bind_ends() +{ + auto const &chain{m_route.chain}; + auto &design{m_route.design}; + design.start = chain.start; + design.end = chain.end; + design.start_direction = glm::normalize(plan_of(chain.start_direction)); + design.end_direction = glm::normalize(plan_of(chain.end_direction)); + design.start_grade = grade_of(chain.start_direction); + design.end_grade = grade_of(chain.end_direction); + design.start_radius = chain.start_radius; + design.end_radius = chain.end_radius; + design.start_turn = chain.start_turn; + design.end_turn = chain.end_turn; + design.start_reserve = editor_track::run_reserve(editor_track::straight_beyond(chain, false, m_straights.tolerance)); + design.end_reserve = editor_track::run_reserve(editor_track::straight_beyond(chain, true, m_straights.tolerance)); +} + +void editor_mode::route_reset() +{ + auto &route{m_route}; + route.chain = {}; + route.error.clear(); + route.status.clear(); + route.vertex = -1; + route.grip = -1; + route.result = {}; + route.trace = {}; + route.clicks.clear(); + route.click_states.clear(); + route.measured = -1; + if (route.from == nullptr || route.to == nullptr) + return; + if (false == editor_track::find_chain(route.from, route.to, route.chain, route.error, true)) + return; + if (false == route.chain.switches.empty()) + route.status = format(STR_C("The fragment runs through %zu switches along their main tracks. They move as a whole with the line, " + "so they have to fall on its straights"), + route.chain.switches.size()); + + auto const &chain{route.chain}; + alignment::design design; + design.norms = route.design.norms; + design.shape = route.design.shape; + design.transition_pieces = route.design.transition_pieces; + design.speed = chain.velocity > 0.0 ? chain.velocity : 100.0; + route.design = design; + route_bind_ends(); + design = route.design; + + glm::dvec2 intersection; + if (false == alignment::collinear(design)) + { + alignment::vertex vertex; + vertex.radius = chain.radius > 0.0 ? std::max(10.0, std::round(chain.radius / 10.0) * 10.0) : 1000.0; + route_recommend(vertex); + if (alignment::tangent_intersection(design, intersection)) + { + route.design.vertices.push_back(vertex); + } + else + { + auto const distance{plan_distance(design.start, design.end)}; + vertex.offset = distance / 3.0; + route.design.vertices.push_back(vertex); + route.design.vertices.push_back(vertex); + } + } + route_update(); +} + +bool editor_mode::route_from_curve(TTrack &Track) +{ + editor_track::curve curve; + if (false == editor_track::find_curve(Track, m_straights.tolerance, m_route.design.norms.gauge, curve)) + { + m_route.chain = {}; + m_route.result = {}; + m_route.vertex = -1; + m_route.grip = -1; + m_route.error = STR_C("No curve here: LMB on a curve"); + return false; + } + m_route.from = curve.from; + m_route.to = curve.to; + route_reset(); + if (m_route.chain.tracks.empty()) + return false; + auto &design{m_route.design}; + auto vertex{route_vertex_of(curve)}; + m_route.designed = curve.designed.has_value() ? 1 : 0; + if (curve.reversals == 0) + { + design.vertices = {vertex}; + route_curved_ends(); + } + else + { + auto const distance{plan_distance(design.start, design.end)}; + vertex.offset = distance / 3.0; + vertex.compound = false; + vertex.reverse_turn = false; + design.vertices = {vertex, vertex}; + route_update(); + } + m_route.status = format(STR_P("Curve of %zu path, turning %d deg", "Curve of %zu paths, turning %d deg", m_route.chain.tracks.size()), m_route.chain.tracks.size(), static_cast(std::round(glm::degrees(curve.turn)))); + return true; +} + +void editor_mode::route_curved_ends() +{ + auto &design{m_route.design}; + design.start_curved = false; + design.end_curved = false; + if (design.vertices.empty() || m_route.chain.tracks.empty()) + { + route_update(); + return; + } + // a curve beginning right at an end of the fragment at the curvature of the track adjoining there, turning its way, goes on from it, + // as a curve laid on from the diverging track of a switch does: laid so again, not from a straight there; so next to a switch laid + // into the curve too. A track of R 10 km or more is a straight there, as the lay tool takes it. The way the first curve and the last + // one turn by the legs of the polygon + auto const count{design.vertices.size()}; + auto const turn_of = [&](bool const Atend) { + if (count == 1) + return cross(design.start_direction, design.end_direction) > 0.0 ? 1 : -1; + glm::dvec2 const in{Atend ? design.vertices[count - 1].position - design.vertices[count - 2].position : design.start_direction}; + glm::dvec2 const out{Atend ? design.end_direction : design.vertices[1].position - design.vertices[0].position}; + return cross(in, out) > 0.0 ? 1 : -1; + }; + auto const goes_on = [&](bool const Atend) { + auto const radius{Atend ? design.end_radius : design.start_radius}; + if (radius <= 0.0 || radius >= 10000.0 || (Atend ? design.end_turn : design.start_turn) != turn_of(Atend)) + return false; + // within a tenth: the path of a switch bent into the curve approximates it at its ends, R 860 m at the start of one in R 800 m + auto const *track{Atend ? m_route.chain.tracks.back() : m_route.chain.tracks.front()}; + auto const bend{editor_track::bend_at(*track, Atend ? m_route.chain.end : m_route.chain.start)}; + return bend.has_value() && std::abs(std::abs(bend->curvature) - 1.0 / radius) <= 0.1 / radius; + }; + design.start_curved = goes_on(false); + design.end_curved = (count > 1 || false == design.start_curved) && goes_on(true); + route_update(); + // a curve read from its paths as going on from the curve adjoining it which the design can't lay along them so, as one whose arc + // going on is too short to be read as an arc: read from a straight there, whichever of the two keeps closer to its paths + if (design.start_curved || design.end_curved) + { + auto const departure = [&]() { + TTrack *worst{nullptr}; + return m_route.result.valid ? alignment_store::deviation(m_route.result, m_route.chain.tracks, worst) : std::numeric_limits::max(); + }; + auto const curved{departure()}; + if (curved > 0.25) + { + auto const kept{design}; + design.start_curved = false; + design.end_curved = false; + route_update(); + if (departure() >= curved) + { + design = kept; + route_update(); + } + } + } +} + +alignment::vertex editor_mode::route_vertex_of(editor_track::curve const &Curve) const +{ + if (Curve.designed.has_value()) + return *Curve.designed; + alignment::vertex vertex; + vertex.radius = Curve.radius > 0.0 ? std::max(1.0, Curve.radius) : 1000.0; + vertex.transition_in = std::max(0.0, Curve.transition_in); + vertex.transition_out = std::max(0.0, Curve.transition_out); + vertex.cant = std::max(0.0, Curve.cant); + vertex.reverse_turn = std::abs(Curve.turn) > glm::pi(); + compound_from(Curve, vertex); + return vertex; +} + + +bool editor_mode::route_load(TTrack &Track) +{ + m_route.designed = 0; + if (false == (m_route.single ? route_from_curve(Track) : route_from_line(Track))) + return false; + route_read_stored(Track); + // the points clicked along the line when it was laid, wherever they're kept + m_route.clicks = alignment_store::clicks_along(m_route.result, 3.0); + m_route.measured = -1; + return true; +} + +// the design kept in the scenery for the fragment takes the place of the one read from the paths; its chainage is carried on +void editor_mode::route_read_stored(TTrack &Track) +{ + auto &route{m_route}; + route.departed = -1; + route.departure = 0.0; + route.origin = 0.0; + if (route.chain.tracks.empty()) + return; + auto const chain{route.chain}; + bool reversed; + auto index{alignment_store::find(chain.start, chain.end, reversed)}; + route.departed = alignment_store::departed(chain.tracks, route.departure); + auto const loose{std::any_of(chain.tracks.begin(), chain.tracks.end(), [](TTrack const *Track) { return false == alignment_store::on_track(*Track).has_value(); })}; + bool digitized{false}; + int parts{0}; + int skipped{0}; + std::string failure; + if (index < 0 && route.departed < 0 && loose && false == route.single) + { + parts = digitize_parts(chain, &failure, skipped); + if (parts == 1 && skipped == 0) + { + alignment_store::settle(); + index = alignment_store::find(chain.start, chain.end, reversed); + digitized = true; + } + else if (parts > 0) + { + alignment_store::settle(); + route_from_line(Track); + route.departed = alignment_store::departed(route.chain.tracks, route.departure); + } + } + if (index >= 0 && false == reversed && false == route.single) + { + route_take_stored(index); + } + else if (auto const km{alignment_store::chainage_at(chain.start)}) + { + auto const ahead{chain.start + glm::dvec3{route.design.start_direction.x, 0.0, route.design.start_direction.y}}; + auto const further{alignment_store::chainage_at(ahead)}; + if (further.has_value() && *further > *km) + route.origin = *km; + } + if (digitized && route.designed == 0) + route.status += STR_C("\nThe line is digitized now, a straight"); + else if (digitized) + route.status += format(STR_C("\nThe line is digitized now, curves kept in the scenery: %d"), route.designed); + else if (parts > 0) + route.status += format(STR_C("\nThe line is digitized in parts: %d, paths left out: %d"), parts, skipped) + (failure.empty() ? std::string{} : " - " + failure); + else if (skipped > 0 && loose && skipped < static_cast(chain.tracks.size())) + route.status += format(STR_C("\nPaths left out of the digitized line: %d"), skipped) + (failure.empty() ? std::string{} : " - " + failure); + else if (false == failure.empty()) + route.status += STR_C("\nThe line can't be digitized: ") + failure; + else if (route.designed > 0) + route.status += format(STR_C("\nCurves read from the design kept in the scenery: %d"), route.designed); + else if (false == route.design.vertices.empty()) + route.status += STR_C("\nCurves recognized from the paths, the scenery keeps no design for them"); +} + +void editor_mode::route_take_stored(int const Index) +{ + auto &route{m_route}; + auto const &records{alignment_store::records()}; + if (Index < 0 || Index >= static_cast(records.size())) + return; + auto const &stored{records[Index]}; + auto &design{route.design}; + design.vertices = stored.design.vertices; + design.shape = stored.design.shape; + design.speed = stored.design.speed; + design.norms = stored.design.norms; + design.transition_pieces = stored.design.transition_pieces; + design.arc_piece_angle = stored.design.arc_piece_angle; + // a curve laid going on from the curve of the track adjoining keeps going on from it, its radius the one which begins it there + design.start_curved = stored.design.start_curved; + design.end_curved = stored.design.end_curved; + design.start_cant = stored.design.start_cant; + design.end_cant = stored.design.end_cant; + route.designed = static_cast(design.vertices.size()); + route.origin = stored.origin; + route.vertex = -1; + route.grip = -1; + route_update(); +} + +void editor_mode::render_route_stored() +{ + auto &route{m_route}; + auto km{route.origin / 1000.0}; + if (begin_fields("##routeorigin")) + { + field_row("Km of the start"); + if (ImGui::InputDouble("##routekm", &km, 0.0, 0.0, "%.3f")) + route.origin = km * 1000.0; + item_tooltip("Chainage of the start of the fragment, kept with the design in the scenery; the vertical profile of these paths counts from it"); + ImGui::EndTable(); + } + auto const &records{alignment_store::records()}; + if (route.departed < 0 || route.departed >= static_cast(records.size()) || false == scene::Layers.valid(records[route.departed].layer)) + return; + auto const &layer{scene::Layers.layer(records[route.departed].layer).name}; + ImGui::PushTextWrapPos(0.0f); + ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), STR_C("The design kept in %s for this fragment departs from its paths by up to %.2f m"), layer.c_str(), route.departure); + ImGui::PopTextWrapPos(); + if (ImGui::SmallButton(STR_C("Take the kept design"))) + { + route_take_stored(route.departed); + route.status = STR_C("The kept design is loaded, applying it lays the paths by it again"); + } + item_tooltip("Loads the design kept in the scenery in place of the one read from the paths; nothing changes until it's applied"); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Forget the kept design"))) + { + alignment_store::forget(route.departed); + alignment_store::settle(); + route.departed = -1; + route.status = format(STR_C("The kept design will be removed from %s on save"), layer.c_str()); + } + item_tooltip("The paths stay as they are, the scenery no longer keeps a design for them"); +} + +void editor_mode::route_store() +{ + auto &route{m_route}; + if (false == route.result.valid || route.chain.tracks.empty() || scene::Layers.empty()) + return; + alignment_store::store(route.design, route.result, route.origin, alignment_store::layer_of(*route.chain.tracks.front()), "designed", 0.0, route.clicks); + route.departed = -1; + route.departure = 0.0; +} + +bool editor_mode::digitize_drawn(std::vector const &Created, bool const Alone) +{ + std::vector drawn; + for (auto *track : Created) + if (track != nullptr && track->eType == tt_Normal && false == track->m_editorremoved && false == track->m_paths.empty()) + drawn.push_back(track); + if (drawn.empty() || scene::Layers.empty()) + return false; + editor_track::chain chain; + std::string error; + if (editor_track::find_run(*drawn.front(), kDrawnReach, chain, error) && digitize_chain(chain)) + return true; + if (Alone && editor_track::find_chain(drawn.front(), drawn.back(), chain, error) && chain.tracks.size() == drawn.size() && digitize_chain(chain)) + return true; + WriteLog("Editor: the drawn paths don't make a line of straights, arcs and transition curves, no design kept for them", logtype::generic); + return false; +} + +void editor_mode::digitize_all(int *Kept, int *Failed) +{ + std::set visited; + int kept{0}; + int failed{0}; + std::string first; + for (auto *track : simulation::Paths.sequence()) + { + if (track == nullptr || track->m_editorremoved || track->eType != tt_Normal || track->m_paths.empty() || false == editor_track::is_supported(*track) || visited.count(track) > 0) + continue; + if (alignment_store::on_track(*track).has_value()) + continue; + editor_track::chain chain; + std::string error; + if (false == editor_track::find_run(*track, kDrawnReach, chain, error) || chain.tracks.empty()) + { + visited.insert(track); + continue; + } + visited.insert(chain.tracks.begin(), chain.tracks.end()); + std::string reason; + kept += digitize_parts(chain, &reason, failed); + if (first.empty()) + first = reason; + } + alignment_store::settle(); + if (Kept != nullptr) + *Kept = kept; + if (Failed != nullptr) + *Failed = failed; + auto text{format(STR_C("Lines digitized: %d, paths left out: %d"), kept, failed)}; + if (false == first.empty()) + text += STR_C(", the first: ") + first; + WriteLog("Editor: " + text, logtype::generic); + ui()->set_status(text, failed > 0); + if (false == m_route.chain.tracks.empty()) + route_load(*m_route.chain.tracks[m_route.chain.tracks.size() / 2]); +} + +int editor_mode::digitize_parts(editor_track::chain const &Chain, std::string *Reason, int &Skipped) +{ + auto const count{Chain.tracks.size()}; + if (count == 0 || std::all_of(Chain.tracks.begin(), Chain.tracks.end(), [](TTrack const *Track) { return alignment_store::on_track(*Track).has_value(); })) + return 0; + TTrack *culprit{nullptr}; + std::string reason; + if (digitize_chain(Chain, &reason, &culprit)) + return 1; + if (count == 1) + { + ++Skipped; + reason = name_of(*Chain.tracks.front()) + ": " + reason; + WriteLog("Editor: digitizing - " + reason, logtype::generic); + if (Reason != nullptr && Reason->empty()) + *Reason = reason; + return 0; + } + auto const found{static_cast(std::find(Chain.tracks.begin(), Chain.tracks.end(), culprit) - Chain.tracks.begin())}; + auto const split{found < count ? std::max(1, found) : count / 2}; + int parts{0}; + for (auto const &[first, last] : {std::pair{0, split - 1}, std::pair{split, count - 1}}) + { + editor_track::chain part; + std::string error; + if (editor_track::find_chain(Chain.tracks[first], Chain.tracks[last], part, error) && part.tracks.size() == last - first + 1) + parts += digitize_parts(part, Reason, Skipped); + else + Skipped += static_cast(last - first + 1); + } + return parts; +} + +bool editor_mode::digitize_chain(editor_track::chain const &Chain, std::string *Reason, TTrack **Culprit) +{ + if (Chain.tracks.empty() || scene::Layers.empty()) + return false; + auto const name = [](TTrack const *Track) { return Track == nullptr || Track->name().empty() ? std::string{STR_C("(no name)")} : Track->name(); }; + auto const nearest = [&](glm::dvec2 const &Point) { + TTrack *found{nullptr}; + double distance{std::numeric_limits::max()}; + for (auto *track : Chain.tracks) + for (auto const end : {segment_data::point::start, segment_data::point::end}) + if (auto const d{glm::distance(plan_of(track->m_paths.front().points[end]), Point)}; d < distance) + { + distance = d; + found = track; + } + return found; + }; + alignment::design design; + design.norms = m_route.design.norms; + design.transition_pieces = m_route.design.transition_pieces; + design.arc_piece_angle = m_route.design.arc_piece_angle; + design.speed = Chain.velocity > 0.0 ? Chain.velocity : 100.0; + design.start = Chain.start; + design.end = Chain.end; + if (glm::length(plan_of(Chain.start_direction)) < 1e-9 || glm::length(plan_of(Chain.end_direction)) < 1e-9) + return false; + design.start_direction = glm::normalize(plan_of(Chain.start_direction)); + design.end_direction = glm::normalize(plan_of(Chain.end_direction)); + design.start_grade = grade_of(Chain.start_direction); + design.end_grade = grade_of(Chain.end_direction); + design.start_radius = Chain.start_radius; + design.end_radius = Chain.end_radius; + design.start_turn = Chain.start_turn; + design.end_turn = Chain.end_turn; + auto const preferred{m_route.design.shape}; + auto const other{preferred == alignment::transition_shape::clothoid ? alignment::transition_shape::cubic_parabola : alignment::transition_shape::clothoid}; + alignment::result result; + alignment::design best; + alignment::result bestresult; + double closest{std::numeric_limits::max()}; + TTrack *farthest{nullptr}; + bool fits{false}; + for (auto const attempt : {0, 1, 2, 3}) + { + auto const shape{attempt % 2 == 0 ? preferred : other}; + design.shape = shape; + if (attempt == 2) + { + design.norms.arc_min = 0.0; + design.norms.arc_min_factor = 0.0; + } + design.vertices.clear(); + for (auto const &entry : editor_track::recognize_line(Chain, m_straights.tolerance, design.norms.gauge, shape)) + { + if (entry.kink) + { + if (Reason != nullptr) + *Reason = format(STR_C("the straights meet with no curve at path %s"), name(nearest(entry.position)).c_str()); + if (Culprit != nullptr) + *Culprit = nearest(entry.position); + return false; + } + auto vertex{route_vertex_of(entry.shape)}; + vertex.position = entry.position; + design.vertices.push_back(vertex); + } + if (design.vertices.size() >= 2) + { + design.vertices.front().offset = std::max(0.0, glm::dot(design.vertices.front().position - plan_of(design.start), design.start_direction)); + design.vertices.back().offset = std::max(0.0, glm::dot(plan_of(design.end) - design.vertices.back().position, design.end_direction)); + } + result = alignment::compute(design); + if (alignment_store::follows(result, Chain.tracks)) + { + fits = true; + break; + } + TTrack *worst{nullptr}; + if (auto const away{alignment_store::deviation(result, Chain.tracks, worst)}; away < closest) + { + closest = away; + farthest = worst; + best = design; + bestresult = result; + } + } + double fit{0.0}; + if (false == fits && closest <= kDigitizeFit) + { + design = best; + result = bestresult; + fit = closest; + fits = true; + } + if (false == fits) + { + if (Culprit != nullptr) + *Culprit = farthest; + if (Reason != nullptr) + *Reason = closest < std::numeric_limits::max() ? format(STR_C("the curves read from the paths leave path %s by %.2f m"), name(farthest).c_str(), closest) : std::string{STR_C("the paths don't make a line of straights, arcs and transition curves")}; + return false; + } + auto const &records{alignment_store::records()}; + std::set covered; + for (auto *track : Chain.tracks) + if (auto const found{alignment_store::on_track(*track)}) + covered.insert(found->record); + double origin{0.0}; + for (auto const index : covered) + { + auto const &old{records[index]}; + auto const start{alignment_store::chainage_on(result, alignment_store::kept_start(old))}; + auto const end{alignment_store::chainage_on(result, alignment_store::kept_end(old))}; + if (false == start.has_value() || false == end.has_value()) + return false; + if (index == *covered.begin() && *end > *start) + origin = old.origin + old.from - *start; + } + auto const layer{covered.empty() ? alignment_store::layer_of(*Chain.tracks.front()) : records[*covered.begin()].layer}; + for (auto index{covered.rbegin()}; index != covered.rend(); ++index) + alignment_store::forget(*index); + alignment_store::store(design, result, origin, layer, "drawn", fit); + return true; +} + +bool editor_mode::route_from_line(TTrack &Track) +{ + auto &route{m_route}; + editor_track::chain run; + if (false == editor_track::find_run(Track, kLineReach, run, route.error)) + return false; + route.from = run.tracks.front(); + route.to = run.tracks.back(); + route_reset(); + if (route.chain.tracks.empty()) + return false; + auto &design{route.design}; + auto const found{editor_track::recognize_line(route.chain, m_straights.tolerance, design.norms.gauge, design.shape)}; + route.designed = 0; + if (false == found.empty()) + { + design.vertices.clear(); + for (auto const &entry : found) + { + alignment::vertex vertex; + if (entry.kink) + { + vertex.radius = std::max(10.0, std::round(alignment::recommend(design.speed, 1000.0, design.norms).radius_min / 10.0) * 10.0); + vertex.transition_in = 0.0; + vertex.transition_out = 0.0; + vertex.cant = 0.0; + } + else + { + vertex = route_vertex_of(entry.shape); + if (entry.shape.designed.has_value()) + ++route.designed; + } + vertex.position = entry.position; + design.vertices.push_back(vertex); + } + if (design.vertices.size() >= 2) + { + design.vertices.front().offset = std::max(0.0, glm::dot(design.vertices.front().position - plan_of(design.start), design.start_direction)); + design.vertices.back().offset = std::max(0.0, glm::dot(plan_of(design.end) - design.vertices.back().position, design.end_direction)); + } + route_curved_ends(); + } + route.status = format(STR_P("Line of %zu path, %.0f m, %zu vertices", "Line of %zu paths, %.0f m, %zu vertices", route.chain.tracks.size()), route.chain.tracks.size(), route.chain.length, design.vertices.size()); + return true; +} + +void editor_mode::route_apply() +{ + m_route.error.clear(); + route_lay(); + if (false == m_route.error.empty()) + refused(m_route.error); +} + +void editor_mode::route_lay() +{ + auto &route{m_route}; + route.status.clear(); + m_infra_carried.clear(); + if (false == route.result.valid || route.chain.tracks.empty()) + return; + editor_track::chain chain; + if (false == editor_track::find_chain(route.from, route.to, chain, route.error, true)) + return; + if (glm::distance(chain.start, route.chain.start) > 1e-3 || glm::distance(chain.end, route.chain.end) > 1e-3) + { + route.error = STR_C("The fragment changed since it was selected, select it again"); + return; + } + auto involved{chain.tracks}; + for (auto const &passage : chain.switches) + involved.push_back(passage.track); + if (false == tracks_editable(involved, route.error)) + return; + // the crossovers of the line can't be moved as their switches are: they're taken out, the line laid again, and they go back + // where they were, onto the new line + if (false == route.relaying) + { + struct again + { + int shape; + glm::dvec3 press, release; + std::string name; + std::vector names; // of the switches at the press and at the release + }; + std::vector crossovers; + std::vector seen; + // a line which ends on a switch of a crossover would be laid again only up to it, the crossover left on a kink + for (auto const &end : {chain.start, chain.end}) + for (auto *track : chain.tracks) + for (auto const &[other, point] : editor_track::connected_points(*track, end)) + if (other != nullptr && other->eType == tt_Switch && crossover_of(*other).has_value()) + { + route.error = format(STR_C("The line ends on the switch %s of a crossover: move the crossover off the curve or take it out, change both lines, then lay it again"), other->name().c_str()); + return; + } + std::vector switches; + for (auto const &passage : chain.switches) + switches.push_back(passage.track); + for (auto *switchtrack : switches) + { + auto const crossover{crossover_of(*switchtrack)}; + if (false == crossover.has_value() || std::find(seen.begin(), seen.end(), crossover->first) != seen.end()) + continue; + seen.push_back(crossover->first); + // the press on this line, the release on the other one + auto *here{crossover->first == switchtrack ? crossover->first : crossover->second}; + auto *there{here == crossover->first ? crossover->second : crossover->first}; + crossovers.push_back({crossover_template(crossover->record), here->m_paths.front().points[segment_data::point::start], there->m_paths.front().points[segment_data::point::start], crossover->first->name(), {here->name(), there->name()}}); + } + if (false == crossovers.empty()) + { + auto const tab{m_track_tab}; + std::vector> states; + std::vector created; + std::vector removed; + // the designs of the outer tracks come down with the lifts taken back, an undo puts them back + profile_library_load(); + auto library{m_profiles}; + bool lifted{false}; + for (auto *switchtrack : switches) + if (auto const crossover{crossover_of(*switchtrack)}) + { + TTrack *first{nullptr}; + TTrack *second{nullptr}; + lifted = lifted || crossover->record.lifted(); + take_out_crossover(*crossover, states, created, removed, first, second); + } + switch_store::follow(); + push_track_snapshot(std::move(states), std::move(created), std::move(removed)); + records_to_history(); + if (lifted) + profiles_to_history(std::move(library)); + show_track_tab(tab); + // the line between the same points again: taking the lift back may have cut its paths + auto const end_at = [&](glm::dvec3 const &Point) -> TTrack * { + for (auto *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved && track->eType == tt_Normal && false == track->m_paths.empty()) + for (auto const which : {segment_data::point::start, segment_data::point::end}) + if (plan_distance(track->m_paths.front().points[which], Point) < 0.01) + return track; + return nullptr; + }; + auto *start{end_at(route.chain.start)}; + auto *finish{end_at(route.chain.end)}; + editor_track::chain refreshed; + std::string error; + if (start != nullptr && finish != nullptr && editor_track::find_chain(start, finish, refreshed, error, true)) + { + route.from = start; + route.to = finish; + route.chain = refreshed; + } + route.relaying = true; + auto const steps{m_history.size()}; + route_apply(); + route.relaying = false; + if (m_history.size() == steps) + { + undo_last(); + return; + } + join_last_steps(); + std::string back, left; + for (auto const &crossover : crossovers) + { + // the new line moved sideways: the press onto it, the release onto the other line + if (lay_crossover(crossover.shape, crossover.press, crossover.release, 30.0, crossover.names)) + { + join_last_steps(); + back += (back.empty() ? "" : ", ") + crossover.name; + } + else + { + left += (left.empty() ? "" : ", ") + crossover.name; + route.crossovers_out.push_back({crossover.shape, crossover.press, crossover.release, crossover.name, crossover.names}); + } + } + show_track_tab(tab); + if (false == back.empty()) + route.status += "\n" + format(STR_C("Crossovers laid again on the new line: %s"), back.c_str()); + if (false == left.empty()) + route.status += "\n" + format(STR_C("Crossovers taken out which don't fit the new line, lay them again: %s"), left.c_str()); + return; + } + } + + std::vector> states; + std::vector created; + // takes back what was done before the paths were re-laid + auto const undo = [&]() { + for (auto *track : created) + editor_track::retire(*track); + for (auto entry = states.rbegin(); entry != states.rend(); ++entry) + { + editor_track::apply(*entry->first, entry->second); + editor_track::commit({entry->first}); + } + }; + auto *from{route.from}; + auto *to{route.to}; + auto const startextension{route.result.start_extension}; + auto const endextension{route.result.end_extension}; + if (startextension > 0.0 || endextension > 0.0) + { + auto const before{chain}; + if (startextension > 0.0) + from = editor_track::take_straight(editor_track::straight_beyond(before, false, m_straights.tolerance), from, before.start, route.result.start, states, created); + if (endextension > 0.0) + to = editor_track::take_straight(editor_track::straight_beyond(before, true, m_straights.tolerance), to, before.end, route.result.end, states, created); + std::string error; + auto const found{editor_track::find_chain(from, to, chain, error, true)}; + auto const startoff{found && startextension > 0.0 ? plan_distance(chain.start, route.result.start) : 0.0}; + auto const endoff{found && endextension > 0.0 ? plan_distance(chain.end, route.result.end) : 0.0}; + if (false == found || startoff > 5.0 || endoff > 5.0) + { + auto const startrun{editor_track::straight_beyond(before, false, m_straights.tolerance)}; + auto const endrun{editor_track::straight_beyond(before, true, m_straights.tolerance)}; + WriteLog(format("editor: cutting the straights failed: found %d, start %.2f m off (extension %.2f, run %zu paths %.2f m), end %.2f m off (extension %.2f, run %zu paths %.2f m), chain %zu paths, from %s, to %s, error '%s'", found ? 1 : 0, startoff, + startextension, startrun.tracks.size(), startrun.length, endoff, endextension, endrun.tracks.size(), endrun.length, chain.tracks.size(), from != nullptr ? from->name().c_str() : "-", to != nullptr ? to->name().c_str() : "-", error.c_str())); + undo(); + route.error = error.empty() ? format(STR_C("The adjoining straights can't be cut at the ends of the curve: the start misses by %.1f m, the end by %.1f m"), startoff, endoff) : error; + return; + } + if (false == tracks_editable(chain.tracks, route.error)) + { + undo(); + return; + } + } + for (auto *track : chain.tracks) + if (std::none_of(states.begin(), states.end(), [&](auto const &Entry) { return Entry.first == track; })) + states.emplace_back(track, editor_track::capture(*track)); + std::vector relaid; + if (chain.switches.empty()) + { + std::vector intervals; + auto pieces{alignment::pieces_at(route.result, route.design, chain.tracks.size(), editor_track::chain_joints(chain), intervals)}; + editor_track::keep_heights(chain, pieces); + relaid = editor_track::relay(chain, pieces, &to, &intervals); + } + else if (false == route_relay_through_switches(chain, states, relaid, to)) + { + undo(); + return; + } + // the straights were cut along their own direction, the curve ends where the design says: the ends are brought together + auto const added{relaid.size()}; + created.insert(created.end(), relaid.begin(), relaid.end()); + push_track_snapshot(std::move(states), std::move(created)); + + route.from = from; + route.to = to; + editor_track::find_chain(route.from, route.to, route.chain, route.error, true); + if (startextension > 0.0 || endextension > 0.0) + { + route_bind_ends(); + auto &vertices{route.design.vertices}; + if (vertices.size() >= 2) + { + vertices.front().offset += startextension; + vertices.back().offset += endextension; + } + route_update(); + } + route_store(); + records_to_history(); + route.status = added > 0 ? format(STR_P("Re-laid %zu path, added %zu", "Re-laid %zu paths, added %zu", chain.tracks.size()), chain.tracks.size(), added) : format(STR_P("Re-laid %zu path", "Re-laid %zu paths", chain.tracks.size()), chain.tracks.size()); + if (startextension > 0.0 || endextension > 0.0) + route.status += format(STR_C(", the curve took over %.2f / %.2f m of the adjoining straights"), startextension, endextension); + route.status += infra_carried_note(); + // the crossovers taken out before which fit the lines now + if (false == route.relaying && false == route.crossovers_out.empty()) + { + auto const tab{m_track_tab}; + std::string back; + for (auto out{route.crossovers_out.begin()}; out != route.crossovers_out.end();) + if (lay_crossover(out->shape, out->press, out->release, 30.0, out->names)) + { + join_last_steps(); + back += (back.empty() ? "" : ", ") + out->name; + out = route.crossovers_out.erase(out); + } + else + ++out; + show_track_tab(tab); + if (false == back.empty()) + route.status += "\n" + format(STR_C("Crossovers laid again on the new line: %s"), back.c_str()); + } + WriteLog("Editor: route design - " + route.status, logtype::generic); +} + +// the switches of the chain are moved as a whole onto the designed line, the regular paths between them re-laid +bool editor_mode::route_relay_through_switches(editor_track::chain const &Chain, std::vector> &States, std::vector &Created, TTrack *&Last) +{ + auto &route{m_route}; + auto const &result{route.result}; + auto const name = [](TTrack const *Track) { return name_of(*Track); }; + auto const plan = [](glm::dvec3 const &Vector) { return glm::normalize(plan_of(Vector)); }; + struct placement + { + TTrack *track; + double from, length; // chainage along the new line + glm::dvec3 entry; // of the main track, where the chain comes in + double angle; + }; + // chainages along the old line, the switches keep their distance from the nearer end of the chain + double before{0.0}; + std::vector starts; + std::size_t next{0}; + for (std::size_t i = 0; i <= Chain.tracks.size(); ++i) + { + for (; next < Chain.switches.size() && Chain.switches[next].before == i; ++next) + { + starts.push_back(before); + before += bezier{Chain.switches[next].track->m_paths.front()}.plan_length(); + } + if (i < Chain.tracks.size()) + before += bezier{Chain.tracks[i]->m_paths.front()}.plan_length(); + } + auto const oldlength{before}; + std::vector placements; + std::vector ends; // of the switches along the new line + for (std::size_t k = 0; k < Chain.switches.size(); ++k) + { + auto const &passage{Chain.switches[k]}; + auto const &main{passage.track->m_paths.front()}; + auto const length{bezier{main}.plan_length()}; + auto const from{starts[k] + length * 0.5 < oldlength * 0.5 ? starts[k] : result.length - (oldlength - starts[k])}; + if (from < 0.0 || from + length > result.length || (false == ends.empty() && from < ends.back() - 0.01)) + { + route.error = format(STR_C("The switch %s doesn't fit on the designed line"), name(passage.track).c_str()); + return false; + } + auto const entry{main.points[passage.forward ? segment_data::point::start : segment_data::point::end]}; + auto const exit{main.points[passage.forward ? segment_data::point::end : segment_data::point::start]}; + bezier const curve{main}; + auto const direction{passage.forward ? plan(curve.first(0.0)) : -plan(curve.first(1.0))}; + auto const first{alignment::evaluate(result, from)}; + auto const last{alignment::evaluate(result, from + length)}; + auto const angle{signed_angle(direction, plan(first.direction))}; + // where the other end of the main track goes, set against the line + auto const moved{plan_of(first.position) + turned(plan_of(exit - entry), angle)}; + auto const departure{glm::distance(moved, plan_of(last.position))}; + if (departure > 0.02) + { + route.error = format(STR_C("The switch %s would leave the designed line by %.2f m at its other end: it lies in a curve of the design. " + "Move the vertices so that the switch falls on a straight"), + name(passage.track).c_str(), departure); + return false; + } + placements.push_back({passage.track, from, length, entry, angle}); + ends.push_back(from); + ends.push_back(from + length); + } + // the regular parts between the switches, cut at the joints of their paths set square onto the new line where they follow one + // another along it, else one interval each; the switches taking the ones between + auto const parts{editor_track::chain_parts(Chain)}; + std::vector breaks; + std::vector counts; + std::vector> owners; // of each interval: the part, -1 for none, and its path, -1 for any + std::size_t part{0}; + for (std::size_t k = 0; k <= Chain.switches.size(); ++k) + { + auto const first{k == 0 ? std::size_t{0} : Chain.switches[k - 1].before}; + auto const last{k == Chain.switches.size() ? Chain.tracks.size() : Chain.switches[k].before}; + if (last > first && part < parts.size()) + { + auto const inner{alignment::breaks_at(result, editor_track::chain_joints(parts[part]), k == 0 ? 0.0 : ends[2 * k - 1], k == Chain.switches.size() ? result.length : ends[2 * k])}; + if (last - first > 1 && inner.size() + 1 == last - first) + for (std::size_t j = 0; j < last - first; ++j) + { + if (j > 0) + breaks.push_back(inner[j - 1]); + counts.push_back(1); + owners.emplace_back(static_cast(part), static_cast(j)); + } + else + { + counts.push_back(last - first); + owners.emplace_back(static_cast(part), -1); + } + ++part; + } + else + { + counts.push_back(last - first); + owners.emplace_back(-1, -1); + } + if (k < Chain.switches.size()) + { + breaks.push_back(ends[2 * k]); + breaks.push_back(ends[2 * k + 1]); + counts.push_back(1); + owners.emplace_back(-1, -1); + } + } + if (part != parts.size()) + { + route.error = STR_C("The paths between the switches can't be read as a chain"); + return false; + } + std::vector intervals; + auto const pieces{alignment::pieces(result, route.design, 0, breaks, counts, &intervals)}; + std::vector> groups(parts.size()); + std::vector> paths(parts.size()); // of each piece of a part, its path, where its joints cut the line + for (std::size_t i = 0; i < pieces.size() && i < intervals.size(); ++i) + if (intervals[i] < owners.size() && owners[intervals[i]].first >= 0) + { + auto const &[owner, path]{owners[intervals[i]]}; + groups[owner].push_back(pieces[i]); + if (path >= 0) + paths[owner].push_back(static_cast(path)); + } + for (std::size_t i = 0; i < parts.size(); ++i) + if (groups[i].size() < parts[i].tracks.size()) + { + route.error = STR_C("The designed line between the switches is too short for the paths there"); + return false; + } + + // all checked, the changes go in + auto const remember = [&](TTrack *Track) { + if (std::none_of(States.begin(), States.end(), [&](auto const &Entry) { return Entry.first == Track; })) + States.emplace_back(Track, editor_track::capture(*Track)); + }; + for (auto const &place : placements) + { + auto joints{editor_track::joints(*place.track)}; + joints.erase(std::remove_if(joints.begin(), joints.end(), [&](editor_track::joint const &Joint) { return std::find(Chain.tracks.begin(), Chain.tracks.end(), Joint.other) != Chain.tracks.end(); }), joints.end()); + remember(place.track); + std::vector changed{place.track}; + for (auto const &joint : joints) + { + remember(joint.other); + if (std::find(changed.begin(), changed.end(), joint.other) == changed.end()) + changed.push_back(joint.other); + } + // the heights stay, the paths between the switches keep theirs too + auto target{alignment::evaluate(result, place.from).position}; + target.y = place.entry.y; + editor_track::place(*place.track, place.entry, target, place.angle); + editor_track::follow(*place.track, joints); + editor_track::commit(changed); + } + for (std::size_t i = 0; i < parts.size(); ++i) + { + auto group{groups[i]}; + editor_track::keep_heights(parts[i], group); + TTrack *last{nullptr}; + auto const added{editor_track::relay(parts[i], group, &last, paths[i].size() == group.size() ? &paths[i] : nullptr)}; + if (last != nullptr && parts[i].tracks.back() == Chain.tracks.back()) + Last = last; + Created.insert(Created.end(), added.begin(), added.end()); + } + return true; +} + +glm::dvec3 editor_mode::route_vertex_position(int const Vertex) const +{ + auto const &design{m_route.design}; + auto const &result{m_route.result}; + auto const count{static_cast(design.vertices.size())}; + glm::dvec2 const start{design.start.x, design.start.z}; + glm::dvec2 const end{design.end.x, design.end.z}; + glm::dvec2 position; + if (Vertex < static_cast(result.vertices.size()) && false == result.vertices.empty()) + position = result.vertices[Vertex]; + else if (count == 1) + { + if (false == alignment::tangent_intersection(design, position)) + position = (start + end) * 0.5; + } + else if (Vertex == 0) + position = start + glm::normalize(design.start_direction) * design.vertices.front().offset; + else if (Vertex == count - 1) + position = end - glm::normalize(design.end_direction) * design.vertices.back().offset; + else + position = design.vertices[Vertex].position; + + auto const height{Vertex < static_cast(result.vertex_elevations.size()) ? result.vertex_elevations[Vertex] : design.start.y + (design.end.y - design.start.y) * (Vertex + 1) / (count + 1.0)}; + return {position.x, height, position.y}; +} + +bool editor_mode::route_hit(int &Vertex, int &Grip) const +{ + if (false == route_active()) + return false; + screen_projection const projection; + float best = kHandleRadius * kHandleRadius; + int hit{-1}; + for (int i = 0; i < static_cast(m_route.design.vertices.size()); ++i) + { + if (auto const distance{projection.mouse_distance2(route_vertex_position(i))}; distance < best) + { + best = distance; + hit = i; + } + } + int griphit{-1}; + for (int i = 0; i < static_cast(m_route.result.vertex_chainages.size()) && m_route.result.length > 0.0; ++i) + { + if (auto const distance{projection.mouse_distance2(alignment::evaluate(m_route.result, m_route.result.vertex_chainages[i]).position)}; distance < best) + { + best = distance; + griphit = i; + hit = -1; + } + } + Vertex = hit; + Grip = griphit; + return hit >= 0 || griphit >= 0; +} + +void editor_mode::route_show_curve(double const From, double const To) +{ + auto const &result{m_route.result}; + if (result.elements.empty() || To <= From) + return; + glm::dvec3 low{std::numeric_limits::max()}; + glm::dvec3 high{std::numeric_limits::lowest()}; + for (int i = 0; i <= 32; ++i) + { + auto const point{alignment::evaluate(result, From + (To - From) * i / 32.0).position}; + low = glm::min(low, point); + high = glm::max(high, point); + } + auto const along{plan_of(alignment::evaluate(result, (From + To) * 0.5).direction)}; + auto const flat{glm::length(along) > 1e-9 ? glm::normalize(along) : glm::dvec2{0.0, 1.0}}; + // from above, leaning a little along the line, the whole curve in sight + auto const look{glm::normalize(glm::dvec3{flat.x * 0.45, -1.0, flat.y * 0.45})}; + auto const extent{std::max(high.x - low.x, high.z - low.z)}; + fly_to((low + high) * 0.5, look, std::clamp(extent * 1.2, 60.0, 3000.0)); +} + +std::vector editor_mode::route_focused() const +{ + using part = route_design::curve_focus::part; + auto const &focus{m_route.focus}; + auto const &result{m_route.result}; + std::vector own; + if (focus.vertex < 0) + return own; + for (std::size_t i = 0; i < result.elements.size(); ++i) + if (result.elements[i].vertex == focus.vertex && result.elements[i].length > 1e-6) + own.push_back(i); + if (own.empty() || focus.what == part::whole) + return own; + // the arcs of a compound curve found by the curvature at the start and at the end of each element and their radii + auto const same = [](double const A, double const B) { return std::abs(A - B) <= 1e-6 * std::max(std::abs(A), std::abs(B)) + 1e-12; }; + std::vector radii; + for (auto const &curve : result.curves) + if (curve.vertex == focus.vertex) + radii = curve.radii.size() > 1 ? curve.radii : std::vector{curve.radius}; + std::vector found; + for (auto const i : own) + { + auto const [start, end] {alignment::end_curvatures(result.elements[i])}; + auto const arc{static_cast(focus.arc)}; + switch (focus.what) + { + case part::entry: if (i == own.front() && start == 0.0 && end > 0.0) found.push_back(i); break; + case part::exit: if (i == own.back() && end == 0.0 && start > 0.0) found.push_back(i); break; + case part::arc: if (arc < radii.size() && radii[arc] > 0.0 && same(start, 1.0 / radii[arc]) && same(end, start)) found.push_back(i); break; + case part::between: + if (arc >= 1 && arc < radii.size() && radii[arc] > 0.0 && radii[arc - 1] > 0.0 && same(start, 1.0 / radii[arc - 1]) && same(end, 1.0 / radii[arc])) + found.push_back(i); + break; + default: break; + } + } + // a part of no length, the arc of two transition curves meeting say, shows the whole curve + return found.empty() ? own : found; +} + +void editor_mode::route_measure_clicks() +{ + auto &route{m_route}; + if (route.measured == route.revision) + return; + route.measured = route.revision; + route.click_states.clear(); + auto const &result{route.result}; + if (route.clicks.empty() || false == result.valid) + return; + std::vector plan; + for (auto const &click : route.clicks) + plan.push_back(plan_of(click)); + auto const projections{alignment::project(result, plan)}; + auto const count{static_cast(route.design.vertices.size())}; + for (std::size_t i = 0; i < plan.size() && i < projections.size(); ++i) + { + route_design::click_state state; + state.offset = projections[i].offset; + // the curve nearest along the line, as the points traced in the plan go to their curves + for (int k = 0; k < count && k < static_cast(result.vertex_chainages.size()); ++k) + if (state.vertex < 0 || std::abs(result.vertex_chainages[k] - projections[i].chainage) < std::abs(result.vertex_chainages[state.vertex] - projections[i].chainage)) + state.vertex = k; + for (int k = 0; k < count && false == state.corner; ++k) + state.corner = plan_distance(route.clicks[i], route_vertex_position(k)) < 0.05; + route.click_states.push_back(state); + } +} + +std::vector editor_mode::route_clicks_of(int const Vertex) const +{ + auto const &route{m_route}; + std::vector points; + for (std::size_t i = 0; i < route.click_states.size() && i < route.clicks.size(); ++i) + { + auto const &state{route.click_states[i]}; + // a point clicked far off the line belongs to none of its curves + if (state.vertex == Vertex && false == state.corner && std::abs(state.offset) <= 3.0) + points.push_back(plan_of(route.clicks[i])); + } + return points; +} + +bool editor_mode::route_hold_clicks(int const Vertex) +{ + auto &route{m_route}; + route_measure_clicks(); + auto const points{route_clicks_of(Vertex)}; + if (points.size() < 3 || Vertex < 0 || Vertex >= static_cast(route.design.vertices.size())) + return false; + auto design{route.design}; + design.norms.checked = true; + auto const fit{alignment::refit_radii(design, static_cast(Vertex), points)}; + if (false == fit.valid) + return false; + route.design.vertices[Vertex] = fit.fitted; + return true; +} + +void editor_mode::draw_route_overlay() const +{ + auto const &route{m_route}; + auto const &design{route.design}; + auto const &result{route.result}; + screen_projection const projection; + ImDrawList *drawlist = ImGui::GetBackgroundDrawList(ImGui::GetMainViewport()); + auto const &start{result.valid ? result.start : design.start}; + auto const &end{result.valid ? result.end : design.end}; + + std::vector polygon{start}; + for (int i = 0; i < static_cast(design.vertices.size()); ++i) + polygon.push_back(route_vertex_position(i)); + polygon.push_back(end); + for (std::size_t i = 0; i + 1 < polygon.size(); ++i) + projection.line(drawlist, polygon[i], polygon[i + 1], IM_COL32(255, 210, 60, 150), 1.5f); + + if (result.length > 0.0 && result.profile.size() >= 2) + { + for (auto const &e : result.elements) + { + ImU32 const color = e.kind == alignment::element_kind::straight ? IM_COL32(255, 255, 255, 230) : e.kind == alignment::element_kind::arc ? overlay_color::grip : IM_COL32(255, 140, 30, 255); + int const steps = std::clamp(static_cast(e.length / 2.0), 1, 400); + auto previous{alignment::evaluate(result, e.chainage).position}; + for (int j = 1; j <= steps; ++j) + { + auto const next{alignment::evaluate(result, e.chainage + e.length * j / steps).position}; + projection.line(drawlist, previous, next, color, 3.0f); + previous = next; + } + ImVec2 screen; + if (projection.project(alignment::evaluate(result, e.chainage).position, screen)) + drawlist->AddCircleFilled(screen, 3.5f, overlay_color::highlight); + } + // what the mouse points at in the band of the curvature in the panel + if (route.band.hot >= 0 && route.band.hot < static_cast(result.elements.size())) + { + auto const &e{result.elements[route.band.hot]}; + int const steps = std::clamp(static_cast(e.length / 2.0), 1, 400); + auto previous{alignment::evaluate(result, e.chainage).position}; + for (int j = 1; j <= steps; ++j) + { + auto const next{alignment::evaluate(result, e.chainage + e.length * j / steps).position}; + projection.line(drawlist, previous, next, IM_COL32(255, 255, 255, 110), 8.0f); + previous = next; + } + } + // the cant ramps: their ends across the track, the ones moved off the transitions brighter, with how the cant goes along them + for (auto const &ramp : result.ramps) + { + if (ramp.cant < 0.5) + continue; + auto const colour{ramp.own ? IM_COL32(255, 170, 40, 255) : IM_COL32(255, 170, 40, 120)}; + for (auto const end : {ramp.from, ramp.to}) + { + auto const station{alignment::evaluate(result, end)}; + glm::dvec3 const across{-station.direction.z * 2.0, 0.0, station.direction.x * 2.0}; + projection.line(drawlist, station.position - across, station.position + across, colour, 3.0f); + } + ImVec2 screen; + if (ramp.own && projection.project(alignment::evaluate(result, (ramp.from + ramp.to) * 0.5).position, screen)) + drawlist->AddText({screen.x + 8.0f, screen.y + 6.0f}, colour, format(STR_C("ramp %.0f m, %.0f mm"), ramp.to - ramp.from, ramp.cant).c_str()); + } + // the part of the curve whose fields are pointed at or edited in the panel, lit up and named + if (auto const focused{route_focused()}; false == focused.empty()) + { + using part = route_design::curve_focus::part; + auto const &focus{route.focus}; + for (auto const index : focused) + { + auto const &e{result.elements[index]}; + int const steps = std::clamp(static_cast(e.length / 2.0), 1, 400); + auto previous{alignment::evaluate(result, e.chainage).position}; + for (int j = 1; j <= steps; ++j) + { + auto const next{alignment::evaluate(result, e.chainage + e.length * j / steps).position}; + projection.line(drawlist, previous, next, IM_COL32(60, 230, 255, 120), 11.0f); + projection.line(drawlist, previous, next, IM_COL32(200, 250, 255, 255), 3.0f); + previous = next; + } + } + auto const &first{result.elements[focused.front()]}; + auto const &last{result.elements[focused.back()]}; + alignment::curve_report const *report{nullptr}; + for (auto const &curve : result.curves) + if (curve.vertex == focus.vertex) + report = &curve; + std::string name; + if (report != nullptr) + { + auto const compound{report->radii.size() > 1}; + auto const arc{static_cast(focus.arc)}; + switch (focus.what) + { + case part::entry: name = format(STR_C("W%d transition in %.0f m"), focus.vertex + 1, first.length); break; + case part::exit: name = format(STR_C("W%d transition out %.0f m"), focus.vertex + 1, last.length); break; + case part::between: name = format(STR_C("W%d transition R%d-R%d %.0f m"), focus.vertex + 1, focus.arc, focus.arc + 1, first.length); break; + case part::arc: + if (compound && arc < report->radii.size()) + name = format(STR_C("W%d R%d %.0f m cant %.0f mm"), focus.vertex + 1, focus.arc + 1, report->radii[arc], arc < report->cants.size() ? report->cants[arc] : report->cant); + else + name = format(STR_C("W%d R %.0f m cant %.0f mm"), focus.vertex + 1, report->radius, report->cant); + break; + default: name = format("W%d ", focus.vertex + 1) + curve_label(*report, design.norms); break; + } + } + ImVec2 middle; + if (false == name.empty() && projection.project(alignment::evaluate(result, (first.chainage + last.chainage + last.length) * 0.5).position, middle)) + { + auto const size{ImGui::GetFontSize() * 1.25f}; + auto const text{ImGui::GetFont()->CalcTextSizeA(size, FLT_MAX, 0.0f, name.c_str())}; + ImVec2 const corner{middle.x - text.x * 0.5f, middle.y - text.y - 22.0f}; + drawlist->AddRectFilled(ImVec2(corner.x - 6.0f, corner.y - 3.0f), ImVec2(corner.x + text.x + 6.0f, corner.y + text.y + 3.0f), IM_COL32(10, 20, 30, 210), 4.0f); + drawlist->AddText(ImGui::GetFont(), size, corner, IM_COL32(200, 250, 255, 255), name.c_str()); + drawlist->AddLine(ImVec2(middle.x, corner.y + text.y + 3.0f), middle, IM_COL32(200, 250, 255, 200), 1.5f); + } + } + ImVec2 pointed; + if (route.band.at >= 0.0 && projection.project(alignment::evaluate(result, std::min(route.band.at, result.length)).position, pointed)) + { + drawlist->AddCircleFilled(pointed, 5.0f, overlay_color::highlight); + drawlist->AddCircle(pointed, 10.0f, overlay_color::highlight, 20, 2.0f); + } + } + + for (auto const atend : {false, true}) + { + auto const &point{atend ? end : start}; + auto const direction{atend ? design.end_direction : design.start_direction}; + ImVec2 screen; + if (projection.project(point, screen)) + drawlist->AddRectFilled(ImVec2(screen.x - 5.0f, screen.y - 5.0f), ImVec2(screen.x + 5.0f, screen.y + 5.0f), IM_COL32(70, 140, 255, 255)); + auto const arrow{glm::dvec3{direction.x, 0.0, direction.y} * (atend ? 15.0 : -15.0)}; + projection.line(drawlist, point, point + arrow, IM_COL32(70, 140, 255, 255), 2.0f); + } + for (int i = 0; i < static_cast(design.vertices.size()); ++i) + { + ImVec2 screen; + if (false == projection.project(route_vertex_position(i), screen)) + continue; + drawlist->AddCircleFilled(screen, 6.0f, overlay_color::marked); + if (i == route.vertex) + drawlist->AddCircle(screen, 11.0f, overlay_color::highlight, 16, 2.5f); + if (i < static_cast(result.vertex_chainages.size()) && result.length > 0.0 && projection.project(alignment::evaluate(result, result.vertex_chainages[i]).position, screen)) + { + drawlist->AddCircleFilled(screen, 6.0f, overlay_color::grip, 4); + if (i == route.grip) + drawlist->AddCircle(screen, 11.0f, overlay_color::highlight, 16, 2.5f); + auto const *report{i < static_cast(result.curves.size()) ? &result.curves[i] : nullptr}; + auto radius{format("R %.0f", report != nullptr ? report->radius : design.vertices[i].radius)}; + if (report != nullptr && report->radii.size() >= 2) + { + radius = "R"; + for (std::size_t k = 0; k < report->radii.size(); ++k) + radius += format(k == 0 ? " %.0f" : " / %.0f", report->radii[k]); + } + drawlist->AddText(ImVec2(screen.x + 9.0f, screen.y + 4.0f), overlay_color::grip, radius.c_str()); + } + drawlist->AddText(ImVec2(screen.x + 9.0f, screen.y - 18.0f), overlay_color::marked, format("W%d", i + 1).c_str()); + } + // the points clicked when the line was laid, in the colours of their departure; how far each is, along the curve in focus + for (std::size_t i = 0; i < route.clicks.size() && i < route.click_states.size(); ++i) + { + auto const &state{route.click_states[i]}; + ImVec2 screen; + if (state.corner || std::abs(state.offset) > 3.0 || false == projection.project(route.clicks[i], screen)) + continue; + auto const departure{std::abs(state.offset)}; + auto const colour{departure <= 0.1 ? IM_COL32(90, 220, 110, 255) : departure <= 0.3 ? IM_COL32(255, 200, 60, 255) : IM_COL32(255, 90, 70, 255)}; + drawlist->AddCircleFilled(screen, 4.5f, IM_COL32(0, 0, 0, 200), 12); + drawlist->AddCircleFilled(screen, 3.0f, colour, 12); + if (state.vertex == route.focus.vertex) + drawlist->AddText(ImVec2(screen.x + 7.0f, screen.y - 7.0f), colour, format("%.0f cm", departure * 100.0).c_str()); + } + if (route.trace.points.empty()) + return; + std::vector plan; + for (auto const &point : route.trace.points) + plan.push_back(plan_of(point)); + auto const projections{alignment::project(result, plan)}; + auto const hit{route_trace_hit()}; + for (std::size_t i = 0; i < route.trace.points.size(); ++i) + { + ImVec2 screen; + if (false == projection.project(route.trace.points[i], screen)) + continue; + auto const departure{i < projections.size() ? std::abs(projections[i].offset) : 0.0}; + auto const colour{departure <= 0.1 ? IM_COL32(90, 220, 110, 255) : departure <= 0.3 ? IM_COL32(255, 200, 60, 255) : IM_COL32(255, 90, 70, 255)}; + drawlist->AddCircle(screen, 5.0f, IM_COL32(0, 0, 0, 200), 12, 3.5f); + drawlist->AddCircle(screen, 5.0f, colour, 12, 2.0f); + if (static_cast(i) == hit) + drawlist->AddCircle(screen, 10.0f, overlay_color::highlight, 16, 2.0f); + if (i < projections.size()) + drawlist->AddText(ImVec2(screen.x + 8.0f, screen.y - 7.0f), colour, format("%.0f cm", departure * 100.0).c_str()); + } +} + +void editor_mode::render_route_trace() +{ + auto &trace{m_route.trace}; + // the curve is traced on the photo with the laying (Tab), the plan has no button of its own for it + if (false == trace.active) + return; + ImGui::SeparatorText(STR_C("Tracing the curve")); + if (segmented("traceradii", trace.radii, + {{0, STR_C("Auto"), "As few radii as follow the points, up to three"}, {1, STR_C("1 R"), "One radius"}, {2, STR_C("2 R"), "A compound curve of two radii"}, {3, STR_C("3 R"), "A compound curve of three radii"}})) + route_trace_fit(); + if (trace.points.empty()) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("Click points along the middle of the track on the photo, spread over the whole curve; a few on the straights at its ends help too")); + ImGui::PopTextWrapPos(); + } + else + { + auto const colour = [](double const Departure) { return Departure <= 0.1 ? IM_COL32(90, 220, 110, 255) : Departure <= 0.3 ? IM_COL32(255, 200, 60, 255) : IM_COL32(255, 90, 70, 255); }; + metric_tiles({{format("%zu", trace.points.size()), STR_C("points"), ImGui::GetColorU32(ImGuiCol_Text)}, + {format("%.0f cm", trace.rms * 100.0), STR_C("departure"), colour(trace.rms)}, + {format("%.0f cm", trace.worst * 100.0), STR_C("at most"), colour(trace.worst)}}); + } + if (main_button(STR_C("Apply Enter"), ImVec2(-1.0f, 0.0f))) + route_trace_end(true); + if (ImGui::Button(STR_C("Drop Esc"))) + route_trace_end(false); + ImGui::SameLine(); + ImGui::BeginDisabled(trace.points.empty()); + if (ImGui::Button(STR_C("Take out the last point Backspace"))) + { + trace.points.pop_back(); + route_trace_fit(); + } + ImGui::EndDisabled(); +} + +void editor_mode::route_trace_start() +{ + auto &trace{m_route.trace}; + trace.active = true; + trace.points.clear(); + trace.before = m_route.design; + trace.rms = 0.0; + trace.worst = 0.0; +} + +// every point goes to the curve nearest to it along the line, the curves without points keep their shape +void editor_mode::route_trace_fit() +{ + auto &route{m_route}; + auto &trace{route.trace}; + auto design{route.design}; + trace.rms = 0.0; + trace.worst = 0.0; + if (trace.points.empty() || design.vertices.empty() || false == route.result.valid) + return; + std::vector plan; + for (auto const &point : trace.points) + plan.push_back(plan_of(point)); + auto const projections{alignment::project(route.result, plan)}; + std::vector> owned(design.vertices.size()); + for (std::size_t i = 0; i < plan.size(); ++i) + { + std::size_t nearest{0}; + for (std::size_t k = 1; k < route.result.vertex_chainages.size() && k < owned.size(); ++k) + if (std::abs(route.result.vertex_chainages[k] - projections[i].chainage) < std::abs(route.result.vertex_chainages[nearest] - projections[i].chainage)) + nearest = k; + owned[nearest].push_back(plan[i]); + } + for (std::size_t k = 0; k < owned.size(); ++k) + { + if (owned[k].empty()) + continue; + auto const fit{alignment::fit_trace(design, k, owned[k], trace.radii)}; + if (fit.valid) + design.vertices[k] = fit.fitted; + } + route.design = design; + route_update(); + double sum{0.0}; + for (auto const &projection : alignment::project(route.result, plan)) + { + sum += projection.offset * projection.offset; + trace.worst = std::max(trace.worst, std::abs(projection.offset)); + } + trace.rms = std::sqrt(sum / static_cast(plan.size())); +} + +void editor_mode::route_trace_end(bool const Keep) +{ + auto &trace{m_route.trace}; + if (false == trace.active) + return; + auto const traced{false == trace.points.empty()}; + if (false == Keep) + { + m_route.design = trace.before; + route_update(); + } + trace = {}; + if (Keep && traced) + route_apply(); +} + +// the photo under the cursor where the depth finds it, else the level of the design there +glm::dvec3 editor_mode::route_trace_cursor() const +{ + if (GfxRenderer->Mouse_Hit()) + return cursor_ground(); + auto const &result{m_route.result}; + auto point{cursor_level(alignment::elevation(result, result.length * 0.5))}; + if (auto const projections{alignment::project(result, {plan_of(point)})}; false == projections.empty()) + point = cursor_level(alignment::elevation(result, projections.front().chainage)); + return point; +} + +int editor_mode::route_trace_hit() const +{ + screen_projection const projection; + float best{kHandleRadius * kHandleRadius}; + int hit{-1}; + for (int i = 0; i < static_cast(m_route.trace.points.size()); ++i) + if (auto const distance{projection.mouse_distance2(m_route.trace.points[i])}; distance < best) + { + best = distance; + hit = i; + } + return hit; +} + +void editor_mode::render_route_gizmo() +{ + auto &route{m_route}; + auto const count{static_cast(route.design.vertices.size())}; + bool const grip{route.grip >= 0 && route.grip < count && route.grip < static_cast(route.result.vertex_chainages.size())}; + if (false == grip && (route.vertex < 0 || route.vertex >= count)) + { + m_route_dragging = false; + return; + } + + auto const position{grip ? alignment::evaluate(route.result, route.result.vertex_chainages[route.grip]).position : route_vertex_position(route.vertex)}; + glm::dvec3 moved{position}; + if (false == handle_drag_step(moved)) + { + if (m_route_dragging) + { + m_route_dragging = false; + route_apply(); + } + return; + } + if (false == m_route_dragging) + m_route_drag_from = route.design; + m_route_dragging = true; + if (grip) + { + auto &vertex{route.design.vertices[route.grip]}; + auto const corner{route_vertex_position(route.grip)}; + auto const distance{plan_distance(moved, corner)}; + for (auto const &curve : route.result.curves) + { + if (curve.vertex != route.grip || vertex.reverse_turn) + continue; + auto const secant{1.0 / std::cos(curve.deflection * 0.5) - 1.0}; + if (secant > 1e-6) + vertex.radius = std::max(10.0, std::round(distance / secant)); + } + route_update(); + return; + } + auto &vertex{route.design.vertices[route.vertex]}; + glm::dvec2 const point{moved.x, moved.z}; + if (count >= 2) + { + if (route.vertex == 0) + vertex.offset = std::max(0.1, glm::dot(point - plan_of(route.design.start), glm::normalize(route.design.start_direction))); + else if (route.vertex == count - 1) + vertex.offset = std::max(0.1, glm::dot(plan_of(route.design.end) - point, glm::normalize(route.design.end_direction))); + else + vertex.position = point; + } + route_update(); +} + +void editor_mode::render_route_ui() +{ + auto &route{m_route}; + if (false == route.error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.35f, 0.3f, 1.0f), "%s", route.error.c_str()); + if (route.chain.tracks.empty()) + return; + + ImGui::AlignTextToFramePadding(); + ImGui::TextDisabled(STR_P("%zu path, %.2f m", "%zu paths, %.2f m", route.chain.tracks.size()), route.chain.tracks.size(), route.chain.length); + auto const reset{STR_C("Reset design")}; + auto const reset_width{ImGui::CalcTextSize(reset).x + ImGui::GetStyle().FramePadding.x * 2.0f}; + ImGui::SameLine(std::max(ImGui::GetCursorPosX(), ImGui::GetWindowContentRegionMax().x - reset_width)); + if (ImGui::Button(reset)) + { + auto *track{route.chain.tracks[route.chain.tracks.size() / 2]}; + route_load(*track); + return; + } + item_tooltip("Reads the curves of the line from the scenery again, dropping the changes not applied"); + auto changed{render_route_band()}; + render_route_trace(); + render_route_stored(); + changed |= render_route_vertices(); + if (ImGui::CollapsingHeader(STR_C("Design speed and limits"))) + changed |= render_route_parameters(); + if (changed) + route_update(); + + ImGui::Separator(); + render_route_result(); + + if (ImGui::CollapsingHeader(STR_C("Digitize the whole scenery"))) + { + ImGui::PushTextWrapPos(0.0f); + ImGui::TextDisabled("%s", STR_C("Keeps the plan of the lines in the scenery as straights, arcs and transitions, so the tools can edit them; the paths stay as they are")); + ImGui::PopTextWrapPos(); + if (ImGui::Button(STR_C("Digitize all the tracks"))) + { + digitize_all(); + return; + } + item_tooltip("Every line of the scenery not digitized yet is kept in it with its straights, arcs and transition curves, the way the drawn tracks are kept; the paths stay as they are"); + ImGui::SameLine(); + if (ImGui::Button(STR_C("Digitize the scenery"))) + { + digitize_scenery(true); + return; + } + item_tooltip("All at once: the lines, the switches with their types out of the catalogue (or the size measured from their shape), the crossovers as connections of switches and the signals, signs, poles and catenary bound to the tracks. The paths and the objects stay as they are, the scenery keeps it on save"); + } +} + +// the curvature along the fragment, the way the designers draw it: straights on the axis, the transitions as ramps, +// the arcs as plateaus at 1/R, in the colours of the overlay in the view. dragging a plateau changes its radius, +// dragging a ramp sideways the length of the transition, the wheel does both in steps +bool editor_mode::render_route_band() +{ + auto &route{m_route}; + auto &design{route.design}; + auto const &result{route.result}; + auto &band{route.band}; + band.hot = -1; + band.at = -1.0; + if (result.elements.empty() || result.length <= 1e-3 || design.vertices.empty()) + { + band.vertex = -1; + return false; + } + auto const font{ImGui::GetFontSize()}; + auto const pad{std::round(font * 0.5f)}; + auto const width{ImGui::GetContentRegionAvail().x}; + auto const height{std::round(font * 6.0f)}; + auto const top{ImGui::GetCursorScreenPos()}; + ImGui::InvisibleButton("##curvature", ImVec2(width, height)); + ImGui::SetItemKeyOwner(ImGuiKey_MouseWheelY); + auto const hovered{ImGui::IsItemHovered()}; + auto const active{ImGui::IsItemActive()}; + auto *list{ImGui::GetWindowDrawList()}; + ImVec2 const bottom{top.x + width, top.y + height}; + list->AddRectFilled(top, bottom, ImGui::GetColorU32(ImGuiCol_FrameBg), std::round(font * 0.35f)); + + auto const ends = [](alignment::element const &Element) -> std::pair { + auto const sign{static_cast(Element.turn)}; + auto const [start, end]{alignment::end_curvatures(Element)}; + return {sign * start, sign * end}; + }; + auto const colour = [](alignment::element const &Element) { + return Element.kind == alignment::element_kind::straight ? IM_COL32(255, 255, 255, 230) : Element.kind == alignment::element_kind::arc ? overlay_color::grip : IM_COL32(255, 140, 30, 255); + }; + double peak{0.0}; + bool left{false}, right{false}; + for (auto const &element : result.elements) + { + auto const [from, to]{ends(element)}; + peak = std::max({peak, std::abs(from), std::abs(to)}); + left |= from > 1e-9 || to > 1e-9; + right |= from < -1e-9 || to < -1e-9; + } + auto const line{ImGui::GetTextLineHeight()}; + auto const inner_left{top.x + pad}; + auto const inner_width{width - 2.0f * pad}; + auto const plot_top{top.y + pad * 0.5f + line}; + auto const plot_bottom{bottom.y - pad * 0.5f - line}; + auto const both{left && right}; + auto const axis{both ? std::round((plot_top + plot_bottom) * 0.5f) : plot_bottom}; + // the curves to one side only grow upwards + auto const flip{(false == both && right) ? -1.0f : 1.0f}; + auto const dragging{band.vertex >= 0}; + auto const metres{dragging ? band.metres : inner_width / static_cast(result.length)}; + auto const curvature{dragging ? band.curvature : (peak > 0.0 ? (axis - plot_top) * 0.85f / static_cast(peak) : 0.0f)}; + auto const x_of = [&](double const Chainage) { return inner_left + static_cast(Chainage) * metres; }; + auto const y_of = [&](double const K) { return axis - flip * static_cast(K) * curvature; }; + auto const mouse{ImGui::GetIO().MousePos}; + auto const count{static_cast(result.elements.size())}; + + // what of its vertex each element is: an arc, the arcs of a compound curve counted from the first one, which are elements of an even + // curvature as an arc is, or a transition, in from the straight, out to it, or between two arcs, which goes on from the arc before it + struct role + { + int part{0}; + int arc{0}; + }; + std::vector roles(static_cast(count)); + std::vector arcs(design.vertices.size(), 0); + { + int vertex{-1}; + int arc{-1}; + double last{0.0}; + for (int i = 0; i < count; ++i) + { + auto const &element{result.elements[i]}; + if (element.vertex != vertex) + { + vertex = element.vertex; + arc = -1; + last = 0.0; + } + if (element.vertex < 0 || element.vertex >= static_cast(design.vertices.size()) || element.kind == alignment::element_kind::straight) + continue; + auto const [from, to]{ends(element)}; + if (element.kind == alignment::element_kind::arc || (std::abs(from - to) <= 1e-6 * std::abs(from) && std::abs(from) > 1e-9)) + { + // the next arc where the curvature isn't the one of the arc before, an arc cut in parts staying one + if (arc < 0 || std::abs(std::abs(from) - last) > 1e-6 * std::abs(from)) + ++arc; + last = std::abs(from); + roles[i] = {1, arc}; + arcs[element.vertex] = std::max(arcs[element.vertex], arc + 1); + } + else + roles[i] = std::abs(from) <= 1e-9 ? role{2, 0} : std::abs(to) <= 1e-9 ? role{3, 0} : role{4, arc + 1}; + } + } + // the element under the mouse and what of it a drag changes: near the ends of a plateau the transitions either side of it, also the + // ones of no length yet + int under{-1}; + int part{0}; + int arc{0}; + if (hovered && false == dragging) + { + for (int i = 0; i < count; ++i) + { + auto const &element{result.elements[i]}; + if (mouse.x < x_of(element.chainage) || mouse.x >= x_of(element.chainage + element.length)) + continue; + under = i; + part = roles[i].part; + arc = roles[i].arc; + if (part == 1) + { + auto const from{x_of(element.chainage)}; + auto const to{x_of(element.chainage + element.length)}; + auto const edge{std::min(std::round(font * 0.5f), (to - from) * 0.25f)}; + if (mouse.x < from + edge) + part = arc == 0 ? 2 : 4; + else if (mouse.x >= to - edge) + { + part = arc + 1 >= arcs[element.vertex] ? 3 : 4; + arc += 1; + } + } + break; + } + } + auto const value_of = [&](int const Vertex, int const Part, int const Arc) -> double & { + auto &vertex{design.vertices[Vertex]}; + auto const later{Arc >= 1 && Arc <= static_cast(vertex.arcs.size())}; + switch (Part) + { + case 1: return later ? vertex.arcs[Arc - 1].radius : vertex.radius; + case 2: return vertex.transition_in; + case 3: return vertex.transition_out; + default: return later ? vertex.arcs[Arc - 1].transition : vertex.transition_in; + } + }; + auto const rounded_radius = [](double const Radius) { + auto const step{Radius < 1000.0 ? 1.0 : 10.0}; + return std::clamp(std::round(Radius / step) * step, 10.0, 100000.0); + }; + bool changed{false}; + if (part != 0 && ImGui::IsItemActivated()) + { + band.vertex = result.elements[under].vertex; + band.part = part; + band.arc = arc; + band.value = value_of(band.vertex, part, arc); + band.press = mouse; + band.metres = metres; + band.curvature = curvature; + } + if (band.vertex >= 0 && band.vertex < static_cast(design.vertices.size()) && active) + { + auto &value{value_of(band.vertex, band.part, band.arc)}; + double wanted{value}; + if (band.part == 1) + { + int turn{1}; + for (auto const &element : result.elements) + if (element.vertex == band.vertex && element.turn != 0) + turn = element.turn; + auto const start{y_of(turn / std::max(1.0, band.value)) + (mouse.y - band.press.y)}; + auto const k{(axis - start) * flip * turn / std::max(1e-6f, curvature)}; + wanted = rounded_radius(1.0 / std::max(1e-5, static_cast(k))); + } + else + { + // the transition in grows to the left, from where it starts; the others to the right + auto const shift{(mouse.x - band.press.x) / std::max(1e-6f, metres)}; + wanted = std::max(0.0, std::round(band.value + (band.part == 2 ? -shift : shift))); + } + if (wanted != value) + { + value = wanted; + changed = true; + } + ImGui::SetMouseCursor(band.part == 1 ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW); + } + else if (dragging && false == active) + { + band.vertex = -1; + } + if (part != 0) + { + ImGui::SetMouseCursor(part == 1 ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW); + if (auto const wheel{ImGui::GetIO().MouseWheel}; wheel != 0.0f) + { + auto &value{value_of(result.elements[under].vertex, part, arc)}; + value = part == 1 ? rounded_radius(value * (wheel > 0.0f ? 0.95 : 1.0 / 0.95)) : std::max(0.0, std::round(value / 5.0) * 5.0 + (wheel > 0.0f ? 5.0 : -5.0)); + changed = true; + } + } + + ImGui::PushClipRect(top, bottom, true); + auto const disabled{ImGui::GetColorU32(ImGuiCol_TextDisabled)}; + list->AddLine(ImVec2(inner_left, axis), ImVec2(inner_left + inner_width, axis), ImGui::GetColorU32(ImGuiCol_TextDisabled, 0.5f)); + auto const hot_vertex{dragging ? band.vertex : under >= 0 ? result.elements[under].vertex : -1}; + for (int i = 0; i < count; ++i) + { + auto const &element{result.elements[i]}; + auto const [from, to]{ends(element)}; + ImVec2 const a{x_of(element.chainage), y_of(from)}; + ImVec2 const b{x_of(element.chainage + element.length), y_of(to)}; + auto const lit{element.vertex >= 0 && element.vertex == hot_vertex}; + auto const tint{colour(element)}; + if (element.kind != alignment::element_kind::straight) + list->AddQuadFilled(ImVec2(a.x, axis), a, b, ImVec2(b.x, axis), (tint & ~IM_COL32_A_MASK) | (lit ? IM_COL32(0, 0, 0, 90) : IM_COL32(0, 0, 0, 40))); + list->AddLine(a, b, tint, lit ? 3.0f : 2.0f); + if (i > 0) + list->AddLine(ImVec2(a.x, axis - 3.0f), ImVec2(a.x, axis + 3.0f), disabled); + } + // the labels: the radius over its plateau, the transition lengths along the axis, the km of the ends at the bottom + std::vector> taken; + auto const place = [&](float const Left, float const Right) { + for (auto const &range : taken) + if (Left < range.second + 4.0f && Right > range.first - 4.0f) + return false; + taken.emplace_back(Left, Right); + return true; + }; + auto const start_km{format("km %s", profile::format_chainage(route.origin).c_str())}; + auto const end_km{format("km %s", profile::format_chainage(route.origin + result.length).c_str())}; + auto const label_y{bottom.y - pad * 0.25f - line}; + auto const start_size{ImGui::CalcTextSize(start_km.c_str())}; + auto const end_size{ImGui::CalcTextSize(end_km.c_str())}; + place(inner_left, inner_left + start_size.x); + list->AddText(ImVec2(inner_left, label_y), disabled, start_km.c_str()); + if (place(inner_left + inner_width - end_size.x, inner_left + inner_width)) + list->AddText(ImVec2(inner_left + inner_width - end_size.x, label_y), disabled, end_km.c_str()); + for (auto const &element : result.elements) + { + auto const from{x_of(element.chainage)}; + auto const to{x_of(element.chainage + element.length)}; + auto const middle{(from + to) * 0.5f}; + if (dragging && element.vertex == band.vertex) + continue; + if (element.kind == alignment::element_kind::arc || (element.kind == alignment::element_kind::spiral && element.curvature_start == element.curvature_end && element.radius > 0.0)) + { + auto const &vertex{design.vertices[std::clamp(element.vertex, 0, static_cast(design.vertices.size()) - 1)]}; + auto text{format("R %.0f", element.radius)}; + if (vertex.cant > 0.0) + { + auto const longer{text + format(" \xc2\xb7 %.0f mm", vertex.cant)}; + if (ImGui::CalcTextSize(longer.c_str()).x <= to - from) + text = longer; + } + auto const size{ImGui::CalcTextSize(text.c_str())}; + auto const y{ends(element).first * flip >= 0.0 ? y_of(ends(element).first) - size.y - 1.0f : y_of(ends(element).first) + 1.0f}; + if (size.x <= std::max(to - from, size.x * 0.8f)) + list->AddText(ImVec2(std::round(middle - size.x * 0.5f), std::round(std::max(top.y + 1.0f, y))), colour(element), text.c_str()); + } + else if (element.kind == alignment::element_kind::transition_in || element.kind == alignment::element_kind::transition_out) + { + auto const text{format("%.0f m", element.length)}; + auto const size{ImGui::CalcTextSize(text.c_str())}; + if (both) + { + auto const y{ends(element).first + ends(element).second > 0.0 ? axis + 2.0f : axis - size.y - 2.0f}; + if (size.x <= to - from + 8.0f) + list->AddText(ImVec2(std::round(middle - size.x * 0.5f), std::round(y)), colour(element), text.c_str()); + } + else if (place(middle - size.x * 0.5f, middle + size.x * 0.5f)) + list->AddText(ImVec2(std::round(middle - size.x * 0.5f), label_y), colour(element), text.c_str()); + } + } + // the point under the mouse, shown in the view too + if (hovered || dragging) + { + auto const at{std::clamp(static_cast((mouse.x - inner_left) / std::max(1e-6f, metres)), 0.0, result.length)}; + band.at = at; + band.hot = dragging ? -1 : under; + if (false == dragging) + list->AddLine(ImVec2(mouse.x, plot_top), ImVec2(mouse.x, plot_bottom), IM_COL32(255, 255, 255, 60)); + } + if (dragging && band.vertex >= 0 && band.vertex < static_cast(design.vertices.size())) + { + auto const value{value_of(band.vertex, band.part, band.arc)}; + auto const text{band.part == 1 ? format("R %.0f m", value) : format("%.0f m", value)}; + auto const size{ImGui::CalcTextSize(text.c_str())}; + ImVec2 const at{std::clamp(mouse.x + pad, top.x, bottom.x - size.x - pad), std::clamp(mouse.y - size.y - pad, top.y, bottom.y - size.y)}; + list->AddRectFilled(ImVec2(at.x - 3.0f, at.y - 1.0f), ImVec2(at.x + size.x + 3.0f, at.y + size.y + 1.0f), IM_COL32(0, 0, 0, 170), 3.0f); + list->AddText(at, IM_COL32(255, 255, 255, 255), text.c_str()); + } + ImGui::PopClipRect(); + if (changed) + first_step_done(first_step::plan_band); + + if (part != 0 && false == dragging && ImGui::IsItemHovered(ImGuiHoveredFlags_ForTooltip)) + { + auto const index{result.elements[under].vertex}; + auto const &vertex{design.vertices[index]}; + auto const value{value_of(index, part, arc)}; + ImGui::BeginTooltip(); + if (part == 1 && arcs[index] > 1) + ImGui::Text(STR_C("Curve %d, arc R%d: %.0f m"), index + 1, arc + 1, value); + else if (part == 1) + ImGui::Text(STR_C("Curve %d: R %.0f m, cant %.0f mm"), index + 1, value, vertex.cant); + else if (part == 4) + ImGui::Text(STR_C("Curve %d, transition between R%d and R%d: %.0f m"), index + 1, arc, arc + 1, value); + else + ImGui::Text(part == 2 ? STR_C("Transition into curve %d: %.0f m") : STR_C("Transition out of curve %d: %.0f m"), index + 1, value); + gesture_rows({{"Drag", part == 1 ? "up or down: the radius" : "sideways: the length"}, {"Wheel", part == 1 ? "the radius by 5%" : "the length by 5 m"}}); + ImGui::EndTooltip(); + } + return changed; +} + +bool editor_mode::render_route_parameters() +{ + auto &design{m_route.design}; + bool changed{false}; + ImGui::TextDisabled("%s", STR_C("Design speed (km/h)")); + ImGui::SetNextItemWidth(-FLT_MIN); + changed |= ImGui::InputDouble("##designspeed", &design.speed, 10.0, 20.0, "%.0f"); + item_tooltip("Speed the cant, the transitions and the recommended radius are designed for"); + changed |= value_chips("designspeeds", design.speed, {60.0, 80.0, 100.0, 120.0, 160.0, 200.0}, "%.0f"); + design.speed = std::max(1.0, design.speed); + ImGui::TextDisabled("%s", STR_C("Transition curve")); + int shape = static_cast(design.shape); + if (segmented("transitionshape", shape, + {{static_cast(alignment::transition_shape::cubic_parabola), STR_C("Cubic parabola"), "The usual one on the Polish lines"}, + {static_cast(alignment::transition_shape::clothoid), STR_C("Clothoid"), "Curvature growing linearly with the length"}})) + { + design.shape = static_cast(shape); + changed = true; + } + + if (ImGui::TreeNode(STR_C("Norms"))) + { + auto &norms{design.norms}; + if (begin_fields("##routelimits", 0.6f)) + { + auto const limit = [&](char const *Label, char const *Id, double &Value, char const *Format) { + field_row(Label); + changed |= ImGui::InputDouble(Id, &Value, 0.0, 0.0, Format); + }; + limit("Rail axes distance (mm)", "##gauge", norms.gauge, "%.0f"); + limit("Unbalanced acceleration (m/s2)", "##unbalanced", norms.unbalanced, "%.2f"); + limit("Maximum cant (mm)", "##cantmax", norms.cant_max, "%.0f"); + limit("Cant change rate (mm/s)", "##cantrate", norms.cant_rate, "%.0f"); + limit("Cant ramp 1:(k*V), k", "##ramp", norms.ramp_factor, "%.1f"); + limit("Unbalanced acc. change rate (m/s3)", "##jerk", norms.jerk, "%.2f"); + limit("Straight between curves (s of travel)", "##tangent", norms.tangent_min_time, "%.1f"); + ImGui::EndTable(); + } + norms.gauge = std::max(100.0, norms.gauge); + norms.cant_rate = std::max(1.0, norms.cant_rate); + norms.jerk = std::max(0.01, norms.jerk); + ImGui::TreePop(); + } + return changed; +} + +bool editor_mode::render_route_vertices() +{ + bool changed{false}; + auto const count{static_cast(m_route.design.vertices.size())}; + m_route.focus = {}; + route_measure_clicks(); + if (false == m_route.clicks.empty()) + { + ImGui::Checkbox(STR_C("Keep to the points clicked"), &m_route.hold); + item_tooltip("The scenery keeps the points clicked when the line was laid: a curve whose transitions or cants are changed gets its radii fitted to them again, so it stays where it was seen on the photo"); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Fit all to them"))) + { + for (int i = 0; i < count; ++i) + changed |= route_hold_clicks(i); + } + item_tooltip("The radii of every curve fitted again to the points clicked along it, the transitions and the cants as they are"); + } + for (int i = 0; i < count; ++i) + { + ImGui::PushID(i); + changed |= render_route_vertex(i); + ImGui::PopID(); + } + return changed; +} + +bool editor_mode::render_route_vertex(int const Index) +{ + auto &route{m_route}; + auto &design{route.design}; + auto &vertex{design.vertices[Index]}; + bool changed{false}; + // a transition or a cant changed, the edit done: the curve fitted to the points clicked again, its radii given by them + bool settled{false}; + using part = route_design::curve_focus::part; + // the field just drawn shows its part of the curve in the view while the mouse is over it or it's being edited + auto const mark = [&](part const What, int const Arc) { + if (ImGui::IsItemActive()) + route.focus = {Index, What, Arc, true}; + else if (false == route.focus.held && ImGui::IsItemHovered()) + route.focus = {Index, What, Arc, false}; + }; + ImGui::BeginGroup(); + // named as the vertex is in the view, W1, W2..., with where it lies along the line + { + auto from{-1.0}; + auto to{-1.0}; + for (auto const &e : route.result.elements) + if (e.vertex == Index) + { + from = from < 0.0 ? e.chainage : from; + to = e.chainage + e.length; + } + auto title{format(STR_C("Curve W%d"), Index + 1)}; + if (from >= 0.0) + title += format(" km %s - %s", profile::format_chainage(route.origin + from).c_str(), profile::format_chainage(route.origin + to).c_str()); + // the vertex picked in the view stands out + auto const picked{route.vertex == Index || route.grip == Index}; + if (picked) + ImGui::PushStyleColor(ImGuiCol_Text, ImGui::ColorConvertU32ToFloat4(overlay_color::highlight)); + ImGui::SeparatorText(title.c_str()); + if (picked) + ImGui::PopStyleColor(); + mark(part::whole, 0); + if (from >= 0.0) + { + if (ImGui::SmallButton(STR_C("Show in the view"))) + route_show_curve(from, to); + item_tooltip("The camera flies over the curve, which is lit up in the view while the mouse is over its fields"); + mark(part::whole, 0); + } + // how far the curve is from the points clicked along it when it was laid + std::size_t clicked{0}; + double sum{0.0}; + double worst{0.0}; + for (auto const &state : route.click_states) + if (state.vertex == Index && false == state.corner && std::abs(state.offset) <= 3.0) + { + ++clicked; + sum += state.offset * state.offset; + worst = std::max(worst, std::abs(state.offset)); + } + if (clicked > 0) + { + ImGui::SameLine(); + auto const colour{worst <= 0.1 ? ImVec4(0.35f, 0.86f, 0.43f, 1.0f) : worst <= 0.3 ? ImVec4(1.0f, 0.78f, 0.24f, 1.0f) : ImVec4(1.0f, 0.35f, 0.27f, 1.0f)}; + ImGui::TextColored(colour, STR_C("points clicked %zu: %.0f cm on average, at most %.0f cm"), clicked, std::sqrt(sum / static_cast(clicked)) * 100.0, worst * 100.0); + item_tooltip("The points clicked along the curve when it was laid, kept in the scenery, and how far the curve is from them now"); + mark(part::whole, 0); + if (clicked >= 3) + { + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Fit to them"))) + changed |= route_hold_clicks(Index); + item_tooltip("The radii of the curve and their shares fitted again to the points clicked, the transitions and the cants as they are"); + } + } + } + // two fields in a row, the name and the unit inside them, a bar in the colour of the element in the band and in the view + auto const half{std::floor((ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f)}; + auto const field = [&](char const *Id, double &Value, float const Speed, char const *Format, ImU32 const Colour, char const *Tooltip, part const What) { + ImGui::SetNextItemWidth(half); + auto const edited{ImGui::DragScalar(Id, ImGuiDataType_Double, &Value, Speed, nullptr, nullptr, Format)}; + // the radius is the user's own, the curve no longer fitted after it + settled |= What != part::arc && ImGui::IsItemDeactivatedAfterEdit(); + mark(What, 0); + auto const low{ImGui::GetItemRectMin()}; + auto const high{ImGui::GetItemRectMax()}; + ImGui::GetWindowDrawList()->AddRectFilled(low, ImVec2(low.x + 3.0f, high.y), Colour, 2.0f, ImDrawFlags_RoundCornersLeft); + item_tooltip(Tooltip); + return edited; + }; + ImU32 const transition{IM_COL32(255, 140, 30, 255)}; + // the first curve, or the last one, may go on from the curve of the track adjoining at that end: it begins right there, its radius + // the one which begins it there, its entry, or exit, the transition between the two curves + auto const count{static_cast(design.vertices.size())}; + for (auto const atend : {false, true}) + { + auto const radius{atend ? design.end_radius : design.start_radius}; + if ((atend ? Index + 1 != count : Index != 0) || radius <= 0.0 || radius >= 10000.0 || (atend && count == 1 && design.start_curved)) + continue; + auto &curved{atend ? design.end_curved : design.start_curved}; + changed |= ImGui::Checkbox((format(atend ? STR_C("Goes into the curve of the track at the end (R %.0f m)") : STR_C("Goes on from the curve of the track at the start (R %.0f m)"), radius) + (atend ? "##curvedend" : "##curvedstart")).c_str(), &curved); + item_tooltip("The curve begins right at the end of the fragment, at the curvature of the track adjoining there, where it turns the same way; its radius is the one " + "which begins it there, the transition at that end goes between the two curves"); + } + changed |= field("##radius", vertex.radius, 5.0f, vertex.compound ? STR_C("R1 %.0f m") : STR_C("R %.0f m"), overlay_color::grip, "Radius of the arc: drag sideways, or a double click to type it", part::arc); + ImGui::SameLine(); + changed |= field("##cant", vertex.cant, 1.0f, STR_C("cant %.0f mm"), IM_COL32(240, 170, 60, 255), + vertex.compound ? "Height of the outer rail above the inner one on the sharpest arc; the arcs with no cant of their own get it in proportion to their curvature" + : "Height of the outer rail above the inner one", + part::whole); + changed |= field("##entry", vertex.transition_in, 1.0f, STR_C("entry %.0f m"), transition, "Length of the transition curve leading into the arc", part::entry); + ImGui::SameLine(); + changed |= field("##exit", vertex.transition_out, 1.0f, STR_C("exit %.0f m"), transition, "Length of the transition curve leading out of the arc", part::exit); + ImGui::PushItemWidth(110.0f); + if (ImGui::Checkbox(STR_C("Two transition curves, no arc"), &vertex.spirals)) + { + changed = true; + if (vertex.spirals) + vertex.compound = false; + } + item_tooltip("The bend eased the way the lines are drawn: two transition curves meeting at the radius, with no arc between them and no cant; their lengths follow from the radius and the angle"); + if (false == vertex.spirals && ImGui::Checkbox(STR_C("Compound curve (several radii)"), &vertex.compound)) + { + changed = true; + if (vertex.compound && vertex.arcs.empty()) + vertex.arcs.push_back({std::max(10.0, std::round(vertex.radius * 0.6 / 10.0) * 10.0), 0.0, 1.0}); + } + if (false == vertex.spirals) + item_tooltip("Curve made of arcs of different radii, each one its own path, joined with transitions"); + if (vertex.compound) + { + auto total{std::max(0.0, vertex.share)}; + for (auto const &arc : vertex.arcs) + total += std::max(0.0, arc.share); + auto const percent = [&](double const Share) { return total > 0.0 ? 100.0 * std::max(0.0, Share) / total : 0.0; }; + auto const cants{alignment::compound_cants(vertex)}; + // the cant of one arc: the one in proportion to the curvature until it's given its own + auto const arc_cant = [&](int const Arc, double &Cant) { + auto value{static_cast(Arc) < cants.size() ? cants[Arc] : std::max(0.0, Cant)}; + auto edited{ImGui::DragScalar(format(STR_C("Cant of R%d (mm)"), Arc + 1).c_str(), ImGuiDataType_Double, &value, 1.0f, nullptr, nullptr, "%.0f")}; + settled |= ImGui::IsItemDeactivatedAfterEdit(); + mark(part::arc, Arc); + if (edited) + Cant = std::max(0.0, value); + item_tooltip("The cant of this arc, ramped along the transition curves to the arcs either side of it; until it's set here, the cant of the curve in proportion to the curvature of the arc"); + ImGui::SameLine(); + if (Cant < 0.0) + ImGui::TextDisabled("%s", STR_C("auto")); + else if (ImGui::SmallButton(STR_C("auto"))) + { + Cant = -1.0; + edited = true; + settled = true; + } + item_tooltip("The cant of the arc in proportion to its curvature again"); + return edited; + }; + changed |= ImGui::DragScalar(format(STR_C("Share of R%d"), 1).c_str(), ImGuiDataType_Double, &vertex.share, 0.01f, nullptr, nullptr, "%.2f"); + mark(part::arc, 0); + ImGui::SameLine(); + ImGui::TextDisabled("%.0f%%", percent(vertex.share)); + changed |= arc_cant(0, vertex.first_cant); + int removed{-1}; + for (int k = 0; k < static_cast(vertex.arcs.size()); ++k) + { + auto &arc{vertex.arcs[k]}; + ImGui::PushID(k); + ImGui::Separator(); + changed |= ImGui::DragScalar(format(STR_C("Radius R%d (m)"), k + 2).c_str(), ImGuiDataType_Double, &arc.radius, 5.0f, nullptr, nullptr, "%.0f"); + mark(part::arc, k + 1); + ImGui::SameLine(); + if (ImGui::SmallButton("x")) + removed = k; + item_tooltip("Takes this radius out of the curve"); + mark(part::arc, k + 1); + changed |= ImGui::DragScalar(format(STR_C("Transition R%d-R%d (m)"), k + 1, k + 2).c_str(), ImGuiDataType_Double, &arc.transition, 1.0f, nullptr, nullptr, "%.0f"); + settled |= ImGui::IsItemDeactivatedAfterEdit(); + mark(part::between, k + 1); + changed |= ImGui::DragScalar(format(STR_C("Share of R%d"), k + 2).c_str(), ImGuiDataType_Double, &arc.share, 0.01f, nullptr, nullptr, "%.2f"); + mark(part::arc, k + 1); + ImGui::SameLine(); + ImGui::TextDisabled("%.0f%%", percent(arc.share)); + changed |= arc_cant(k + 1, arc.cant); + arc.radius = std::max(1.0, arc.radius); + arc.transition = std::max(0.0, arc.transition); + arc.share = std::max(0.0, arc.share); + ImGui::PopID(); + } + vertex.share = std::max(0.0, vertex.share); + if (removed >= 0) + { + vertex.arcs.erase(vertex.arcs.begin() + removed); + if (vertex.arcs.empty()) + vertex.compound = false; + changed = true; + } + if (ImGui::SmallButton(STR_C("Add a radius"))) + { + auto const last{vertex.arcs.empty() ? vertex.radius : vertex.arcs.back().radius}; + vertex.arcs.push_back({std::max(10.0, std::round(last * 0.8 / 10.0) * 10.0), 0.0, 1.0}); + changed = true; + } + item_tooltip("Another arc after the last one, the angle of the curve is shared out by the shares"); + ImGui::Separator(); + } + ImGui::PopItemWidth(); + vertex.radius = std::max(1.0, vertex.radius); + vertex.transition_in = std::max(0.0, vertex.transition_in); + vertex.transition_out = std::max(0.0, vertex.transition_out); + vertex.cant = std::max(0.0, vertex.cant); + { + // the transitions follow the radii, which follow the points clicked: a few rounds settle them + auto const reshape = [&](auto const &Shape) { + for (int pass = 0; pass < 3; ++pass) + { + Shape(); + if (false == route.hold || false == route_hold_clicks(Index)) + break; + } + changed = true; + }; + if (ImGui::SmallButton(STR_C("Apply recommended for V"))) + reshape([&] { route_recommend(vertex); }); + if (ImGui::IsItemHovered()) + { + auto const recommended{alignment::recommend(design.speed, vertex.radius, design.norms)}; + ImGui::SetTooltip("%s\n%s", STR_C("Cant and transitions recommended for the design speed and the radius"), + format(STR_C("For %.0f km/h: R min %.0f m, cant %.0f mm (equilibrium %.0f, min %.0f), transition %.0f m"), design.speed, recommended.radius_min, recommended.cant, recommended.cant_equilibrium, recommended.cant_min, recommended.transition).c_str()); + } + if (false == vertex.spirals) + { + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Transitions for these cants"))) + reshape([&] { alignment::norm_transitions(vertex, design.speed, design.norms); }); + item_tooltip("The transition curves as long as the norms ask for at these radii and cants, the cants staying: a cant lowered asks for longer ones"); + mark(part::whole, 0); + } + } + // the cant ramps at the ends of the curve: along its transitions, or where they're put, off a switch laid on a transition say + if (false == vertex.spirals && ImGui::TreeNode(STR_C("Cant ramps"))) + { + std::vector ramps; + for (auto const &ramp : route.result.ramps) + if (ramp.vertex == Index) + ramps.push_back(ramp); + auto const ramp = [&](char const *Id, char const *Label, double &Offset, double &Length, std::size_t const Which, part const What) { + ImGui::PushID(Id); + auto along{Length < 0.0}; + if (ImGui::Checkbox(Label, &along)) + { + // let go of the transition where it lay along it, to be moved from there + Length = along ? -1.0 : Which < ramps.size() ? ramps[Which].to - ramps[Which].from : 0.0; + Offset = 0.0; + changed = true; + } + mark(What, 0); + item_tooltip("The norms recommend the cant ramp along the transition curve; off it, it may lie on the straight before the curve or on the arc, a switch on the transition keeping the same cant all along"); + if (false == along) + { + ImGui::SetNextItemWidth(half); + changed |= ImGui::DragScalar("##offset", ImGuiDataType_Double, &Offset, 0.5f, nullptr, nullptr, STR_C("into the curve %.1f m")); + mark(What, 0); + item_tooltip("How far the outer end of the ramp lies into the curve from its end, below 0 out along the straight before it"); + ImGui::SameLine(); + ImGui::SetNextItemWidth(half); + changed |= ImGui::DragScalar("##length", ImGuiDataType_Double, &Length, 0.5f, nullptr, nullptr, STR_C("length %.1f m")); + mark(What, 0); + item_tooltip("The length of the ramp, the cant rising evenly along it"); + Length = std::max(0.0, Length); + } + if (Which < ramps.size() && ramps[Which].to > ramps[Which].from) + ImGui::TextDisabled(STR_C("km %s - %s, %.2f mm/m"), profile::format_chainage(route.origin + ramps[Which].from).c_str(), profile::format_chainage(route.origin + ramps[Which].to).c_str(), + ramps[Which].cant / (ramps[Which].to - ramps[Which].from)); + ImGui::PopID(); + }; + ramp("in", STR_C("Ramp in along the transition curve"), vertex.ramp_in_offset, vertex.ramp_in_length, 0, part::entry); + ramp("out", STR_C("Ramp out along the transition curve"), vertex.ramp_out_offset, vertex.ramp_out_length, 1, part::exit); + ImGui::TreePop(); + } + if (ImGui::TreeNode(STR_C("Details"))) + { + for (auto const &curve : route.result.curves) + { + if (curve.vertex != Index) + continue; + ImGui::Text(STR_C("Deflection %.4f deg, tangents %.2f / %.2f m, arc %.2f m"), glm::degrees(curve.deflection), curve.tangent_in, curve.tangent_out, curve.arc_length); + ImGui::Text(STR_C("Unbalanced acc. %.3f m/s2, cant rate %.1f / %.1f mm/s, acc. rate %.3f / %.3f m/s3"), curve.unbalanced, curve.cant_rate_in, curve.cant_rate_out, curve.jerk_in, curve.jerk_out); + } + changed |= ImGui::Checkbox(STR_C("Turn the longer way (over 180 deg)"), &vertex.reverse_turn); + item_tooltip("For the loops: the curve turns by more than a half circle"); + ImGui::TreePop(); + } + ImGui::EndGroup(); + if (route.focus.vertex != Index && false == route.focus.held && ImGui::IsItemHovered()) + route.focus = {Index, part::whole, 0, false}; + if (settled && route.hold) + changed |= route_hold_clicks(Index); + return changed; +} + +void editor_mode::render_route_result() +{ + auto const &route{m_route}; + auto const &design{route.design}; + auto const &result{route.result}; + if (result.length > 0.0 && (result.start_extension > 0.0 || result.end_extension > 0.0)) + ImGui::Text(STR_C("Takes over %.2f m of the straight at the start, %.2f m at the end"), result.start_extension, result.end_extension); + for (auto const &error : result.errors) + ImGui::TextColored(ImVec4(1.0f, 0.35f, 0.3f, 1.0f), "%s", error.c_str()); + for (auto const &warning : result.warnings) + ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), "%s", warning.c_str()); + + ImGui::PushID("routeresult"); + if (result.length > 0.0 && ImGui::TreeNode(STR_C("Details"))) + { + auto const pieces{alignment::minimum_pieces(result, design)}; + ImGui::Text(STR_P("Length %.2f m (now %.2f m), %zu element", "Length %.2f m (now %.2f m), %zu elements", result.elements.size()), result.length, route.chain.length, result.elements.size()); + ImGui::TextDisabled(STR_C("Paths: %zu in the fragment, %zu needed%s"), route.chain.tracks.size(), pieces, pieces > route.chain.tracks.size() ? STR_C(" (copies of the neighbours will be added)") : ""); + ImGui::TreePop(); + } + ImGui::PopID(); + if (ImGui::TreeNode(STR_C("Elements"))) + { + ImGui::TextDisabled(STR_C("Straight available beyond the ends: %.2f / %.2f m"), design.start_reserve, design.end_reserve); + static char const *const kinds[] = {"straight", "transition", "arc", "transition", "transition between arcs"}; + for (auto const &e : result.elements) + ImGui::Text("km %s %-10s L %8.2f m%s", profile::format_chainage(m_route.origin + e.chainage).c_str(), STR_C(kinds[static_cast(e.kind)]), e.length, e.kind == alignment::element_kind::straight ? "" : (" R " + std::to_string(static_cast(std::round(e.radius))) + " m").c_str()); + ImGui::TreePop(); + } + + if (result.valid) + { + if (main_button(STR_C("Apply to the scenery"), ImVec2(-1.0f, 28.0f))) + { + route_apply(); + first_step_done(first_step::plan_apply); + } + } + else + { + ImGui::TextDisabled(STR_C("Correct the errors to apply the design")); + } + if (false == route.status.empty()) + ImGui::TextUnformatted(route.status.c_str()); +} + +editor_track::straight const &editor_mode::current_straight() +{ + auto *track{selected_track()}; + if (track != m_straights.current_for) + { + m_straights.current_for = track; + m_straights.handle = -1; + m_straights.current = track != nullptr ? editor_track::find_straight(*track, m_straights.tolerance) : editor_track::straight{}; + find_neighbour_straights(); + } + return m_straights.current; +} diff --git a/application/editormodeselection.cpp b/application/editormodeselection.cpp new file mode 100644 index 000000000..42d3d5d50 --- /dev/null +++ b/application/editormodeselection.cpp @@ -0,0 +1,365 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +// more models selected at once, the clipboard, groups and the menu at the cursor of the scenery editor + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editormodeshared.h" +#include "application/editoruilayer.h" +#include "application/editorprojection.h" +#include "editor/editorFormat.hpp" + +#include "model/AnimModel.h" +#include "rendering/renderer.h" +#include "scene/scenelayers.h" +#include "scene/scenenodegroups.h" +#include "simulation/simulation.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "imgui/imgui.h" + +#include +#include +#include + +namespace +{ + +// the models of the selection can be grouped, copied and dropped onto the ground; tracks and other nodes are left out +TAnimModel *as_model(scene::basic_node *Node) +{ + return Node != nullptr ? dynamic_cast(Node) : nullptr; +} + +} // namespace + +std::vector editor_mode::selected_nodes() const +{ + std::vector nodes; + if (m_node == nullptr) + return nodes; + nodes.push_back(m_node); + // the selection of more models is a thing of the surroundings + if (ui()->mode() != nodebank_panel::MODIFY) + return nodes; + for (auto *node : m_selection) + if (node != nullptr && std::find(nodes.begin(), nodes.end(), node) == nodes.end()) + nodes.push_back(node); + return nodes; +} + +std::vector editor_mode::selection_with_groups() const +{ + auto nodes{selected_nodes()}; + auto const count{nodes.size()}; + for (std::size_t index = 0; index < count; ++index) + { + // NOTE: the groups up to the first one stand for no group, see scene::basic_editor + if (nodes[index]->group() <= 1) + continue; + for (auto *member : scene::Groups.group(nodes[index]->group()).nodes) + if (std::find(nodes.begin(), nodes.end(), member) == nodes.end()) + nodes.push_back(member); + } + return nodes; +} + +void editor_mode::select_node(scene::basic_node *Node, bool const Additive) +{ + if (false == Additive) + { + m_selection.clear(); + m_node = Node; + ui()->set_node(m_node); + return; + } + if (Node == nullptr) + return; + if (m_node == nullptr) + { + m_node = Node; + } + else if (Node == m_node) + { + // taken out; the one selected before it takes the gizmo + if (m_selection.empty()) + { + m_node = nullptr; + } + else + { + m_node = m_selection.back(); + m_selection.pop_back(); + } + } + else if (auto const found{std::find(m_selection.begin(), m_selection.end(), Node)}; found != m_selection.end()) + { + m_selection.erase(found); + } + else + { + // the model selected last gets the gizmo + m_selection.push_back(m_node); + m_node = Node; + } + ui()->set_node(m_node); + auto const count{selected_nodes().size()}; + if (count > 1) + ui()->set_status(format(STR_C("%zu models selected; Shift+LMB adds or takes one out"), count)); +} + +void editor_mode::draw_selection_overlay() +{ + if (ui()->mode() != nodebank_panel::MODIFY || m_node == nullptr) + return; + auto const nodes{selection_with_groups()}; + if (nodes.size() < 2) + return; + // a ring around each model of the selection, the one with the gizmo brighter, the models of their groups dimmer + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const direct{selected_nodes()}; + for (auto *node : nodes) + { + ImVec2 point; + if (false == projection.project(node->location(), point)) + continue; + auto const chosen{std::find(direct.begin(), direct.end(), node) != direct.end()}; + auto const color{node == m_node ? overlay_color::highlight : chosen ? overlay_color::selected : overlay_color::marked}; + drawlist->AddCircle(point, node == m_node ? 9.0f : 7.0f, color, 16, 2.0f); + } +} + +void editor_mode::selection_snapshots(EditorSnapshot::Action const Action) +{ + // one step of the history for all of them + auto joined{false}; + for (auto *node : selection_with_groups()) + { + push_snapshot(node, Action); + if (false == m_history.empty()) + m_history.back().joined = joined; + joined = true; + } +} + +void editor_mode::selection_follow(glm::dvec3 const &Moved, glm::vec3 const &Turned, glm::dvec3 const &Pivot) +{ + // a group is moved by any of its models, once; the one of m_node is moved with it already + std::vector moved; + if (m_node != nullptr && m_node->group() > 1) + moved.push_back(m_node->group()); + for (auto *node : selected_nodes()) + { + if (node == m_node) + continue; + if (node->group() > 1) + { + if (std::find(moved.begin(), moved.end(), node->group()) != moved.end()) + continue; + moved.push_back(node->group()); + } + if (Turned != glm::vec3(0.0f)) + { + // turned in place, then carried around the turning point + m_editor.rotate(node, Turned, 0.0f); + auto const location{Pivot + glm::rotateY(node->location() - Pivot, glm::radians(Turned.y))}; + m_editor.translate(node, location, true); + } + if (Moved != glm::dvec3(0.0)) + m_editor.translate(node, node->location() + Moved, true); + } +} + +glm::dvec3 editor_mode::cursor_ground() +{ + return placement_on_ground(Camera.Pos + clamp_mouse_offset_to_max(GfxRenderer->Mouse_Position())); +} + +void editor_mode::copy_selection() +{ + auto const nodes{selection_with_groups()}; + auto const *anchor{as_model(m_node)}; + if (anchor == nullptr) + { + ui()->set_status(STR("Select a model to copy"), true); + return; + } + m_clipboard.clear(); + std::map groups; + for (auto *node : nodes) + { + auto *model{as_model(node)}; + if (model == nullptr) + continue; + clipboard_entry entry; + model->export_as_text(entry.definition); + entry.offset = model->location() - anchor->location(); + entry.angles = model->Angles(); + entry.scale = model->Scale(); + if (model->group() > 1) + entry.group = groups.emplace(model->group(), static_cast(groups.size())).first->second; + m_clipboard.push_back(std::move(entry)); + } + ui()->set_status(format(STR_C("%zu models copied; Ctrl+V puts them at the cursor"), m_clipboard.size())); +} + +void editor_mode::paste_clipboard(glm::dvec3 const &Location) +{ + if (m_clipboard.empty()) + { + ui()->set_status(STR("Nothing copied yet; Ctrl+C copies the selected models"), true); + return; + } + // one step of the history, the way an array is: the copies are taken out together + EditorSnapshot snap; + snap.action = EditorSnapshot::Action::Array; + std::vector made; + std::map> groups; + for (auto const &entry : m_clipboard) + { + // NOTE: no names for the copies, same as with the brush and the array + auto *model{simulation::State.create_model(entry.definition, std::string{}, Location + entry.offset)}; + if (model == nullptr) + continue; + model->location(Location + entry.offset); + model->Angles(entry.angles); + model->Scale(entry.scale); + add_to_hierarchy(model); + EditorSnapshot::array_copy copy; + copy.model = model; + copy.uuid = model->uuid; + snap.copies.push_back(std::move(copy)); + snap.layer = model->layer(); + made.push_back(model); + if (entry.group >= 0) + groups[entry.group].push_back(model); + } + if (made.empty()) + return; + m_history.push_back(std::move(snap)); + g_redo.clear(); + for (auto const &group : groups) + if (group.second.size() > 1) + scene::Groups.make(group.second); + // the copies are the selection now + m_selection.assign(made.begin() + 1, made.end()); + m_node = made.front(); + ui()->set_node(m_node); + ui()->set_status(format(STR_C("%zu models pasted; Ctrl+Z takes them back"), made.size())); +} + +void editor_mode::group_selection() +{ + auto nodes{selection_with_groups()}; + nodes.erase(std::remove_if(nodes.begin(), nodes.end(), [](scene::basic_node *Node) { return as_model(Node) == nullptr; }), nodes.end()); + if (nodes.size() < 2) + { + ui()->set_status(STR("Select two models or more to group them: Shift+LMB adds one to the selection"), true); + return; + } + for (auto *node : nodes) + { + std::string reason; + if (node->from_template() || false == scene::Layers.editable(node, &reason)) + { + if (reason.empty()) + reason = STR("it's a part of a scenery template"); + ui()->set_status(format(STR_C("\"%s\" can't be grouped: %s"), name_of(*node).c_str(), reason.c_str()), true); + return; + } + } + // a group is written to the scenery as one block, in the layer of the model with the gizmo + for (auto *node : nodes) + if (node->layer() != m_node->layer()) + scene::Layers.move(node, m_node->layer()); + scene::Groups.make(nodes); + m_selection.clear(); + ui()->set_status(format(STR_C("%zu models grouped: a click on one selects them all; Ctrl+Shift+G takes the group apart"), nodes.size())); +} + +void editor_mode::ungroup_selection() +{ + std::vector groups; + for (auto *node : selected_nodes()) + { + if (node->group() <= 1 || std::find(groups.begin(), groups.end(), node->group()) != groups.end()) + continue; + // the groups of the scenery templates are their includes, they can't be taken apart here + auto const &members{scene::Groups.group(node->group()).nodes}; + if (std::any_of(members.begin(), members.end(), [](scene::basic_node const *Member) { return Member->from_template(); })) + continue; + groups.push_back(node->group()); + } + if (groups.empty()) + { + ui()->set_status(STR("The selected model isn't in a group"), true); + return; + } + for (auto const group : groups) + scene::Groups.dissolve(group); + ui()->set_status(format(STR_C("%zu groups taken apart"), groups.size())); +} + +void editor_mode::drop_selection_to_ground() +{ + // each model by itself, a group follows the ground under its models + auto joined{false}; + for (auto *node : selection_with_groups()) + { + auto const size{m_history.size()}; + snap_to_ground(node, true, joined); + joined = joined || m_history.size() != size; + } +} + +void editor_mode::render_context_menu() +{ + if (m_contextopen) + { + ImGui::OpenPopup("##editorcontext"); + m_contextopen = false; + } + if (false == ImGui::BeginPopup("##editorcontext")) + return; + auto const selected{m_node != nullptr}; + auto const model{as_model(m_node) != nullptr}; + auto const count{selected_nodes().size()}; + if (count > 1) + ImGui::TextDisabled(STR_C("%zu models selected"), count); + else if (selected) + ImGui::TextDisabled("%s", name_of(*m_node).c_str()); + else + ImGui::TextDisabled("%s", STR_C("Nothing selected")); + ImGui::Separator(); + auto const item = [](char const *Label, char const *Keys, bool const Enabled, char const *Tooltip) { + auto const chosen{ImGui::MenuItem(Label, Keys, false, Enabled)}; + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + ImGui::SetTooltip("%s", Tooltip); + return chosen; + }; + if (item(STR_C("Copy"), "Ctrl+C", model, STR_C("Copies the selected models with their groups"))) + copy_selection(); + if (item(STR_C("Paste here"), "Ctrl+V", false == m_clipboard.empty(), STR_C("Puts the copied models here, around this point as they were around the selected one"))) + paste_clipboard(m_contextpoint); + ImGui::Separator(); + if (item(STR_C("Group together"), "Ctrl+G", model && count > 1, STR_C("The selected models move together from now on; a click on one selects them all"))) + group_selection(); + if (item(STR_C("Ungroup"), "Ctrl+Shift+G", selected && m_node->group() > 1, STR_C("The models of the group move each by itself again"))) + ungroup_selection(); + if (item(STR_C("Drop to the ground"), "End", selected, STR_C("Puts each selected model, also each model of their groups, down onto the terrain or the object under it"))) + drop_selection_to_ground(); + ImGui::Separator(); + if (item(STR_C("Fly to the selected"), "F", selected, STR_C("The camera flies to the selected model and looks at it"))) + start_focus(m_node, 0.6); + if (item(STR_C("Delete"), STR_C("Del"), selected, STR_C("Deletes the selected models"))) + delete_selected(); + ImGui::EndPopup(); +} diff --git a/application/editormodeselftest.cpp b/application/editormodeselftest.cpp new file mode 100644 index 000000000..f81b73f3a --- /dev/null +++ b/application/editormodeselftest.cpp @@ -0,0 +1,285 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "application/editormode.h" +#include "editor/editorSettings.hpp" +#include "editor/editorGeometry.hpp" +#include "application/application.h" +#include "application/editoruilayer.h" +#include "application/editorprojection.h" +#include "application/editorgestures.h" +#include "imgui/imgui.h" + +#include "simulation/simulation.h" +#include "simulation/simulationtime.h" +#include "scene/scenelayers.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "world/Track.h" +#include "world/TrackRails.h" +#include "world/MemCell.h" +#include "world/Event.h" +#include "vehicle/DynObj.h" +#include "model/AnimModel.h" +#include "model/Model3d.h" +#include "rendering/renderer.h" +#include "world/Sweep.h" +#include "input/keyboardinput.h" +#include "launcher/textures_scanner.h" +#include +#include +#include +#include "editor/editorFormat.hpp" +#include "editor/editorAlignmentStore.hpp" +#include "editor/editorSwitchStore.hpp" +#include "scene/sceneterrain.h" +#include "editor/editorSpeed.hpp" + +#include +#include +#include +#include +#include +#include + +#include "application/editormodeselftest.h" + +editor_mode::selftest_result editor_mode::selftest_dispatch(std::string const &command, std::istringstream &words) +{ + for (auto const group : {&editor_mode::selftest_scene, &editor_mode::selftest_sleepers, &editor_mode::selftest_sweep, &editor_mode::selftest_track, &editor_mode::selftest_switch, &editor_mode::selftest_rails, &editor_mode::selftest_join, &editor_mode::selftest_signal, &editor_mode::selftest_terrain, &editor_mode::selftest_props, &editor_mode::selftest_monkey}) + if (auto const result{(this->*group)(command, words)}; result != selftest_result::unhandled) + return result; + for (auto *tool : m_tools) + if (auto const result{tool->selftest(command, words)}; result != selftest_result::unhandled) + return result; + return selftest_result::unhandled; +} + +// the script is a text file, one action a line: +// wait +// camera from the first point, looking at the second +// select +// selectat the path nearest the point, within 3 m, as a click on it +// trackends logs the ends of the first path of the track against the ground under them +// kbreak K on the track nearest the point: split there, a break of the grade at the height of the ground +// blade [name] logs the blades of each switch cut from the rails: tip, 50 mm head, full head, heel, drop of the head, open flangeway, the gauge lines apart against x^2/2R, vertices in both positions +// frog [name] logs where the inner rails of each switch cross: distance on both paths, 1:n, throat, nose, check rails +// guards [name] logs each guard rail and what each of its ends and breaks is cut along; a fault when a cut is not along a rail or a glued end not on the guard rail of the other track +// railtime lays out the rails of every track, as when its geometry is made, and logs how long it took +// throw <0|1> sets every switch to the path and moves its blades there at once +// crossings [name] logs where rails of tracks cross rails of other tracks and of what kind (acute, obtuse, middle acute or obtuse, wide), checks that each acute crossing has one partner and one nose +// switchtimbers the model of the timbers set on all the switches and crossings, as the buttons of the switch tool do it +// frogkey name [on|off] sets or clears the frogs key of a switch (one undo step); logs the key, whether it is written, the frog and the crossings +// geomhash [name] logs the number of vertices and a hash of the drawn geometry of each rail track (rails, trackbed, cut faces), to compare builds; exact: the bits of every value, userdata and tread materials too +// sweep =... model, params (separated by commas), lateral, height, side (origin, near, far, +// centre), top (origin, bottom, top, edge), mode (bend, repeat), step, +// length (original, all, or metres), from, to, widen (0, 1), face (0, 1), tilt (0, 1) +// selectmodel the model instance nearest the point +// bend =... the selected model bent along a track: track (index on the list), axis (auto, z, x), +// turned (0, 1), along (start, origin, middle, end, point), side (origin, near, far, +// middle, point), height (origin, bottom, top, edge, point), point=,,, +// pick=,, (a point of the scene picked as the reference point), go (0, 1) +// selectinclude the include placed nearest the point +// addmodel the model instance nearest the point added to the selection, or taken out (Shift+LMB) +// selection logs the selected models, with the models of their groups +// moveselection the selection moved by the offset, as the gizmo moves it +// turnselection the selection turned around the model with the gizmo +// copy, paste , group, ungroup, drop, delete as the keys of the selection do them +// bendset =... the bent model being edited: length, lateral, height, along, side, height +// bendprobe logs the bent model being edited +// undo, redo +// key [ctrl] a key or right button event, as the window gives it +// lineside the tab of the objects along the track in the track window +// event queues the event +// memcell logs the memory cell +// bendpanel unfolds the bend section of the toolset +// openscenerypopup the window of File / Open scenery, its list searched for zz_ +// openscenery the editor starts again with the scenery +// checkspans logs whether the text the scenery files hold at each node's place starts and ends it +// spread logs the paths the spread from the track takes +// newscenery the editor starts again with the wizard of a new scenery +// mapstate logs the orthophoto, the top view and the //$o line of the scenery +// trainset [km/h] the trainset tool puts the vehicle in the middle of the track +// vehicles logs each vehicle: its head, facing, and what its couplers hold +// terrainmode the terrain field of work, with its texture browser +// terrainsculpt , terrainpaint , +// terrainlevel [mode] as a stroke of the brush +// terrainadd chunks made around the camera, count x count, as the button of the chunks panel does it +// terrainprobe logs the height of the heightmap terrain and the materials of the chunk +// terrainconvert converts every material of the terrain files of the scenery +// terrainmodifier a straight modifier, as the vertical profile makes them +// terraintouchup <0|1> the brushes touch up over the modifiers, or shape the ground under them +// terrainrestore a stroke of the restore brush +// terrainbake the modifier baked into the ground +// terrainselect [add] the chunk selected with the spacing tool (add: Ctrl) +// terrainresolution [paint 0|1] the selected chunks converted, as the button of the resolution panel does it +// terrainfill ... the area outlined filled, as the fill tool does it +// terrainturn the textures of the palette entry turned +// terrainwater [size] material and repeat of a body of water; terrainwaterdefault +// orthophoto [in scene 0|1] the imagery layer on, placed and fitted as given +// orthoarea ... | clear the download area through the points of the world, as drawn on the map; orthoareapause 0|1 +// orthohires 0|1 the 4K tiles on or off; orthostats logs the tiles, the area and the requests made +// orthosettings [on|radius|opacity|lift|height|year|hires|drape|scene ]... the settings of the orthophoto changed as its +// panel and its checkbox change them, kept with the editor, and logged with the origin of the scenery +// nmtsettings [band|around|shape|common|follow|grow|offset|fitted ]... the settings of the terrain model changed as the terrain +// panel changes them, and logged with the offset of the model to the scenery +// join [radius] [variant] [transitions 0|1] the free ends at the points joined, as a drag from one to the other +// layto from the free end at the first point towards the second, as a drag in the layout +// layclicks ... clicks of the lay tool at the points, a free end within 3 m joined +// laymonkey [case] random lines laid to and from the free ends of the scenery, as the preview shows them: gaps and +// angles at the joints, loops, the turning wasted and the sharpest curve logged; case: that one alone +// layspeed the speed set for the laying, and whether it goes also on from a track with its own +// laymode , laytrace as the panel of the laying sets them +// endcurves logs every free end of the rails: where, the way out and the curvature its track goes on with +// curvejoint logs the paths meeting at the end nearest the point, the curvature of each and its jump from the ones before to the ones after +// cantcheck