diff --git a/CMakeLists.txt b/CMakeLists.txt index f196cb322..6d2daf5d4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -228,6 +228,7 @@ set(SOURCES "editor/project/projectMigration.cpp" "editor/project/sceneryText.cpp" "editor/project/scenarioIndex.cpp" +"editor/project/projectSession.cpp" "editor/editorNormsReport.cpp" "editor/editorProfile.cpp" "editor/editorGauge.cpp" @@ -267,6 +268,7 @@ set(SOURCES "application/editormodeinfra.cpp" "application/editormodespeed.cpp" "application/editormodenorms.cpp" +"application/editormodemodel.cpp" "application/editormodesrk.cpp" "application/editormodekm.cpp" "application/editormodejoints.cpp" diff --git a/application/editormode.cpp b/application/editormode.cpp index 82d4acc85..f1619393d 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -987,6 +987,7 @@ void editor_mode::nullify_history_pointers(scene::basic_node *node) infra_forget(node); for (auto *tool : m_tools) tool->forget(node); + model_forget(node); auto const followed = [node](infra::object_state const &State) { return State.saved.node == node; }; for (auto &s : m_history) @@ -1798,6 +1799,8 @@ bool editor_mode::update() render_orthophoto_window(); draw_selection_overlay(); render_context_menu(); + // the track geometry edited through the model: the project of the map + model_update(); steps.step("windows"); // --- ImGui: Editor Settings & History windows --- @@ -1857,6 +1860,23 @@ void editor_mode::render_settings() ImGui::SeparatorText(STR_C("Terrain")); render_terrain_loading(); + // the tracks laid and edited through the model of the track geometry, a trial: off, as the editor was + ImGui::SeparatorText(STR_C("Tracks")); + { + bool model{EditorSettings.model_editing()}; + if (ImGui::Checkbox(STR_C("Editing on the model (trial)"), &model)) + { + EditorSettings.model_editing(model); + EditorSettings.save(); + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("A line laid in the straights, or applied by the route design, becomes a line of the model of the track geometry: its tracks are made by the model, " + "its edits checked against the norms and refused with the reasons, the project of the map kept next to it.\n" + "The tracks there were stay as they are, edited the old way. Off, the editor works as it did")); + if (auto const error{model_error()}; model && false == error.empty()) + ImGui::TextColored(ImVec4(1.0f, 0.6f, 0.2f, 1.0f), "%s", format(STR_C("The project of the map can't be opened: %s"), error.c_str()).c_str()); + } + // as the history of the changes has it ImGui::SeparatorText(STR_C("Surroundings")); if (begin_fields("##settingsplacement", 0.45f)) @@ -3415,6 +3435,8 @@ bool editor_mode::save() if (placed == 0) starter_trainset(trailing); auto const result = scene::Layers.save(rootstatements, trailing, statements); + // the project of the map after the scenery: the tracks of its lines as they were written + model_saved(result.success); if (result.success && controls) m_turntable_included = true; if (result.success && noses) diff --git a/application/editormode.h b/application/editormode.h index 24de86e8f..d93193ecf 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -50,6 +50,7 @@ http://mozilla.org/MPL/2.0/. #include "editor/editorGauge.hpp" #include "editor/editorClips.hpp" #include "editor/editorIcons.hpp" +#include "editor/layout/layoutCommands.hpp" #include "application/scriptedinput.h" #include "world/Sweep.h" @@ -74,6 +75,13 @@ class TAnimModel; struct editor_tool_button; class TTrack; +// the state of the editing through the model of the track geometry, editormodemodel.cpp +struct editor_model; +struct editor_model_deleter +{ + void operator()(editor_model *Model) const; +}; + class editor_mode : public application_mode, private editor_track::observer, private editor_services { @@ -3335,6 +3343,39 @@ class editor_mode : public application_mode, private editor_track::observer, pri selftest_result selftest_monkey(std::string const &command, std::istringstream &words); // the expectations of the script, which make the run fail (editormodeselftestexpect.cpp) selftest_result selftest_expect(std::string const &command, std::istringstream &words); + // the commands and the expectations of the editing through the model of the track geometry (editormodemodel.cpp) + selftest_result selftest_model(std::string const &command, std::istringstream &words); + + // the track geometry edited through the model (editor-tracks-domain.md §3, §4, §8, §9; stage E4, editormodemodel.cpp), with the + // setting "Editing on the model (trial)" on: the project of the map opened with the scenery and written with it, the tracks the + // generator wrote marked as the tracks of their lines and written as it made them while nothing else changes them. Off, nothing of it + // runs + struct managed_track + { + layout::line_id line{layout::line_id::none}; + std::size_t index{0}; // of the pieces of the line, from its start + std::string text; // its entry as written while it's as it was made: the generator's, or the file's it was read from + glm::dvec3 offset{0.0}; // of the placement the coordinates of the text are in + std::string baseline; // its own export as it was made: another one tells a change by the other tools + }; + // the project, the managed tracks (editormodemodel.cpp); made as it's needed + friend struct editor_model; + mutable std::unique_ptr m_model; + editor_model &model() const; + std::string model_error() const; + void model_forget(scene::basic_node const *Node); + // the setting is on and the project of the map is open + bool model_on() const; + // opens the project of the map once the scenery is there + void model_update(); + void model_open(); + // the managed track, nullptr for an old one + managed_track const *model_track(TTrack const *Track) const; + // the lines whose tracks were changed by the other tools since they were made + std::set model_seen_changed() const; + // the save: the text of a managed track as made, the project written after the scenery + std::optional model_path_text(TTrack const &Track, glm::dvec3 const &Offset); + void model_saved(bool const Success); selftest_result selftest_dispatch(std::string const &command, std::istringstream &words); void selftest_step(); // a value typed during a gesture, taken instead of the one the cursor gives diff --git a/application/editormodemodel.cpp b/application/editormodemodel.cpp new file mode 100644 index 000000000..af79b22ac --- /dev/null +++ b/application/editormodemodel.cpp @@ -0,0 +1,319 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.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 track geometry edited through the model (editor-tracks-domain.md §3, §4, §8, §9, §10; stage E4), with the setting "Editing on the +// model (trial)" on. The project of the map is opened with the scenery (made of its //$ lines the first time) and written with it; a line +// laid by the lay tool in the straights, or a line of the model the route design is applied to, goes through the commands of the model, +// its tracks made by the generator and marked as the line's; a refused command changes nothing and tells why, one kept is one step of the +// history; a line whose tracks were changed by hand is written over only when the user says so; a track the scenarios of the map name goes +// only when the user says so. The old tracks stay as they are, the old tools edit them. + +#include "stdafx.h" +#include "application/editormode.h" +#include "application/editormodeselftest.h" +#include "application/editormodeshared.h" +#include "application/editoruilayer.h" +#include "editor/editorFormat.hpp" +#include "editor/editorSettings.hpp" +#include "editor/project/projectGenerated.hpp" +#include "editor/project/projectSession.hpp" +#include "editor/project/sceneryText.hpp" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/translation.h" +#include "utilities/utilities.h" +#include "world/Track.h" +#include "application/scriptedinput.h" + +#include "imgui/imgui.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +std::string line_name(layout::line_id const Line) +{ + return format("L%u", layout::number(Line)); +} + +// the text of the track as the scenery save writes it: its own export +std::string export_of(TTrack const &Track) +{ + std::string text; + Track.export_as_text(text); + text.erase(text.find_last_not_of(" \t\r\n") + 1); + return text; +} + +// what the entry of the track has between its length and its path: the width, the friction, the sound distance, the quality, the damage, +// the environment and the visibility with the materials; empty where it isn't a plain track +// the setting as a self-test sets it for its run, not kept in the settings of the editor; else the one of the settings +std::optional &run_setting() +{ + static std::optional value; + return value; +} + +bool model_setting() +{ + return run_setting().value_or(EditorSettings.model_editing()); +} + +void expectation(bool const Passed, std::string const &What, std::string const &Got, std::string const &Wanted) +{ + ++editor_selftest::expectations(); + if (Passed) + { + WriteLog("SELFTEST PASS " + What); + return; + } + ++editor_selftest::failures(); + WriteLog("SELFTEST FAIL " + What + ": got " + Got + ", expected " + Wanted); +} + +} // namespace + +struct editor_model +{ + project::session session; + bool tried{false}; // the project opened for the scenery, or failed to + std::string error; + std::unordered_map tracks; + std::vector> written; // by the save under way, the texts written +}; + +void editor_model_deleter::operator()(editor_model *Model) const +{ + delete Model; +} + +editor_model &editor_mode::model() const +{ + if (m_model == nullptr) + m_model.reset(new editor_model); + return *m_model; +} + +std::string editor_mode::model_error() const +{ + return model().error; +} + +void editor_mode::model_forget(scene::basic_node const *Node) +{ + if (m_model != nullptr) + m_model->tracks.erase(Node); +} + +bool editor_mode::model_on() const +{ + return model_setting() && model().session.is_open(); +} + +void editor_mode::model_update() +{ + if (false == model_setting()) + return; + if (false == model().tried && Global.editor_session && false == scene::Layers.empty()) + model_open(); +} + +void editor_mode::model_open() +{ + model().tried = true; + model().error.clear(); + auto const map{scene::Layers.layer(scene::layer_handle{1}).name}; + std::filesystem::path const folder{paths::scenery}; + auto opened{model().session.open(folder, map)}; + if (false == opened.done) + { + model().error = opened.error; + ui()->set_status(format(STR_C("The project of the map can't be opened: %s. The tracks are edited the old way"), opened.error.c_str()), true); + WriteLog("Editor: the project of the map " + map + " can't be opened: " + opened.error, logtype::generic); + return; + } + WriteLog(format("Editor: the project of the map %s %s, %zu lines of the model", map.c_str(), opened.migrated ? "made of its //$ lines" : "read", model().session.network().lines().size()), logtype::generic); + for (auto const ¬e : opened.notes) + WriteLog("Editor: project: " + note, logtype::generic); + for (auto const &change : opened.hand_changes) + WriteLog(format("Editor: project: the track %s of line %s in %s %s outside the editor", change.name.c_str(), line_name(change.line).c_str(), change.file.c_str(), change.missing ? "is gone" : "was changed"), logtype::generic); + // the tracks the generator wrote, found in the scene by their names; written again as the files have them while nothing changes them + model().tracks.clear(); + std::map> files; + std::map counts; + for (auto const &node : model().session.project().generated) + { + if (node.kind != "track") + continue; + auto *track{simulation::Paths.find(node.name)}; + if (track == nullptr || track->m_editorremoved) + continue; + auto found{files.find(node.file)}; + if (found == files.end()) + { + std::ifstream stream{folder / node.file, std::ios::binary}; + found = files.emplace(node.file, stream.is_open() ? std::optional{std::string{std::istreambuf_iterator(stream), std::istreambuf_iterator()}} : std::nullopt).first; + } + managed_track entry; + entry.line = node.line; + entry.index = counts[node.line]++; + if (found->second.has_value()) + if (auto const text{scenery_text::node_text(*found->second, node.name)}) + entry.text = *text; + if (auto const *source{scene::Layers.source(track)}) + entry.offset = source->context.offset; + entry.baseline = export_of(*track); + model().tracks[track] = std::move(entry); + } + scene::Layers.path_writer = [this](TTrack const &Track, glm::dvec3 const &Offset) { return model_path_text(Track, Offset); }; + ui()->set_status(format(STR_C("Editing on the model: the project of the map is %s, %zu lines of the model"), project::path_of(map).generic_string().c_str(), model().session.network().lines().size())); +} + +editor_mode::managed_track const *editor_mode::model_track(TTrack const *Track) const +{ + if (Track == nullptr || false == model_on()) + return nullptr; + auto const found{model().tracks.find(Track)}; + if (found == model().tracks.end() || model().session.network().find(found->second.line) == nullptr) + return nullptr; + return &found->second; +} + +std::set editor_mode::model_seen_changed() const +{ + std::set result; + for (auto const &[node, entry] : model().tracks) + { + auto const *track{dynamic_cast(node)}; + if (track != nullptr && false == track->m_editorremoved && false == result.contains(entry.line) && export_of(*track) != entry.baseline) + result.insert(entry.line); + } + return result; +} + +std::optional editor_mode::model_path_text(TTrack const &Track, glm::dvec3 const &Offset) +{ + if (false == model_on() || Track.m_editorremoved) + return std::nullopt; + auto const found{model().tracks.find(&Track)}; + if (found == model().tracks.end() || found->second.text.empty()) + return std::nullopt; + auto const &entry{found->second}; + // changed by the other tools since it was made: its own export, a change by hand + if (export_of(Track) != entry.baseline) + return std::nullopt; + if (Offset != entry.offset) + { + WriteLog("Editor: model: the track " + Track.name() + " goes into a file of another placement, written by its own export", logtype::generic); + return std::nullopt; + } + model().written.emplace_back(&Track, entry.text); + return entry.text; +} + +void editor_mode::model_saved(bool const Success) +{ + if (false == model_on()) + { + model().written.clear(); + return; + } + if (false == Success) + { + model().written.clear(); + return; + } + // the tracks written, by their lines and the files they went into + std::map, std::vector> lines; + for (auto const &[track, text] : model().written) + { + auto const found{model().tracks.find(track)}; + auto const *source{scene::Layers.source(track)}; + if (found == model().tracks.end() || source == nullptr) + continue; + lines[{found->second.line, scene::Layers.layer(source->layer).name}].push_back({track->name(), text}); + } + model().written.clear(); + for (auto const &[key, pieces] : lines) + model().session.record_written(key.first, pieces, key.second); + for (auto const line : model_seen_changed()) + model().session.mark_hand_changed(line); + std::string error; + if (false == model().session.save(error)) + { + ui()->set_status(format(STR_C("The project of the map isn't saved: %s"), error.c_str()), true); + WriteLog("Editor: the project of the map isn't saved: " + error, logtype::generic); + return; + } + WriteLog(format("Editor: the project of the map saved, %zu lines, %zu tracks of them written now", model().session.network().lines().size(), [&] { + std::size_t count{0}; + for (auto const &entry : lines) + count += entry.second.size(); + return count; + }()), logtype::generic); +} + +editor_mode::selftest_result editor_mode::selftest_model(std::string const &command, std::istringstream &words) +{ + if (command == "modelediting") + { + int on{0}; + words >> on; + // for this run, not kept in the settings of the editor + run_setting() = on != 0; + if (on != 0 && false == model().tried && false == scene::Layers.empty()) + model_open(); + WriteLog(format("SELFTEST modelediting %d: the project %s, %zu lines", on, model().session.is_open() ? "open" : "not open", model().session.network().lines().size())); + return selftest_result::handled; + } + if (command != "expect") + return selftest_result::unhandled; + auto const start{words.tellg()}; + std::string what; + words >> what; + if (what == "modellines") + { + std::size_t count{0}; + words >> count; + auto const got{model().session.network().lines().size()}; + expectation(model_on() && got == count, "modellines", std::to_string(got) + (model_on() ? "" : " (no model)"), std::to_string(count)); + return selftest_result::handled; + } + if (what == "projectfile") + { + std::string wanted; + std::size_t lines{0}; + words >> wanted; + auto const file{project::path_of(std::filesystem::path{paths::scenery} / scene::Layers.layer(scene::layer_handle{1}).name)}; + auto const there{std::filesystem::exists(file)}; + if (wanted == "lines") + { + // the lines of the project as the file has them + words >> lines; + auto const read{project::load(file)}; + auto const got{read.project.has_value() ? read.project->network.lines().size() : std::size_t{0}}; + expectation(read.project.has_value() && got == lines, "projectfile lines", read.project.has_value() ? std::to_string(got) : read.error, std::to_string(lines)); + return selftest_result::handled; + } + expectation(there == (wanted == "present"), "projectfile " + file.generic_string(), there ? "present" : "absent", wanted); + return selftest_result::handled; + } + words.clear(); + words.seekg(start); + return selftest_result::unhandled; +} diff --git a/application/editormodeselftest.cpp b/application/editormodeselftest.cpp index 2ef5b5747..85eeb8df9 100644 --- a/application/editormodeselftest.cpp +++ b/application/editormodeselftest.cpp @@ -53,7 +53,7 @@ http://mozilla.org/MPL/2.0/. editor_mode::selftest_result editor_mode::selftest_dispatch(std::string const &command, std::istringstream &words) { - for (auto const group : {&editor_mode::selftest_scene, &editor_mode::selftest_sleepers, &editor_mode::selftest_sweep, &editor_mode::selftest_track, &editor_mode::selftest_switch, &editor_mode::selftest_rails, &editor_mode::selftest_join, &editor_mode::selftest_signal, &editor_mode::selftest_terrain, &editor_mode::selftest_props, &editor_mode::selftest_monkey, &editor_mode::selftest_expect}) + for (auto const group : {&editor_mode::selftest_scene, &editor_mode::selftest_sleepers, &editor_mode::selftest_sweep, &editor_mode::selftest_track, &editor_mode::selftest_switch, &editor_mode::selftest_rails, &editor_mode::selftest_join, &editor_mode::selftest_signal, &editor_mode::selftest_terrain, &editor_mode::selftest_props, &editor_mode::selftest_monkey, &editor_mode::selftest_model, &editor_mode::selftest_expect}) if (auto const result{(this->*group)(command, words)}; result != selftest_result::unhandled) return result; for (auto *tool : m_tools) diff --git a/editor/editorSettings.cpp b/editor/editorSettings.cpp index 742b9690f..380a0da36 100644 --- a/editor/editorSettings.cpp +++ b/editor/editorSettings.cpp @@ -145,6 +145,8 @@ bool editorSettings::load() parse(value, m_palette); else if (key == "first_steps") m_first_steps = (value == "1"); + else if (key == "model_editing") + m_model_editing = (value == "1"); else if (key == "terrain_offer") m_terrain_offer = (value == "1"); else if (key == "terrain_buried_ask") @@ -271,6 +273,7 @@ bool editorSettings::save() stream << "nodebank_card " << m_nodebank_card << "\n"; stream << "colours " << m_palette << "\n"; stream << "first_steps " << (m_first_steps ? 1 : 0) << "\n"; + stream << "model_editing " << (m_model_editing ? 1 : 0) << "\n"; stream << "terrain_offer " << (m_terrain_offer ? 1 : 0) << "\n"; stream << "terrain_buried_ask " << (m_terrain_buried_ask ? 1 : 0) << "\n"; stream << "track_tools_all " << (m_track_tools_more ? 1 : 0) << "\n"; diff --git a/editor/editorSettings.hpp b/editor/editorSettings.hpp index f0e1381c5..62720d534 100644 --- a/editor/editorSettings.hpp +++ b/editor/editorSettings.hpp @@ -78,6 +78,10 @@ public: // the tutorial (Help > Tutorial) opens by itself when an editor session starts bool first_steps() const { return m_first_steps; } void first_steps(bool Show) { m_first_steps = Show; } + // the tracks laid and edited through the model of the track geometry, its commands and the project file of the map (stage E4, + // a trial): off, the editor works as it did + bool model_editing() const { return m_model_editing; } + void model_editing(bool const On) { m_model_editing = On; } // a scenery begun with no terrain is offered the terrain model as the first track is laid bool terrain_offer() const { return m_terrain_offer; } void terrain_offer(bool Offer) { m_terrain_offer = Offer; } @@ -144,6 +148,7 @@ private: int m_nodebank_card{96}; int m_palette{0}; bool m_first_steps{true}; + bool m_model_editing{false}; bool m_terrain_offer{true}; bool m_terrain_buried_ask{true}; bool m_track_tools_more{false}; diff --git a/editor/project/projectSession.cpp b/editor/project/projectSession.cpp new file mode 100644 index 000000000..9973efe46 --- /dev/null +++ b/editor/project/projectSession.cpp @@ -0,0 +1,199 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "editor/project/projectSession.hpp" +#include "editor/project/projectGenerated.hpp" +#include "editor/project/projectMigration.hpp" + +#include +#include +#include + +namespace project +{ + +void differences(layout::network const &Before, layout::network const &After, std::set &Changed, std::set &Removed) +{ + for (auto const &[id, line] : After.lines()) + if (auto const *earlier{Before.find(id)}; earlier == nullptr || false == (*earlier == line)) + Changed.insert(id); + for (auto const &[id, line] : Before.lines()) + if (After.find(id) == nullptr) + Removed.insert(id); +} + +session::open_result session::open(std::filesystem::path const &Folder, std::string const &Map, norms::area_map const &Areas) +{ + close(); + open_result result; + auto opened{open_project(Folder, Map, Areas)}; + result.migrated = opened.migrated; + result.notes = std::move(opened.notes); + if (false == opened.project.project.has_value()) + { + result.error = opened.project.error; + return result; + } + result.notes.insert(result.notes.end(), opened.project.notes.begin(), opened.project.notes.end()); + m_project = std::move(*opened.project.project); + m_folder = Folder; + m_map = Map; + // the tracks written by the generator, as the files have them now: one changed or gone outside the editor marks its line + result.hand_changes = find_hand_changes(m_project, [&](std::string const &File) -> std::optional { + std::ifstream stream{m_folder / File, std::ios::binary}; + if (false == stream.is_open()) + return std::nullopt; + return std::string{std::istreambuf_iterator(stream), std::istreambuf_iterator()}; + }); + mark_hand_changes(m_project, result.hand_changes); + m_model = layout::model{m_project.network}; + m_open = true; + result.done = true; + return result; +} + +void session::close() +{ + m_open = false; + m_folder.clear(); + m_map.clear(); + m_project = {}; + m_model = {}; + m_done.clear(); + m_undone.clear(); +} + +std::filesystem::path session::file() const +{ + return path_of(m_folder / m_map); +} + +session::effect session::trial(layout::command const &Command, layout::edit_policy const Policy) const +{ + effect result; + layout::model copy{m_model.state()}; + result.outcome = copy.execute(Command, Policy); + if (result.outcome.done) + differences(m_model.state(), copy.state(), result.changed, result.removed); + return result; +} + +std::set session::hand_changed(effect const &Effect, std::set const &Seen) const +{ + std::set result; + for (auto const *lines : {&Effect.changed, &Effect.removed}) + for (auto const line : *lines) + if (false == may_overwrite(m_project, line) || Seen.contains(line)) + result.insert(line); + return result; +} + +session::applied session::execute(layout::command const &Command, std::set const &Overwrite, layout::edit_policy const Policy) +{ + applied result; + auto const before{m_model.state()}; + result.outcome = m_model.execute(Command, Policy); + if (false == result.outcome.done) + return result; + differences(before, m_model.state(), result.changed, result.removed); + step kept; + kept.token = ++m_last_token; + kept.hand_before = m_project.hand_changed; + for (auto const line : Overwrite) + m_project.hand_changed.erase(line); + kept.hand_after = m_project.hand_changed; + m_done.push_back(std::move(kept)); + // the model forgets the steps taken back once a command is kept: so do the tokens + m_undone.clear(); + result.token = m_last_token; + return result; +} + +bool session::undo(std::uint64_t const Token, effect *Effect) +{ + if (m_done.empty() || m_done.back().token != Token) + return false; + auto const before{m_model.state()}; + if (false == m_model.undo()) + return false; + auto taken{std::move(m_done.back())}; + m_done.pop_back(); + m_project.hand_changed = taken.hand_before; + if (Effect != nullptr) + { + *Effect = {}; + Effect->outcome.done = true; + differences(before, m_model.state(), Effect->changed, Effect->removed); + } + m_undone.push_back(std::move(taken)); + return true; +} + +bool session::redo(std::uint64_t const Token, effect *Effect) +{ + if (m_undone.empty() || m_undone.back().token != Token) + return false; + auto const before{m_model.state()}; + if (false == m_model.redo()) + return false; + auto taken{std::move(m_undone.back())}; + m_undone.pop_back(); + m_project.hand_changed = taken.hand_after; + if (Effect != nullptr) + { + *Effect = {}; + Effect->outcome.done = true; + differences(before, m_model.state(), Effect->changed, Effect->removed); + } + m_done.push_back(std::move(taken)); + return true; +} + +layout::generated_line session::generate(layout::line_id const Line) const +{ + return layout::generate(m_model.state(), Line, m_options); +} + +void session::record_written(layout::line_id const Line, std::vector const &Pieces, std::string const &File) +{ + layout::generated_line written; + written.line = Line; + for (auto const &piece : Pieces) + { + layout::generated_piece entry; + entry.name = piece.name; + entry.text = piece.text; + written.pieces.push_back(std::move(entry)); + } + record_generated(m_project, written, File); +} + +void session::mark_hand_changed(layout::line_id const Line) +{ + m_project.hand_changed.insert(Line); +} + +bool session::save(std::string &Error) +{ + if (false == m_open) + { + Error = "no project is open"; + return false; + } + auto const &now{m_model.state()}; + // the tracks of the lines gone went from the scenery with them + std::erase_if(m_project.generated, [&](generated_node const &Node) { return now.find(Node.line) == nullptr; }); + for (auto line{m_project.hand_changed.begin()}; line != m_project.hand_changed.end();) + line = now.find(*line) == nullptr ? m_project.hand_changed.erase(line) : std::next(line); + m_project.network = now; + return project::save(m_project, file(), Error); +} + +} // namespace project diff --git a/editor/project/projectSession.hpp b/editor/project/projectSession.hpp new file mode 100644 index 000000000..8ae277eab --- /dev/null +++ b/editor/project/projectSession.hpp @@ -0,0 +1,127 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "editor/layout/layoutCommands.hpp" +#include "editor/layout/layoutGenerator.hpp" +#include "editor/project/projectFile.hpp" +#include "editor/project/projectGenerated.hpp" + +#include +#include +#include +#include +#include +#include +#include + +// The project of the map open in the editor, edited through the commands of the model (editor-tracks-domain.md §3, §4, §9; stage E4): +// the project file read when the map is opened (made of its //$ lines the first time) and written with the scenery, the model of the +// track geometry its commands edit, and what the editor needs around them: which lines a command lays anew or takes away, so their tracks +// are made again or go; which lines were changed by hand, so they aren't written over unasked; the steps of the model's history, which +// the editor's history takes back and brings again by their tokens, one step of the editor a command. No scene: the editor puts the tracks +// the generator makes into its scene and tells which it wrote into which file. +namespace project +{ + +// the lines which differ between two states of the network: Changed, in the second one and not the same there (laid anew, or new), and +// Removed, gone from it +void differences(layout::network const &Before, layout::network const &After, std::set &Changed, std::set &Removed); + +class session +{ + public: + struct open_result + { + bool done{false}; + bool migrated{false}; // there was no project file: made of the //$ lines of the files of the map and written + std::string error; // why there's no project: a file of a newer schema, one which can't be read or written + std::vector notes; // of the migration, and the lines the file has which can't be laid as written + std::vector hand_changes; // the tracks of the generator changed in the files since they were written + }; + // the project of the map (relative to the folder of the sceneries): its file read, or made of the //$ lines of the map; the tracks the + // generator wrote compared with the files as they are now, the lines of the ones changed outside the editor marked as changed by hand + open_result open(std::filesystem::path const &Folder, std::string const &Map, norms::area_map const &Areas = {}); + void close(); + bool is_open() const { return m_open; } + std::filesystem::path const &folder() const { return m_folder; } + std::string const &map() const { return m_map; } + // .eu07proj next to the map + std::filesystem::path file() const; + + layout::network const &network() const { return m_model.state(); } + // the generated tracks, the lines changed by hand, the //$ lines kept; its network is the one at the last open or save, network() is now + document const &project() const { return m_project; } + + // what a command does + struct effect + { + layout::outcome outcome; + std::set changed; // laid anew or new: their tracks are made again + std::set removed; // gone: their tracks go + }; + // the command tried on a copy of the network, nothing of the session changed: refused with the reasons, or the lines it changes + effect trial(layout::command const &Command, layout::edit_policy const Policy = layout::edit_policy::refuse_block) const; + // the lines of the effect, changed or taken away, which may not be written over unasked: the ones the project marks as changed by hand + // (found so in the files) and the ones given (whose tracks the editor sees changed by other tools since they were made) + std::set hand_changed(effect const &Effect, std::set const &Seen = {}) const; + + struct applied : effect + { + std::uint64_t token{0}; // of the step of the history kept; 0 for a command refused + }; + // the command carried out: the lines of Overwrite may be written over, their marks of a change by hand taken off with it. A command + // kept is a step of the history, the marks with it; refused, nothing changes + applied execute(layout::command const &Command, std::set const &Overwrite = {}, layout::edit_policy const Policy = layout::edit_policy::refuse_block); + // the step of the token taken back, or brought again; only the latest one kept (undo) or taken back (redo) can be: false for another one, + // nothing changed. The lines it changes, as the effect of a command tells them + bool undo(std::uint64_t const Token, effect *Effect = nullptr); + bool redo(std::uint64_t const Token, effect *Effect = nullptr); + std::size_t undoable() const { return m_done.size(); } + std::size_t redoable() const { return m_undone.size(); } + + // the tracks of the line as the generator makes them now, named as the options name them + layout::generated_line generate(layout::line_id const Line) const; + layout::generator_options &options() { return m_options; } + layout::generator_options const &options() const { return m_options; } + + // a piece written into a scenery file: its name and the text written, the coordinates those of the file + struct written_piece + { + std::string name; + std::string text; + }; + // the tracks of the line written with the scenery into the file, as they were written: the project records them, by the checksums of + // their text, in the place of the ones it had of the line, and doesn't take the line for changed by hand any more + void record_written(layout::line_id const Line, std::vector const &Pieces, std::string const &File); + // the line's tracks were changed by other tools: so marked in the project, not written over unasked from now on + void mark_hand_changed(layout::line_id const Line); + // the project written next to the map, with the network as it is now and the records of the generated tracks of the lines gone taken out + bool save(std::string &Error); + + private: + struct step + { + std::uint64_t token{0}; + std::set hand_before; + std::set hand_after; + }; + bool m_open{false}; + std::filesystem::path m_folder; + std::string m_map; + document m_project; + layout::model m_model; + layout::generator_options m_options; + std::vector m_done; + std::vector m_undone; + std::uint64_t m_last_token{0}; +}; + +} // namespace project diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 348779bd6..5fc04864a 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -14861,3 +14861,21 @@ msgstr "Rozjazd %s wstawiony · Ctrl+Z cofa" msgid "Switch %s: drag it along its track to move it" msgstr "Rozjazd %s: przeciągnij go wzdłuż toru, aby przesunąć" + +msgid "Editing on the model (trial)" +msgstr "Edycja na modelu (wersja próbna)" + +msgid "A line laid in the straights, or applied by the route design, becomes a line of the model of the track geometry: its tracks are made by the model, its edits checked against the norms and refused with the reasons, the project of the map kept next to it.\nThe tracks there were stay as they are, edited the old way. Off, the editor works as it did" +msgstr "Linia ułożona prostymi albo zastosowana w projekcie trasy staje się linią modelu geometrii torów: jej tory tworzy model, jej zmiany są sprawdzane z normami i odrzucane z podaniem powodów, a projekt mapy leży obok niej.\nTory, które już były, zostają bez zmian i są edytowane po staremu. Wyłączone: edytor działa jak dotąd" + +msgid "The project of the map can't be opened: %s" +msgstr "Nie można otworzyć projektu mapy: %s" + +msgid "The project of the map can't be opened: %s. The tracks are edited the old way" +msgstr "Nie można otworzyć projektu mapy: %s. Tory są edytowane po staremu" + +msgid "Editing on the model: the project of the map is %s, %zu lines of the model" +msgstr "Edycja na modelu: projekt mapy to %s, linii modelu: %zu" + +msgid "The project of the map isn't saved: %s" +msgstr "Projekt mapy nie został zapisany: %s" diff --git a/scene/scenelayers.h b/scene/scenelayers.h index c2070e3ac..e547a9e30 100644 --- a/scene/scenelayers.h +++ b/scene/scenelayers.h @@ -12,10 +12,14 @@ http://mozilla.org/MPL/2.0/. #include "scene/scenenode.h" #include +#include #include #include +#include #include +class TTrack; + namespace scene { @@ -353,6 +357,17 @@ class node_layers // Rootstatements: additional statements to place at the end of the scenario file; Statements: the same for other layers save_result save(std::vector const &Rootstatements = {}, std::vector const &Trailingstatements = {}, std::map> const &Statements = {}); std::string check_sources() const; + // the text a track is saved with in place of its own export, for a track made of what the editor keeps elsewhere (the tracks of the + // lines of the track geometry, written as the generator made them): given the track and the offset of the place of the file it goes + // to, none for its own export + std::function(TTrack const &Track, glm::dvec3 const &Offset)> path_writer; + // where the node is defined: the file and the placement there, since the load or the last save; nullptr for a node made in the editor + // and not saved yet + node_source const *source(basic_node const *Node) const + { + auto const found{m_sources.find(Node)}; + return found != m_sources.end() ? &found->second : nullptr; + } private: // types diff --git a/scene/scenelayerssave.cpp b/scene/scenelayerssave.cpp index 7c0b84241..88110bfe8 100644 --- a/scene/scenelayerssave.cpp +++ b/scene/scenelayerssave.cpp @@ -965,7 +965,13 @@ save_result node_layers::save(std::vector const &Rootstatements, st } std::vector savedpaths; std::vector droppedpaths; - auto const path_text = [](TTrack &Path, glm::dvec3 const &Offset) { + auto const path_text = [this](TTrack &Path, glm::dvec3 const &Offset) { + if (path_writer) + if (auto own{path_writer(Path, Offset)}) + { + own->erase(own->find_last_not_of(" \t\r\n") + 1); + return std::move(*own); + } auto const paths{Path.m_paths}; for (auto &path : Path.m_paths) path.translate(-Offset); diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index a142cd396..ead870127 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -71,6 +71,8 @@ add_executable(${UNIT_TESTS_NAME} "${CMAKE_SOURCE_DIR}/editor/project/projectMigration.cpp" "${CMAKE_SOURCE_DIR}/editor/project/sceneryText.cpp" "${CMAKE_SOURCE_DIR}/editor/project/scenarioIndex.cpp" + # the project of the map open in the editor, its commands kept as steps of the editor's history (test_project_session.cpp) + "${CMAKE_SOURCE_DIR}/editor/project/projectSession.cpp" ${UNIT_TEST_CASES}) # the core library brings the game's build settings along diff --git a/tests/unit/test_project_session.cpp b/tests/unit/test_project_session.cpp new file mode 100644 index 000000000..30688cd8c --- /dev/null +++ b/tests/unit/test_project_session.cpp @@ -0,0 +1,245 @@ +// the project of the map open in the editor (editor/project/projectSession.cpp, editor-tracks-domain.md §4 "Edycja = polecenie", §9; E4): +// a map opened gets its project file; a command tried changes nothing, carried out tells the lines whose tracks go or are made again; +// each command kept a step the editor's history takes back and brings again by its token, the marks of the lines changed by hand with it; +// the tracks written with the scenery recorded, a track changed in the file afterwards marking its line, the line written over only when +// the author decides + +#include "stdafx.h" +#include "doctest.h" +#include "layout_fixture.h" +#include "scratch.h" +#include "editor/project/projectGenerated.hpp" +#include "editor/project/projectSession.hpp" + +#include +#include +#include + +namespace { + +using namespace test::layout_fixture; +using layout::line_id; + +std::string file_text(std::filesystem::path const &Path) { + std::ifstream file{Path, std::ios::binary}; + REQUIRE(file.is_open()); + return {std::istreambuf_iterator(file), std::istreambuf_iterator()}; +} + +// a straight of 400 m along z +layout::create_line straight(double const X) { + layout::create_line result; + result.start = {X, 10.0, 0.0}; + result.end = {X, 10.0, 400.0}; + result.category = line_class(); + return result; +} + +// the tracks of the line written into the map as the editor writes them: the generator's text +void write_tracks(project::session &Session, test::scratch_folder const &Folder, std::string const &Map, std::vector const &Lines) { + std::string text{"// a map of the tests of the project of the editor\n"}; + for (auto const line : Lines) { + auto const made{Session.generate(line)}; + REQUIRE(made.errors.empty()); + std::vector written; + for (auto const &piece : made.pieces) { + text += piece.text; + written.push_back({piece.name, piece.text}); + } + Session.record_written(line, written, Map); + } + Folder.write(Map, text); +} + +} // namespace + +TEST_CASE("project session: the map opened gets its project, a command tried changes nothing, carried out tells its lines") { + test::scratch_folder folder{"project_session_commands"}; + folder.write("mapa.scn", "// a new scenery\n"); + project::session session; + auto const opened{session.open(folder.root(), "mapa.scn")}; + REQUIRE(opened.done); + CHECK(opened.migrated); + CHECK(std::filesystem::exists(folder.root() / "mapa.eu07proj")); + CHECK(session.file() == folder.root() / "mapa.eu07proj"); + CHECK(session.network().lines().empty()); + + // a curve sharper than the norms let a line of 80 km/h have: refused with its reasons, tried or carried out, nothing changed + auto sharp{three_curves()}; + sharp.vertices[1].radius = 120.0; + auto const tried{session.trial(sharp)}; + CHECK_FALSE(tried.outcome.done); + CHECK_FALSE(tried.outcome.reasons.empty()); + auto const refused{session.execute(sharp)}; + CHECK_FALSE(refused.outcome.done); + CHECK(refused.token == 0); + CHECK(session.network().lines().empty()); + CHECK(session.undoable() == 0); + + // tried: what it'd make, the network as it was (the identifiers a refused command took aren't given again) + auto const trial{session.trial(three_curves())}; + REQUIRE(trial.outcome.done); + REQUIRE(trial.outcome.lines.size() == 1); + auto const id{trial.outcome.lines.front()}; + CHECK(trial.changed == std::set{id}); + CHECK(session.network().lines().empty()); + auto const laid{session.execute(three_curves())}; + REQUIRE(laid.outcome.done); + CHECK(laid.token != 0); + CHECK(laid.changed == std::set{id}); + CHECK(laid.removed.empty()); + + // split: the line laid again as it was is the same, the part after the node is new + auto const *line{session.network().find(id)}; + REQUIRE(line != nullptr); + auto const split{session.execute(layout::split_line{id, 0.5 * line->solved.length})}; + REQUIRE(split.outcome.done); + CHECK(split.changed.contains(id)); + CHECK(split.changed.size() == 2); + auto const second{*std::prev(split.changed.end())}; + // a curve of the second part made wider: that part alone + auto const *part{session.network().find(second)}; + REQUIRE(part != nullptr); + REQUIRE_FALSE(part->shape.vertices.empty()); + auto const vertex{part->shape.vertices.back()}; + auto const moved{session.execute(layout::set_vertex{second, vertex.id, vertex.radius + 100.0})}; + REQUIRE(moved.outcome.done); + CHECK(moved.changed == std::set{second}); + // deleted: gone, nothing laid anew + auto const deleted{session.execute(layout::delete_line{second})}; + REQUIRE(deleted.outcome.done); + CHECK(deleted.changed.empty()); + CHECK(deleted.removed == std::set{second}); + CHECK(session.undoable() == 4); +} + +TEST_CASE("project session: each command a step the editor takes back and brings again by its token, in the order of its history") { + test::scratch_folder folder{"project_session_undo"}; + folder.write("mapa.scn", "// a new scenery\n"); + project::session session; + REQUIRE(session.open(folder.root(), "mapa.scn").done); + auto const empty{session.network()}; + auto const first{session.execute(straight(0.0))}; + REQUIRE(first.outcome.done); + auto const one{session.network()}; + auto const second{session.execute(straight(50.0))}; + REQUIRE(second.outcome.done); + auto const two{session.network()}; + + // only the latest step is taken back, the one before it next; a token of another step changes nothing + CHECK_FALSE(session.undo(first.token)); + CHECK(session.network().same(two)); + project::session::effect effect; + REQUIRE(session.undo(second.token, &effect)); + CHECK(session.network().same(one)); + CHECK(effect.removed == std::set{line_id{2}}); + CHECK_FALSE(session.redo(first.token)); + REQUIRE(session.undo(first.token, &effect)); + CHECK(session.network().same(empty)); + CHECK(effect.removed == std::set{line_id{1}}); + // brought again in the order taken back, the last one taken back first + CHECK_FALSE(session.redo(second.token)); + REQUIRE(session.redo(first.token, &effect)); + CHECK(effect.changed == std::set{line_id{1}}); + CHECK(session.network().same(one)); + REQUIRE(session.redo(second.token)); + CHECK(session.network().same(two)); + + // a command kept after a step taken back: that step is gone, as the editor's redo of it is + REQUIRE(session.undo(second.token)); + auto const third{session.execute(straight(100.0))}; + REQUIRE(third.outcome.done); + CHECK_FALSE(session.redo(second.token)); + CHECK(session.redoable() == 0); + // identifiers are never handed out again: the new line isn't the one taken back + CHECK(third.changed == std::set{line_id{3}}); + // a refused command isn't a step + auto sharp{three_curves()}; + sharp.vertices[1].radius = 120.0; + CHECK(session.execute(sharp).token == 0); + CHECK(session.undoable() == 2); +} + +TEST_CASE("project session: the tracks written recorded, one changed in the file marks its line, written over only when the author decides") { + test::scratch_folder folder{"project_session_hand"}; + folder.write("mapa.scn", "// a new scenery\n"); + { + project::session session; + REQUIRE(session.open(folder.root(), "mapa.scn").done); + REQUIRE(session.execute(three_curves()).outcome.done); + REQUIRE(session.execute(straight(-100.0)).outcome.done); + write_tracks(session, folder, "mapa.scn", {line_id{1}, line_id{2}}); + std::string error; + REQUIRE(session.save(error)); + CHECK(session.project().generated.size() > 2); + } + auto const saved{file_text(folder.root() / "mapa.eu07proj")}; + project::session session; + { + // opened again: nothing changed in the file, the network the same to the bit + auto const opened{session.open(folder.root(), "mapa.scn")}; + REQUIRE(opened.done); + CHECK_FALSE(opened.migrated); + CHECK(opened.hand_changes.empty()); + CHECK(session.project().hand_changed.empty()); + layout::model laid{norms::area_map{}}; + REQUIRE(laid.execute(three_curves()).done); + CHECK(*session.network().find(line_id{1}) == *laid.state().find(line_id{1})); + // a vertex moved changes line 1 alone, which nobody changed by hand + auto const *line{session.network().find(line_id{1})}; + auto const &vertex{line->shape.vertices.front()}; + auto const effect{session.trial(layout::set_vertex{line_id{1}, vertex.id, 850.0})}; + REQUIRE(effect.outcome.done); + CHECK(session.hand_changed(effect).empty()); + // one the editor saw changed by other tools is + CHECK(session.hand_changed(effect, {line_id{1}}) == std::set{line_id{1}}); + } + + // the speed of a track of line 1 edited outside the editor + auto text{file_text(folder.root() / "mapa.scn")}; + auto const name{session.generate(line_id{1}).pieces.front().name}; + auto const at{text.find("velocity 80", text.find(name))}; + REQUIRE(at != std::string::npos); + text.replace(at, 11, "velocity 60"); + folder.write("mapa.scn", text); + auto const opened{session.open(folder.root(), "mapa.scn")}; + REQUIRE(opened.done); + REQUIRE(opened.hand_changes.size() == 1); + CHECK(opened.hand_changes.front().name == name); + CHECK(session.project().hand_changed == std::set{line_id{1}}); + auto const *line{session.network().find(line_id{1})}; + auto const vertex{line->shape.vertices.front()}; + layout::set_vertex const wider{line_id{1}, vertex.id, 850.0}; + auto const effect{session.trial(wider)}; + REQUIRE(effect.outcome.done); + CHECK(session.hand_changed(effect) == std::set{line_id{1}}); + // deleting it is writing over it too + CHECK(session.hand_changed(session.trial(layout::delete_line{line_id{1}})) == std::set{line_id{1}}); + // line 2 isn't + CHECK(session.hand_changed(session.trial(layout::delete_line{line_id{2}})).empty()); + + // written over: the mark goes with the step, and comes back with its undo + auto const done{session.execute(wider, {line_id{1}})}; + REQUIRE(done.outcome.done); + CHECK(session.project().hand_changed.empty()); + REQUIRE(session.undo(done.token)); + CHECK(session.project().hand_changed == std::set{line_id{1}}); + REQUIRE(session.redo(done.token)); + CHECK(session.project().hand_changed.empty()); + // written with the scenery: recorded again, the file the same as written, nothing changed by hand + write_tracks(session, folder, "mapa.scn", {line_id{1}, line_id{2}}); + std::string error; + REQUIRE(session.save(error)); + CHECK(file_text(folder.root() / "mapa.eu07proj") != saved); + REQUIRE(session.open(folder.root(), "mapa.scn").hand_changes.empty()); + CHECK(session.network().find(line_id{1})->shape.vertices.front().radius == 850.0); + + // a line deleted and saved: its tracks' records go with it, a mark of it too + session.mark_hand_changed(line_id{2}); + REQUIRE(session.execute(layout::delete_line{line_id{2}}, {line_id{2}}).outcome.done); + REQUIRE(session.save(error)); + for (auto const &node : session.project().generated) { + CHECK(node.line == line_id{1}); + } + CHECK(session.project().hand_changed.empty()); +}