diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 131cccf11..ff39d872f 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 @@ -33,8 +41,16 @@ jobs: with: python-version: '3.14' + # A mirror that stops answering used to hold this step for over an hour. + # Time out each download, retry it, and give up on the whole step early. - 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 \ @@ -102,6 +118,7 @@ jobs: --exclude='*.o' \ --exclude='*.a' \ --exclude='*.so' \ + --exclude='*.so.*' \ -C "$GITHUB_WORKSPACE" . - name: Upload analysis input diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index 406f50990..65d74e36f 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -27,9 +27,31 @@ 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 is built twice: with AVX2 (the default of ENABLE_AVX2) and without it, for CPUs older + # than Haswell (2013). Each variant has its own concurrency group, or one would cancel the other. + windows: - name: Windows x64 / MSVC + name: Windows x64 / MSVC / ${{ matrix.variant.name }} runs-on: windows-2022 + concurrency: + group: ${{ github.workflow }}-windows-${{ matrix.variant.suffix }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} + cancel-in-progress: true + + strategy: + fail-fast: false + matrix: + variant: + - name: "AVX2" + suffix: "avx2" + cmake_flags: "-DENABLE_AVX2=ON" + - name: "No AVX2" + suffix: "noavx2" + cmake_flags: "-DENABLE_AVX2=OFF" steps: - name: Checkout repository @@ -76,6 +98,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: | @@ -83,11 +126,13 @@ jobs: $pythonRoot = Split-Path $pythonExe Write-Host "Python root: $pythonRoot" + Write-Host "Extra CMake flags: ${{ matrix.variant.cmake_flags }}" cmake -S . -B build ` -G "Visual Studio 17 2022" ` -A x64 ` - "-DPython3_ROOT_DIR=$pythonRoot" + "-DPython3_ROOT_DIR=$pythonRoot" ` + ${{ matrix.variant.cmake_flags }} - name: Build shell: pwsh @@ -138,7 +183,7 @@ jobs: - name: Upload Windows build uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: maszyna-windows-x64-${{ env.CONFIG_WIN }} + name: maszyna-windows-x64-${{ matrix.variant.suffix }}-${{ env.CONFIG_WIN }} path: | build/bin/${{ env.CONFIG_WIN }}/ if-no-files-found: error @@ -147,7 +192,7 @@ jobs: - name: Upload Windows debug symbols uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: maszyna-windows-x64-symbols-${{ env.CONFIG_WIN }} + name: maszyna-windows-x64-symbols-${{ matrix.variant.suffix }}-${{ env.CONFIG_WIN }} path: | build/pdb/${{ env.CONFIG_WIN }}/*.pdb build/bin/${{ env.CONFIG_WIN }}/*.map @@ -160,8 +205,23 @@ jobs: # ============================================================ linux: - name: Linux x64 / GCC + name: Linux x64 / GCC / ${{ matrix.variant.name }} runs-on: ubuntu-24.04 + # see the notes above the windows job: two variants, each with a concurrency group of its own + concurrency: + group: ${{ github.workflow }}-linux-${{ matrix.variant.suffix }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} + cancel-in-progress: true + + strategy: + fail-fast: false + matrix: + variant: + - name: "AVX2" + suffix: "avx2" + cmake_flags: "-DENABLE_AVX2=ON" + - name: "No AVX2" + suffix: "noavx2" + cmake_flags: "-DENABLE_AVX2=OFF" steps: - name: Checkout repository @@ -176,12 +236,25 @@ jobs: with: python-version: "3.14" + # A mirror that stops answering used to hold this step for over an hour. + # Time out each download, retry it, and give up on the whole step early. - 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 \ @@ -190,6 +263,7 @@ jobs: libluajit-5.1-dev \ libserialport-dev \ libsndfile1-dev \ + libcurl4-openssl-dev \ xorg-dev \ libxkbcommon-dev \ libwayland-dev \ @@ -207,12 +281,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 \ @@ -239,6 +318,7 @@ jobs: -DWITH_ZMQ=OFF \ -DWITH_OPENVR=OFF \ -DUSE_LTO=OFF \ + ${{ matrix.variant.cmake_flags }} \ -DPython3_EXECUTABLE="${{ steps.python.outputs.python-path }}" \ -DCMAKE_CXX_FLAGS="-Wno-attributes -fno-inline-functions-called-once" @@ -247,7 +327,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)')" @@ -280,7 +384,7 @@ jobs: - name: Upload Linux build uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: maszyna-linux-x64-${{ env.CONFIG_LINUX }} + name: maszyna-linux-x64-${{ matrix.variant.suffix }}-${{ env.CONFIG_LINUX }} path: | build/bin/ if-no-files-found: error @@ -303,29 +407,47 @@ jobs: cancel-in-progress: false steps: - - name: Download Windows build + # the AVX2 build keeps the old name of the download, so the links already handed out still work + - name: Download Windows build (AVX2) uses: actions/download-artifact@v4 with: - name: maszyna-windows-x64-${{ env.CONFIG_WIN }} + name: maszyna-windows-x64-avx2-${{ env.CONFIG_WIN }} path: dist/maszyna-windows-x64 - - name: Download Linux build + - name: Download Windows build (no AVX2) uses: actions/download-artifact@v4 with: - name: maszyna-linux-x64-${{ env.CONFIG_LINUX }} + name: maszyna-windows-x64-noavx2-${{ env.CONFIG_WIN }} + path: dist/maszyna-windows-x64-noavx2 + + - name: Download Linux build (AVX2) + uses: actions/download-artifact@v4 + with: + name: maszyna-linux-x64-avx2-${{ env.CONFIG_LINUX }} path: dist/maszyna-linux-x64 + - name: Download Linux build (no AVX2) + uses: actions/download-artifact@v4 + with: + name: maszyna-linux-x64-noavx2-${{ env.CONFIG_LINUX }} + path: dist/maszyna-linux-x64-noavx2 + - 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 + # the artifacts lose the executable bit + for dir in maszyna-linux-x64 maszyna-linux-x64-noavx2; do + find "$dir" -type f -exec sh -c 'file -b "$1" | grep -q "^ELF" && chmod +x "$1"' _ {} \; + if [ -d "$dir/linuxpython64/bin" ]; then + chmod +x "$dir"/linuxpython64/bin/* + fi + done (cd maszyna-windows-x64 && zip -qr9 ../maszyna-windows-x64.zip .) + (cd maszyna-windows-x64-noavx2 && zip -qr9 ../maszyna-windows-x64-noavx2.zip .) tar -czf maszyna-linux-x64.tar.gz -C maszyna-linux-x64 . + tar -czf maszyna-linux-x64-noavx2.tar.gz -C maszyna-linux-x64-noavx2 . ls -la - name: Publish rolling release of the branch @@ -345,14 +467,18 @@ jobs: "" \ "Download without a GitHub account:" \ "- Windows: $base/maszyna-windows-x64.zip" \ + "- Windows, CPUs without AVX2 (older than Haswell, 2013): $base/maszyna-windows-x64-noavx2.zip" \ "- Linux: $base/maszyna-linux-x64.tar.gz" \ + "- Linux, CPUs without AVX2: $base/maszyna-linux-x64-noavx2.tar.gz" \ "" \ "Unpack over a MaSzyna installation (the game data isn't included). Build log: $RUN_URL")" gh release delete "$tag" --yes --cleanup-tag || true gh release create "$tag" \ dist/maszyna-windows-x64.zip \ + dist/maszyna-windows-x64-noavx2.zip \ dist/maszyna-linux-x64.tar.gz \ + dist/maszyna-linux-x64-noavx2.tar.gz \ --target "$SHA" \ --prerelease \ --latest=false \ @@ -361,4 +487,6 @@ jobs: echo "### Public download" >> "$GITHUB_STEP_SUMMARY" echo "- Windows: $base/maszyna-windows-x64.zip" >> "$GITHUB_STEP_SUMMARY" + echo "- Windows, no AVX2: $base/maszyna-windows-x64-noavx2.zip" >> "$GITHUB_STEP_SUMMARY" echo "- Linux: $base/maszyna-linux-x64.tar.gz" >> "$GITHUB_STEP_SUMMARY" + echo "- Linux, no AVX2: $base/maszyna-linux-x64-noavx2.tar.gz" >> "$GITHUB_STEP_SUMMARY" 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/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 index 283058cbe..bbbaa3835 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,168 +1,5 @@ # MaSzyna: notes for Claude Code -## The code builds and works with GCC, not only MSVC +The instructions for every coding agent in this repository are in `AGENTS.md`. Add or change rules there, not here. -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. +@AGENTS.md diff --git a/CMakeLists.txt b/CMakeLists.txt index c38285647..9e9b55d86 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -83,6 +83,7 @@ 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_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(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) @@ -189,6 +190,7 @@ set(SOURCES "scene/scene.cpp" "scene/scenenode.cpp" "simulation/simulation.cpp" +"simulation/blackboxrecorder.cpp" "model/vertex.cpp" "audio/audio.cpp" "audio/audiorenderer.cpp" @@ -213,6 +215,8 @@ set(SOURCES "editor/editorIncludeInfo.cpp" "editor/editorTerrain.cpp" "editor/editorTrack.cpp" +"editor/editorTrackTrace.cpp" +"editor/editorFouling.cpp" "editor/editorRoad.cpp" "editor/editorAlignment.cpp" "editor/editorTrackShape.cpp" @@ -249,7 +253,9 @@ set(SOURCES "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" @@ -259,6 +265,8 @@ set(SOURCES "application/editormodeprofile.cpp" "application/editormodetextures.cpp" "application/editormodegauge.cpp" +"application/editormoderide.cpp" +"application/editormodeminimap.cpp" "application/editormodeinfra.cpp" "application/editormodespeed.cpp" "application/editormodesrk.cpp" @@ -634,6 +642,11 @@ if (ADD_VERSION_SUFFIX) set (SUFFIX "_${SRC_SHORT_DATE}_${GIT_HASH}") endif() +# a build without AVX2 says so in its name, so a starter can pick it on a CPU without AVX2 +if (NOT ENABLE_AVX2) + set (SUFFIX "${SUFFIX}_noavx2") +endif() + set(OPENVR_LIBRARY "openvr_api") set(OPENVR_INCLUDE_DIR "") @@ -695,6 +708,7 @@ 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" @@ -703,11 +717,15 @@ set(CORE_SOURCES "scripting/scriptscreenkernels.cpp" "scripting/scriptscreendrawing.cpp" "simulation/simulationtestrules.cpp" +"vehicle/blackbox.cpp" +"utilities/physicslog.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) @@ -869,6 +887,12 @@ else() 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(eu07_settings INTERFACE OpenAL::OpenAL) @@ -899,7 +923,8 @@ if (WIN32) target_link_libraries(eu07_settings INTERFACE ws2_32) endif() -# http client of the editor's geoportal orthophoto layer: WinHTTP on Windows, libcurl elsewhere when available +# 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() @@ -908,7 +933,7 @@ else() 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 layer will only show cached tiles") + message(STATUS "libcurl not found: the editor's orthophoto and terrain model will only show what's cached, its topo map nothing") endif() endif() @@ -925,6 +950,41 @@ if (WIN32) ) endif () +# 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) add_custom_command( TARGET ${PROJECT_NAME} POST_BUILD 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/EU07.cpp b/EU07.cpp index e8d226b75..8255c6907 100644 --- a/EU07.cpp +++ b/EU07.cpp @@ -23,11 +23,17 @@ Stele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others #include "utilities/Globals.h" #include "utilities/Logs.h" #include "utilities/crashdump.h" +#include "utilities/physicslog.h" #include #include #include #include #include +#ifdef _WIN32 +#include +#else +#include +#endif #ifdef _MSC_VER #ifdef EU07_CPU_PREFLIGHT @@ -72,6 +78,8 @@ void finish_log() [[noreturn]] void end_test_run(std::string_view const Reason) { simulation::test().conclude(simulation::test_result::error, Reason); + // the last two seconds of the physics logs, which the runner of the tests reads + PhysicsLogs.stop(); finish_log(); fflush(stdout); fflush(stderr); @@ -101,10 +109,29 @@ void finish_log() end_test_run("the simulator stopped before the test ended"); } +// the physics logs used to keep a file open for every vehicle with a driver, and on a scenery with some five hundred +// of them they took all the files the C library of Windows lets a process have open by default (512): the files +// opened after them, the shaders of the map among them, couldn't be read. they keep none open now (physicslog.h), +// but the limit is raised to the most either system allows still, for whatever else opens many files at once +void raise_open_files_limit() +{ +#ifdef _WIN32 + _setmaxstdio(8192); +#else + rlimit limit{}; + if (getrlimit(RLIMIT_NOFILE, &limit) == 0 && limit.rlim_cur < limit.rlim_max) + { + limit.rlim_cur = limit.rlim_max; + setrlimit(RLIMIT_NOFILE, &limit); + } +#endif +} + } // namespace int main(int argc, char *argv[]) { + raise_open_files_limit(); crashdump_install(); // init start timestamp Global.startTimestamp = std::chrono::steady_clock::now(); @@ -182,6 +209,9 @@ int main(int argc, char *argv[]) MessageBoxA(nullptr, msg.c_str(), "Simulator crashed :(", MB_ICONERROR); } #endif + // the last two seconds of the physics logs, also after an error caught above; Application.exit() stops them + // otherwise, and a second stop only writes what came since + PhysicsLogs.stop(); } stop_log_service(); #ifndef _WIN32 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 6bea69b0d..d4730f617 100644 --- a/McZapkie/MOVER.h +++ b/McZapkie/MOVER.h @@ -14,7 +14,9 @@ http://mozilla.org/MPL/2.0/. #include #include #include "hamulce.h" +#include "couplerphysics.h" #include "scripting/ladderlogic.h" +#include "vehicle/odometerreading.h" class cParser; /* @@ -299,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 { @@ -1257,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 @@ -1266,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 @@ -2009,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 @@ -2017,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 @@ -2114,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*/ @@ -2150,6 +2175,11 @@ class TMoverParameters // 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}; @@ -2209,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 @@ -2385,6 +2419,10 @@ 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*/ @@ -2547,6 +2585,17 @@ class TMoverParameters 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}; @@ -2592,6 +2641,26 @@ class TMoverParameters { 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 @@ -2638,6 +2707,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); @@ -2650,6 +2724,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 diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp index 94917b15e..ed8275bc9 100644 --- a/McZapkie/Mover.cpp +++ b/McZapkie/Mover.cpp @@ -439,7 +439,7 @@ double TMoverParameters::Current(double n, double U) // writepaslog("Delta ", FloatToStr(Delta)); // writepaslog("DeltaQ ", FloatToStr(DeltaQ)); // writepaslog("U ", FloatToStr(U)); - if (Mains) + if (MainCircuitPowered()) { if (U > 0) MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n + std::sqrt(Delta)) / (2.0 * Rz); @@ -644,6 +644,9 @@ bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters * // stykaja sie zderzaki i kompatybilne typy sprzegow, chyba że łączenie na starcie if (thiscoupler.CouplingFlag == coupling::faux) { + // a new coupling: the play of the coupling as set up anew, without the stretch of the one before + thiscoupler.physics_state.couple(); + othercoupler.physics_state.couple(); // jeśli wcześniej nie było połączone, ustalenie z której strony rysować sprzęg thiscoupler.Render = true; // tego rysować othercoupler.Render = false; // a tego nie @@ -1335,6 +1338,15 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) auto const otherend{Neighbours[End].vehicle_end}; auto const &othercoupler{othervehicle->Couplers[otherend]}; + auto const physical{coupler_physics_at(End)}; + if (physical && false == coupler_stop_hit(End, *othervehicle, otherend)) + { + return; + } + // the share of the energy of the relative motion the hit takes: in the physical model the springs gone solid give + // for good, rather than spring back as the legacy model has it + auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0}; + // the velocities along this vehicle's axis: the other vehicle's one is turned around when the vehicles face each // other (touch with the same ends), as in CouplerForce() auto const otherdirection{DirPatch(End, otherend)}; @@ -1348,12 +1360,12 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) { case 0: { - CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, (thiscoupler.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, (thiscoupler.beta + othercoupler.beta) / 2.0, VirtualCoupling) / dt; + CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, loss, VirtualCoupling) / dt; break; } default: @@ -1364,7 +1376,8 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) if (Global.crash_damage) { - if (-thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.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); @@ -1393,18 +1406,21 @@ void TMoverParameters::CollisionDetect(int const End, double const dt) } } - // 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}; - AccS += accelerationchange; + AccS += accelerationchange * accelerationspike; V = velocity; } if (false == TestFlag(othervehicle->DamageFlag, dtrain_out)) { auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->V) / dt}; - othervehicle->AccS += othervehicleaccelerationchange; + othervehicle->AccS += othervehicleaccelerationchange * accelerationspike; othervehicle->V = othervehiclenewvelocity; } } @@ -1422,39 +1438,72 @@ void TMoverParameters::damage_coupler(int const End) if (SetFlag(DamageFlag, dtrain_coupling)) EventFlag = true; - if ((thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose) + auto const hosetorn{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; + if (hosetorn) { // hamowanie nagle - zerwanie przewodow hamulcowych AlarmChainFlag = true; } thiscoupler.CouplingFlag = 0; + thiscoupler.broken = true; if (thiscoupler.Connected != nullptr) { - 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: - { - thiscoupler.Connected->Couplers[end::rear].CouplingFlag = coupling::faux; - break; - } - case 1: - { - thiscoupler.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)) @@ -1597,6 +1646,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 @@ -1663,6 +1713,7 @@ double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Sh dL)}; DistCounter += fabs(dL) / 1000.0; + Odometer.run(dL); dL = 0; // koniec procedury, tu nastepuja dodatkowe procedury pomocnicze @@ -1824,7 +1875,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) { @@ -1903,7 +1955,7 @@ void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling c 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: @@ -2160,7 +2212,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) @@ -2246,7 +2298,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: @@ -2355,9 +2407,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 && @@ -2387,6 +2437,19 @@ void TMoverParameters::MotorBlowersCheck(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; @@ -2416,7 +2479,8 @@ void TMoverParameters::PantographsCheck(double const /*Timestep*/) 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}; @@ -3814,7 +3878,8 @@ bool TMoverParameters::MainSwitchCheck() const 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: @@ -3824,7 +3889,8 @@ bool TMoverParameters::MainSwitchCheck() const } return powerisavailable && (ScndCtrlPos == 0 || EngineType == ElectricInductionMotor) && MainsInitTimeCountdown <= 0.0 && - (ConvOvldFlag == false || ConverterOverloadRelayOffWhenMainIsOff) && true == GroundRelay && true == NoVoltRelay && true == OvervoltageRelay && LastSwitchingTime > CtrlDelay && + (ConvOvldFlag == false || ConverterOverloadRelayOffWhenMainIsOff) && true == GroundRelay && (true == NoVoltRelay || PantographsRequireMains) && true == OvervoltageRelay && + LastSwitchingTime > CtrlDelay && (HasCamshaft ? IsMainCtrlActualNoPowerPos() : LineBreakerClosesOnlyAtNoPowerPos ? IsMainCtrlNoPowerPos() : true) && @@ -3929,6 +3995,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 @@ -4522,7 +4607,7 @@ void TMoverParameters::CompressorCheck(double dt) } // the main circuit, also for a compressor driven by the engine, otherwise the low voltage - auto const compressorpower{CompressorPower == 0 || CompressorPower == 3 ? Mains : Power110vIsAvailable}; + 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 @@ -5495,6 +5580,10 @@ 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 &thiscoupler{Couplers[End]}; auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; @@ -5608,27 +5697,9 @@ double TMoverParameters::CouplerForce(int const End, double dt) // zderzenie thiscoupler.CheckCollision = true; } - if (-newdistance >= std::min(collisiondistance, dEpsilon) && thiscoupler.type() == TCouplerType::Automatic && thiscoupler.type() == othercoupler.type() && thiscoupler.CouplingFlag == coupling::faux && - thiscoupler.AutomaticCouplingAllowed && - othercoupler.AutomaticCouplingAllowed) + if (-newdistance >= std::min(collisiondistance, dEpsilon)) { - // 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, *othervehicle, otherend, couplingtype); - - // too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect()) - auto const safe{AutomaticCouplingSafe(End, *othervehicle, otherend)}; - auto const caught{safe && Attach(End, otherend, othervehicle, 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; + automatic_coupling(End, *othervehicle, otherend); } } } @@ -5643,6 +5714,172 @@ double TMoverParameters::CouplerForce(int const End, double dt) 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) @@ -5728,7 +5965,7 @@ double TMoverParameters::TractionForce(double dt) case TEngineType::ElectricSeriesMotor: { - if (true == Mains) + if (MainCircuitPowered()) { switch (RVentType) { @@ -5860,11 +6097,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; } @@ -5873,7 +6117,8 @@ double TMoverParameters::TractionForce(double dt) { // TODO: check if we can use instead the code for electricseriesmotor // nie wchodzić w funkcję bez potrzeby - if (Mains && (std::max(GetTrainsetHighVoltage(), PantographVoltage) < EnginePowerSource.CollectorParameters.MinV || + // (a line breaker closed ahead of the pantographs holds without voltage) + if (Mains && ((std::max(GetTrainsetHighVoltage(), PantographVoltage) < EnginePowerSource.CollectorParameters.MinV && false == PantographsRequireMains) || std::max(GetTrainsetHighVoltage(), PantographVoltage) > EnginePowerSource.CollectorParameters.MaxV + 200)) { MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide @@ -6394,7 +6639,7 @@ 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 const &inv : Inverters) @@ -7312,9 +7557,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) @@ -7687,7 +7959,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) @@ -11012,6 +11284,82 @@ 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) { @@ -11090,11 +11438,21 @@ void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Inde 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) @@ -11321,6 +11679,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)); @@ -11388,6 +11747,14 @@ void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : start_t::manual; MotorBlowers[end::front].start_type = MotorBlowers[end::rear].start_type; } + // what else the line contactors need to close + { + std::map> const interlocks{{"Converter", line_contactors_interlock::converter}, + {"MotorBlowers", line_contactors_interlock::motor_blowers}}; + auto lookup = interlocks.find(extract_value("LineContactorsInterlock", line)); + LineContactorsInterlock = lookup != interlocks.end() ? lookup->second : line_contactors_interlock::none; + } + extract_value(LouvresOpenPressure, "LouvresOpenPressure", line, ""); // compartment lights { auto lookup = starts.find(extract_value("CompartmentLightsStart", line)); 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/hamulce.cpp b/McZapkie/hamulce.cpp index 9411dc425..b30372e5e 100644 --- a/McZapkie/hamulce.cpp +++ b/McZapkie/hamulce.cpp @@ -1467,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; @@ -1770,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; @@ -1989,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-); diff --git a/application/application.cpp b/application/application.cpp index 01b2ce9a6..bed4bf3ae 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -18,12 +18,14 @@ 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" @@ -33,6 +35,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/dictionary.h" #include "version_info.h" #include "simulation/simulationtest.h" +#include "utilities/physicslog.h" #include #include #include @@ -747,6 +750,14 @@ void eu07_application::exit() 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 physics logs"); + // what is kept of them, the black box's written last + PhysicsLogs.stop(); step("the modes"); for (auto &mode : m_modes) mode.reset(); @@ -758,6 +769,8 @@ void eu07_application::exit() m_network.reset(); // SafeDelete( simulation::Train ); + step("the odometers"); + simulation::Vehicles.save_odometers(); step("the scenery"); SafeDelete(simulation::Region); @@ -1436,9 +1449,9 @@ int eu07_application::create_main_window() Global.bFullScreen = true; } - // a selftest of the editor run while the computer is in use for something else draws into a window never shown nor focused, - // and test mode keeps its window hidden: glfw, the ui and the input still need one, but nothing is shown in it - bool const shown{std::getenv("EU07_EDITOR_SELFTEST_HIDDEN") == nullptr && false == Global.test.enabled}; + // 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) diff --git a/application/driverhints.cpp b/application/driverhints.cpp index ae39ede7a..0c6f02cc8 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -326,6 +326,14 @@ 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( diff --git a/application/drivermode.cpp b/application/drivermode.cpp index 71a343d6b..efaba691b 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #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" @@ -160,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() { @@ -318,6 +343,17 @@ bool driver_mode::update() Timer::subsystem.sim_lights.start(); simulation::Lights.update(); Timer::subsystem.sim_lights.stop(); + { + // 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) { diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 3b4e6c9c2..91fb2ff62 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -40,6 +40,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() { @@ -47,6 +67,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 ) }; @@ -72,53 +94,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 }; - if( auto const speedatproximitydistance { min_speed( schedulespeedlimit, static_cast( owner->VelNext ) ) }; 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( @@ -223,6 +199,12 @@ drivingaid_panel::render_contents() { } } + // only the coupler the camera is next to, and the one of the vehicle it was coupled with + if( m_brokenvehicle != nullptr && ImGui::Button( STR_C( "Repair coupler" ) ) ) { + command_relay commandrelay; + commandrelay.post( user_command::repaircoupler, m_brokenend, 0.0, GLFW_PRESS, 0, glm::vec3( 0.0f ), &m_brokenvehicle->name() ); + } + ui_panel::render_contents(); } @@ -546,6 +528,7 @@ void debug_panel::update() m_powergridlines.clear(); m_cameralines.clear(); m_rendererlines.clear(); + m_couplerlines.clear(); #ifdef WITH_UART m_uartlines.clear(); #endif @@ -559,6 +542,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 @@ -608,6 +592,7 @@ debug_panel::render() { 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 ); @@ -1510,6 +1495,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 ) { diff --git a/application/driveruipanels.h b/application/driveruipanels.h index ed971f9ff..0e8b6917e 100644 --- a/application/driveruipanels.h +++ b/application/driveruipanels.h @@ -26,6 +26,9 @@ public: 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 { @@ -90,6 +93,8 @@ private: void update_section_powergrid( std::vector &Output ) const; void update_section_camera( std::vector &Output ) const; void update_section_renderer( std::vector &Output ); + // 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 ) const; #endif @@ -102,6 +107,8 @@ private: bool render_section_scenario(); bool render_section_eventqueue(); bool render_section_renderer(); + // 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 @@ -119,6 +126,14 @@ private: std::vector m_rendererlines; std::vector m_renderersections; // the data of the renderer, each part under a header of its own 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(); diff --git a/application/editormode.cpp b/application/editormode.cpp index 61f1405fc..93498a58d 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "world/TrackSleepers.h" #include +#include #include #include #include @@ -26,6 +27,7 @@ extern char **environ; #include "application/editorprojection.h" #include "application/application.h" +#include "editor/editorKilometrage.hpp" #include "editor/editorSettings.hpp" #include "editor/editorModelSets.hpp" #include "editor/editorTrackPresets.hpp" @@ -44,6 +46,7 @@ extern char **environ; #include "simulation/simulationtime.h" #include "simulation/simulationenvironment.h" #include "widgets/weatherpanel.h" +#include "simulation/blackboxrecorder.h" #include "utilities/Timer.h" #include "Console.h" #include "rendering/renderer.h" @@ -702,7 +705,7 @@ bool editor_mode::init() 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); - m_nmt_state.shape = model.shape; + // 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(); @@ -753,6 +756,8 @@ void editor_mode::start_focus(scene::basic_node *node, double duration) 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; @@ -1397,6 +1402,7 @@ bool editor_mode::update() Global.editor_tracks = (current_work_area() == work_area::tracks); selftest_step(); steps.step("selftest"); + thumbnails_trim(); // 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) { @@ -1528,6 +1534,9 @@ bool editor_mode::update() { 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) { @@ -1591,6 +1600,7 @@ bool editor_mode::update() 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"); @@ -1620,7 +1630,7 @@ bool editor_mode::update() draw_switch_slide(); if (m_track_tab == track_tab::turntable) draw_turntable_overlay(); - if (m_track_tab == track_tab::srk) + if (m_track_tab == track_tab::signals) { signal_refresh(); signal_move_update(); @@ -1658,6 +1668,12 @@ bool editor_mode::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(); @@ -1665,6 +1681,7 @@ bool editor_mode::update() 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(); @@ -1681,6 +1698,7 @@ bool editor_mode::update() } 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(); @@ -1704,6 +1722,9 @@ bool editor_mode::update() 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(); if (m_terrain_open) @@ -1808,6 +1829,12 @@ void editor_mode::render_terrain_ui() 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(); + // 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)) { @@ -1843,11 +1870,6 @@ void editor_mode::render_terrain_ui() } } - if (nmt_busy()) - ImGui::SetNextItemOpen(true); - if (ImGui::CollapsingHeader(STR_C("Terrain model (NMT)"))) - render_nmt_ui(); - if (ImGui::CollapsingHeader(STR_C("Chunk resolution"), m_terrain_tool == terrain_tool::spacing ? ImGuiTreeNodeFlags_DefaultOpen : 0)) { // chunks removed since are no longer selected @@ -1983,9 +2005,7 @@ void editor_mode::render_terrain_ui() 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.")); } - ImGui::SetNextItemWidth(160.0f); - ImGui::InputText(STR_C("Material"), m_terrain_material, IM_ARRAYSIZE(m_terrain_material)); - material_drop(m_terrain_material, IM_ARRAYSIZE(m_terrain_material)); + 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); @@ -2083,11 +2103,9 @@ void editor_mode::render_terrain_ui() 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; - ImGui::SetNextItemWidth(160.0f); - ImGui::InputText(STR_C("Material##water"), m_water_material, IM_ARRAYSIZE(m_water_material)); - material_drop(m_water_material, IM_ARRAYSIZE(m_water_material)); + 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("Empty: %s, the water material of the terrain"), m_streamer.manifest().water_material.c_str()); + 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"))) { @@ -2157,12 +2175,9 @@ void editor_mode::render_terrain_ui() m_water_material_of = m_water_selected; } bool retexture = false; - ImGui::SetNextItemWidth(160.0f); - ImGui::InputText(STR_C("Material of the chosen"), m_water_selected_material, IM_ARRAYSIZE(m_water_selected_material)); - retexture |= ImGui::IsItemDeactivatedAfterEdit(); - retexture |= material_drop(m_water_selected_material, IM_ARRAYSIZE(m_water_selected_material)); + 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("A material or a texture (drag one from the texture browser).\nEmpty: %s, the water material of the terrain"), m_streamer.manifest().water_material.c_str()); + 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); @@ -2188,17 +2203,12 @@ void editor_mode::render_terrain_ui() m_water_material_of = -1; } // the material of the bodies of water which don't name their own - if (false == m_water_default_edited) - std::snprintf(m_water_default_material, sizeof(m_water_default_material), "%s", m_streamer.manifest().water_material.c_str()); - ImGui::SetNextItemWidth(160.0f); - ImGui::InputText(STR_C("Default water material"), m_water_default_material, IM_ARRAYSIZE(m_water_default_material)); - m_water_default_edited = ImGui::IsItemActive(); - bool redefault = ImGui::IsItemDeactivatedAfterEdit(); - redefault |= material_drop(m_water_default_material, IM_ARRAYSIZE(m_water_default_material)); + 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(m_water_default_material); + m_streamer.water_material(defaultmaterial); } if (ImGui::CollapsingHeader(STR_C("Modifiers"))) @@ -2266,9 +2276,9 @@ void editor_mode::draw_terrain_overlay() return; screen_projection const projection; auto *drawlist = ImGui::GetBackgroundDrawList(); - glm::dvec3 const offset = GfxRenderer->Mouse_Position(); - bool const hovering = glm::length(offset) > 1e-3 && false == ImGui::GetIO().WantCaptureMouse; - glm::dvec3 const cursor = Camera.Pos + offset; + // 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; @@ -2283,12 +2293,12 @@ void editor_mode::draw_terrain_overlay() } }; - // the holes and the grass are aimed at the ground itself, also over an opening and behind the blades + // the brush aimed at the ground itself along the ray through the cursor glm::dvec3 brushcentre = cursor; - bool const onground = (m_terrain_tool == terrain_tool::holes || m_terrain_tool == terrain_tool::grass) && false == ImGui::GetIO().WantCaptureMouse && terrain_cursor(brushcentre); - if (terrain_brush() && (hovering || onground)) + bool const onground = false == ImGui::GetIO().WantCaptureMouse && terrain_cursor(brushcentre); + if (terrain_brush() && onground) { - auto const cursor = onground ? brushcentre : Camera.Pos + offset; + auto const cursor = brushcentre; std::vector circle; for (int i = 0; i < 64; ++i) { @@ -2479,7 +2489,7 @@ void editor_mode::load_orthophoto_settings() 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}, "//$a"); + 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)); @@ -2624,17 +2634,54 @@ void editor_mode::render_orthophoto_ui() if (ImGui::TreeNode(STR_C("More settings"))) { - if (ImGui::Checkbox(STR_C("Fit to terrain"), &config.drape)) + // 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 { - changed = true; - persist = true; + 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) { + if (ImGui::RadioButton(Label, current == Look) && current != Look) + { + config.in_scene = Look != look::overlay; + config.drape = Look != look::sheet; + changed = true; + persist = true; + } + }; + 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 (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("Lays the imagery onto the ground geometry (terrain shapes, terrain tile models, heightmap terrain).\n" - "Places without any ground use the height below.")); + if (config.drape) { - ImGui::SameLine(); if (ImGui::Button(STR_C("Refit"))) { // the ground was edited: what's kept of it has to go as well @@ -2645,33 +2692,22 @@ void editor_mode::render_orthophoto_ui() layer->refit(); } if (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("Samples the ground again, after it was edited")); + 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.")); + } } - - begin_disabled(!config.drape); ImGui::SetNextItemWidth(160.0f); - changed |= ImGui::DragFloat(STR_C("Lift above ground (m)"), &config.lift, 0.01f, 0.0f, 50.0f, "%.2f"); + 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(); - end_disabled(!config.drape); - if (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("Raises the fitted imagery above the ground. Keep it below the objects you want to see:\n" - "in the scene everything lower than this ends up under the imagery.")); - - begin_disabled(config.drape); - ImGui::SetNextItemWidth(160.0f); - changed |= ImGui::DragFloat(STR_C("Height (m)"), &config.height, 0.1f, -1000.0f, 3000.0f, "%.2f"); - persist |= ImGui::IsItemDeactivatedAfterEdit(); - end_disabled(config.drape); - - if (ImGui::Checkbox(STR_C("Covered by objects and terrain"), &config.in_scene)) - { - changed = true; - persist = true; - } - if (ImGui::IsItemHovered()) - ImGui::SetTooltip(STR_C("Draws the imagery as part of the scene, so tracks, models and terrain in front of it hide it.\n" - "It is lit like the scene. Fully opaque, mouse placement lands on it as on any surface;\n" - "translucent, it doesn't catch the mouse.")); + ImGui::Spacing(); ImGui::SetNextItemWidth(160.0f); changed |= ImGui::SliderFloat(STR_C("Opacity"), &config.opacity, 0.0f, 1.0f, "%.2f"); @@ -2775,7 +2811,8 @@ void editor_mode::draw_ortho_compass() const ImGuiIO const &io = ImGui::GetIO(); float const radius{36.0f}; float const margin{16.0f}; - ImVec2 const center{io.DisplaySize.x - margin - radius, margin + radius}; + // 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); @@ -2897,10 +2934,9 @@ void editor_mode::add_chunks_around(int const Count) void editor_mode::handle_terrain_click(bool const Shift) { - glm::dvec3 const offset = GfxRenderer->Mouse_Position(); - if (glm::length(offset) < 1e-3) - return; // nothing under the cursor (yet) - glm::dvec3 const world = Camera.Pos + offset; + glm::dvec3 world; + if (false == cursor_on_ground(world)) + return; // nothing under the cursor switch (m_terrain_tool) { case terrain_tool::chunks: @@ -3350,7 +3386,7 @@ bool editor_mode::save() 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}, "//$a", area); + scene::Layers.mark(scene::layer_handle{1}, "//$z", area); } auto const controls{turntable_controls(rootstatements)}; auto const noses{nose_controls(rootstatements)}; @@ -3403,6 +3439,7 @@ void editor_mode::toggle_include(scene::instance_handle const Instance) 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())); } @@ -3439,6 +3476,7 @@ void editor_mode::restore_includes(EditorSnapshot &Snapshot) } 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); @@ -3483,6 +3521,7 @@ void editor_mode::select_include(scene::instance_handle const Instance) 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 && @@ -3515,19 +3554,51 @@ void editor_mode::apply_include() } } 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; - if (false == m_include.info.signal_read.empty()) + // 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)) { - 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 (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) @@ -3546,6 +3617,12 @@ void editor_mode::apply_include() 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) @@ -3625,18 +3702,11 @@ void editor_mode::export_scenery() void editor_mode::handle_terrain_brush(double Deltatime) { - // world point under the cursor (Mouse_Position is camera-relative, like the brush placement uses) - glm::dvec3 const offset = GfxRenderer->Mouse_Position(); - glm::dvec3 world = Camera.Pos + offset; - if (m_terrain_tool == terrain_tool::holes || m_terrain_tool == terrain_tool::grass) - { - // the ground itself: the cursor may be over a hole (and what's seen through it), or over the blades of the grass - if (false == terrain_cursor(world)) - return; - } - else if (glm::length(offset) < 1e-3) + // 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 (avoids editing on a stale depth read) + // only when the cursor is over the terrain if (terrain_at(world.x, world.z) == nullptr) return; @@ -3695,12 +3765,20 @@ void editor_mode::handle_terrain_brush(double Deltatime) } } +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 to what the depth under the cursor shows, or, with nothing there, the ray through the cursor - glm::dvec3 const offset = GfxRenderer->Mouse_Position(); - if (glm::length(offset) > 1e-3) - return m_streamer.raycast(Camera.Pos, glm::normalize(offset), 5000.0, World); + // 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; @@ -3714,7 +3792,11 @@ bool editor_mode::terrain_cursor(glm::dvec3 &World) const auto const direction = point(0.5f) - point(0.0f); if (glm::length(direction) < 1e-9) return false; - return m_streamer.raycast(GfxRenderer->Camera_Position() + point(0.0f), glm::normalize(direction), 5000.0, World); + // 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::render_grass_ui() @@ -3871,10 +3953,10 @@ void editor_mode::convert_selected_chunks() bool editor_mode::pick_terrain_target() { - glm::dvec3 const offset = GfxRenderer->Mouse_Position(); - if (glm::length(offset) < 1e-3) + glm::dvec3 world; + if (false == cursor_on_ground(world)) return false; // nothing under the cursor - m_terrain_target = static_cast(Camera.Pos.y + offset.y); + m_terrain_target = static_cast(world.y); m_terrain_status = format(STR_C("Target height: %.2f m"), m_terrain_target); return true; } @@ -3939,6 +4021,11 @@ void editor_mode::capture_terrain() // 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 @@ -4095,6 +4182,9 @@ 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); @@ -4408,6 +4498,14 @@ void editor_mode::render_view_menu() 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()) @@ -4652,6 +4750,26 @@ void editor_mode::terrain_workspace(bool const Open) 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() @@ -4674,14 +4792,13 @@ void editor_mode::render_object_menu() void editor_mode::add_area_fill_point() { - // like the other placement tools, the point comes from the depth buffer under the cursor - // (ground geometry only), relative to the camera - glm::dvec3 const offset = GfxRenderer->Mouse_Position(); - if (glm::length(offset) < 1e-3) - return; // no ground under the cursor (yet) + // 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(Camera.Pos + offset)); + m_fill_points.push_back(placement_on_ground(world)); } void editor_mode::undo_last_area_fill() @@ -4911,7 +5028,8 @@ 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); - ImGui::Text(STR_C("Points: %zu Area: %.0f m² (%.2f ha)"), m_fill_points.size(), area, area / 10000.0); + // 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(); @@ -5379,7 +5497,7 @@ void editor_mode::render_workspaces() }; 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, objects along the track, checks of the line")}, + {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")}, {STR_C("Catenary"), work_area::catenary, editor_icons::icon::work_catenary, STR_C("The overhead catenary: poles with cantilevers, gantries, the wires of the chains")}, @@ -5498,7 +5616,7 @@ void editor_mode::render_help_menu() 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("Thirteen short lessons with clips and drawings: the camera, laying track, curves, correcting a curve, joining, switches, signals and posts, fixing, the gizmo, the grade line, terrain, older sceneries, saving and driving")); + 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(); } @@ -5507,6 +5625,12 @@ 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 { @@ -5573,23 +5697,92 @@ void tutorial_profile_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const Hi 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))}; - ImVec2 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, 4, IM_COL32(170, 170, 170, 160), 0, 1.0f); - List.AddPolyline(points, 4, IM_COL32(90, 220, 110, 255), 0, 2.5f); - for (int i = 0; i < 4; ++i) + 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 (int i = 0; i < 3; ++i) + 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}; - char text[32]; - std::snprintf(text, sizeof(text), "%+.1f", std::abs(grade) < 0.05f ? 0.0f : grade); + 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).x * 0.5f, middle.y), i == 0 ? IM_COL32(200, 200, 200, 255) : IM_COL32(255, 255, 255, 255), text); + 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) @@ -5603,7 +5796,7 @@ void tutorial_route_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High 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 - ImVec2 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)}; + 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))}; @@ -5642,7 +5835,7 @@ void tutorial_route_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const High 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") : STR_C("LMB on a track: its whole line")}; + 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); } @@ -5658,13 +5851,10 @@ void tutorial_signal_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const Hig // 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) { - float x{0.02f}; - while (x < 1.0f) - { - List.AddLine(ImVec2(at(x, 0.0f).x, middle - gauge * 1.6f), ImVec2(at(x, 0.0f).x, middle + gauge * 1.6f), IM_COL32(110, 90, 70, 255), 3.0f); - x += 0.025f; - } + 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); @@ -5691,11 +5881,9 @@ void tutorial_signal_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const Hig 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); - for (int i = 0; i < 3; ++i) - { - ImU32 const lights[]{IM_COL32(230, 60, 50, 255), IM_COL32(70, 210, 90, 255), IM_COL32(240, 240, 240, 255)}; - List.AddCircleFilled(ImVec2(foot.x, head_low.y + height * (0.04f + 0.065f * i)), height * 0.025f, lights[i]); - } + 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"); @@ -5706,15 +5894,14 @@ void tutorial_signal_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const Hig 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 * i, 0.0f).x}; + 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); - char text[16]; - std::snprintf(text, sizeof(text), "12.%d", i + 1); - auto const size{ImGui::CalcTextSize(text)}; - 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); + 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: the hectometre posts of the whole line at once")); + 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 @@ -5728,9 +5915,12 @@ void tutorial_vehicle(ImDrawList &List, ImVec2 const Low, ImVec2 const High, ImU auto const windows{Locomotive ? 2 : 5}; for (int i = 0; i < windows; ++i) { - auto const left{Locomotive ? (i == 0 ? Low.x + width * 0.06f : High.x - width * 0.2f) : Low.x + width * (0.08f + 0.18f * 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(left, Low.y + height * 0.15f), ImVec2(left + size, Low.y + height * 0.42f), IM_COL32(30, 40, 50, 255), 2.0f); + 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}) { @@ -5748,14 +5938,15 @@ void tutorial_trainset_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const H 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))}; - ImU32 const colours[]{IM_COL32(200, 60, 50, 255), IM_COL32(60, 120, 70, 255), IM_COL32(70, 100, 160, 255)}; + 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 (int i = 0; i < 3; ++i) + for (std::size_t i = 0; i < colours.size(); ++i) { - auto const top{0.08f + 0.28f * i}; - auto const clicked{cycle > 0.8f + 1.4f * i && cycle < 1.2f + 1.4f * i}; - if (clicked) + 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); @@ -5763,7 +5954,7 @@ void tutorial_trainset_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const H } // 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 * row)}; + 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)}; @@ -5780,10 +5971,10 @@ void tutorial_trainset_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const H 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 (int i = 0; i < added; ++i) + for (std::size_t i = 0; i < static_cast(added); ++i) { - auto const left{at(0.46f, 0.0f).x + (car + 3.0f) * i - run}; - tutorial_vehicle(List, ImVec2(left, rail - height * 0.24f), ImVec2(left + car, rail), colours[i], i == 0); + 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"); @@ -5804,7 +5995,8 @@ void tutorial_terrain_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const Hi 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, track; + std::vector ground; + std::vector track; for (int i = 0; i <= steps; ++i) { auto const share{static_cast(i) / steps}; @@ -5815,15 +6007,14 @@ void tutorial_terrain_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const Hi List.Flags &= ~ImDrawListFlags_AntiAliasedFill; for (int i = 0; i < steps; ++i) { - ImVec2 const quad[]{ground[i], ground[i + 1], ImVec2(ground[i + 1].x, High.y), ImVec2(ground[i].x, High.y)}; - List.AddConvexPolyFilled(quad, 4, IM_COL32(95, 120, 70, 120)); + 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}; - ImVec2 const quad[]{track[i], track[i + 1], ground[i + 1], ground[i]}; - List.AddQuadFilled(quad[0], quad[1], quad[2], quad[3], fill ? IM_COL32(190, 150, 90, 150) : IM_COL32(60, 45, 30, 150)); + 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); @@ -5834,14 +6025,215 @@ void tutorial_terrain_sketch(ImDrawList &List, ImVec2 const Low, ImVec2 const Hi } // namespace -void editor_mode::render_first_steps() +// 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 { - if (false == m_first_steps_open) + // 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 { - if (false == m_tutorial_clip.path().empty()) - m_tutorial_clip.close(); - return; - } + 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) @@ -5856,160 +6248,67 @@ void editor_mode::render_first_steps() 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); - enum class trial { none, top, lay, turnout, select, profile, terrain, plan, trainset, signals }; - struct input + 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) { - char const *keys; - char const *text; + 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()); }; - struct goal + // 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) { - first_step step; - char const *text; - }; - struct lesson + m_tutorial_followed = followed; + open_lesson(followed); + } + if (m_tutorial_goto != nullptr) { - char const *title; - char const *clip; - std::vector inputs; - std::vector goals; - trial action; - void (*sketch)(ImDrawList &, ImVec2, ImVec2, double){nullptr}; - }; - static std::vector const lessons{ - {"Looking around", - "camera", - {{"RMB + move", "Hold the right button and move the mouse: look around"}, - {"RMB + W S A D", "With the right button held: fly forwards, back and to the sides; E and Q: up and down"}, - {"O", "The top view, and back to 3D"}, - {"wheel", "Zoom in and out where the cursor points"}, - {"MMB + move", "In the top view: hold the wheel and drag to move the map"}, - {"F", "Fly to what is selected"}}, - {{first_step::look, "Look around with the right button held"}, {first_step::top, "Switch to the top view"}}, - trial::top}, - {"Laying track", - "lay", - {{"F3", "The Tracks field of work"}, - {"L", "The lay tool"}, - {"LMB", "A click on the ground or on a free end: where the track starts"}, - {"LMB", "Each next click: a bend of the line, the curve at it made by itself. The line shown isn't a track yet"}, - {"Enter", "Lays the track clicked; to go on from its end, click the end"}, - {"Backspace", "Takes the last point back"}, - {"Esc", "Ends laying; the points not laid yet go only with the second Esc"}}, - {{first_step::tracks, "Open the Tracks field of work"}, {first_step::lay, "Turn the lay tool on"}, {first_step::laid, "Click a few points and lay them with Enter"}}, - trial::lay}, - {"Curves", - "curves", - {{"LMB", "Click the bends of the line: each gets a curve as large as fits; one too sharp for the speed set in the panel has its label in orange"}, - {"Tab", "A curve seen on the photo: click points along its middle, the curve ending at the last one; one of two or three radii comes out a compound curve"}, - {"Alt", "Held: the direction turns in steps of 15 degrees, or to 1:9, 1:6.6... to a straight track it starts by or crosses"}, - {"0 1 2 3", "Type the length of the next straight, Enter puts the point"}, - {"wheel", "Alone it zooms, as everywhere"}}, - {{first_step::bend, "Lay a track with a bend in it"}, {first_step::trace, "Switch to tracing a curve with Tab"}}, - trial::lay}, - {"Correcting a curve", - "plan", - {{"G", "The plan tool: a click on a curve shows its design, the vertex and the radius to drag in the view"}, - {"LMB + move", "In the panel, the band of the curvature: drag the plateau of an arc up or down for its radius, each arc of a compound curve its own"}, - {"LMB + move", "Drag a ramp sideways: the transition curve gets longer or shorter"}, - {"wheel", "Over the band: the radius by 5%, a transition by 5 m"}, - {"LMB", "Apply to the scenery: the tracks are laid by the design"}}, - {{first_step::plan, "Open the plan of a curve"}, {first_step::plan_band, "Change the curve in the band"}, {first_step::plan_apply, "Apply it to the scenery"}}, - trial::plan}, - {"Joining tracks", - "join", - {{"LMB + move", "Press on a free end (a magenta ring) and drag: a new track goes out of it"}, - {"LMB", "Let go on another free end: a curve joins the two tracks"}, - {"Ctrl + wheel", "While over the other end: the radius of the joining curve"}, - {"Shift + wheel", "While over the other end: another way to join"}}, - {{first_step::join, "Join two free ends"}, {first_step::wheel, "Change the radius of the joining curve with Ctrl+wheel"}}, - trial::lay}, - {"Switches", - "switch", - {{"T", "The switch tool; at the top: what to place"}, - {"LMB", "Click a track: the one the switch goes into"}, - {"LMB + move", "Press on it and drag: along the direction, sideways the side; let go: the switch is laid"}, - {"LMB + move", "Connection: drag from a straight onto the other track; a crossover, a double one or scissors, as chosen at the top"}, - {"LMB + move", "Switch ladder: drag from the straight to the side the tracks go off to; the ones missing are laid with it"}, - {"Esc", "Back to selecting"}}, - {{first_step::turnout, "Put a switch into a track"}}, - trial::turnout}, - {"Signals and posts", - nullptr, - {{"I", "The signalling tool: click a type of signal in its Signals, from the templates of the scenery"}, - {"LMB", "A click by a track places the signal on that side"}, - {"LMB + move", "Press by the track and drag along it: the trains running that way see the signal"}, - {"LMB + move", "Drag a standing signal: it moves along its track"}, - {"B", "Objects along the track: the hectometre posts and the W17 markers of a whole line at once, and trainsets"}}, - {{first_step::signal, "Place a signal"}, {first_step::posts, "Place the hectometre posts of a line"}}, - trial::signals, - tutorial_signal_sketch}, - {"Selecting and fixing", - "edit", - {{"Esc", "The select tool"}, - {"LMB", "Click a track: it is selected, with its ends"}, - {"LMB + move", "Drag an end: at a joint the neighbours follow, from a free end a new track goes out, with Ctrl the end moves"}, - {"RMB", "A click on a track: what can be done with it"}, - {"Del", "Deletes the selected"}, - {"Ctrl + Z", "Takes the last change back; Ctrl+Y brings it back again"}, - {"Q W E", "The gizmo, to move, turn or bend the track: the next lesson"}}, - {{first_step::select, "Select a track"}, {first_step::undo, "Take a change back"}}, - trial::select}, - {"Editing with the gizmo", - "gizmo", - {{"Q", "The gizmo on the selected track, hidden until then: arrows which move it"}, - {"W", "Rings which turn it: its direction, its grade and its cant; the tracks joined to it follow"}, - {"E", "Handles which lengthen it at its free end, the curve keeping its radius"}, - {"LMB + move", "With the gizmo out the control vectors are there too: drag one, the curve follows it"}, - {"LMB", "A click on a point of the track: the gizmo goes to it, that point alone is moved or turned"}, - {"Ctrl", "Held while dragging: the gizmo goes by its step"}, - {"Esc", "Releases the point; the arrow above the view hides the gizmo again"}}, - {{first_step::gizmo, "Bring out the gizmo with Q, W or E"}, {first_step::vector, "Bend a track by a control vector, or move it with the gizmo"}}, - trial::select}, - {"The grade line", - nullptr, - {{"P", "The profile tool: a click on a track opens the grade line of its whole line in the strip below"}, - {"Shift + LMB", "A click adds a track, a box from the empty ground takes the tracks in it: the route runs between the outermost of them"}, - {"LMB + move", "Drag a point of the grade line: the grades on both sides of it follow"}, - {"LMB LMB", "A double click on the line adds a point"}, - {"Del", "Removes the chosen point"}, - {"Ctrl + wheel", "Over the plot: the heights stretched, the grades seen better"}, - {"RMB + move", "Over the plot: the view moves along the line"}}, - {{first_step::profile, "Open the grade line of a track"}, {first_step::profile_point, "Move or add a point"}, {first_step::profile_apply, "Apply it: the tracks take its heights"}}, - trial::profile, - tutorial_route_sketch}, - {"Terrain from the terrain model", - nullptr, - {{"L", "In a scenery begun from nothing the first L asks: the real terrain of the place, or the flat plane"}, - {"F5", "The Terrain field of work: the terrain model (NMT) is in its tool options"}, - {"1", "Location: where the scenery lies, a click on the map or the place typed"}, - {"2", "Load along the tracks, or around the camera: the model comes from geoportal.gov.pl"}, - {"3", "Tracks onto the terrain: the tracks not fitted yet go onto the model, the ones fitted stay; the terrain to some tracks only: select them, Terrain in the inspector"}, - {"Ctrl + Z", "Takes the changes back"}}, - {{first_step::terrain, "Open the Terrain field of work"}, {first_step::nmt, "Load terrain from the model"}}, - trial::terrain, - tutorial_terrain_sketch}, - {"Sceneries made before", - nullptr, - {{"LMB", "A track of an include or of a file that isn't saved: the inspector says why it can't be changed"}, - {"T", "Switches laid before keep their shape; Replace the geometry with the template, under More settings of the switch, gives them the one of the catalogue"}, - {"P", "Grade lines kept by an older editor are read as they were kept"}, - {"Ctrl + S", "Only what changed is written: the other lines stay as they were, the comment lines of other tools too"}}, - {}, - trial::none}, - {"Saving and driving", - nullptr, - {{"Ctrl + S", "Saves the scenery"}, - {"LMB", "Trainset tool: a click on the track where the train stands"}, - {"LMB LMB", "A double click on a vehicle of the list puts it into the train; a click on a vehicle of the train moves it, turns it or takes it out"}, - {"LMB", "Place and drive: the train goes onto the track and the cab is yours"}}, - {{first_step::save, "Save the scenery"}, {first_step::drive, "Drive on the new track"}}, - trial::trainset, - tutorial_trainset_sketch}, - }; - auto const done = [&](lesson const &Lesson) { - return false == Lesson.goals.empty() && std::all_of(Lesson.goals.begin(), Lesson.goals.end(), [&](goal const &Goal) { return m_first_steps_done[static_cast(Goal.step)]; }); - }; + 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) @@ -6019,6 +6318,20 @@ void editor_mode::render_first_steps() 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); @@ -6032,171 +6345,181 @@ void editor_mode::render_first_steps() 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)); - if (lesson.clip != nullptr && false == m_tutorial_clip.missing()) - { - auto const height{width * 320.0f / 520.0f}; - if (auto const texture{m_tutorial_clip.texture(ImGui::GetTime() - m_tutorial_since)}; texture != 0) - { - ImGui::Image(static_cast(texture), ImVec2(width, width * m_tutorial_clip.height() / std::max(1, m_tutorial_clip.width()))); - 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)); - } - ImGui::SeparatorText(STR_C("Mouse and keys")); - for (auto const &entry : lesson.inputs) - tutorial_input(entry.keys, entry.text, 150.0f * 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 (m_tutorial_page == 1 && ui()->mode() == nodebank_panel::TRACK && false == GfxRenderer->Mouse_Hit()) - ImGui::TextColored(ImVec4(1.0f, 0.7f, 0.2f, 1.0f), "%s", STR_C("No ground under the cursor: track goes onto the level 0 plane, drawn as a grid. Terrain: F5")); - switch (lesson.action) - { - case trial::top: - if (ImGui::Button(Global.EditorOrtho ? STR_C("3D view (O)") : STR_C("Top view, orthographic (O)"))) - toggle_ortho(); - break; - case trial::profile: - { - auto const on{ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::profile}; - ImGui::BeginDisabled(on); - if (ImGui::Button(STR_C("The profile tool (P)"))) - { - choose_work_area(work_area::tracks); - show_track_tab(track_tab::profile); - } - ImGui::EndDisabled(); - break; - } - case trial::signals: - { - ImGui::BeginDisabled(ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::srk); - if (ImGui::Button(STR_C("The signalling tool (I)"))) - { - choose_work_area(work_area::tracks); - show_track_tab(track_tab::srk); - } - ImGui::EndDisabled(); - break; - } - case trial::trainset: - { - ImGui::BeginDisabled(ui()->mode() == nodebank_panel::TRACK && m_track_tab == track_tab::lineside && m_vehicle.tab().open); - if (ImGui::Button(STR_C("The trainset tool"))) - { - choose_work_area(work_area::tracks); - show_track_tab(track_tab::lineside); - m_vehicle.tab().expand = true; - } - ImGui::EndDisabled(); - break; - } - case trial::plan: - { - ImGui::BeginDisabled(ui()->mode() == nodebank_panel::TRACK && (m_track_tab == track_tab::route || m_track_tab == track_tab::straights)); - if (ImGui::Button(STR_C("The plan tool (G)"))) - { - choose_work_area(work_area::tracks); - show_track_tab(track_tab::straights); - } - ImGui::EndDisabled(); - break; - } - case 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(); - break; - } - case trial::lay: - case trial::turnout: - case trial::select: - { - auto const tab{lesson.action == trial::lay ? track_tab::lay : lesson.action == trial::turnout ? track_tab::turnout : track_tab::path}; - auto const on{ui()->mode() == nodebank_panel::TRACK && m_track_tab == tab}; - ImGui::BeginDisabled(on); - if (ImGui::Button(lesson.action == trial::lay ? STR_C("Lay track (L)") : lesson.action == trial::turnout ? STR_C("The switch tool (T)") : STR_C("The select tool (Esc)"))) - { - choose_work_area(work_area::tracks); - show_track_tab(tab); - } - ImGui::EndDisabled(); - break; - } - default: break; - } + render_tutorial_media(lesson, width); + render_tutorial_goals(lesson); + render_tutorial_trial(lesson); ImGui::PopTextWrapPos(); ImGui::Separator(); - 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 < static_cast(lessons.size()); ++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{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 < static_cast(lessons.size())) - { - 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(); - } + 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) @@ -6229,6 +6552,13 @@ void editor_mode::render_shortcuts_window() {"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"}, @@ -6250,7 +6580,7 @@ void editor_mode::render_shortcuts_window() {"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 / B", "Signalling / objects along the track"}, + {"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"}, @@ -6375,7 +6705,7 @@ void editor_mode::render_gizmo_options() 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::srk && + 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}; @@ -6608,11 +6938,16 @@ void editor_mode::render_include_gizmo(glm::mat4 const &View, glm::mat4 const &P if (positions == 0) return; // nothing tells where the include is - // only the axes the template has parameters for can be manipulated + // 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) + 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); @@ -6637,14 +6972,18 @@ void editor_mode::render_include_gizmo(glm::mat4 const &View, glm::mat4 const &P // 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::srk && false == ImGuizmo::IsUsing() && (m_signal.moving || m_signal.placing || signal_hit() >= 0)}; + 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); @@ -6674,6 +7013,7 @@ void editor_mode::render_include_gizmo(glm::mat4 const &View, glm::mat4 const &P } } apply_include(); + signal_gizmo_step(); } glm::mat4 editor_mode::projection_matrix(float const Aspect) @@ -6688,10 +7028,13 @@ glm::mat4 editor_mode::projection_matrix(float const Aspect) 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) { - first_step_done(first_step::top); m_ortho_pitch = Camera.Angle.x; Camera.Angle.x = -M_PI_2; Camera.Angle.z = 0.0; @@ -6700,6 +7043,7 @@ void editor_mode::toggle_ortho() { Camera.Angle.x = m_ortho_pitch; ortho_pan_stop(); + camera_above_ground(); } } @@ -6711,8 +7055,11 @@ void editor_mode::ortho_pan_to(double const Horizontal, double const Vertical) 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{2.0 * static_cast(Global.EditorOrthoExtent) / static_cast(io.DisplaySize.y)}; - auto const world{RotateY(glm::dvec3{dx * scale, 0.0, dy * scale}, static_cast(Camera.Angle.y))}; + 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 = {}; @@ -6729,6 +7076,13 @@ 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; @@ -6784,6 +7138,12 @@ void editor_mode::update_camera(double const Deltatime) 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 @@ -6837,11 +7197,41 @@ void editor_mode::update_camera(double const Deltatime) 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) { @@ -6939,7 +7329,10 @@ void editor_mode::enter() 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; @@ -7085,6 +7478,27 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in 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; @@ -7129,6 +7543,14 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in 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) { @@ -7167,12 +7589,12 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in if (from != nullptr) copy_track_style(*from); else - ui()->set_status(STR_C("Select one track, or point at one, to copy its properties"), true); + 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("Copy the properties of a track first: Ctrl+Shift+C"), true); + 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 paste the properties on"), true); + ui()->set_status(STR_C("Select the tracks to set the properties on"), true); else paste_track_style(tracks); } @@ -7205,7 +7627,7 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in return; // 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)) + 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)) { @@ -7257,6 +7679,12 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in // 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) { @@ -7278,12 +7706,16 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in 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::srk && m_signal.armed) + 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({}); @@ -7311,6 +7743,16 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in 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) { @@ -7399,6 +7841,16 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const return; } + // 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)) + 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; + } + // 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) { @@ -7439,6 +7891,18 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const // 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 @@ -7673,7 +8137,7 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const // 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 && Global.EditorOrtho) + else if (Button == GLFW_MOUSE_BUTTON_MIDDLE) { if (is_press(Action)) { @@ -7681,6 +8145,17 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const 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(); @@ -7776,7 +8251,9 @@ void editor_mode::on_event_poll() 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) diff --git a/application/editormode.h b/application/editormode.h index 38d51286e..60da345e4 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #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" @@ -31,6 +33,7 @@ http://mozilla.org/MPL/2.0/. #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" @@ -60,6 +63,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include class TAnimModel; @@ -168,6 +172,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 @@ -186,6 +191,10 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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(); @@ -233,6 +242,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri bool m_dragging = false; 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; @@ -241,6 +251,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 @@ -253,6 +264,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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(); @@ -263,11 +276,31 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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) @@ -345,6 +378,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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}; @@ -363,6 +398,31 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 @@ -412,6 +472,28 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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}; @@ -455,6 +537,9 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 @@ -472,6 +557,9 @@ class editor_mode : public application_mode, private editor_track::observer, pri // 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 @@ -483,9 +571,15 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 3 of the terrain model (Terrain_panel), and in + // 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; @@ -501,10 +595,45 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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(); @@ -563,6 +692,10 @@ class editor_mode : public application_mode, private editor_track::observer, pri bool terrain_cursor(glm::dvec3 &World) const; // the grass of the terrain: the palette, the kind grown, presets void render_grass_ui(); + // 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 @@ -618,12 +751,23 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 + struct thumbnail + { + int texture{0}; // 0: none + int material{0}; // the material the texture is the first of, 0: a texture alone + double shown{0.0}; // when it was last asked for, ImGui time + }; + std::map thumbnails; // texture shown for the item of the name + bool refresh{false}; // all the images to be let go of and read again 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); + // the textures of the images out of sight for a while taken out of the memory: a picker of thousands of them scrolled + // through would keep them all, full size, until the memory ran out + void thumbnails_trim(); // 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 @@ -693,8 +837,6 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 - char m_water_default_material[128]{""}; // of the waters which don't name their own, while it's edited - bool m_water_default_edited{false}; 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 @@ -830,6 +972,28 @@ class editor_mode : public application_mode, private editor_track::observer, pri } 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 @@ -1212,6 +1376,11 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 @@ -1380,6 +1549,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 @@ -1444,13 +1614,18 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 - bool rail_only{true}; // the templates listed only for the rail of the selected track, where its rail profile tells it + 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 @@ -1466,12 +1641,45 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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; @@ -1513,6 +1721,9 @@ class editor_mode : public application_mode, private editor_track::observer, pri // 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(); @@ -1525,7 +1736,6 @@ class editor_mode : public application_mode, private editor_track::observer, pri void advance_switch_name(); void join_last_steps(); bool render_switch_drive_choice(); - int m_turnout_template{0}; struct turntable_template { std::string file; @@ -1654,6 +1864,31 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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}; @@ -1706,12 +1941,16 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 there: where a press on the ground starts it, at the free end of a track within reach or right there + // 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); @@ -1741,6 +1980,23 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 @@ -1797,7 +2053,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri // 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); + 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 @@ -1814,8 +2070,9 @@ class editor_mode : public application_mode, private editor_track::observer, pri double along{0.0}; int direction{1}; int side{1}; - segment_data insert; + 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 @@ -1974,8 +2231,10 @@ class editor_mode : public application_mode, private editor_track::observer, pri editor_icons::icon picture; int family; // 0 builds the track, 1 equips it, 2 checks it }; - static std::array const &track_modes(); + 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}; @@ -1994,7 +2253,18 @@ class editor_mode : public application_mode, private editor_track::observer, pri bool stretched{true}; double quick_radius{300.0}; double quick_ratio{9.0}; - double quick_straight{0.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; @@ -2004,6 +2274,14 @@ class editor_mode : public application_mode, private editor_track::observer, pri // 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(); @@ -2051,7 +2329,6 @@ class editor_mode : public application_mode, private editor_track::observer, pri // 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 - using track_hover = ::track_hover; track_hover m_hover; track_hover track_under_cursor(TTrack const *Only = nullptr, float const Pixels = 0.0f) const; track_hover split_spot() const; @@ -2067,7 +2344,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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, switch_slide, pick_style, fouling, measure, route_trace, kilometrage, srk_boundary, catenary }; + 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, catenary }; kind what{kind::none}; TTrack *track{nullptr}; int path{0}; @@ -2244,14 +2521,43 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 track_textures_index(); - // the picker of a texture of the rails (Kind 0) or of the trackbed (1), in an open combo. returns: true when one is chosen, its name in Chosen, "none" for no texture + 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 for the picker, 0 while there's none + // 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); @@ -2278,8 +2584,34 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 { @@ -2290,34 +2622,41 @@ class editor_mode : public application_mode, private editor_track::observer, pri int frame{0}; }; track_field m_track_field; - struct track_texture_use - { - material_handle material{null_handle}; - std::string name; - int count{0}; - }; - std::array, 2> m_track_textures; // of the rails, of the trackbed - std::array m_track_texture_filter{}; + 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_track_texture_index; // sorted by the name - bool m_track_texture_indexed{false}; - std::string m_track_texture_hovered; // the tile under the mouse in the picker, shown large above them - // properties copied from a track, to be pasted on others + 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; - // speed, environment, overhead line, track circuits, rails, trackbed, its shape, sleepers, ride and sound, frogs, sleeper placement, texture blending + // ticked at first by their groups: speed, environment, overhead line, track circuits, rails, trackbed, its shape, sleepers, ride and + // sound, frogs, sleeper placement, texture blending track_groups groups{false, false, false, false, true, true, true, true, false, true, true, true}; - bool open{false}; - bool picking{false}; // the next click on a track in the view copies its properties + 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 @@ -2339,6 +2678,16 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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); @@ -2359,10 +2708,12 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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() override; + void render_signal_templates(std::vector const &Kinds) override; struct signal_template { @@ -2379,6 +2730,25 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 { @@ -2391,6 +2761,10 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 { @@ -2400,26 +2774,33 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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}; + 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)}; - std::size_t standing_redo{static_cast(-1)}; double standing_time{-1.0}; int hover{-1}; scene::instance_handle selected{0}; @@ -2429,13 +2810,52 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 @@ -2445,21 +2865,93 @@ class editor_mode : public application_mode, private editor_track::observer, pri void signal_release(); bool signal_place(signal_spot const &Spot, signal_template const &Template); void signal_move_update(); - bool signal_standing_spot(signal_standing const &Standing, signal_spot &Spot) const; + // 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; @@ -2616,13 +3108,17 @@ class editor_mode : public application_mode, private editor_track::observer, pri bool marker_valid{false}; glm::dvec3 marker{0.0}; std::string status; - int dragging{0}; + 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; }; @@ -2640,6 +3136,16 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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); @@ -2734,6 +3240,14 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 @@ -2774,24 +3288,30 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 "//$f" comment lines: a track + // 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 m_fitted; + 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); + 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); @@ -2924,6 +3444,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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(); @@ -2935,9 +3456,11 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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}; + srk_tool m_srk{*this, *this, *this, *this, *this, *this}; km_tool m_km{*this, *this, *this, *this}; - std::vector m_tools{&m_gauge, &m_speed, &m_joints, &m_vehicle, &m_hekto, &m_fouling, &m_parallel, &m_srk, &m_km}; + 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(); @@ -2991,6 +3514,11 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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 @@ -3011,20 +3539,13 @@ class editor_mode : public application_mode, private editor_track::observer, pri bool hashover{false}; glm::dvec3 mouse{0.0}; std::string status; - char surface[128]{}; - char sides[2][128]{}; - char filter[64]{"asph"}; - char kerbtext[128]{}; - char mediantext[128]{}; - char banktext[128]{}; - char islandtext[128]{"none"}; }; 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, char *Buffer, std::size_t const Size, std::string &Value); + 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 @@ -3035,6 +3556,13 @@ class editor_mode : public application_mode, private editor_track::observer, pri 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(); diff --git a/application/editormodeconnection.cpp b/application/editormodeconnection.cpp index 459d2480a..275e5754e 100644 --- a/application/editormodeconnection.cpp +++ b/application/editormodeconnection.cpp @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "editor/editorAlignmentStore.hpp" #include "editor/editorSwitchStore.hpp" #include "editor/editorGeometry.hpp" +#include "application/editormodetrackshared.h" #include "scene/scene.h" #include "simulation/simulation.h" @@ -30,6 +31,7 @@ namespace { using geometry::cross; +using geometry::plan_distance; using geometry::plan_of; std::vector spacings_of(char const *Text) @@ -53,6 +55,34 @@ 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) @@ -182,6 +212,209 @@ bool editor_mode::plan_connection(connection::request &Request, connection::resu 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) @@ -218,17 +451,28 @@ void editor_mode::insert_connection() 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{tool.line.tracks.front()}; + auto *style{Style}; auto const fail = [&](std::string const &Reason) { for (auto *track : created) editor_track::retire(*track); @@ -265,13 +509,13 @@ void editor_mode::insert_connection() if (found.tracks.empty()) { fail(STR_C("A switch of the connection goes where its track isn't a plain straight")); - return; + 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; + return false; } } else @@ -280,23 +524,39 @@ void editor_mode::insert_connection() if (made.empty()) { fail(tool.status); - return; + 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; })}; - if (made == created.end() || glm::distance((*made)->m_paths.front().points[segment_data::point::start], start) > 0.01) + // 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; + 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 const &insert : plan.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()); @@ -324,19 +584,19 @@ void editor_mode::insert_connection() join_last_steps(); names += (names.empty() ? "" : ", ") + track->name(); } - tool.status = format(STR_C("%s laid, switches %s"), connection_name(tool.connection), names.c_str()) + "\n" + connection_readout(plan); + 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}; - if (tool.connection < 0) - return; + // 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##connectionsecond"); + 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)) @@ -346,24 +606,10 @@ void editor_mode::render_connection_options() tool.connection_second = i; ImGui::EndCombo(); } - item_tooltip("Template of the switches on the other track and along a ladder; the first switch is the one chosen on the list above"); + 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"); - if (tool.connection == static_cast(connection::kind::double_crossover)) - { - field_row("Gap between the switches, m##connectiongap"); - ImGui::InputDouble("##connectiongap", &tool.connection_gap, 0.5, 1.0, "%.2f"); - tool.connection_gap = std::clamp(tool.connection_gap, 0.0, 100.0); - item_tooltip("Straight between the starts of the two switches meeting on one track"); - } - if (tool.connection == static_cast(connection::kind::ladder)) - { - field_row("New tracks, m##connectionstub"); - ImGui::InputDouble("##connectionstub", &tool.connection_stub, 5.0, 25.0, "%.0f"); - tool.connection_stub = std::clamp(tool.connection_stub, 1.0, 1000.0); - item_tooltip("Length of the new tracks of the fan where there are none to lead onto"); - } ImGui::EndTable(); } diff --git a/application/editormodeconnectioncurve.cpp b/application/editormodeconnectioncurve.cpp index 0aae4951b..15e8f8c67 100644 --- a/application/editormodeconnectioncurve.cpp +++ b/application/editormodeconnectioncurve.cpp @@ -69,6 +69,44 @@ TTrack *curve_ahead(TTrack &Track, editor_track::straight_tolerance const &Toler 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 @@ -251,6 +289,7 @@ void editor_mode::insert_curved_connection() 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")); @@ -399,10 +438,8 @@ void editor_mode::insert_curved_connection() 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); - std::size_t raised{0}; glm::dvec3 flatfrom{0.0}, flatto{0.0}; - double ramplength{0.0}; - if (std::abs(lift) > 0.002) + 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)}; @@ -425,99 +462,100 @@ void editor_mode::insert_curved_connection() } return chainage; }; - auto const outerx{swapped ? 0.0 : -offset}; + // 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); - auto const ramp{std::abs(lift) / (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); - ramplength = ramp; - auto const share = [&](double const Chainage) { - if (Chainage <= c1 - ramp || Chainage >= c2 + ramp) - return 0.0; - if (Chainage < c1) - return (Chainage - (c1 - ramp)) / ramp; - if (Chainage > c2) - return ((c2 + ramp) - Chainage) / ramp; - return 1.0; - }; - auto const slope = [&](double const Chainage) { - if (Chainage > c1 - ramp && Chainage < c1) - return 1.0 / ramp; - if (Chainage > c2 && Chainage < c2 + ramp) - return -1.0 / ramp; - return 0.0; - }; - std::vector breaks; - for (auto const chainage : {c1 - ramp, c1, c2, c2 + ramp}) - if (chainage > 0.5 && chainage < route.length - 0.5) - breaks.push_back(chainage); - // 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) + lift * share(Chainage); }, - [&](double const Chainage) { return editor_track::sampled_grade(samples, Chainage) + lift * slope(Chainage); }, breaks, raisestates, raisecreated); - raised = raisestates.size() + raisecreated.size(); - 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()) + // 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) { - profile_take(route, route.spans.front().track, route.spans.back().track); - std::vector points; - for (auto point : before.points) + 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()) { - point.elevation += lift * share(point.chainage); - points.push_back(point); - } - for (auto const chainage : breaks) - { - profile::pvi corner; - corner.chainage = chainage; - corner.elevation = profile::elevation(before, chainage) + lift * share(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) + profile_take(route, route.spans.front().track, route.spans.back().track); + std::vector points; + for (auto point : before.points) { - // 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; + 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(); } - 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); } - WriteLog(format("Editor: curved crossover - the outer track %s raised by %.3f m from %.1f to %.1f m of its line, ramps %.1f m", outertrack->name().c_str(), lift, c1, c2, ramp), logtype::generic); } // the outer curve again, as it lies now std::vector outerframe; std::vector outertracks; { - auto const probe{mapping.point({swapped ? 0.0 : -offset, 0.0, 0.5 * (low + high)})}; + 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()) @@ -555,8 +593,10 @@ void editor_mode::insert_curved_connection() for (auto const end : {segment_data::point::start, segment_data::point::end}) { auto const &point{paths.front().points[end]}; - if (plan_distance(sample_at(frame, nearest_station(frame, point)).position, point) > 0.1) + 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")); } @@ -621,14 +661,15 @@ void editor_mode::insert_curved_connection() } 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 (std::abs(lift) > 0.002) + if (raise.ramp > 0.0) for (auto entry : switch_store::connections(*switches.front())) if (entry.kind == "connection" && entry.name == switches.front()->name()) { - entry.lift = lift; + entry.lift = raise.first; + entry.lift_end = raise.second; entry.lift_from = flatfrom; entry.lift_to = flatto; - entry.ramp = ramplength; + entry.ramp = raise.ramp; switch_store::put(entry, entry.layer); } push_track_snapshot(std::move(states), std::move(created), std::move(removed)); @@ -647,8 +688,8 @@ void editor_mode::insert_curved_connection() 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 (std::abs(lift) > 0.002) - 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::abs(lift), std::max(0.5, kRampShare * m_profile.line.norms.curve_threshold)); + 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); } @@ -714,7 +755,7 @@ bool editor_mode::take_out_crossover(curved_crossover const &Crossover, std::vec First = plains[0]; Second = plains[1]; auto const &record{Crossover.record}; - if (std::abs(record.lift) <= 0.002 || record.ramp <= 0.0) + 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}; @@ -744,42 +785,24 @@ bool editor_mode::take_out_crossover(curved_crossover const &Crossover, std::vec } return chainage; }; - auto c1{chainage_of(record.lift_from)}; - auto c2{chainage_of(record.lift_to)}; - if (c1 > c2) - std::swap(c1, c2); - auto const ramp{record.ramp}; - auto const share = [&](double const Chainage) { - if (Chainage <= c1 - ramp || Chainage >= c2 + ramp) - return 0.0; - if (Chainage < c1) - return (Chainage - (c1 - ramp)) / ramp; - if (Chainage > c2) - return ((c2 + ramp) - Chainage) / ramp; - return 1.0; - }; - auto const slope = [&](double const Chainage) { - if (Chainage > c1 - ramp && Chainage < c1) - return 1.0 / ramp; - if (Chainage > c2 && Chainage < c2 + ramp) - return -1.0 / ramp; - return 0.0; - }; - std::vector breaks; - for (auto const chainage : {c1 - ramp, c1, c2, c2 + ramp}) - if (chainage > 0.5 && chainage < route.length - 0.5) - breaks.push_back(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) - record.lift * share(Chainage); }, - [&](double const Chainage) { return editor_track::sampled_grade(samples, Chainage) - record.lift * slope(Chainage); }, breaks, States, Created); + 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 -= record.lift * share(point.chainage); + point.elevation -= lowered.at(point.chainage); points.push_back(point); } for (std::size_t k = 1; k + 1 < points.size();) @@ -799,18 +822,19 @@ bool editor_mode::take_out_crossover(curved_crossover const &Crossover, std::vec profile_check(); profile_store(); } - WriteLog(format("Editor: curved crossover - the outer track %s down by %.3f m again", outer->name().c_str(), record.lift), logtype::generic); + 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 -bool editor_mode::slide_curved_connection(TTrack &Switch, double const Distance) +// 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{crossover_template(crossover->record)}; + 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"); @@ -853,7 +877,7 @@ bool editor_mode::slide_curved_connection(TTrack &Switch, double const Distance) switch_store::follow(); push_track_snapshot(std::move(states), std::move(created), std::move(removed)); records_to_history(); - if (std::abs(crossover->record.lift) > 0.002) + if (crossover->record.lifted()) profiles_to_history(std::move(library)); // laid again if (false == lay_crossover(shape, press, release, 3.0, names)) @@ -865,7 +889,7 @@ bool editor_mode::slide_curved_connection(TTrack &Switch, double const Distance) return false; } join_last_steps(); - tool.status = format(STR_C("Crossover moved %.2f m"), Distance) + "\n" + tool.status; + 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; } @@ -910,6 +934,9 @@ std::size_t editor_mode::follow_crossovers(std::vectorfirst == 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); @@ -1020,12 +1047,8 @@ int editor_mode::crossover_template(switch_store::record const &Record) auto &tool{m_switch}; show_track_tab(track_tab::turnout); arm_switch(); - for (int i = 0; i < static_cast(tool.templates.size()); ++i) - { - auto const &candidate{tool.templates[i]}; - if (candidate.source == nullptr && false == candidate.double_slip && false == candidate.twofold() && std::abs(candidate.radius - Record.radius) < 0.5 && std::abs(candidate.ratio - Record.ratio) < 0.01 && (Record.rail == "-" || candidate.rail == Record.rail)) - return i; - } + 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; diff --git a/application/editormodegauge.cpp b/application/editormodegauge.cpp index 42ecf58cc..7e11b9615 100644 --- a/application/editormodegauge.cpp +++ b/application/editormodegauge.cpp @@ -580,6 +580,41 @@ 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) diff --git a/application/editormodegauge.h b/application/editormodegauge.h index 0f0507bbd..b37a85c0d 100644 --- a/application/editormodegauge.h +++ b/application/editormodegauge.h @@ -16,6 +16,8 @@ http://mozilla.org/MPL/2.0/. #include #include +class TAnimModel; + class gauge_tool final : public editor_tool { public: @@ -34,6 +36,9 @@ class gauge_tool final : public editor_tool 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: 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 index abc9f30af..d5212f56a 100644 --- a/application/editormodeinfra.cpp +++ b/application/editormodeinfra.cpp @@ -54,6 +54,7 @@ std::string const kBindingMark{"//$b"}; 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) @@ -1187,6 +1188,10 @@ void editor_mode::infra_adopt(TTrack &Track) 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; @@ -1196,12 +1201,19 @@ void editor_mode::infra_adopt(TTrack &Track) 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) { @@ -1222,6 +1234,14 @@ void editor_mode::infra_adopt(TTrack &Track) 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)); }; @@ -1302,6 +1322,7 @@ 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(); @@ -1310,16 +1331,20 @@ void editor_mode::track_captured(TTrack const &Track) if (m_bindings.empty()) return; Live.refresh(); - for (auto &binding : m_bindings) + 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 + // 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(); ++i) + 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())) @@ -1330,15 +1355,28 @@ void editor_mode::track_captured(TTrack const &Track) auto placed{anchor}; if (glm::distance(infra::place(placed), points[i]) <= 0.01) continue; - anchor = infra::make_anchor(anchor.at.track, anchor.at.path, points[i]); + 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 (binding.turns && yaw.has_value() && binding.anchors.front().at.track == &Track) + 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) @@ -1347,6 +1385,7 @@ void editor_mode::tracks_committed(std::vector const &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(); @@ -1469,9 +1508,16 @@ void editor_mode::track_retired(TTrack &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)}; diff --git a/application/editormodejoints.cpp b/application/editormodejoints.cpp index 1d61aa664..12c1e4357 100644 --- a/application/editormodejoints.cpp +++ b/application/editormodejoints.cpp @@ -774,8 +774,14 @@ editor_selftest_result joints_tool::selftest(std::string const &Command, std::is started = false; std::size_t count{0}; for (auto const &issue : m_joints.issues) - if (issue.type == joint_issue::kind::model && count++ < 40) - 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)); + { + 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; } @@ -784,7 +790,16 @@ editor_selftest_result joints_tool::selftest(std::string const &Command, std::is live_update(); std::string text; for (auto const &issue : m_live.issues) - text += format(" [%s %s at %.1f %.1f]", kind_name(issue.type), value_text(issue).c_str(), issue.position.x, issue.position.z); + { + 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; } diff --git a/application/editormodekm.cpp b/application/editormodekm.cpp index d1fe83624..2135d4afe 100644 --- a/application/editormodekm.cpp +++ b/application/editormodekm.cpp @@ -610,6 +610,7 @@ void km_tool::read_posts() 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"}}); diff --git a/application/editormodelay.cpp b/application/editormodelay.cpp index f66a831e4..ed7e8c78b 100644 --- a/application/editormodelay.cpp +++ b/application/editormodelay.cpp @@ -102,9 +102,11 @@ alignment::trace_stretch turned_round(alignment::trace_stretch const &Fit) 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 && (End.track->eType == tt_Normal || (End.track->eType == tt_Switch && 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 @@ -156,6 +158,7 @@ void editor_mode::update_build_tools() 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) @@ -199,11 +202,26 @@ void editor_mode::update_build_tools() 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.mouse_snap}; + auto end{lay.settling->snap}; if (end.track != nullptr && glm::distance(end.position, points.front()) > 1.0) { points.push_back(end.position); @@ -212,15 +230,32 @@ void editor_mode::update_build_tools() else { end = {}; - if (plan_distance(lay.mouse, points.back()) > 1.0) + if (plan_distance(mouse, points.back()) > 1.0) { - points.push_back(lay.mouse); + 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) { @@ -365,6 +400,26 @@ std::vector const &editor_mode::free_end_points(glm::dvec3 const &Ce 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; @@ -589,6 +644,43 @@ std::optional editor_mode::eased_layout(TTrack const *Fro 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(); @@ -637,6 +729,8 @@ std::vector editor_mode::extend_pieces() const 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; } @@ -826,12 +920,23 @@ void editor_mode::finish_extend() 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; })}; - if (glm::distance(plan.insert.points[segment_data::point::start], plan.insert.points[segment_data::point::end]) > 0.01) + std::vector inserts; + for (auto piece : plan.inserts) { - auto *insert{editor_track::create_path(*origin, plan.insert)}; - editor_track::commit({insert}); - created.push_back(insert); + 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)) @@ -969,8 +1074,12 @@ bool editor_mode::track_wheel(double const Offset) 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) - tool.connection = (tool.connection + step + connection::kind_count) % connection::kind_count; + { + 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}; @@ -980,7 +1089,7 @@ bool editor_mode::track_wheel(double const Offset) index = i; tool.connection_radius = radii[std::clamp(index + step, 0, static_cast(std::size(radii)) - 1)]; } - else + else if (false == tool.recognised) tool.connection_together = false == tool.connection_together; return true; } @@ -1080,6 +1189,7 @@ std::vector editor_mode::lay_pieces(std::vector const 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 = {}; @@ -1143,7 +1253,7 @@ std::vector editor_mode::lay_pieces(std::vector const 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, {EditorSettings.corner_low(), EditorSettings.corner_high()}, bends_fit())}; + auto const easedshape{alignment::ease_corners(easeddesign, plan.corners, {}, bends_fit())}; if (easedshape.valid) { Length = editor_track::eased_length(in, easedshape.length, out); @@ -1174,6 +1284,10 @@ std::vector editor_mode::lay_pieces(std::vector const 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; @@ -1200,7 +1314,7 @@ bool editor_mode::lay_line(std::vector const &Points, std::vector 1e-6) @@ -1532,6 +1646,8 @@ bool editor_mode::lay_line(std::vector const &Points, std::vector std::optional> { constexpr double kFlatter{4.0}; auto const count{fitted_points.size()}; @@ -1543,15 +1659,14 @@ bool editor_mode::lay_line(std::vector const &Points, std::vector 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}; - auto fit{fitted_heading(heading)}; - if (false == fit.has_value()) - return std::nullopt; // 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 @@ -1559,6 +1674,17 @@ bool editor_mode::lay_line(std::vector const &Points, std::vectorrms > 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()) @@ -1616,6 +1742,10 @@ bool editor_mode::lay_line(std::vector const &Points, std::vectorsecond; 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}; @@ -1626,12 +1756,19 @@ bool editor_mode::lay_line(std::vector const &Points, std::vector 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; @@ -1647,6 +1784,8 @@ bool editor_mode::lay_line(std::vector const &Points, std::vector const &Points, std::vector const &Points, std::vector editor_mode::traced_stretch(alignment::d 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}}; @@ -1969,6 +2116,7 @@ void editor_mode::lay_finish(editor_track::snap_target const &End) 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(); @@ -2148,7 +2296,7 @@ TTrack const *editor_mode::skew_reference(glm::dvec3 const &From, glm::dvec3 con return nearest; } -editor_mode::track_hover editor_mode::split_spot() const +track_hover editor_mode::split_spot() const { auto const *selected{selected_track()}; if (selected == nullptr || ui()->mode() != nodebank_panel::TRACK || ImGui::GetIO().WantCaptureMouse) @@ -2195,44 +2343,17 @@ void editor_mode::render_lay_ui() ImGui::PushItemWidth(120.0f); if (tool.mode == lay_mode::straights) { - double low{EditorSettings.corner_low()}; - double high{EditorSettings.corner_high()}; ImGui::TextDisabled("%s", STR_C("Radius of the curves at the bends")); - auto changed{ImGui::DragScalar(STR_C("from (m)"), ImGuiDataType_Double, &low, 10.0f, nullptr, nullptr, "%.0f")}; - // the settings file written when a drag ends, not at each frame of it - auto release{ImGui::IsItemDeactivatedAfterEdit()}; - item_tooltip("The radius the two transition curves of a bend meet at, at least; where they don't fit at it, an arc of the norms as large as fits"); - changed |= ImGui::DragScalar(STR_C("to (m)"), ImGuiDataType_Double, &high, 10.0f, nullptr, nullptr, "%.0f"); - release |= ImGui::IsItemDeactivatedAfterEdit(); - item_tooltip("The radius tried first; a bend too slight for transitions long enough at the speed takes a larger one"); - ImGui::PushID("bends"); - auto first{true}; - for (auto const &[from, to] : {std::pair{1000.0, 2000.0}, std::pair{2000.0, 4000.0}, std::pair{3000.0, 6000.0}, std::pair{4000.0, 8000.0}}) + ImGui::SameLine(); + if (ImGui::SmallButton("?##corners")) { - if (false == first) - ImGui::SameLine(); - first = false; - auto const chosen{std::abs(low - from) < 0.5 && std::abs(high - to) < 0.5}; - if (chosen) - ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive)); - if (ImGui::SmallButton(format("%.0f-%.0f", from, to).c_str())) - { - low = from; - high = to; - changed = true; - release = true; - } - if (chosen) - ImGui::PopStyleColor(); + m_first_steps_open = true; + m_tutorial_goto = "Radius of the curves at the bends"; } - ImGui::PopID(); - if (changed) - { - low = std::max(10.0, low); - EditorSettings.corners(low, std::max(low, high)); - } - if (release) - EditorSettings.save(); + 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 { @@ -2280,6 +2401,7 @@ void editor_mode::render_lay_ui() 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)}; @@ -2330,7 +2452,6 @@ void editor_mode::render_lay_ui() tool.copy_selected = source == 1; if (false == tool.copy_selected) { - m_textures.loads = 0; 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); diff --git a/application/editormodelineside.cpp b/application/editormodelineside.cpp index b22a19b32..1c2fc9e9c 100644 --- a/application/editormodelineside.cpp +++ b/application/editormodelineside.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "editor/editorGeometry.hpp" #include "editor/editorIncludeInfo.hpp" #include "editor/editorKilometrage.hpp" +#include "editor/editorTrackTrace.hpp" #include "scene/scene.h" #include "scene/scenelayers.h" @@ -136,72 +137,6 @@ std::string km_text(int const Hectometres) return format("%d.%d", Hectometres / 10, Hectometres % 10); } -// points along the track from the end of a path on, the way a train goes: through a switch along its main track -std::vector trace(TTrack &Track, int const Path, bool const Forward, double const Limit) -{ - std::vector points; - auto *track{&Track}; - auto path{Path}; - auto forward{Forward}; - double length{0.0}; - for (int guard = 0; guard < 64 && track != nullptr && length < Limit; ++guard) - { - bezier const curve{track->m_paths[path]}; - auto const count{std::clamp(static_cast(curve.plan_length() / 1.0), 4, 400)}; - for (int k = points.empty() ? 0 : 1; k <= count; ++k) - { - auto const point{curve.point(forward ? static_cast(k) / count : 1.0 - static_cast(k) / count)}; - if (false == points.empty()) - length += plan_distance(points.back(), point); - points.push_back(point); - } - auto const exit{points.back()}; - TTrack *next{nullptr}; - int nextpath{0}; - bool nextforward{true}; - for (auto const &connection : editor_track::connected_points(*track, exit)) - { - auto *other{connection.first}; - if (other == track || (other->iCategoryFlag & 15) != kRailCategory) - continue; - bool const start{connection.second.kind == editor_track::point_kind::start}; - // entering a switch at its start the train takes the main track - if (next == nullptr || (other == next && start && connection.second.path == 0)) - { - next = other; - nextpath = connection.second.path; - nextforward = start; - } - } - track = next; - path = nextpath; - forward = nextforward; - } - return points; -} - -// nearest point of the polyline -glm::dvec3 nearest_on(std::vector const &Line, glm::dvec3 const &Point, double &Distance) -{ - Distance = std::numeric_limits::max(); - glm::dvec3 result{Point}; - auto const point{plan_of(Point)}; - for (std::size_t i = 1; i < Line.size(); ++i) - { - auto const a{plan_of(Line[i - 1])}; - auto const ab{plan_of(Line[i]) - 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; - result = glm::mix(Line[i - 1], Line[i], t); - } - } - return result; -} - void draw_label(ImDrawList *Draw, ImVec2 const At, ImU32 const Colour, std::string const &Text) { auto const size{ImGui::CalcTextSize(Text.c_str())}; @@ -256,22 +191,61 @@ scene::layer_handle editor_mode::output_layer(std::string const &Part) 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{ToLower(stem + "_" + Part + (attempt > 1 ? std::to_string(attempt) : std::string{}) + ".scm")}; - auto layer{null_handle}; - for (std::size_t index = 1; index <= scene::Layers.size() && layer == null_handle; ++index) - if (auto const &existing{scene::Layers.layer(static_cast(index))}; false == existing.dead && false == existing.removed && existing.name == name) - layer = scene::Layers.resolve(static_cast(index)); - if (layer == null_handle) - layer = scene::Layers.create(name, scene::layer_handle{1}, reason, false); - if (layer != null_handle && scene::Layers.accepts(layer, &reason)) - { - scene::Layers.visible(layer, true); - scene::Layers.locked(layer, false); + 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; @@ -279,6 +253,7 @@ scene::layer_handle editor_mode::output_layer(std::string const &Part) 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()) @@ -366,6 +341,7 @@ std::size_t editor_mode::move_templates(std::vector const &Instances) { + m_drives_standing.reset(); EditorSnapshot snap; for (auto const instance : Instances) { @@ -670,6 +646,14 @@ void hekto_tool::render_options() 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)"); @@ -842,36 +826,16 @@ void fouling_tool::fouling_update() { if (track->m_paths.size() < 2 || false == editor_track::is_supported(*track)) continue; - auto const main{trace(*track, 0, true, kFoulingTrace)}; - auto const branch{trace(*track, 1, true, kFoulingTrace)}; - if (main.size() < 2 || branch.size() < 2) + track_trace::fouling found; + if (false == track_trace::fouling_of(*track, tool.spacing, kFoulingTrace, found)) continue; - glm::dvec3 previous{branch.front()}; - double previousdistance{0.0}; - for (std::size_t i = 1; i < branch.size(); ++i) - { - double distance; - nearest_on(main, branch[i], distance); - if (distance < tool.spacing) - { - previous = branch[i]; - previousdistance = distance; - continue; - } - auto const f{distance - previousdistance > 1e-9 ? (tool.spacing - previousdistance) / (distance - previousdistance) : 1.0}; - auto const onbranch{glm::mix(previous, branch[i], std::clamp(f, 0.0, 1.0))}; - double unused; - auto const onmain{nearest_on(main, onbranch, unused)}; - fouling_point point; - point.track = track; - auto const middle{(onbranch + onmain) * 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 * (onbranch.y + onmain.y) + kRailHeight + tool.height, middle.z} : m_ground.placement_on_ground({middle.x, std::max(onbranch.y, onmain.y), middle.z}); - auto const back{plan_of(previous - branch[i])}; - point.yaw = std::fmod(heading_of(glm::length(back) > 1e-9 ? glm::normalize(back) : glm::dvec2{0.0, 1.0}) + tool.turn, 360.0); - tool.points.push_back(point); - break; - } + 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; })}; @@ -1073,7 +1037,7 @@ void fouling_tool::render_options() 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("3.5 m on the straight track; more on the curves, where the cars lean out")); + 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"); @@ -1227,8 +1191,14 @@ editor_selftest_result fouling_tool::selftest(std::string const &Command, std::i WriteLog("SELFTEST fouling: " + tool.status); int shown{0}; for (auto const &found : tool.found) - if (found.wrong && shown++ < 5) - WriteLog(format("SELFTEST fouling: %s %.2f m off, %+.3f m high", found.marker.file.c_str(), found.error, found.height_error)); + { + 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 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 index d92837e35..13465a006 100644 --- a/application/editormodenmt.cpp +++ b/application/editormodenmt.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #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" @@ -31,7 +32,10 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include +#include +#include #include #include @@ -144,6 +148,109 @@ bool ground_card(char const *Id, char const *Title, char const *Text, bool const 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}; @@ -402,6 +509,7 @@ void editor_mode::nmt_fit() 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..."); } @@ -423,6 +531,9 @@ void editor_mode::nmt_under_start() } 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..."); } @@ -587,7 +698,11 @@ void editor_mode::nmt_make(std::vector const &Keys, bool c 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; @@ -631,6 +746,20 @@ std::optional editor_mode::nmt_terrain_offset(std::vector co 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)}; @@ -719,8 +848,7 @@ void editor_mode::nmt_follow_tracks() // 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()}; - for (auto const &name : dropped) - m_streamer.remove_modifier(name); + m_streamer.remove_modifiers(dropped); auto const laid{shaped.empty() ? std::size_t{0} : nmt_shape_tracks(&shaped)}; if (false == dropped.empty()) forget_ground(); @@ -920,8 +1048,7 @@ std::size_t editor_mode::nmt_shape_tracks(std::vector const *Only) if ((modifier.name == own || modifier.name.starts_with(own + " ")) && false == kept.contains(modifier.name)) gone.push_back(modifier.name); } - for (auto const &name : gone) - m_streamer.remove_modifier(name); + m_streamer.remove_modifiers(gone); } if (Only == nullptr) { @@ -931,8 +1058,7 @@ std::size_t editor_mode::nmt_shape_tracks(std::vector const *Only) 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); - for (auto const &name : gone) - m_streamer.remove_modifier(name); + m_streamer.remove_modifiers(gone); } auto const count{laid.size()}; m_streamer.modifiers(std::move(laid)); @@ -946,17 +1072,158 @@ std::size_t editor_mode::nmt_shape_tracks(std::vector const *Only) 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, where the scenery is placed and its terrain is there - if (auto const wanted{m_nmt.placed() && m_streamer.active() ? m_orthophoto.area() : std::vector{}}; wanted != m_nmt_prefetched) + // 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(); @@ -973,7 +1240,20 @@ void editor_mode::nmt_update() } 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()}; @@ -983,7 +1263,6 @@ void editor_mode::nmt_update() m_streamer.end_change(); } int made{0}; - std::size_t apart{0}; std::vector changed; for (auto it{state.pending.begin()}; it != state.pending.end() && made < 4;) { @@ -993,34 +1272,22 @@ void editor_mode::nmt_update() it = state.pending.erase(it); continue; } - // ahead of the track the terrain goes on from the one there is, at its height over the model - std::optional offset; - if (state.grown && false == refilled) + // 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})) { - bool foreign{false}; - offset = nmt_seam_offset(*it, foreign); - if (foreign) - { - state.given_up.insert(*it); - it = state.pending.erase(it); - ++state.foreign; - ++made; - continue; - } - if (false == offset.has_value()) - { - ++apart; - ++it; - continue; - } + ++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; } - if (offset.has_value() && chunk == nmt_chunk::made) + // 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); @@ -1032,16 +1299,9 @@ void editor_mode::nmt_update() else ++state.empty; } - // the chunks ahead which no terrain made from the model touches any more are given up - if (made == 0 && apart > 0 && apart == state.pending.size()) - { - state.foreign += apart; - state.given_up.insert(state.pending.begin(), state.pending.end()); - state.pending.clear(); - state.refill.clear(); - made = 1; - } - if (made > 0) + // 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 @@ -1057,7 +1317,10 @@ void editor_mode::nmt_update() 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()) { - if (state.shape && state.reshape) + 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); @@ -1077,13 +1340,18 @@ 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 || false == m_nmt.placed()) + 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})) @@ -1091,7 +1359,9 @@ void editor_mode::nmt_grow() // 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()}; - if (false == laying || m_streamer.resident() == 0) + // 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 @@ -1151,6 +1421,9 @@ void editor_mode::nmt_stop() 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) @@ -1163,25 +1436,34 @@ 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()}; - fraction = -1.0f * static_cast(ImGui::GetTime()); + // 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}; @@ -1235,8 +1517,7 @@ void editor_mode::nmt_restore_terrain(std::vector const &Tracks) gone.push_back(modifier.name); } terrain_history_step(); - for (auto const &name : gone) - m_streamer.remove_modifier(name); + m_streamer.remove_modifiers(gone); if (false == gone.empty()) forget_ground(); terrain_history_step(); @@ -1293,7 +1574,7 @@ void editor_mode::render_track_terrain(std::vector const &Tracks) render_nmt_all_tracks(false); if (busy) render_nmt_progress(true); - if (false == state.status.empty()) + else if (false == state.status.empty()) { ImGui::PushTextWrapPos(0.0f); ImGui::TextDisabled("%s", state.status.c_str()); @@ -1309,52 +1590,104 @@ 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}; + 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(); }}; - // the tracks fitted already stay as they are: a track laid or changed since goes onto the model, all of them only when asked - ImGui::BeginDisabled(busy || false == placed || unfitted == 0); - if (main_button(STR_C("Tracks onto the terrain"), ImVec2(-FLT_MIN, tall_button_height()))) - 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"); - ImGui::EndDisabled(); 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(); } - if (unfitted == all) - told(STR_C("All the tracks go down or up onto the terrain model, which is loaded along them by itself")); - else if (unfitted > 0) - told(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).c_str()); - else - told(STR_C("All the tracks are fitted to the terrain; a track changed since goes onto it again")); - toggle_chips("nmtshape", {{STR_C("Formation and slopes along the tracks"), &state.shape, - "Each track gets its formation with slopes 1:1.5 down or up to the terrain, as a modifier of the terrain; bridges and tunnels keep the model under them"}}); - ImGui::Spacing(); - ImGui::TextDisabled("%s", STR_C("Or:")); - ImGui::BeginDisabled(busy || false == placed || all == 0); - if (ImGui::Button(STR_C("All anew, the fitted ones too"), ImVec2(-FLT_MIN, 0.0f))) - nmt_auto_start(false); + // 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(); - ImGui::BeginDisabled(busy || false == placed || all == 0); - if (ImGui::Button(STR_C("Terrain under the tracks"), ImVec2(-FLT_MIN, 0.0f))) + 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::EndDisabled(); - told(STR_C("The tracks stay at their heights and the terrain comes up or down to them")); + 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(); @@ -1362,6 +1695,112 @@ void editor_mode::render_nmt_all_tracks(bool const Terrain_panel) } } +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}; @@ -1545,11 +1984,11 @@ void editor_mode::draw_download_area() const return; screen_projection const projection; auto *drawlist{ImGui::GetBackgroundDrawList()}; - // the tiles of the area as they are: in the disk cache, failed; the ones waiting left clear + // 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 == 0) + if (square.state != 2) continue; std::array corners; auto seen{true}; @@ -1557,7 +1996,7 @@ void editor_mode::draw_download_area() const 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], square.state == 1 ? IM_COL32(90, 220, 120, 45) : IM_COL32(240, 80, 70, 80)); + 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)}; @@ -1582,6 +2021,14 @@ void editor_mode::draw_download_area() const } } +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()}; @@ -1613,17 +2060,63 @@ void editor_mode::render_download_area_ui(editor_orthophoto::statistics const &S 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 (area.empty()) + if (false == area.empty()) { ImGui::SameLine(); - ImGui::TextDisabled("%s", STR_C("none: the tiles around the camera, wherever it is")); - return; + 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")); } - ImGui::SameLine(); - if (ImGui::Button(STR_C("Remove"))) - m_orthophoto.area({}); + // 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"))) @@ -1643,6 +2136,18 @@ void editor_mode::render_download_area_ui(editor_orthophoto::statistics const &S 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() @@ -1677,13 +2182,192 @@ void editor_mode::render_nmt_banner() 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::TextUnformatted(STR_C("Click the middle of the scenery on the map")); + 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})) @@ -1770,81 +2454,84 @@ void editor_mode::render_nmt_ui() 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)}; - step_heading(2, STR_C("Load")); - if (busy && false == tracks_busy) - render_nmt_progress(false); - else - { - ImGui::BeginDisabled(busy); - auto const half{std::floor((ImGui::GetContentRegionAvail().x - ImGui::GetStyle().ItemSpacing.x) * 0.5f)}; - if (tracks) - { - if (main_button(STR_C("Load along the tracks"), ImVec2(half, tall_button_height()))) - 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"); - ImGui::SameLine(); - } - if (main_button(STR_C("Load around the camera"), ImVec2(-FLT_MIN, tall_button_height()))) - { - if (false == tracks && 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)) - { - if (tracks) - { - 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"); - } - else - { - 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::EndDisabled(); - } - ImGui::PushTextWrapPos(0.0f); - ImGui::TextDisabled("%s", STR_C("A chunk there is already is never made anew")); - ImGui::PopTextWrapPos(); - 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(); - } - state.band = std::clamp(state.band, 50.0, 3000.0); - if (tracks && ImGui::TreeNode(STR_C("Height offset of the model"))) - { - if (begin_fields("##nmtoffset", 0.5f)) - { - field_row("Height offset (m)"); - ImGui::InputDouble("##nmtheightoffset", &state.offset, 0.1, 1.0, "%.2f"); - ImGui::TableNextRow(); - ImGui::TableSetColumnIndex(1); - if (ImGui::Button(STR_C("Fit to the tracks"), ImVec2(-FLT_MIN, 0.0f))) - nmt_fit(); - 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(); - } - ImGui::TreePop(); - } - if (tracks) { - step_heading(3, STR_C("Tracks and terrain")); + 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(); - if (false == state.status.empty()) + // 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()); @@ -2053,16 +2740,12 @@ std::size_t editor_mode::nmt_level_turntables() for (auto const &[track, path, atend] : table.ends) { auto const end{end_of(*track, path, atend)}; - if (state.unfitted && grade_fitted(*track)) + 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))}; - auto out{kPitWall}; - while (out <= kPitWall + 6.0) - { - if (double height; m_nmt.height(end.point.x + away.x * out, end.point.z + away.y * out, height)) + 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()); - out += 1.0; - } } auto &heights{fitted.empty() ? model : fitted}; if (heights.empty()) @@ -2119,12 +2802,20 @@ std::size_t editor_mode::nmt_level_turntables() 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; @@ -2133,7 +2824,7 @@ void editor_mode::nmt_auto_start(bool const Unfitted) std::vector kept; for (auto const &place : nmt_track_places(20.0)) if (place.shapes) - (false == Unfitted || false == grade_fitted(*place.track) ? state.probes : kept).push_back(place); + (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"); @@ -2147,6 +2838,10 @@ void editor_mode::nmt_auto_start(bool const Unfitted) 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..."); } @@ -2158,8 +2853,12 @@ bool editor_mode::nmt_fit_line(TTrack &Track, std::functiontrack)) --first; @@ -2174,7 +2873,10 @@ bool editor_mode::nmt_fit_line(TTrack &Track, std::functiontable->name()}); - auto at{from}; - while (at <= from + level + 1e-6) - { - options.bounds.push_back({at, height - kJoin, height + kJoin, false}); - at += 1.0; - } + 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) { + 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(); }; + 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}); @@ -2371,6 +3069,20 @@ bool editor_mode::nmt_fit_line(TTrack &Track, std::function 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)}; @@ -2386,7 +3098,7 @@ bool editor_mode::nmt_fit_line(TTrack &Track, std::function 1.0 || std::abs(across) >= kNear || std::abs(point.was - Sample.position.y) > kSameLevel) + 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) @@ -2399,39 +3111,43 @@ bool editor_mode::nmt_fit_line(TTrack &Track, std::function 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; track != nullptr && shapes_ground(*track) && false == in_pit(sample.position) && m_nmt.height(sample.position.x, sample.position.z, height)) + 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(); - 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 (distance < kReach && (false == std::isfinite(model[i]) || std::abs(beside - model[i]) <= kLevel)) - { - chainages.push_back(sample.chainage); - ground.push_back(beside); - tolerances.push_back(std::max(kRail, kSpread * distance)); - reaches.push_back(kLevel); - } - if (track != nullptr) - 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); - } } - if (std::none_of(ground.begin(), ground.end(), [](double const Height) { return std::isfinite(Height); })) - return false; // 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 @@ -2489,10 +3205,123 @@ bool editor_mode::nmt_fit_line(TTrack &Track, std::function 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()}; @@ -2508,16 +3337,13 @@ bool editor_mode::nmt_fit_line(TTrack &Track, std::functionname()}); } - // 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 - for (auto const &found : crossings_of(m_nmt_state.laid)) + for (auto const &hold : crossing_holds) { - auto const at{static_cast(std::distance(chainages.begin(), std::upper_bound(chainages.begin(), chainages.end(), found.chainage)))}; - chainages.insert(chainages.begin() + at, found.chainage); - ground.insert(ground.begin() + at, found.height); - tolerances.insert(tolerances.begin() + at, kCrossingHeight); - reaches.insert(reaches.begin() + at, kLevel); + 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 @@ -2556,18 +3382,24 @@ bool editor_mode::nmt_fit_line(TTrack &Track, std::function::max(); + 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(); @@ -2594,7 +3426,9 @@ bool editor_mode::nmt_fit_line(TTrack &Track, std::functionname().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) { @@ -2655,6 +3494,44 @@ bool editor_mode::nmt_fit_line(TTrack &Track, std::function= 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, @@ -2888,6 +3765,816 @@ bool editor_mode::nmt_fit_laid(std::size_t const From, glm::dvec3 const End) 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}; @@ -2939,19 +4626,23 @@ void editor_mode::nmt_auto_step() // 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 == state.unfitted || false == grade_fitted(*track))) + 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 - if (state.unfitted) - for (auto *track : simulation::Paths.sequence()) - if (track != nullptr && rail(*track) && grade_fitted(*track)) - state.done.push_back(track); + 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()) @@ -3024,7 +4715,13 @@ void editor_mode::nmt_auto_step() 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(); diff --git a/application/editormodeparallel.cpp b/application/editormodeparallel.cpp index 31fd8b27b..28861b93f 100644 --- a/application/editormodeparallel.cpp +++ b/application/editormodeparallel.cpp @@ -71,17 +71,15 @@ bool side_picker(int &Side, double const Spacing) 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 sleepers = [list, left, right, font, gauge](float const Y, ImU32 const Colour) { - auto x{left + font * 0.3f}; - while (x < right) - { - 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); - x += std::round(font * 0.9f); - } - }; 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) - sleepers(Y, Colour); + 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) @@ -89,11 +87,10 @@ bool side_picker(int &Side, double const Spacing) list->AddLine(ImVec2(left, rail), ImVec2(right, rail), Colour, 1.5f); continue; } - auto x{left}; - while (x < right) + 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); - x += font; } } }; diff --git a/application/editormodeprofile.cpp b/application/editormodeprofile.cpp index 9db2485a2..2b7956f97 100644 --- a/application/editormodeprofile.cpp +++ b/application/editormodeprofile.cpp @@ -54,6 +54,7 @@ double constexpr kNoBed{0.05}; // m, a trackbed shallower is none 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)}; @@ -83,7 +84,7 @@ double nice_step(double const Approximate) } std::string const kProfileMark{"//$p"}; -std::string const kFittedMark{"//$f"}; +std::string const kFittedMark{"//$t"}; profile::line reversed_line(profile::line Line, double const Length) { @@ -103,6 +104,27 @@ bool end_locked(profile::line const &Line, profile::context const &Context, int 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; }); @@ -278,7 +300,8 @@ std::uint64_t editor_mode::fitted_shape(TTrack const &Track) for (auto const &path : Track.m_paths) for (auto const &point : path.points) for (int axis = 0; axis < 3; ++axis) - add(std::llround(point[axis] * 100.0)); + // 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; } @@ -292,14 +315,18 @@ void editor_mode::fitted_load() for (auto const &text : scene::Layers.marked(layer, kFittedMark)) { std::istringstream line{text}; - std::string keyword, name, shape; + std::string keyword, name, shape, kind; line >> keyword >> name >> shape; if (keyword == "fitted" && false == line.fail()) - m_fitted[name] = {layer, std::strtoull(shape.c_str(), nullptr, 16)}; + { + 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) +void editor_mode::fitted_set(std::vector const &Tracks, bool const Hand) { fitted_load(); std::vector layers; @@ -314,41 +341,51 @@ void editor_mode::fitted_set(std::vector const &Tracks) if (false == scene::Layers.valid(layer) || false == scene::Layers.accepts(layer)) layer = scene::Layers.active(); } - if (auto const found{m_fitted.find(track->name())}; found != m_fitted.end() && found->second.layer != layer) - layers.push_back(found->second.layer); - m_fitted[track->name()] = {layer, fitted_shape(*track)}; + // 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; - // the marks of the tracks there are no more, or changed since, aren't written again std::vector lines; - for (auto const &[name, mark] : m_fitted) + for (auto const &[key, mark] : m_fitted) { - if (mark.layer != layer) - continue; - auto const *track{simulation::Paths.find(name)}; - if (track == nullptr || track->m_editorremoved || fitted_shape(*track) != mark.shape) + 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", name.c_str(), static_cast(mark.shape))); + 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(); - auto const found{m_fitted.find(Track.name())}; - return found != m_fitted.end() && found->second.shape == fitted_shape(Track); + return m_fitted.contains({Track.name(), fitted_shape(Track)}); } int editor_mode::profile_find(bool &Reversed) const @@ -582,6 +619,12 @@ bool editor_mode::profile_restore_parts() 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); @@ -685,12 +728,15 @@ std::optional editor_mode::profile_stored_route(stored_prof 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) || std::abs(route.length - Entry.length) > 0.5) - continue; - auto const samples{editor_track::sample_route(route, 1.0)}; - if (samples.empty() || plan_distance(samples.front().position, Entry.start) > 0.1 || plan_distance(editor_track::sampled_position(samples, route.length * 0.5), Entry.middle) > 0.5) + 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; @@ -701,6 +747,91 @@ std::optional editor_mode::profile_stored_route(stored_prof 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}; @@ -709,9 +840,13 @@ void editor_mode::profile_open_stored(std::size_t const Index) auto const entry{m_profiles[Index]}; TTrack *from{nullptr}; TTrack *to{nullptr}; - if (profile_stored_route(entry, &from, &to).has_value()) + // 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)}) { - profile_open(from, to); + state.open = true; + state.status.clear(); + state.error.clear(); + profile_take(std::move(*route), from, to); return; } state.open = true; @@ -1006,11 +1141,23 @@ void editor_mode::profile_recognize() grades.push_back(sample.grade); } auto const norms{state.line.norms}; - state.line = profile::recognize(chainages, elevations, grades, {}); - state.line.norms = norms; - state.line.speed = editor_track::route_speed(state.route); - state.selected = -1; - profile_check(); + 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); } @@ -1425,6 +1572,9 @@ 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 { @@ -1533,6 +1683,7 @@ void editor_mode::profile_frame_view() 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 = {}; @@ -1570,9 +1721,10 @@ void editor_mode::profile_apply(bool const Terrain, std::vector tracks; @@ -1590,7 +1742,25 @@ void editor_mode::profile_apply(bool const Terrain, std::vector ends; for (auto const &span : state.route.spans) ends.insert(ends.end(), {span.from, span.to}); - auto cuts{Fewest > 0.0 ? profile::fewest_breaks(line, ends, Fewest) : profile::breaks(line)}; + 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}; @@ -1605,7 +1775,7 @@ void editor_mode::profile_apply(bool const Terrain, std::vector 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); @@ -1787,6 +1960,7 @@ void editor_mode::render_profile_body() 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(); @@ -1797,6 +1971,8 @@ void editor_mode::render_profile_body() 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 @@ -2709,11 +2885,10 @@ void editor_mode::draw_profile_canvas(profile_view const &View, ImDrawList &Draw // breaks the grade over them Draw.PushClipRect(ImVec2(left, plottop), ImVec2(right, plotbottom), true); auto const height{plotbottom - plottop}; - auto x = left - height; - while (x < right) + 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); - x += 8.0f; } Draw.PopClipRect(); Draw.AddLine(ImVec2(left, plottop), ImVec2(left, plotbottom), kSharedEdge, 1.0f); @@ -2938,6 +3113,11 @@ void editor_mode::draw_profile_overlay() const 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}; diff --git a/application/editormoderecords.cpp b/application/editormoderecords.cpp index 3e855066c..67498ba73 100644 --- a/application/editormoderecords.cpp +++ b/application/editormoderecords.cpp @@ -440,6 +440,39 @@ std::optional editor_mode::slip_of(TTrack const &Track) c 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 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 index fe27efa90..7c2a69da3 100644 --- a/application/editormoderoad.cpp +++ b/application/editormoderoad.cpp @@ -28,7 +28,9 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include +#include +#include +#include namespace { @@ -229,6 +231,13 @@ glm::dvec3 path_direction(segment_data const &Path, double const T) 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; @@ -320,12 +329,6 @@ void editor_mode::road_select(road_node *Road) tool.settings.missing = {}; } tool.varied = tool.settings.changing(); - copy_text(tool.surface, sizeof(tool.surface), tool.settings.surface); - for (int side = 0; side < 2; ++side) - copy_text(tool.sides[side], sizeof(tool.sides[side]), tool.settings.sides[side].material); - copy_text(tool.kerbtext, sizeof(tool.kerbtext), tool.settings.kerbmaterial); - copy_text(tool.mediantext, sizeof(tool.mediantext), tool.settings.median.material); - copy_text(tool.banktext, sizeof(tool.banktext), tool.settings.bankmaterial); } void editor_mode::junction_select(junction_node *Junction) @@ -339,12 +342,6 @@ void editor_mode::junction_select(junction_node *Junction) 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()); - // the fields for the names of materials are shared with the roads - copy_text(tool.surface, sizeof(tool.surface), Junction->definition().surface); - copy_text(tool.sides[0], sizeof(tool.sides[0]), Junction->definition().side.material); - copy_text(tool.kerbtext, sizeof(tool.kerbtext), Junction->definition().kerbmaterial); - copy_text(tool.banktext, sizeof(tool.banktext), Junction->definition().bankmaterial); - copy_text(tool.mediantext, sizeof(tool.mediantext), Junction->definition().medianmaterial); } void editor_mode::roadpoint_select(roadpoint_node *Point) @@ -752,7 +749,7 @@ void editor_mode::render_junction_layout(junction_node &Junction) 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", tool.surface, sizeof(tool.surface), state.surface)) + if (render_road_material("Surface", state.surface)) changed = true; if (number(STR_C("Texture length [m]"), state.texturelength, 0.5f, "%.2f")) { @@ -771,7 +768,7 @@ void editor_mode::render_junction_layout(junction_node &Junction) state.kerbwidth = std::clamp(state.kerbwidth, 0.05f, 2.0f); changed = true; } - if (render_road_material("Kerb material", tool.kerbtext, sizeof(tool.kerbtext), state.kerbmaterial)) + 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")) { @@ -798,7 +795,7 @@ void editor_mode::render_junction_layout(junction_node &Junction) state.side.width = std::clamp(state.side.width, 0.1f, 20.0f); changed = true; } - if (render_road_material("Material", tool.sides[0], sizeof(tool.sides[0]), state.side.material)) + 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")); @@ -829,7 +826,7 @@ void editor_mode::render_junction_layout(junction_node &Junction) // banks leading from the corners to the ground if (ImGui::CollapsingHeader(STR_C("Banks to the ground##banks"))) { - if (render_road_material("Bank material", tool.banktext, sizeof(tool.banktext), state.bankmaterial)) + 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); @@ -873,7 +870,7 @@ void editor_mode::render_junction_layout(junction_node &Junction) } 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", tool.mediantext, sizeof(tool.mediantext), state.medianmaterial)) + if (state.median == road_node::median_type::island && render_road_material("Island material", state.medianmaterial)) changed = true; } @@ -954,6 +951,8 @@ void editor_mode::render_junction_layout(junction_node &Junction) 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; @@ -1157,6 +1156,90 @@ void editor_mode::road_profile(std::vector &Pieces, double const * } } +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}; @@ -1186,7 +1269,11 @@ void editor_mode::road_click() } tool.marker = nullptr; glm::dvec3 joint; - if (editor_road::nearest_joint(ground, kPointRadius, 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; })}; @@ -1202,12 +1289,10 @@ void editor_mode::road_click() return; } tool.points.clear(); - auto *road{editor_road::nearest(ground, 1.5)}; - auto *junction{road == nullptr ? editor_road::nearest_junction(ground) : nullptr}; - if (road == nullptr && junction == nullptr) + if (under == nullptr && junction_under == nullptr) tool.status = STR_C("No road here"); - road_select(road); - junction_select(junction); + road_select(under); + junction_select(junction_under); return; } @@ -1928,62 +2013,44 @@ void editor_mode::restore_road_snapshot(EditorSnapshot const &Snapshot, std::vec tool.aimedkind = -1; } -// a field for the name of a material, with a list of the ones in the texture folder to pick from. returns: true if the material was changed -bool editor_mode::render_road_material(char const *Label, char *Buffer, std::size_t const Size, std::string &Value) +// 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) { - auto &tool{m_roadtool}; - bool picked{false}; ImGui::PushID(Label); - ImGui::SetNextItemWidth(200.0f); - if (ImGui::InputText("##name", Buffer, Size, ImGuiInputTextFlags_EnterReturnsTrue) || ImGui::IsItemDeactivatedAfterEdit()) - { - auto const name{lower_case(Buffer)}; - if (name != Value && name.find(' ') == std::string::npos) - { - Value = name.empty() ? std::string{"none"} : name; - picked = true; - } - copy_text(Buffer, Size, Value); - } - ImGui::SameLine(); - if (ImGui::Button("...")) - ImGui::OpenPopup("pick"); - item_tooltip("Pick from the materials in the texture folder"); - ImGui::SameLine(); - ImGui::TextUnformatted(STR_C(Label)); - if (ImGui::BeginPopup("pick")) - { - ImGui::TextDisabled("%s", STR_C("Materials and images found in the texture folder")); - ImGui::SetNextItemWidth(200.0f); - ImGui::InputText(STR_C("Filter"), tool.filter, sizeof(tool.filter)); - auto const filter{lower_case(tool.filter)}; - std::vector listed; - for (auto const &name : editor_road::materials()) - if (filter.empty() || name.find(filter) != std::string::npos) - listed.emplace_back(&name); - ImGui::BeginChild("list", ImVec2(340.0f, 280.0f), true); - ImGuiListClipper clipper; - clipper.Begin(static_cast(listed.size())); - while (clipper.Step()) - { - for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; ++i) - { - if (ImGui::Selectable(listed[i]->c_str(), *listed[i] == Value)) - { - Value = *listed[i]; - copy_text(Buffer, Size, Value); - picked = true; - ImGui::CloseCurrentPopup(); - } - } - } - ImGui::EndChild(); - ImGui::EndPopup(); - } + 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) { @@ -1994,7 +2061,6 @@ bool editor_mode::render_road_layout(road_node::state &State) ImGui::SetNextItemWidth(120.0f); return ImGui::InputFloat(Label, &Value, Step, Step * 4.0f, Format, ImGuiInputTextFlags_EnterReturnsTrue); }; - auto const material = [this](char const *Label, char *Buffer, std::size_t const Size, std::string &Value) { return render_road_material(Label, Buffer, Size, Value); }; // lanes. a piece of a road which is there already can end with other lanes than it starts with { @@ -2071,7 +2137,7 @@ bool editor_mode::render_road_layout(road_node::state &State) State.markings = (colour == 1 ? road_node::marking_colour::white : colour == 2 ? road_node::marking_colour::orange : road_node::marking_colour::none); changed = true; } - if (material("Surface", tool.surface, sizeof(tool.surface), State.surface)) + 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")}; @@ -2096,7 +2162,7 @@ bool editor_mode::render_road_layout(road_node::state &State) data.width = std::clamp(data.width, 0.1f, 20.0f); changed = true; } - if (material("Material", tool.sides[side], sizeof(tool.sides[side]), data.material)) + 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")); @@ -2114,7 +2180,7 @@ bool editor_mode::render_road_layout(road_node::state &State) if (State.kerbs[0] || State.kerbs[1] || island) { ImGui::Indent(); - if (material("Kerb material", tool.kerbtext, sizeof(tool.kerbtext), State.kerbmaterial)) + 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")); @@ -2169,7 +2235,7 @@ bool editor_mode::render_road_layout(road_node::state &State) } ImGui::PopID(); } - if (material("Bank material", tool.banktext, sizeof(tool.banktext), State.bankmaterial)) + 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) @@ -2213,7 +2279,7 @@ bool editor_mode::render_road_layout(road_node::state &State) item_tooltip(apart); if (State.median.type == road_node::median_type::island) { - if (material("Island material", tool.mediantext, sizeof(tool.mediantext), State.median.material)) + 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" @@ -2353,8 +2419,8 @@ void editor_mode::render_road_tool_options() 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.islandtext, sizeof(tool.islandtext), tool.island); - item_tooltip("What the middle is covered with; it's raised on a kerb as high as the kerbs of the road.\nnone: the middle is left as it is"); + 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 { @@ -2863,8 +2929,26 @@ void editor_mode::draw_road_overlay() const drawpoint(point, kSelectedColor, 6.0f, true); drawpoint(point, kSelectedColor, 11.0f, false); } - hint = 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 Shift+LMB: add a point or take it out Del: delete the points Ctrl+Z: undo") : + 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"); diff --git a/application/editormoderoute.cpp b/application/editormoderoute.cpp index 651f06dc1..dd79147ac 100644 --- a/application/editormoderoute.cpp +++ b/application/editormoderoute.cpp @@ -735,7 +735,7 @@ void editor_mode::route_lay() { TTrack *first{nullptr}; TTrack *second{nullptr}; - lifted = lifted || std::abs(crossover->record.lift) > 0.002; + lifted = lifted || crossover->record.lifted(); take_out_crossover(*crossover, states, created, removed, first, second); } switch_store::follow(); diff --git a/application/editormodeselftest.cpp b/application/editormodeselftest.cpp index 5e1d41bd6..367cea0d3 100644 --- a/application/editormodeselftest.cpp +++ b/application/editormodeselftest.cpp @@ -134,15 +134,19 @@ editor_mode::selftest_result editor_mode::selftest_dispatch(std::string const &c // 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|follow|grow|offset|fitted ]... the settings of the terrain model changed as the terrain +// 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 , layradius , laytrace as the panel of the laying sets them +// 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