18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-01 11:47:06 +01:00
Files
maszyna/scene/scenelayers.cpp
T
maj00r c3b987abb2 test(editor): golden round trips of the tracks and of the //$ lines, the cant at the joints (#455)
* fix(editor): track edits keep the joints, the norms, the records and the saved speed together

- The cant typed in the inspector goes on into the track joined at that end, as the gizmo and the
  joints tool do it; the neighbours go into the same undo step. The joint stepped before.
- A track laid on from a canted joint takes the cant off along the ramp the norms ask for at the
  speed (`alignment::cant_ramp_length`), not at a fixed 1.5 mm a metre whatever the speed and the
  norms: 120 mm at 100 km/h over 120 m, not 80 m.
- Deleting a track of the line under the route tool keeps the laying norms. They went back to the
  defaults, and every later lay, extend and join used those.
- The gauge is a paste group of its own, off by default: pasting how a track rides or sounds no
  longer changes its gauge.
- The speed of a turntable set in the editor is the one saved. The editor changed the speed the
  turntable runs at, while the file keeps the limit it was loaded with.
- Deleting a set of tracks does what Del does with each: a double switch, a slip and a crossover go
  whole, the records of the switches go with them, and the model and events of a turntable too. The
  records stayed behind and on saving were given to another switch, which then showed a wrong type.
- Deleting a switch of a crossover takes the crossover out whole, as the connection tools do: the
  outer track of a crossover on a curve comes down by its lift and the record of the connection
  goes. Alone, the switch left the outer track up for good, and the connection to the next switch
  given its name. A switch bent out of the shape of its record is found by its name.

Tests: a unit test of the norm ramp. The other changes are in the editor's UI, which the unit tests
don't reach.

* test(editor): self-test scripts that fail, a runner, and a case for each fix of the track editing

The editor's self-test scripts only logged: nothing made a run fail. Now:

- `expect` commands check the state and log `SELFTEST PASS` or `SELFTEST FAIL ... got X, expected Y`:
  the cant at a track end, the joint at an end (gap, angle, cant step), the records of a switch and
  the connections naming it, speed, gauge, a track present or removed, the laying norms' gauge,
  heights and lifts against a mark, whether a track is in the line under the route tool, and the
  includes of a turntable. A command no group takes counts as a failure, so a mistyped one can't
  make the checks after it pass.
- At `quit` the result is logged, and a script whose expectations failed ends the editor with exit
  code 2 (a failed start stays 1; the simulator's test mode is unchanged).
- The commit of the inspector's cant field is `track_cant_commit`, which the inspector and the
  `trackcant` command both call; `routegauge` sets the laying norms as the route tool does, and
  `tracksetdelete` deletes a set of tracks by name.
- `tests/editor/run.py` runs each script of `tests/editor/cases` on a copy of the fixture scenery
  in the game folder, with a wall-time limit and a memory cap, reads the exit code and the
  `SELFTEST` lines, and deletes the copy. A `#> reopen` line restarts the editor on the saved
  scenery. See `tests/editor/README.md`.
- One case per fix of the track editing quick fixes (inspector cant, norms after deleting, the
  gauge paste group, turntable speed saved, deleting a set, a set with a double switch, a slip
  and a crossover, deleting a switch of a crossover, a bent switch). All pass; with the fixes
  reverted all fail.

* feat(editor): the track tool panels keep their fields, results and buttons within the panel

- The card of the tool: after a long gesture the action goes under it, at its indent, when what is
  left of the row is narrower than 8 font sizes or the longest word of the action. It was squeezed
  into a sliver and broken in the middle of its words.
- A click on the title row of the card folds it to that row (icon, name, family, key, and a small
  triangle marker) and opens it again. One flag for all the tools, kept with the editor settings
  (`track_card_folded` in eu07_editor.ini), open by default: the card took 250-300 px at the top
  of every tool and repeats the hint bar of the view.
- The grade labels of the vertical profile, on the graph and in the view, write the per mille as
  the panel does (the translated "per mille", the per mille sign in Polish), not "o/oo".
- The track analysis window: the thresholds of the speed check and of the joints keep to their
  widest name and a field of 10 font sizes where the window is wider than that, as docked across
  the bottom (`begin_fields_fitted`). The results are tables with each column as wide as what is in
  it: the speed check with its column names kept at the top as the list scrolls, the joints with
  the kind, the value and the two tracks next to each other. A click on a row shows it as before.
- `same_line_if_fits` puts the next button beside the one before only when it fits in what is left
  of the line, at the start of the next line otherwise. Used where the route design puts buttons
  side by side, for "Forget the design" in the profile panel, which was cut off at the edge, and for
  the buttons of a switch in the inspector.
- The laying options: the speed, the curve radius and the longest path are fields with the name on
  the left in two columns (`begin_fields`/`field_row`), as in the inspector, the route and the
  profile, the chips of the quick values under them. The segmented choices give the short names
  less of the room when a long one doesn't fit in its even share, and go on in a second bar when
  they don't fit side by side: "Through the clicked points" overflowed its third of the bar.

* fix(editor): a switch laid gets the speed of its diverging track, one breaking a hard rule of ST-T1-A6 isn't laid

- Every switch laid writes the speed of its diverging track (`velocity`): the switch tool on a
  straight, into a curve, from a free end and linked, a double switch, the switches of a slip, a
  switch given another template of the catalogue, and a switch moved along the curve it's bent
  into. A switch of the catalogue had no limit before, one copied from a switch of the scenery kept
  that one's, one laid without a track had the laying speed on both its tracks. The limit is for the
  diverging track alone (`velocity -V`); the own limit of the track it goes into stays for both
  where it's the lower. The switch tool says the speed and what gives it.
- The speed is formula 9.9 of PKP PLK ST-T1-A6 the other way round, V = sqrt((I + D) r / 11.8), with
  the normal cant deficiency of the frog of table 9.7 (110 mm a fixed frog, 130 mm a movable nose),
  rounded down to the steps of the speed limits and no more than table 11.2 gives the basic switch.
  For the fixed frogs the formula gives table 11.2 itself (190 40, 300 50, 500 60, 760 80, 1200
  100 km/h); the 2500-1:26.5 with a movable nose stays 130. A switch bent into a curve takes the
  radius of its diverging track from table 11.8 (one-sided r" = (Rr - t^2)/(R + r), two-sided
  (Rr + t^2)/(R - r)) and the cant of the line with its sign: leaning against the diverging track it
  takes speed away, where the speed check counted it as helping. Rz 60E1-190-1:9 bent out of the
  curve R 600 m with 60 mm: 30 km/h, not 40; the 60E1-500-1:12 of the review, out of R 1200 m with
  60 mm: 60 km/h at its fixed frog (54 at I = 100 mm, the 0.65 m/s2 the editor took), not 107.
- A switch breaking a hard rule isn't laid, the tracks left as they were, and the switch tool says
  why, with the value, the limit and the paragraph: the cant changing within it (11.4 pkt 7), a cant
  ramp ending within it or nearer than 6 m (9.6 pkt 16-17; one ending right at an end of the switch
  is let be, as the snapping of the start offers it), a double switch, a slip or a crossing bent
  (11.4 pkt 4), the curvature of its diverging or its main track turning from one side to the other
  (9.7 pkt 12, KZW II). They were warnings shown after the switch was laid, and on a straight the
  cant wasn't looked at at all. The line is looked at 10 m past the ends of the curve or the
  straight too, so the ramp on the straight before a curve counts. The previews show the refusals.
- A switch moved along its straight or the curve it's bent into, a double switch moved along its
  straight, and a switch given another template go through the same checks; one breaking a rule
  stays as it is.
- Warnings still: 1:9.403 and steeper than 1:9 bent (11.4 pkt 4c-d), a rule of the running and the
  main tracks, which the editor doesn't tell from the side ones, as the warning now says; the limits
  of table 11.9 and a cant over 100 mm in a bent switch (table 9.6), as before.

Tests: unit tests of tables 11.8 and 11.9 (the least main radius bends the diverging track to the
least radius the table gives), table 9.7, the speeds of table 11.2 by formula 9.9, the speed of a
bent switch with the cant with its sign (the example of the review), the cant over a switch on a
straight and a double switch bent. Editor cases `q2_1_switch_speed`, `q2_2_switch_refusals` and
`q2_3_switch_move`, with `expect status` (the status of the switch tool) and `expect steps` (the
undo steps), the fixture with a straight taking a cant on and a compound curve without cant. All
pass; with the changes of the editor reverted all three fail.

* test(editor): golden round trips of the tracks and of the //$ lines, the cant at the joints

The safety net of the track editor before its domain model changes (E0 of
editor-tracks-tests.md): what the editor reads from the scenery files and
writes back is read, written and read again in tests/unit, with no game data.

Tracks (test_track_text.cpp, data/tracks/). Entries written the way the game
writes them, read by TTrack::Load() and written by export_as_text(), come out
byte for byte the same, and read again give the same track field by field:
plain tracks with all their attributes (events, speed, isolated, overhead,
vradius, rail profile, friction cell), a curve with cant, radius, uneven,
buckle, cwr and sleeper models, a bridge, switches with trackbed, frogs,
movable nose, blades, uneven of both paths and timbers, a turntable, paths of
pieces, the speeds +40, -40, 0.5, 0 and none of tracks, switches and
turntables, a river, a tributary, a road and a crossing. What the game writes
otherwise than given is checked as it is (table as turn, mountain as
mountains, the length of the path, a switch heard from 10 m, the events in
order, names in lower case, model paths with forward slashes, the texture
length, rolls as floats, no overhead and no vradius left out).

The seam: TTrack built from text with no scene. The engine stubs of the tests
had none of it, so the tests link the few sources reading and writing a track
takes (world/Track.cpp, Segment.cpp, TrackUneven.cpp, MemCell.cpp,
scene/scenenode.cpp, utilities/Timer.cpp, rendering/geometrybank.cpp) and
track_stubs.cpp stands in for the rest: a renderer keeping the materials by
their names, and the scene, events, vehicles and the geometry of the rails,
which reading and writing never reach and which stop the test with their name
if one does. It tests the game's own Load() and export, where a parser of its
own would have meant rewriting Load(), and changes no code of the game. The
stub of basic_node::radius_() goes, scenenode.cpp brings the real one. The
rails don't buckle in the tests (TrackBuckle.cpp needs the environment), the
buckle declared is read and written either way; material names go through a
stand-in, the game's material manager isn't tested here.

The //$ lines (test_editor_records.cpp, data/records/). Their readers and
writers were members of editor_mode, srk_tool and the stores, with the scene
around them; they move as they were into editor/editorRecords.cpp, the one
place each kind is read and written, which the stores call (and which the
migration to the project file of E3 will need apart anyway). The methods of
scene::layer_context move into scene/scenelayercontext.cpp so it links alone.
Each kind, h r k p t w b s c o z, read from golden lines and written back comes
out the same, in the coordinates of the file and of a file placed at an
origin; //$e, the descriptions of the templates, read and saved by
editor_includes in a template in a scratch folder, leaves the file as it was.

Cant (test_cant.cpp). The paths an alignment lays roll by asin(cant/gauge),
signed with the turn, back to the cant of the line at every end; a curve the
other way rolls the other way. At a joint editor_track::match_rolls() gives
the joined track the roll for the travel across it, turned where the paths
face or stand back to back, and the track written keeps it. The inspector's
own conversion on 1500 mm stays in its lambdas here; named, as
editor_mode::cant_of_roll()/roll_of_cant(), it comes with the quick fixes.

Known bugs found, tests of the change each (doctest::should_fail, passing
until fixed, then reported to drop the decorator), data/tracks/known_lost.scn:
- angle1/angle2 are read and dropped: not written back.
- fouling1/fouling2 are read and dropped: not written back.
- name@circuit: the circuit is taken out of the name with the letter before
  the @ ("tor1@iso1" becomes track "tor"; substr(0, i - 1)).
- the attributes of the entry (gauge, friction, texture sizes, speed...) are
  written to 6 significant digits, a float has 9: more digits are lost on the
  first save.
None in the //$ lines.

Unit tests: 957 cases before, 974 after, all passing.

* test(editor): a mistyped track fails the self-test, indented comments are skipped, case 7b checks the switch got bent

- A blank line or an indented `#` comment in a script is no longer a command no group takes.
- `trackcant`, `routegauge` and `tracksetdelete` with a track that isn't there count as a failed expectation.
- `expect shaped <switch> <yes|no>`: 7b checks that the gizmo drag bent the switch out of its record before deleting it.
- The ramp-length loop of test_alignment counts in an integer (Sonar S2193).

* test(editor): the entries known to be lost are checked apart from should_fail, the cant test says where the inspector conversion is tested

- A normal test checks that known_lost.scn and each of its entries are there and read, so the should_fail tests can't pass for
  data gone missing.
- The comment of test_cant.cpp said the tests of cant_of_roll()/roll_of_cant() are here; they are the self-test case
  1_inspector_cant.txt, as the unit tests don't link the editor.
2026-11-27 03:57:53 +01:00

1190 lines
36 KiB
C++

/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "scene/scenelayers.h"
#include "simulation/simulation.h"
#include "model/AnimModel.h"
#include "world/Track.h"
#include "world/Traction.h"
#include "utilities/Globals.h"
#include "utilities/utilities.h"
#include "utilities/translation.h"
#include "editor/editorFormat.hpp"
#include <algorithm>
#include <array>
#include <fstream>
#include <functional>
#include <iterator>
#include <sstream>
#include <string_view>
namespace scene
{
node_layers Layers;
// layer_context: scene/scenelayercontext.cpp, which the unit tests of the //$ lines of the editor link alone
std::size_t basic_layer::item_count() const
{
return std::accumulate(std::begin(items), std::end(items), std::size_t{0});
}
// indicates start of content of the scenario file. returns: handle to its layer
layer_handle node_layers::open(std::string const &Name)
{
// the same file can be included more than once, all its content goes to a single layer then
auto const lookup{std::find_if(std::begin(m_layers), std::end(m_layers), [&](basic_layer const &Layer) { return Layer.name == Name && false == Layer.dead; })};
auto layerhandle{static_cast<layer_handle>(std::distance(std::begin(m_layers), lookup) + 1)};
if (lookup == std::end(m_layers))
{
if (m_layers.size() < static_cast<std::size_t>(std::numeric_limits<layer_handle>::max()))
{
m_layers.emplace_back();
m_layers.back().name = Name;
m_layers.back().parent = handle();
m_layers.back().late = m_initialized;
stat(layerhandle);
scan(layerhandle);
}
else
{
// out of handles, content of the file is attributed to the parent layer
layerhandle = handle();
}
}
if (valid(layerhandle) && layerhandle != handle())
{
layer(layerhandle).context_begin = m_context;
}
// NOTE: the stack receives an entry even if the layer wasn't created, to keep it in sync with close() calls
m_stack.emplace_back(layerhandle);
return layerhandle;
}
// indicates start of content of specified scenery file, included by specified directive. returns: handle to the layer of the file
layer_handle node_layers::open(std::string const &Name, include_site Site)
{
Site.parent = handle();
auto const layerhandle{open(Name)};
if (valid(layerhandle) && layerhandle != Site.parent)
{
layer(layerhandle).sites.emplace_back(Site);
}
return layerhandle;
}
// indicates end of content of the current scenery file. returns: handle to the parent layer, or null_handle if the stack is empty
layer_handle node_layers::close()
{
if (false == m_stack.empty())
{
auto const closing{m_stack.back()};
m_stack.pop_back();
if (valid(closing) && closing != handle())
{
layer(closing).context_end = m_context;
}
}
return handle();
}
void node_layers::clear()
{
m_layers.clear();
m_stack.clear();
m_active = null_handle;
m_context = layer_context();
m_sources.clear();
m_erased.clear();
m_renamed.clear();
m_shapes.clear();
m_shapeserased = false;
m_templates.clear();
m_instances.clear();
m_instance = 0;
m_initialized = false;
m_terraindirective = false;
m_marked.clear();
m_marking.clear();
}
// indicates the scenario initialization (FirstInit) is being performed
void node_layers::initialization(source_span const &Span, bool const Infile)
{
if (m_initialized)
{
return;
}
m_initialized = true;
if (m_stack.empty() || false == valid(m_stack.back()))
{
return;
}
// the layer file being loaded holds the directive, or includes the template which does
auto &holder{layer(m_stack.back())};
if (Infile)
{
// NOTE: scenario without the directive is initialized at its end, with nothing in the file to point at
std::string text(Span.valid() ? static_cast<std::size_t>(Span.end - Span.begin) : 0, '\0');
std::ifstream input{path(m_stack.back()), std::ios_base::binary};
if (text.empty() || false == input.is_open() || false == input.seekg(Span.begin).good() || false == input.read(text.data(), static_cast<std::streamsize>(text.size())).good() ||
ToLower(text) != "firstinit")
{
return;
}
holder.init = Span;
}
else if (tracked(m_instance) && instance(m_instance).layer == m_stack.back())
{
holder.init = instance(m_instance).span;
}
else
{
return;
}
holder.context_init = m_context;
// for the files it was included through the initialization takes place at their include directives
for (auto level{m_stack.size() - 1}; level > 0; --level)
{
auto const child{m_stack[level]};
auto const parent{m_stack[level - 1]};
if (false == valid(parent) || parent == child || layer(child).sites.empty() || layer(child).sites.back().parent != parent || layer(child).sites.back().fixed ||
false == layer(child).sites.back().span.valid())
{
break;
}
layer(parent).init = layer(child).sites.back().span;
layer(parent).context_init = layer(child).context_begin;
}
}
// true if specified layer can receive content added in the editor
bool node_layers::accepts(layer_handle Layer, std::string *Reason) const
{
Layer = resolve(Layer);
if (false == valid(Layer) || layer(Layer).removed)
{
return false;
}
if (false == writable(Layer, Reason))
{
return false;
}
if (layer(Layer).late)
{
if (Reason != nullptr)
{
*Reason = STR_C("the file is loaded after the scenario initialization (FirstInit), which only vehicles should follow");
}
return false;
}
return true;
}
// follows layer merges. returns: handle of the layer which currently holds content of specified layer
layer_handle node_layers::resolve(layer_handle Layer) const
{
// NOTE: merge() rules out cycles, the counter is only a safeguard
for (auto hops = 0; hops < 64 && valid(Layer) && layer(Layer).merged != null_handle; ++hops)
{
Layer = layer(Layer).merged;
}
return Layer;
}
int node_layers::depth(layer_handle Layer) const
{
auto depth{0};
Layer = resolve(Layer);
while (valid(Layer) && layer(Layer).parent != null_handle && depth < 64)
{
Layer = resolve(layer(Layer).parent);
++depth;
}
return depth;
}
std::vector<layer_handle> node_layers::tree() const
{
std::vector<layer_handle> order;
order.reserve(m_layers.size());
// NOTE: the layers are few, plain scans do
std::function<void(layer_handle)> const add = [&](layer_handle const Parent) {
for (std::size_t idx = 0; idx < m_layers.size(); ++idx)
{
auto const candidate{static_cast<layer_handle>(idx + 1)};
if (listed(candidate) && resolve(layer(candidate).parent) == Parent && order.size() < m_layers.size())
{
order.emplace_back(candidate);
add(candidate);
}
}
};
add(null_handle);
return order;
}
void node_layers::count(layer_handle Layer, layer_item const Item, int const Change)
{
Layer = resolve(Layer);
if (false == valid(Layer))
{
return;
}
auto &itemcount{layer(Layer).items[static_cast<std::size_t>(Item)]};
if (Change >= 0)
{
itemcount += static_cast<std::size_t>(Change);
}
else
{
itemcount -= std::min(itemcount, static_cast<std::size_t>(-Change));
}
}
void node_layers::active(layer_handle Layer)
{
Layer = resolve(Layer);
if (false == accepts(Layer))
{
return;
}
// new items land in the active layer, they'd be out of reach right away if it was hidden or locked
visible(Layer, true);
locked(Layer, false);
m_active = Layer;
}
// shows or hides nodes of specified layer. visibility defined in the scenery is preserved, hidden layer only overrides it
void node_layers::visible(layer_handle Layer, bool const Visible)
{
Layer = resolve(Layer);
if (false == valid(Layer) || layer(Layer).visible == Visible)
{
return;
}
layer(Layer).visible = Visible;
auto const update_node = [this, Layer, Visible](basic_node *Node) {
if (Node == nullptr || resolve(Node->layer()) != Layer)
{
return;
}
if (Visible)
{
// nodes of a removed include stay out of sight, and so do the ones the editor replaced with its own
if (Node->m_layerhidden && (false == tracked(Node->m_instance) || (false == instance(Node->m_instance).removed && false == stale(Node))))
{
Node->visible(true);
Node->m_layerhidden = false;
}
}
else if (Node->visible())
{
// nodes which are invisible on their own aren't marked, so they stay that way when the layer is shown again
Node->visible(false);
Node->m_layerhidden = true;
}
};
// only these node types are drawn by the renderers basing on their visibility flag
for (auto *instance : simulation::Instances.sequence())
{
update_node(instance);
}
for (auto *path : simulation::Paths.sequence())
{
update_node(path);
}
for (auto *traction : simulation::Traction.sequence())
{
update_node(traction);
}
}
void node_layers::locked(layer_handle Layer, bool const Locked)
{
Layer = resolve(Layer);
if (valid(Layer))
{
layer(Layer).locked = Locked;
}
}
// true if the file of specified layer can be rewritten with changed nodes. optionally explains why it can't
bool node_layers::writable(layer_handle Layer, std::string *Reason) const
{
Layer = resolve(Layer);
if (false == valid(Layer))
{
return false;
}
auto const &target{layer(Layer)};
char const *reason{nullptr};
if (target.binary)
{
reason = STR_C("the file is loaded from binary terrain cache");
}
else if (target.sites.size() > 1)
{
// one definition yields several nodes, there's no telling which of them should be written back
reason = STR_C("the file is included more than once");
}
else if (false == target.sites.empty() && target.sites.front().parameters)
{
reason = STR_C("the file is included with parameters");
}
if (reason != nullptr && Reason != nullptr)
{
*Reason = reason;
}
return reason == nullptr;
}
// true if nodes of specified layer can be selected and modified in the editor
bool node_layers::editable(layer_handle Layer) const
{
Layer = resolve(Layer);
// nodes without a layer (regular load, or created by the simulation) aren't restricted
return false == valid(Layer) || (layer(Layer).visible && false == layer(Layer).locked && false == layer(Layer).removed && writable(Layer));
}
// true if specified node can be selected and modified in the editor. optionally explains why it can't
bool node_layers::editable(basic_node const *Node, std::string *Reason) const
{
if (Node == nullptr)
{
return false;
}
auto const nodelayer{resolve(Node->layer())};
if (false == valid(nodelayer))
{
return true;
}
std::string reason;
if (Node->from_template())
{
reason = STR_C("it's a part of an include template (.inc)");
}
else if (false == writable(nodelayer, &reason))
{
// reason was filled by the call
}
else if (layer(nodelayer).locked)
{
reason = STR_C("its layer is locked");
}
else if (false == layer(nodelayer).visible || layer(nodelayer).removed)
{
reason = STR_C("its layer is hidden");
}
if (false == reason.empty() && Reason != nullptr)
{
*Reason = reason;
}
return reason.empty();
}
// moves specified node to specified layer
void node_layers::move(basic_node *Node, layer_handle Layer)
{
Layer = resolve(Layer);
if (Node == nullptr || false == valid(Layer) || resolve(Node->layer()) == Layer)
{
return;
}
// NOTE: the only nodes the editor creates and moves between layers are model instances
count(Node->layer(), layer_item::model, -1);
Node->layer(Layer);
count(Layer, layer_item::model, 1);
}
std::vector<layer_handle> node_layers::hidden() const
{
std::vector<layer_handle> layers;
for (std::size_t idx = 0; idx < m_layers.size(); ++idx)
{
if (false == m_layers[idx].visible)
{
layers.emplace_back(static_cast<layer_handle>(idx + 1));
}
}
return layers;
}
void node_layers::show_all()
{
for (auto const hiddenlayer : hidden())
{
// layers dropped from the scenery stay out of sight
if (false == layer(hiddenlayer).removed)
{
visible(hiddenlayer, true);
}
}
}
// stores origin of a node defined directly in a layer file, to allow rewriting its definition on save
void node_layers::track(basic_node const *Node, source_span const &Span, glm::vec3 const &Angles, glm::vec3 const &Scale)
{
if (Node == nullptr || Node->from_template() || false == valid(Node->layer()) || false == Span.valid())
{
return;
}
m_sources[Node] = {Node->layer(), Span, m_context, Node->location(), Angles, Scale};
}
// indicates specified node was removed from the scene
void node_layers::forget(basic_node const *Node)
{
auto const lookup{m_sources.find(Node)};
if (lookup == m_sources.end())
{
return;
}
m_erased.emplace_back(lookup->second.layer, lookup->second.span);
m_sources.erase(lookup);
m_renamed.erase(Node);
}
// indicates specified node was given another name in the editor
void node_layers::renamed(basic_node const *Node)
{
// NOTE: a node which isn't defined by a scenery file yet is written whole on save, along with its name
if (m_sources.find(Node) != m_sources.end())
{
m_renamed.emplace(Node);
}
}
void node_layers::shape(material_handle const Material, source_span const &Span)
{
auto const current{handle()};
if (false == valid(current) || false == Span.valid() || m_instance != 0)
{
return;
}
m_shapes.push_back({current, Span, Material, false});
}
std::pair<std::size_t, std::size_t> node_layers::erase_shapes(std::set<material_handle> const &Materials, std::set<layer_handle> const *Layers)
{
std::pair<std::size_t, std::size_t> result{0, 0};
for (auto &shape : m_shapes)
{
if (shape.erased || Materials.count(shape.material) == 0 || (Layers != nullptr && Layers->count(shape.layer) == 0))
{
continue;
}
if (false == writable(shape.layer))
{
++result.second;
continue;
}
shape.erased = true;
m_erased.emplace_back(shape.layer, shape.span);
m_shapeserased = true;
++result.first;
}
return result;
}
bool node_layers::is_descendant(layer_handle Layer, layer_handle const Ancestor) const
{
// NOTE: content of a merged layer, includes of other files among it, belongs to the layer it was merged into
for (auto hops = 0; hops < 64 && valid(Layer); ++hops)
{
Layer = resolve(layer(Layer).parent);
if (Layer == Ancestor)
{
return true;
}
}
return false;
}
std::string node_layers::path(layer_handle const Layer) const
{
auto const named{Global.asCurrentSceneryPath + layer(Layer).name};
auto const cased{FileCased(named)};
return cased.empty() ? named : cased;
}
// stores current state of the layer file, to detect later whether it was changed behind our back
void node_layers::stat(layer_handle const Layer)
{
std::error_code error;
auto const filepath{std::filesystem::path(path(Layer))};
auto const filesize{std::filesystem::file_size(filepath, error)};
layer(Layer).filesize = error ? 0 : filesize;
auto const filetime{std::filesystem::last_write_time(filepath, error)};
layer(Layer).filetime = error ? std::filesystem::file_time_type{} : filetime;
}
// creates empty layer, included from specified one. returns: handle to the new layer, or null_handle with the explanation in Reason
layer_handle node_layers::create(std::string Name, layer_handle Parent, std::string &Reason, bool const Activate, std::string Header)
{
Parent = resolve(Parent);
if (false == valid(Parent) || layer(Parent).removed || layer(Parent).binary)
{
Reason = STR_C("the parent layer can't include other files");
return null_handle;
}
if (layer(Parent).late)
{
Reason = STR_C("the parent layer is loaded after the scenario initialization (FirstInit), which only vehicles should follow");
return null_handle;
}
// file names in the scenery are processed in lower case, with forward slashes
Name = ToLower(Name);
replace_slashes(Name);
Name.erase(0, Name.find_first_not_of(" \t"));
Name.erase(Name.find_last_not_of(" \t") + 1);
if (Name.empty())
{
Reason = STR_C("the layer needs a file name");
return null_handle;
}
if (Name.find_first_of(" \t\";:*?<>|") != std::string::npos || Name.front() == '/' || Name.back() == '/' || contains(Name, ".."))
{
Reason = STR_C("the file name has to be a plain path inside the scenery directory, without spaces");
return null_handle;
}
if (std::filesystem::path(Name).extension().empty())
{
Name += ".scm";
}
if (Name.ends_with(".inc"))
{
Reason = STR_C(".inc files are include templates, not layers");
return null_handle;
}
if (m_layers.size() >= static_cast<std::size_t>(std::numeric_limits<layer_handle>::max()))
{
Reason = STR_C("too many layers");
return null_handle;
}
auto const taken{std::any_of(std::begin(m_layers), std::end(m_layers), [&](basic_layer const &Layer) { return Layer.name == Name && false == Layer.dead; })};
if (taken || FileExists(Global.asCurrentSceneryPath + Name))
{
Reason = format(STR_C("the file \"%s\" already exists"), Name.c_str());
return null_handle;
}
// the include directive goes after the last file included by the parent ahead of the scenario initialization,
// so the scenery files stay ahead of what follows them in a scenario, like the vehicles
auto anchor{null_handle};
std::streamoff anchorend{-1};
auto const &init{layer(Parent).init};
for (std::size_t idx = 0; idx < m_layers.size(); ++idx)
{
auto const &sibling{m_layers[idx]};
if (sibling.dead || sibling.created || sibling.sites.size() != 1)
{
continue;
}
auto const &site{sibling.sites.front()};
if (site.parent == Parent && false == site.fixed && site.span.end > anchorend && (false == init.valid() || site.span.end <= init.begin))
{
anchor = static_cast<layer_handle>(idx + 1);
anchorend = site.span.end;
}
}
m_layers.emplace_back();
auto const layerhandle{static_cast<layer_handle>(m_layers.size())};
auto &created{m_layers.back()};
created.name = Name;
created.parent = Parent;
created.created = true;
created.editormade = true;
created.anchor = anchor;
created.header = std::move(Header);
// placement the new file is going to be loaded with
created.context_begin = valid(anchor) ? layer(anchor).context_end : layer(Parent).context_insert();
created.context_end = created.context_begin;
if (Activate)
{
active(layerhandle);
}
return layerhandle;
}
bool node_layers::can_remove(layer_handle Layer, std::string &Reason) const
{
if (false == listed(Layer) || layer(Layer).removed)
{
Reason = STR_C("no such layer");
return false;
}
auto const &target{layer(Layer)};
if (target.created)
{
return true;
}
if (target.sites.empty())
{
Reason = STR_C("the scenario file can't be removed");
return false;
}
if (target.binary)
{
Reason = STR_C("the file is loaded from binary terrain cache");
return false;
}
if (target.sites.size() > 1)
{
Reason = STR_C("the file is included more than once");
return false;
}
if (target.sites.front().fixed)
{
Reason = STR_C("the file is included by an include template (.inc)");
return false;
}
return true;
}
// marks specified layer and the layers it includes as dropped from the scenery. their files are left on the disk
bool node_layers::remove(layer_handle Layer)
{
std::string reason;
if (false == can_remove(Layer, reason))
{
return false;
}
for (std::size_t idx = 0; idx < m_layers.size(); ++idx)
{
auto const candidate{static_cast<layer_handle>(idx + 1)};
// layers merged elsewhere keep going, their content is no longer a part of the removed file
if (false == listed(candidate) || (candidate != Layer && false == is_descendant(candidate, Layer)))
{
continue;
}
visible(candidate, false);
layer(candidate).removed = true;
if (m_active == candidate)
{
m_active = null_handle;
}
}
if (m_active == null_handle)
{
// fall back on the scenario file, which is always there
active(1);
}
return true;
}
// takes back remove() which wasn't saved yet
void node_layers::restore(layer_handle Layer)
{
if (false == valid(Layer) || false == layer(Layer).removed || layer(Layer).dead)
{
return;
}
// a layer can't be brought back without the file which includes it
auto const parent{resolve(layer(Layer).parent)};
if (valid(parent) && layer(parent).removed)
{
restore(parent);
}
for (std::size_t idx = 0; idx < m_layers.size(); ++idx)
{
auto const candidate{static_cast<layer_handle>(idx + 1)};
if (false == listed(candidate) || (candidate != Layer && false == is_descendant(candidate, Layer)))
{
continue;
}
layer(candidate).removed = false;
visible(candidate, true);
}
}
bool node_layers::can_merge(layer_handle Source, layer_handle Target, std::string &Reason) const
{
if (false == listed(Source) || false == listed(Target) || layer(Source).removed || layer(Target).removed)
{
Reason = STR_C("no such layer");
return false;
}
if (Source == Target)
{
Reason = STR_C("pick another layer to merge into");
return false;
}
auto const &source{layer(Source)};
auto const &target{layer(Target)};
if (false == writable(Target, &Reason))
{
return false;
}
if (is_descendant(Target, Source))
{
// the merged text would include the file it was put in
Reason = STR_C("the target layer is included by the merged one");
return false;
}
if (target.late != source.late && (source.created || source.sites.empty() || resolve(source.sites.front().parent) != Target))
{
// the content would change sides of the scenario initialization
Reason = (target.late ? STR_C("the target layer is loaded after the scenario initialization (FirstInit), which only vehicles should follow") :
STR_C("the merged layer is loaded after the scenario initialization (FirstInit), its content has to stay there"));
return false;
}
if (false == source.context_insert().matches(target.context_insert()))
{
// directives of includes placed in the editor are prepared for the place their layer file receives them at
auto const unsaved{std::any_of(std::begin(m_instances), std::end(m_instances), [&](include_instance const &Instance) {
return false == Instance.dead && false == Instance.removed && false == Instance.span.valid() && resolve(Instance.layer) == Source;
})};
if (unsaved)
{
Reason = STR_C("the merged layer has includes which weren't saved yet, save the scenery first");
return false;
}
}
if (source.created)
{
// nothing but the nodes made in the editor to move
return true;
}
if (source.sites.empty())
{
Reason = STR_C("the scenario file can't be merged into another layer");
return false;
}
if (false == writable(Source, &Reason))
{
return false;
}
if (source.sites.front().fixed)
{
Reason = STR_C("the file is included by an include template (.inc)");
return false;
}
if (resolve(source.sites.front().parent) != Target)
{
// the text is moved to another file. its statements have to keep their meaning there,
// and can't leave anything behind for what used to follow it
if (false == source.context_begin.matches(target.context_insert()) || false == source.context_end.matches(source.context_begin))
{
Reason = STR_C("the layers are loaded with different origin, rotation or scale");
return false;
}
}
return true;
}
// moves content of the source layer to the target layer
bool node_layers::merge(layer_handle Source, layer_handle Target)
{
std::string reason;
if (false == can_merge(Source, Target, reason))
{
return false;
}
// start with the same visibility on both sides, as it's kept per node
visible(Source, true);
visible(Target, true);
for (std::size_t idx = 0; idx < layer(Source).items.size(); ++idx)
{
layer(Target).items[idx] += layer(Source).items[idx];
}
layer(Source).merged = Target;
if (m_active == Source)
{
active(Target);
}
return true;
}
// true if there are layer changes awaiting save. NOTE: doesn't account for modified nodes
bool node_layers::pending() const
{
return false == m_marking.empty() ||
std::any_of(std::begin(m_layers), std::end(m_layers), [](basic_layer const &Layer) { return false == Layer.dead && (Layer.created || Layer.removed || Layer.merged != null_handle); });
}
namespace
{
// marks of the lines the editor keeps track of. The letters the starters read in a scenery file are left to them: the title //$n,
// the description //$d, the attachments //$f, the image //$i, the id //$l and the old scenery //$a, in the trainsets //$o and //$r
std::array<char const *, 11> const editormarks{"//$p", "//$h", "//$r", "//$b", "//$c", "//$o", "//$s", "//$k", "//$z", "//$w", "//$t"};
// the marks some of these had before, on the letters of the starters: the download area //$z was //$a, the shared grade lines //$w
// were //$n, the fitted tracks //$t were //$f. Their lines are read only by the word the editor wrote in them, or by the start of
// the comment line it put before them, and are kept under the mark they have now: saved, they go and are written again with it
struct moved_mark
{
std::string_view before;
char const *now;
std::string_view word;
std::string_view note;
};
std::array<moved_mark, 3> const movedmarks{{
{"//$a", "//$z", "point", "# the area the editor downloads"},
{"//$n", "//$w", "gradeline", "# the tracks sharing a grade line"},
{"//$f", "//$t", "fitted", "# the tracks whose grade line was fitted"},
}};
std::string_view first_word(std::string const &Text)
{
return std::string_view{Text}.substr(0, Text.find_first_of(" \t"));
}
// other tools put lines of their own after some of these marks: Rainsted its includes after //$r, the starters the descriptions
// of the trainsets after //$o. The editor's lines of them are told by their first words, and so are those of most marks of its
// own, so a line the editor didn't write is never taken off as the scenery is saved
bool editor_line(std::string_view const Mark, std::string const &Text)
{
if (Mark == "//$o")
{
// "on 0" or "on 1", the origin after it (older builds put the settings of the imagery there, from the year on); a trainset
// described as "on ..." isn't the editor's
std::istringstream words{Text};
std::string on, state, next;
return words >> on >> state && on == "on" && (state == "0" || state == "1") && (false == static_cast<bool>(words >> next) || next == "origin" || next == "year");
}
static std::array<std::pair<std::string_view, std::array<std::string_view, 11>>, 7> const words{{
{"//$h", {"#", "alignment", "source", "ends", "norms", "pieces", "kept", "vertex", "click", "element", "end"}},
{"//$r", {"#", "switch", "slip", "crossing", "double", "connection"}},
{"//$s", {"#", "station"}},
{"//$k", {"#", "mark", "via"}},
{"//$z", {"#", "point"}},
{"//$w", {"#", "gradeline"}},
{"//$t", {"#", "fitted"}},
}};
auto const lookup{std::find_if(words.begin(), words.end(), [&](auto const &Entry) { return Entry.first == Mark; })};
if (lookup == words.end())
{
return true;
}
auto const word{first_word(Text)};
return std::any_of(lookup->second.begin(), lookup->second.end(), [&](std::string_view const Known) { return false == Known.empty() && Known == word; });
}
} // namespace
void node_layers::scan(layer_handle const Layer)
{
m_marked.erase(Layer);
std::ifstream file{path(Layer), std::ios_base::binary};
if (false == file.is_open())
{
return;
}
std::string content{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
if (content.find("//$") == std::string::npos)
{
return;
}
std::size_t begin{0};
while (begin < content.size())
{
auto end{content.find('\n', begin)};
end = (end == std::string::npos ? content.size() : end + 1);
auto const first{content.find_first_not_of(" \t", begin)};
// the text after the mark, if the line starts with it
auto const marked_text = [&](std::string_view const Mark, std::string &Text) {
auto const length{Mark.size()};
if (content.compare(first, length, Mark) != 0 || (first + length < end && content[first + length] != ' ' && content[first + length] != '\t' && content[first + length] != '\r' && content[first + length] != '\n'))
{
return false;
}
Text = content.substr(first + length, end - first - length);
while (false == Text.empty() && (Text.back() == '\n' || Text.back() == '\r'))
{
Text.pop_back();
}
Text.erase(0, Text.find_first_not_of(" \t"));
return true;
};
if (first < end)
{
std::string text;
char const *taken{nullptr};
bool moved{false};
auto const mark{std::find_if(editormarks.begin(), editormarks.end(), [&](char const *Mark) { return marked_text(Mark, text); })};
if (mark != editormarks.end())
{
taken = (editor_line(*mark, text) ? *mark : nullptr);
}
else if (auto const before{std::find_if(movedmarks.begin(), movedmarks.end(), [&](moved_mark const &Moved) { return marked_text(Moved.before, text); })}; before != movedmarks.end())
{
taken = (first_word(text) == before->word || text.starts_with(before->note) ? before->now : nullptr);
moved = true;
}
if (nullptr != taken)
{
m_marked[Layer].push_back({taken, {static_cast<std::streamoff>(begin), static_cast<std::streamoff>(end)}, std::move(text), moved});
}
}
begin = end;
}
}
std::vector<std::string> node_layers::marked(layer_handle const Layer, std::string const &Mark) const
{
std::vector<std::string> result;
if (auto const pending{m_marking.find({Layer, Mark})}; pending != m_marking.end())
{
return pending->second;
}
if (auto const lookup{m_marked.find(Layer)}; lookup != m_marked.end())
{
for (auto const &line : lookup->second)
{
if (line.mark == Mark)
{
result.push_back(line.text);
}
}
}
return result;
}
std::vector<layer_handle> node_layers::marked_layers(std::string const &Mark) const
{
std::vector<layer_handle> result;
for (auto const &entry : m_marked)
{
if (listed(entry.first) && std::any_of(entry.second.begin(), entry.second.end(), [&](marked_line const &Line) { return Line.mark == Mark; }))
{
result.push_back(entry.first);
}
}
for (auto const &entry : m_marking)
{
if (entry.first.second == Mark && std::find(result.begin(), result.end(), entry.first.first) == result.end())
{
result.push_back(entry.first.first);
}
}
return result;
}
void node_layers::mark(layer_handle const Layer, std::string const &Mark, std::vector<std::string> Lines)
{
if (valid(Layer))
{
m_marking[{Layer, Mark}] = std::move(Lines);
}
}
// indicates start of content of a template, included by directive at specified location of the layer file being loaded
void node_layers::instance_begin(std::string const &File, source_span const &Span)
{
if (m_instances.size() + 1 >= untracked_instance)
{
m_instance = untracked_instance;
return;
}
m_instances.emplace_back();
auto &included{m_instances.back()};
included.layer = handle();
included.file = &(*m_templates.emplace(File).first);
included.span = Span;
included.context = m_context;
m_instance = static_cast<instance_handle>(m_instances.size());
}
// true if specified include can be removed in the editor. optionally explains why it can't
bool node_layers::removable(instance_handle Instance, std::string *Reason) const
{
std::string reason;
if (false == tracked(Instance) || instance(Instance).dead)
{
reason = STR_C("it's a part of an include template (.inc)");
}
else
{
auto const includelayer{resolve(instance(Instance).layer)};
if (false == valid(includelayer) || layer(includelayer).removed)
{
reason = STR_C("its layer is no longer a part of the scenery");
}
else if (false == writable(includelayer, &reason))
{
// reason was filled by the call
}
else if (layer(includelayer).locked)
{
reason = STR_C("its layer is locked");
}
}
if (false == reason.empty() && Reason != nullptr)
{
*Reason = reason;
}
return reason.empty();
}
// drops specified include from the scenery, or brings it back
void node_layers::removed(instance_handle Instance, bool Removed)
{
if (false == tracked(Instance) || m_instances[Instance - 1].dead || m_instances[Instance - 1].removed == Removed)
{
return;
}
m_instances[Instance - 1].removed = Removed;
auto const includelayer{resolve(m_instances[Instance - 1].layer)};
auto const layervisible{false == valid(includelayer) || layer(includelayer).visible};
auto const update_node = [=, this](basic_node *Node, layer_item const Item) {
if (Node == nullptr || Node->m_instance != Instance || (Item == layer_item::model && stale(Node)))
{
return;
}
count(Node->layer(), Item, Removed ? -1 : 1);
if (Removed)
{
if (Node->visible())
{
Node->visible(false);
Node->m_layerhidden = true;
}
}
else if (Node->m_layerhidden && layervisible)
{
Node->visible(true);
Node->m_layerhidden = false;
}
};
for (auto *modelinstance : simulation::Instances.sequence())
{
update_node(modelinstance, layer_item::model);
}
for (auto *path : simulation::Paths.sequence())
{
update_node(path, layer_item::track);
}
for (auto *traction : simulation::Traction.sequence())
{
update_node(traction, layer_item::traction);
}
}
// registers include directive made in the editor, to be written to the file of specified layer on save
instance_handle node_layers::place(layer_handle Layer, std::string const &File, std::string const &Directive)
{
Layer = resolve(Layer);
if (false == accepts(Layer) || m_instances.size() + 1 >= untracked_instance)
{
return 0;
}
m_instances.emplace_back();
auto &included{m_instances.back()};
included.layer = Layer;
included.file = &(*m_templates.emplace(File).first);
included.directive = Directive;
included.context = layer(Layer).context_insert();
return static_cast<instance_handle>(m_instances.size());
}
// text of the directive of specified include, as changed in the editor or as it stands in the scenery file
std::string node_layers::directive(instance_handle const Instance) const
{
if (false == tracked(Instance))
{
return {};
}
auto const &included{instance(Instance)};
if (false == included.directive.empty() || false == included.span.valid() || false == valid(included.layer))
{
return included.directive;
}
std::string text(static_cast<std::size_t>(included.span.end - included.span.begin), '\0');
std::ifstream input{path(included.layer), std::ios_base::binary};
if (false == input.is_open() || false == input.seekg(included.span.begin).good() || false == input.read(text.data(), static_cast<std::streamsize>(text.size())).good())
{
return {};
}
return text;
}
// replaces the directive of specified include, the scenery file receives it on save
bool node_layers::modify(instance_handle const Instance, std::string const &Directive, std::string const &File)
{
if (false == tracked(Instance) || m_instances[Instance - 1].dead || Directive.empty())
{
return false;
}
m_instances[Instance - 1].directive = Directive;
if (false == File.empty())
{
m_instances[Instance - 1].file = &(*m_templates.emplace(File).first);
}
return true;
}
// takes the models specified include was loaded with out of the scene, once the editor shows its own in their place
void node_layers::rebuilt(instance_handle const Instance)
{
if (false == tracked(Instance) || m_instances[Instance - 1].rebuilt)
{
return;
}
auto const removed{m_instances[Instance - 1].removed};
for (auto *model : simulation::Instances.sequence())
{
if (model == nullptr || model->m_instance != Instance || model->m_preview)
{
continue;
}
// NOTE: the models themselves are left alone, events of the scenery can refer to them
simulation::Region->erase(model);
if (false == removed)
{
count(model->layer(), layer_item::model, -1);
}
if (model->visible())
{
model->visible(false);
model->m_layerhidden = true;
}
}
m_instances[Instance - 1].rebuilt = true;
}
} // namespace scene
//---------------------------------------------------------------------------
std::string scene::node_layers::check_sources() const
{
std::map<scene::layer_handle, std::string> files;
std::size_t good{0};
std::size_t bad{0};
std::string report;
for (auto const &[node, source] : m_sources)
{
auto &text{files[source.layer]};
if (text.empty())
{
std::ifstream file(path(source.layer), std::ios::binary);
text.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
}
auto const ok{source.span.valid() && static_cast<std::size_t>(source.span.end) <= text.size()};
std::string piece{ok ? text.substr(source.span.begin, source.span.end - source.span.begin) : std::string{}};
auto const model{dynamic_cast<TAnimModel const *>(node) != nullptr};
auto const fine{ok && piece.rfind("node", 0) == 0 && (false == model || (piece.size() >= 8 && piece.compare(piece.size() - 8, 8, "endmodel") == 0))};
if (fine)
++good;
else if (++bad <= 5)
report += " [" + node->name() + " " + std::to_string(source.span.begin) + "-" + std::to_string(source.span.end) + ": " + piece.substr(0, 60) + " ... " + (piece.size() > 30 ? piece.substr(piece.size() - 30) : std::string{}) + "]"; // NOSONAR
}
return std::to_string(good) + " good, " + std::to_string(bad) + " bad" + report;
}