diff --git a/application/editormode.cpp b/application/editormode.cpp index a0cddd9b3..a63604f60 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -562,6 +562,17 @@ editor_mode::editor_mode() { ui()->set_workspace_options(editor_ui::workspace::roads, [this]() { render_road_tool_options(); }, [this]() { render_road_selection(); }); ui()->set_workspace_options(editor_ui::workspace::terrain, [this]() { render_terrain_tool_options(); }); ui()->set_workspace_bank(editor_ui::workspace::terrain, [this]() { render_texture_browser(); }, STR("Textures")); + ui()->set_workspace_options(editor_ui::workspace::models, [this]() { ui()->model_panel().render_tools(); }, [this]() { ui()->model_panel().render_selection(); }); + ui()->set_workspace_bank(editor_ui::workspace::models, [this]() { ui()->model_panel().render_bank(); }, STR("Model")); + ui()->set_edit_model([this]() { choose_work_area(work_area::models); }); + ui()->model_panel().place_model = [this](std::string const &File) { place_model_file(File); }; + ui()->model_panel().place_vehicle = [this]() { + // the Trainset tool of the tracks: a click on a track, the vehicle picked, Place + choose_work_area(work_area::tracks); + show_track_tab(track_tab::lineside); + m_vehicle.tab().expand = true; + ui()->set_status(STR("Click a track, pick the vehicle and Place it; F7 goes back to the models")); + }; // a node picked in the scene window is selected as if clicked in the view; a double click flies the camera to it ui()->set_scene_select([this](scene::basic_node *Node, bool const Focus) { if (Focus) @@ -1733,7 +1744,13 @@ bool editor_mode::update() update_road_tool(); draw_road_overlay(); // the roads and the terrain are fields of work, their tools are drawn in the tool options window in place of the edit mode ones - ui()->set_workspace(m_terrain_open ? editor_ui::workspace::terrain : m_roadtool.window ? editor_ui::workspace::roads : editor_ui::workspace::none); + ui()->set_workspace([this]() { + if (m_models_open) + return editor_ui::workspace::models; + if (m_terrain_open) + return editor_ui::workspace::terrain; + return m_roadtool.window ? editor_ui::workspace::roads : editor_ui::workspace::none; + }()); steps.step("roads"); // --- array: the one made last is kept in line with its settings --- @@ -4811,6 +4828,8 @@ void editor_mode::render_open_scenery_popup() void editor_mode::terrain_workspace(bool const Open) { m_terrain_open = Open; + if (Open) + m_models_open = false; if (false == Open) m_terrain_tool = terrain_tool::none; else if (m_streamer.active()) @@ -5797,8 +5816,9 @@ void editor_mode::render_array() void editor_mode::choose_edit_mode(nodebank_panel::edit_mode const Mode) { - // an edit mode is the field of work instead of the tracks, roads or terrain + // an edit mode is the field of work instead of the tracks, roads, terrain or models m_track_window_open = false; + m_models_open = false; m_roadtool.window = false; terrain_workspace(false); if (Mode != nodebank_panel::MODIFY) @@ -5806,8 +5826,32 @@ void editor_mode::choose_edit_mode(nodebank_panel::edit_mode const Mode) ui()->set_mode(Mode); } +void editor_mode::place_model_file(std::string const &File) +{ + // on the ground some way ahead of the camera, as far as Insert would put it by a click there + auto const view{GfxRenderer->Camera_View_Matrix()}; + glm::dvec3 ahead{-view[0][2], 0.0, -view[2][2]}; + ahead = glm::length(ahead) > 1e-6 ? glm::normalize(ahead) : glm::dvec3{0.0, 0.0, 1.0}; + auto const where{placement_on_ground(Camera.Pos + ahead * 12.0)}; + auto *placed{simulation::State.create_model("node -1 0 none model 0 0 0 0 " + File + " none endmodel", "editor_", where)}; + if (placed == nullptr) + { + ui()->set_status(format(STR_C("The model %s couldn't be put in, the log says why"), File.c_str()), true); + return; + } + placed->m_name = "editor_" + placed->uuid.to_string(); + std::string as_text; + placed->export_as_text(as_text); + push_snapshot(placed, EditorSnapshot::Action::Add, as_text); + m_node = placed; + ui()->set_node(m_node); + ui()->set_status(format(STR_C("%s stands in the scenery; Whole model in the toolbar moves it"), File.c_str())); +} + editor_mode::work_area editor_mode::current_work_area() const { + if (m_models_open) + return work_area::models; // the terrain is shown over the tracks, see the tool options window if (m_terrain_open) return work_area::terrain; @@ -5836,6 +5880,7 @@ void editor_mode::choose_work_area(work_area const Area) break; case work_area::roads: m_track_window_open = false; + m_models_open = false; terrain_workspace(false); m_roadtool.window = true; break; @@ -5844,6 +5889,11 @@ void editor_mode::choose_work_area(work_area const Area) m_roadtool.window = false; terrain_workspace(true); break; + case work_area::models: + // a model of the scenery or a vehicle; a click on another model selects it, as in the surroundings + choose_edit_mode(nodebank_panel::MODIFY); + m_models_open = true; + break; } } @@ -5862,8 +5912,9 @@ void editor_mode::render_workspaces() {STR_C("Roads"), work_area::roads, editor_icons::icon::work_roads, STR_C("Roads and junctions, level crossings, the points where the traffic comes and goes")}, {STR_C("Terrain"), work_area::terrain, editor_icons::icon::work_terrain, STR_C("Heightmap terrain: chunks, sculpting, painting, water, orthophoto")}, {STR_C("Catenary"), work_area::catenary, editor_icons::icon::work_catenary, STR_C("The overhead catenary: poles with cantilevers, gantries, the wires of the chains")}, + {STR_C("Models"), work_area::models, editor_icons::icon::work_models, STR_C("The models of the vehicles and of the scenery: their lights, the parts of a vehicle, moving and turning their parts")}, }; - char const *const keys[] = {"F2", "F3", "F4", "F5", "F6"}; + char const *const keys[] = {"F2", "F3", "F4", "F5", "F6", "F7"}; auto const current{current_work_area()}; auto const &style{ImGui::GetStyle()}; auto *list{ImGui::GetWindowDrawList()}; @@ -7047,6 +7098,9 @@ void editor_mode::render_shortcuts_window() bool editor_mode::gizmo_shown() const { + // the models move their parts with a gizmo of their own, the model as a whole only when Whole model is chosen + if (m_models_open) + return ui()->model_panel().moves_whole(); return ui()->mode() == nodebank_panel::TRACK ? m_track_gizmo_on : m_gizmo_enabled; } @@ -7897,6 +7951,7 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in case GLFW_KEY_F4: choose_work_area(work_area::roads); break; case GLFW_KEY_F5: choose_work_area(work_area::terrain); break; case GLFW_KEY_F6: choose_work_area(work_area::catenary); break; + case GLFW_KEY_F7: choose_work_area(work_area::models); break; // the edit modes in the order of the toolbar; in the track mode the digits typed as a value were taken already case GLFW_KEY_1: handled = ui()->mode() != nodebank_panel::TRACK; if (handled) choose_edit_mode(nodebank_panel::MODIFY); break; case GLFW_KEY_2: handled = ui()->mode() != nodebank_panel::TRACK; if (handled) choose_edit_mode(nodebank_panel::ADD); break; @@ -7995,6 +8050,18 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in // shortcuts: undo/redo. not in the middle of a drag, it would go on from the state which was undone if (Global.ctrlState && (Key == GLFW_KEY_Z || Key == GLFW_KEY_Y) && is_press(Action) && (m_track_gizmo_using || m_track_set_using || m_straights.dragging || m_extend.active || m_switch.placing || m_point_drag.active || m_handle_drag.active || m_roadtool.lifting)) return; + // in the field of work of the models the changes of the model are taken back first, then those of the scenery (a model put in or + // moved as a whole); while the whole model is moved, those of the scenery + if (Global.ctrlState && (Key == GLFW_KEY_Z || Key == GLFW_KEY_Y) && is_press(Action) && m_models_open) + { + auto &panel{ui()->model_panel()}; + auto const whole{panel.moves_whole()}; + if (Key == GLFW_KEY_Z && (whole || false == panel.undo())) + undo_last(); + else if (Key == GLFW_KEY_Y && (whole || false == panel.redo())) + redo_last(); + return; + } if (Global.ctrlState && Key == GLFW_KEY_Z && is_press(Action)) { // in the catenary tool its own changes are taken back first @@ -8037,6 +8104,8 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in // the chunks of the terrain selected, where the terrain is the field of work; else what's selected in the scenery if (is_press(Action) && m_terrain_open && false == m_terrain_selection.empty()) remove_selected_chunks(); + else if (is_press(Action) && m_models_open) + ui()->model_panel().remove_selected(); // a light of the model; the scenery isn't changed there else if (is_press(Action)) delete_selected(); break; @@ -8368,6 +8437,10 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const // the press turned out to be meant for the UI, or for the gizmo or a mark of a light of the model window if (!viewport_click() || ui()->model_took_press()) return; + // in the field of work of the models a click picks a part of the model shown, or another model; anything else + // leaves the selection as it is + if (m_models_open && (ui()->model_panel().pick(node) || dynamic_cast(node) == nullptr)) + return; auto *const previous{m_node}; m_node = nullptr; diff --git a/application/editormode.h b/application/editormode.h index 73041034d..744fafe98 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -871,6 +871,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri // samples the selected model instance's geometry into the chunks of the terrain it covers, then removes it void capture_terrain(); bool m_terrain_open{false}; // the terrain is the field of work, chosen in the toolbar + bool m_models_open{false}; // the models are the field of work, chosen in the toolbar + void place_model_file(std::string const &File); // a model of the folder of the models put in the scenery and selected float m_terrain_spacing{2.0f}; // point spacing of the chunks made and of the spacing tool float m_terrain_baseheight{0.0f}; // height of chunks made where there's no ground int m_terrain_add_count{4}; // chunks along a side added around the camera @@ -1000,6 +1002,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri void render_viewport_overlays(); // the tools of the field of work, in the order of the toolbar void work_area_tools(std::vector &Buttons); + void model_tools(std::vector &Buttons); // the toolbar of the field of work of the models // the tools of the field of work in the toolbar, as icons with their names void render_toolbar_tools(); // what the row of the toolbar holds, written at its left end: the fields of work, the tools @@ -1213,7 +1216,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri tracks, roads, terrain, - catenary // the catenary tool of the tracks, as a field of work of its own + catenary, // the catenary tool of the tracks, as a field of work of its own + models // the EU07M models of the scenery and of the vehicles }; work_area current_work_area() const; void choose_work_area(work_area const Area); diff --git a/application/editormodeselftestscene.cpp b/application/editormodeselftestscene.cpp index 6763b1c27..70f79fa1b 100644 --- a/application/editormodeselftestscene.cpp +++ b/application/editormodeselftestscene.cpp @@ -368,6 +368,67 @@ editor_mode::selftest_result editor_mode::selftest_scene(std::string const &comm WriteLog(format("SELFTEST mapstate tiles on the ground %zu, at guessed heights %zu", grounded, guessed)); return selftest_result::handled; } + if (command == "modelmode") + { + // the field of work of the models + choose_work_area(work_area::models); + WriteLog("SELFTEST modelmode"); + return selftest_result::handled; + } + if (command == "modeltool") + { + // lights, parts, elements or animations + std::string name; + words >> name; + using model_tool = eu07m_model_panel::tool; + auto tool{model_tool::lights}; + if (name == "parts") + tool = model_tool::parts; + else if (name == "elements") + tool = model_tool::elements; + else if (name == "animations") + tool = model_tool::animations; + ui()->model_panel().choose_tool(tool); + WriteLog("SELFTEST modeltool " + name); + return selftest_result::handled; + } + if (command == "modelplace") + { + // a model of the folder of the models put in front of the camera + std::string file; + words >> file; + place_model_file(file); + WriteLog("SELFTEST modelplace " + file + (m_node != nullptr ? "" : ": not placed")); + return selftest_result::handled; + } + if (command == "modelimport") + { + auto const imported{ui()->model_panel().import_model()}; + WriteLog(std::string{"SELFTEST modelimport"} + (imported ? "" : ": not imported")); + return selftest_result::handled; + } + if (command == "modeladdlight") + { + // a light added in the middle of the part picked: spot or point + std::string kind; + words >> kind; + auto const added{ui()->model_panel().add_test_light(kind == "spot")}; + WriteLog("SELFTEST modeladdlight " + kind + (added ? "" : ": not added")); + return selftest_result::handled; + } + if (command == "modelundo" || command == "modelredo" || command == "modelremove") + { + auto &panel{ui()->model_panel()}; + auto done{false}; + if (command == "modelundo") + done = panel.undo(); + else if (command == "modelredo") + done = panel.redo(); + else + done = panel.remove_selected(); + WriteLog("SELFTEST " + command + (done ? "" : ": nothing done")); + return selftest_result::handled; + } if (command == "modelnode") { // a node picked in the window of the EU07M model shown diff --git a/application/editormodetrack.cpp b/application/editormodetrack.cpp index 8da1413b3..8bfdef532 100644 --- a/application/editormodetrack.cpp +++ b/application/editormodetrack.cpp @@ -507,6 +507,7 @@ void editor_mode::show_track_tab(track_tab const Wanted) { auto const Tab{Wanted == track_tab::straights || Wanted == track_tab::route ? plan_tab_for(selected_track()) : Wanted}; m_track_window_open = true; + m_models_open = false; m_roadtool.window = false; if (Tab == m_track_tab) return; diff --git a/application/editormodeviewport.cpp b/application/editormodeviewport.cpp index c0aa76bfc..5cfcc06ae 100644 --- a/application/editormodeviewport.cpp +++ b/application/editormodeviewport.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "editor/editorFormat.hpp" #include "editor/editorIcons.hpp" #include "editor/editorSettings.hpp" +#include "model/AnimModel.h" #include "rendering/renderer.h" #include "utilities/Globals.h" #include "utilities/translation.h" @@ -235,6 +236,9 @@ void editor_mode::work_area_tools(std::vector &Buttons) Buttons.push_back({icon::lanes, STR_C("Show lanes"), nullptr, STR_C("The lanes of the roads drawn as the paths the vehicles take"), tool.lanes, [&tool]() { tool.lanes = !tool.lanes; }, true}); break; } + case work_area::models: + model_tools(Buttons); + break; case work_area::terrain: { // what the left button does on the terrain @@ -287,6 +291,41 @@ void editor_mode::work_area_tools(std::vector &Buttons) } } +void editor_mode::model_tools(std::vector &Buttons) +{ + using model_tool = eu07m_model_panel::tool; + auto &panel{ui()->model_panel()}; + auto const add = [&Buttons, &panel](icon const Picture, char const *Label, char const *Tooltip, model_tool const Tool) { + Buttons.push_back({Picture, Label, nullptr, Tooltip, panel.current_tool() == Tool, [&panel, Tool]() { panel.choose_tool(Tool); }}); + }; + add(icon::light, STR_C("Lights"), STR_C("The light sources of the model: change them, add them by a click on the model"), model_tool::lights); + if (panel.has_vehicle()) + add(icon::pantograph, STR_C("Parts of the vehicle"), STR_C("Pantographs up or down, lamps lit or off, couplers and hoses connected or not"), model_tool::parts); + add(icon::parts_tree, STR_C("All parts"), STR_C("All the parts of the model as a tree, with a search by name"), model_tool::elements); + if (panel.has_animations()) + add(icon::animation, STR_C("Animations"), STR_C("The animations of the model, tried in the view"), model_tool::animations); + auto const turning{panel.turning()}; + // the gizmo of the editor follows them while it moves the whole model + Buttons.push_back({icon::translate, STR_C("Move"), nullptr, STR_C("The arrows in the view move the part picked"), false == turning, [this, &panel]() { + panel.set_turning(false); + m_gizmo_op = gizmo_operation::translate; + }, true}); + Buttons.push_back({icon::rotate, STR_C("Turn"), nullptr, STR_C("The rings in the view turn the part picked"), turning, [this, &panel]() { + panel.set_turning(true); + m_gizmo_op = gizmo_operation::rotate; + }}); + auto const whole{panel.moves_whole()}; + Buttons.push_back({icon::objects, STR_C("Whole model"), nullptr, STR_C("The gizmo moves or turns the whole model in the scenery, not its part; the change is one of the scenery, saved with it"), whole, + [this, &panel, whole]() { + panel.set_whole(false == whole); + m_gizmo_op = panel.turning() ? gizmo_operation::rotate : gizmo_operation::translate; + }}); + Buttons.back().enabled = (dynamic_cast(m_node) != nullptr); + auto const marks{panel.marks_shown()}; + Buttons.push_back({icon::select, STR_C("Marks of the lights"), nullptr, STR_C("The round marks of the light sources in the view; a click on one picks the light"), marks, + [&panel, marks]() { panel.show_marks(false == marks); }, true}); +} + void editor_mode::render_toolbar_caption(char const *Text) { // as wide in both rows, so the buttons of the rows start one under the other. the rows are drawn with no spacing of items @@ -449,7 +488,7 @@ void editor_mode::render_viewport_gizmo() // the gizmo moves the models and the tracks; on the terrain the mouse is the brush's // in the tracks the row stays with the gizmo hidden, so it can be brought out with a click auto const tracks{ui()->mode() == nodebank_panel::TRACK}; - if ((false == tracks && false == m_gizmo_enabled) || current_work_area() == work_area::terrain || (tracks && track_plan_tab())) + if ((false == tracks && false == m_gizmo_enabled) || current_work_area() == work_area::terrain || current_work_area() == work_area::models || (tracks && track_plan_tab())) return; auto const tooltip{STR_C("What the handles of the gizmo on the selection do when dragged; Ctrl held snaps the values")}; auto const on{gizmo_shown()}; diff --git a/application/editoruilayer.cpp b/application/editoruilayer.cpp index 4abaabc18..a1eb0746a 100644 --- a/application/editoruilayer.cpp +++ b/application/editoruilayer.cpp @@ -637,7 +637,7 @@ void editor_ui::render_() render_tool_options(); render_inspector(); render_scene(); - m_modelpanel.render(m_node); + m_modelpanel.update(m_node, m_workspace == workspace::models); // status bar: the outcome of the last operation, and the selected node if (ImGui::BeginViewportSideBar("##editorstatusbar", viewport, ImGuiDir_Down, ImGui::GetFrameHeight(), flags)) { @@ -732,7 +732,7 @@ void editor_ui::render_tool_options() return; ImGui::SetNextWindowSize(ImVec2S(400, 300), ImGuiCond_FirstUseEver); auto const current{mode()}; - auto const active{m_workspace == workspace::terrain || (m_workspace == workspace::roads && current != nodebank_panel::TRACK) ? m_workspace : workspace::none}; + auto const active{m_workspace == workspace::terrain || m_workspace == workspace::models || (m_workspace == workspace::roads && current != nodebank_panel::TRACK) ? m_workspace : workspace::none}; // a change of the mode brings the window forward, in case it shares its dock with another one auto const shown{active != workspace::none ? 100 + static_cast(active) : static_cast(current)}; if (shown != m_toolmode) @@ -767,6 +767,8 @@ void editor_ui::render_tool_options() name = STR_C("Roads"); else if (active == workspace::terrain) name = STR_C("Terrain"); + else if (active == workspace::models) + name = STR_C("Models"); ImGui::SeparatorText(name); if (active != workspace::none) { @@ -781,7 +783,8 @@ void editor_ui::render_tool_options() } else render_mode_options(current); - if (ImGui::CollapsingHeader(STR_C("Gizmo"))) + // the models have a gizmo of their own, over the part picked + if (active != workspace::models && ImGui::CollapsingHeader(STR_C("Gizmo"))) { if (m_gizmooptions) m_gizmooptions(); @@ -811,6 +814,8 @@ void editor_ui::render_inspector() ImGui::End(); return; } + if (m_editmodel && m_modelpanel.editable(m_node) && ImGui::Button(STR_C("Edit this model (F7)"))) + m_editmodel(); if (ImGui::CollapsingHeader(STR_C("Node properties"), ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::Indent(); diff --git a/application/editoruilayer.h b/application/editoruilayer.h index 2f408c60a..fcf0f2a94 100644 --- a/application/editoruilayer.h +++ b/application/editoruilayer.h @@ -122,6 +122,10 @@ class editor_ui : public ui_layer // the last press in the 3d view went to that gizmo or to a mark of a light of the model, not to picking a node bool model_took_press() const { return m_modelpanel.took_press(); } bool select_model_node(std::string_view Name) { return m_modelpanel.select_node(Name); } + // the field of work of the models: the model shown and edited there + eu07m_model_panel &model_panel() { return m_modelpanel; } + // the inspector offers to edit the model selected in the field of work of the models + void set_edit_model(std::function Edit) { m_editmodel = std::move(Edit); } // draws the base layers under the scenery at the bottom of the layers window (they live in the editor mode) void set_base_layers(std::function Renderer) { m_layerspanel.base_layers = std::move(Renderer); } void show_layers() @@ -151,6 +155,7 @@ class editor_ui : public ui_layer none, roads, terrain, + models, count_ }; void set_workspace(workspace const Workspace) @@ -275,7 +280,8 @@ class editor_ui : public ui_layer std::function m_bendoptions; bool m_bendexpand{false}; scene::basic_node *m_node{nullptr}; // currently bound scene node, if any - eu07m_model_panel m_modelpanel; // the EU07M model of the selected instance, its components + eu07m_model_panel m_modelpanel; // the EU07M model of the selected instance or of a vehicle, in the field of work of the models + std::function m_editmodel; bool m_track{false}; // windows of an unpinned dock, and the edge they're hidden at struct autohide_group diff --git a/application/editoruimodel.cpp b/application/editoruimodel.cpp index 4e172c363..06368faa0 100644 --- a/application/editoruimodel.cpp +++ b/application/editoruimodel.cpp @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "model/AnimModel.h" #include "model/Model3d.h" #include "model/eu07m/eu07m_build.h" +#include "model/eu07m/eu07m_convert.h" #include "model/eu07m/eu07m_dump.h" #include "model/eu07m/eu07m_io.h" #include "model/eu07m/eu07m_store.h" @@ -32,11 +33,14 @@ http://mozilla.org/MPL/2.0/. #include #include +#include #include #include #include #include #include +#include +#include #include #include @@ -55,9 +59,6 @@ constexpr double node_focus_radius{1.0}; // (0x8000) and the passes it is drawn in (0xB0) constexpr std::uint32_t light_node_flags{0x80B0}; -// the width of the fields beside their labels, in heights of the font -constexpr float field_width{11.f}; - // the room left for the labels beside the fields of the properties, in heights of the font constexpr float label_width{13.f}; @@ -201,59 +202,6 @@ template bool edit_enum(char const *Label, Enum_ &Value, std::i return true; } -// how the editor holds a part of the vehicle: as the vehicle has it, or in one of the states of its submodels -void render_part_hold(TDynamicObject &Vehicle, std::size_t const Part) -{ - auto const *name{TDynamicObject::held_part_name(Part)}; - auto hold{Vehicle.held_part(Part)}; - auto const label{std::format("{}##part{}", part_text(name), Part)}; - ImGui::SetNextItemWidth(ImGui::GetFontSize() * field_width); - auto const changed{is_lamp(name) ? edit_enum(label.c_str(), hold, {STR_C("Automatic"), STR_C("Lamp off"), STR_C("Lamp on"), STR_C("Lamp dimmed")}) - : edit_enum(label.c_str(), hold, {STR_C("Automatic"), STR_C("Disconnected"), STR_C("Connected"), STR_C("Other position")})}; - if (ImGui::IsItemHovered()) - { - ImGui::SetTooltip("%s_off / %s_on / %s_xon", name, name, name); - } - if (changed) - { - Vehicle.hold_part(Part, hold); - } -} - -void render_pantograph_hold(TDynamicObject &Vehicle, int const Pantograph) -{ - auto hold{Vehicle.held_pantograph(Pantograph)}; - auto const number{Pantograph + 1}; - auto const label{std::vformat(STR("Pantograph {}"), std::make_format_args(number))}; - ImGui::SetNextItemWidth(ImGui::GetFontSize() * field_width); - if (edit_enum(label.c_str(), hold, {STR_C("Automatic"), STR_C("Pantograph down"), STR_C("Pantograph up")})) - { - Vehicle.hold_pantograph(Pantograph, hold); - } -} - -// the parts of the vehicle the model has, of those Pick takes -template void render_hold_group(TDynamicObject &Vehicle, char const *Title, Pick_ &&Pick) -{ - std::vector parts; - for (std::size_t idx = 0; idx < TDynamicObject::held_part_total; ++idx) - { - if (Vehicle.held_part_present(idx) && Pick(std::string_view{TDynamicObject::held_part_name(idx)})) - { - parts.push_back(idx); - } - } - if (parts.empty()) - { - return; - } - ImGui::SeparatorText(Title); - for (auto const part : parts) - { - render_part_hold(Vehicle, part); - } -} - bool edit_flag(char const *Label, std::uint8_t &Flags, std::uint8_t const Bit) { auto set{(Flags & Bit) != 0}; @@ -626,25 +574,380 @@ constexpr float mark_radius{7.f}; } // namespace +namespace +{ + +using part_hold = TDynamicObject::part_hold; +using pantograph_hold = TDynamicObject::pantograph_hold; + +// the buttons of a lamp, a coupler or a hose, and of a pantograph, in the order of these holds +constexpr std::array part_holds{part_hold::on, part_hold::off, part_hold::xon, part_hold::none}; +constexpr std::array pantograph_holds{pantograph_hold::up, pantograph_hold::down, pantograph_hold::none}; + +// the most changes taken back +constexpr std::size_t undo_depth{50}; + +// how far from the box of the geometry of a part a click still picks it, metres +constexpr double pick_margin{0.03}; + +// the radius of the sphere the camera frames around a vehicle, in its lengths +constexpr double vehicle_focus{0.6}; + +struct colour_preset +{ + char const *name; + std::array colour; +}; + +// the colours a light is often given +constexpr std::array colour_presets{{{"Warm white", {1.f, 0.85f, 0.6f}}, + {"White", {1.f, 1.f, 1.f}}, + {"Cold white", {0.8f, 0.9f, 1.f}}, + {"Red", {1.f, 0.08f, 0.04f}}, + {"Yellow", {1.f, 0.75f, 0.1f}}, + {"Green", {0.1f, 1.f, 0.3f}}, + {"Blue", {0.2f, 0.45f, 1.f}}}}; + +// a row of buttons of which one is chosen, as a switch of a few positions; the position clicked, none when none was +std::optional choice_buttons(char const *Id, std::size_t const Chosen, std::span const Labels) +{ + std::optional clicked; + ImGui::PushID(Id); + for (std::size_t idx = 0; idx < Labels.size(); ++idx) + { + if (idx > 0) + { + ImGui::SameLine(0.f, ImGui::GetStyle().ItemInnerSpacing.x); + } + auto const chosen{idx == Chosen}; + if (chosen) + { + ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyleColorVec4(ImGuiCol_HeaderActive)); + } + if (ImGui::Button(Labels[idx])) + { + clicked = idx; + } + if (chosen) + { + ImGui::PopStyleColor(); + } + } + ImGui::PopID(); + return clicked; +} + +template std::size_t position_of(std::array const &Values, Value_ const Value) +{ + return static_cast(std::ranges::find(Values, Value) - Values.begin()); +} + +// the name of a part in the first column of a table, the tooltip on it +void part_cell(char const *Text, char const *Tooltip) +{ + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::AlignTextToFramePadding(); + ImGui::TextUnformatted(Text); + if ((Tooltip != nullptr) && ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", Tooltip); + } + ImGui::TableNextColumn(); +} + +// a row of a table: how the editor holds a part of the vehicle +void part_hold_row(TDynamicObject &Vehicle, std::size_t const Part) +{ + auto const *name{TDynamicObject::held_part_name(Part)}; + auto const variants{std::format("{0}_on / {0}_off / {0}_xon", name)}; + part_cell(part_text(name), variants.c_str()); + std::array const lamp{STR_C("Lit"), STR_C("Off"), STR_C("Dimmed"), STR_C("As the vehicle has it")}; + std::array const coupler{STR_C("Connected"), STR_C("Disconnected"), STR_C("Other position"), STR_C("As the vehicle has it")}; + if (auto const clicked{choice_buttons(name, position_of(part_holds, Vehicle.held_part(Part)), is_lamp(name) ? lamp : coupler)}) + { + Vehicle.hold_part(Part, part_holds[*clicked]); + } +} + +// a row of a table: how the editor holds a pantograph +void pantograph_hold_row(TDynamicObject &Vehicle, int const Pantograph) +{ + auto const number{Pantograph + 1}; + auto const label{std::vformat(STR("Pantograph {}"), std::make_format_args(number))}; + part_cell(label.c_str(), nullptr); + std::array const labels{STR_C("Up"), STR_C("Down"), STR_C("As the vehicle has it")}; + if (auto const clicked{choice_buttons(label.c_str(), position_of(pantograph_holds, Vehicle.held_pantograph(Pantograph)), labels)}) + { + Vehicle.hold_pantograph(Pantograph, pantograph_holds[*clicked]); + } +} + +// the parts of the vehicle Pick takes, those the model has, in a table under the title, with buttons to hold them all at once +template void part_group(TDynamicObject &Vehicle, char const *Title, bool const Lamps, Pick_ const &Pick) +{ + std::vector parts; + for (std::size_t idx = 0; idx < TDynamicObject::held_part_total; ++idx) + { + if (Vehicle.held_part_present(idx) && Pick(std::string_view{TDynamicObject::held_part_name(idx)})) + { + parts.push_back(idx); + } + } + if (parts.empty()) + { + return; + } + ImGui::SeparatorText(Title); + ImGui::PushID(Title); + auto const all = [&Vehicle, &parts](part_hold const Hold) { + for (auto const part : parts) + { + Vehicle.hold_part(part, Hold); + } + }; + if (ImGui::SmallButton(Lamps ? STR_C("Light them all") : STR_C("Connect them all"))) + { + all(part_hold::on); + } + ImGui::SameLine(); + if (ImGui::SmallButton(Lamps ? STR_C("Put them all out") : STR_C("Disconnect them all"))) + { + all(part_hold::off); + } + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("All as the vehicle has them"))) + { + all(part_hold::none); + } + if (ImGui::BeginTable("##parts", 2, ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg)) + { + for (auto const part : parts) + { + part_hold_row(Vehicle, part); + } + ImGui::EndTable(); + } + ImGui::PopID(); +} + +// the vehicle is still in the simulation +bool vehicle_exists(TDynamicObject const *Vehicle) +{ + return std::ranges::find(simulation::Vehicles.sequence(), Vehicle) != simulation::Vehicles.sequence().end(); +} + +// the scenery model is still in the scenery +bool instance_exists(TAnimModel const *Instance) +{ + return std::ranges::find(simulation::Instances.sequence(), Instance) != simulation::Instances.sequence().end(); +} + +// the place of the node, its range and its flags as another record has them +bool same_place(eu07m::node_record const &Left, eu07m::node_record const &Right) +{ + return (Left.translation == Right.translation) && (Left.rotation == Right.rotation) && (Left.scale == Right.scale) && (Left.flags == Right.flags) && + (Left.range_min_sq == Right.range_min_sq) && (Left.range_max_sq == Right.range_max_sq); +} + +// the point lies in the box, or within the margin of it +bool inside(std::pair const &Box, glm::dvec3 const &Point, double const Margin) +{ + auto const low{glm::dvec3{Box.first} - Margin}; + auto const high{glm::dvec3{Box.second} + Margin}; + return (Point.x >= low.x) && (Point.y >= low.y) && (Point.z >= low.z) && (Point.x <= high.x) && (Point.y <= high.y) && (Point.z <= high.z); +} + +// the turn which brings -z, the axis of a spot, onto the direction +glm::quat aim(glm::vec3 const &Direction) +{ + glm::vec3 const axis{0.f, 0.f, -1.f}; + auto const cosine{glm::dot(axis, Direction)}; + if (cosine < -0.9999f) + { + // the other way round: half a turn about y + return glm::quat{0.f, 0.f, 1.f, 0.f}; + } + auto const cross{glm::cross(axis, Direction)}; + return glm::normalize(glm::quat{1.f + cosine, cross.x, cross.y, cross.z}); +} + +// a text with no case, to look for another in it +std::string lowered(std::string_view const Text) +{ + std::string result{Text}; + std::ranges::transform(result, result.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return result; +} + +// the half angle of a cone in degrees, from its cosine +float cone_degrees(float const Cosine) +{ + return glm::degrees(std::acos(std::clamp(Cosine, -1.f, 1.f))); +} + +// the width of the beam of a spot and its bright middle, in degrees from its axis +bool edit_beam(payload::light &Light) +{ + auto changes{false}; + auto width{cone_degrees(Light.cos_falloff)}; + auto middle{std::min(cone_degrees(Light.cos_hotspot), width)}; + if (ImGui::SliderFloat(STR_C("Width of the beam, degrees"), &width, 1.f, 89.f, "%.0f")) + { + Light.cos_falloff = std::cos(glm::radians(width)); + Light.cos_hotspot = std::cos(glm::radians(std::min(middle, width))); + changes = true; + } + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("From the axis of the beam to its edge")); + } + if (ImGui::SliderFloat(STR_C("Bright middle, degrees"), &middle, 0.f, width, "%.0f")) + { + Light.cos_hotspot = std::cos(glm::radians(middle)); + changes = true; + } + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("The middle of the beam lit fully; from there to the edge it fades")); + } + return changes; +} + +} // namespace + +void eu07m_model_panel::update(scene::basic_node *Selected, bool const Active) +{ + m_gizmoshown = false; + m_active = Active; + if ((m_pickedvehicle != nullptr) && (false == vehicle_exists(m_pickedvehicle))) + { + m_pickedvehicle = nullptr; + } + if ((m_target.vehicle != nullptr) && (false == vehicle_exists(m_target.vehicle))) + { + open(target{}); + } + // the time stands still in the editor: the held pantographs are moved here + if (m_target.vehicle != nullptr) + { + m_target.vehicle->step_held_pantographs(ImGui::GetIO().DeltaTime); + } + if (false == Active) + { + m_placing.reset(); + m_tookpress = false; + return; + } + if ((m_target.instance != nullptr) && (false == instance_exists(m_target.instance))) + { + open(target{}); + } + if (Selected != m_lastselected) + { + // a scenery model clicked is edited in place of the vehicle picked + m_lastselected = Selected; + if (dynamic_cast(Selected) != nullptr) + { + m_pickedvehicle = nullptr; + } + } + auto const next{wanted(Selected)}; + if (next == m_target) + { + m_kept.reset(); + } + else if (false == m_dirty) + { + open(next); + } + else if ((false == m_kept.has_value()) || (*m_kept != next)) + { + m_pending = next; + } + render_unsaved_popup(); + if (m_placing && ImGui::IsKeyPressed(ImGuiKey_Escape, false)) + { + m_placing.reset(); + } + if ((m_source == nullptr) || m_path.empty()) + { + return; + } + // the model as it is between the presses and the drags: a change made by the next one takes it back to this + if ((false == ImGui::IsAnyItemActive()) && (false == ImGuizmo::IsUsing())) + { + m_before = take(false); + m_changing = false; + } + render_view(); +} + +eu07m_model_panel::target eu07m_model_panel::wanted(scene::basic_node *Selected) const +{ + target result; + if (m_pickedvehicle != nullptr) + { + result.vehicle = m_pickedvehicle; + } + else if (auto *instance{dynamic_cast(Selected)}; instance != nullptr) + { + result.instance = instance; + return result; + } + else if (simulation::Train != nullptr) + { + result.vehicle = simulation::Train->Dynamic(); + } + // the cab isn't loaded while the driver is outside + if ((result.vehicle != nullptr) && (m_part == 1) && (result.vehicle->mdKabina != nullptr)) + { + result.part = 1; + } + return result; +} + +void eu07m_model_panel::open(target const &Target) +{ + m_target = Target; + m_pending.reset(); + m_kept.reset(); + m_undo.clear(); + m_redo.clear(); + m_placing.reset(); + m_source = nullptr; + m_path.clear(); + m_problem.clear(); + m_importable = false; + m_model = eu07m::model{}; + m_submodels.clear(); + m_boxes.clear(); + m_selected = -1; + m_dirty = false; + m_message.clear(); + auto *source{Target.instance != nullptr ? Target.instance->pModel : vehicle_model(Target.vehicle, Target.part)}; + if (source != nullptr) + { + load(*source); + } +} + bool eu07m_model_panel::load(TModel3d &Model) { m_source = &Model; - m_tofront = true; - m_path.clear(); - m_model = eu07m::model{}; - m_submodels.clear(); - m_selected = -1; - m_box.reset(); - m_dirty = false; - m_message.clear(); - m_open = true; if (false == Global.modelformat_eu07m) { + m_problem = STR("The models of the EU07M format are turned off (modelformat in eu07.ini)"); return false; } auto const path{FileCased(Model.NameGet() + ".eu07m")}; if (path.empty()) { + // one is made of the model as the game loaded it: for a vehicle, its body or its cab, that is what the game writes to the + // .e3d it makes of a .t3d (convertmodels) + m_importable = (false == FileCased(Model.NameGet() + ".e3d").empty()) || (false == FileCased(Model.NameGet() + ".t3d").empty()); + m_problem = m_importable ? STR("This model has no EU07M file yet. Import it to change its lights and parts.") + : STR("This model has no EU07M file, so it can't be edited here. The command eu07 -eu07m convert makes one of its E3D or T3D file"); return false; } std::ifstream file{path, std::ios::binary | std::ios::ate}; @@ -655,7 +958,7 @@ bool eu07m_model_panel::load(TModel3d &Model) options.blocks = eu07m::store_source(eu07m::family_store(path)); if (auto const result{eu07m::read(data, m_model, options)}; false == result.ok) { - m_message = result.error; + m_problem = std::vformat(STR("The EU07M file of the model can't be read: {}"), std::make_format_args(result.error)); return false; } m_path = path; @@ -665,131 +968,325 @@ bool eu07m_model_panel::load(TModel3d &Model) { m_submodels.clear(); } + for (std::uint32_t idx = 0; idx < m_model.nodes.size(); ++idx) + { + m_boxes.push_back(node_box(m_model, idx)); + } m_cliptimes.assign(m_model.clips.size(), 0.f); m_channels.clear(); for (auto const &channel : Model.channels()) { m_channels.push_back(channel.initial); } + m_before = take(false); return true; } -void eu07m_model_panel::render(scene::basic_node *Node) +void eu07m_model_panel::render_unsaved_popup() { - m_gizmoshown = false; - // a scenery model selected, or with nothing selected, the vehicle driven - auto *instance{dynamic_cast(Node)}; - auto *vehicle{(Node == nullptr) && (simulation::Train != nullptr) ? simulation::Train->Dynamic() : nullptr}; - auto *source{instance != nullptr ? instance->pModel : vehicle_model(vehicle, m_vehiclepart)}; - if ((source == nullptr) && (vehicle != nullptr) && (m_vehiclepart != 0)) + auto const title{std::string{STR_C("Changes not saved")} + "###eu07munsaved"}; + if (m_pending && (false == ImGui::IsPopupOpen(title.c_str()))) { - // the cab isn't loaded while the driver is outside - m_vehiclepart = 0; - source = vehicle_model(vehicle, 0); + ImGui::OpenPopup(title.c_str()); } - if (source == nullptr) - { - m_source = nullptr; - m_instance = nullptr; - m_vehicle = nullptr; - return; - } - if ((source != m_source) || (instance != m_instance) || (vehicle != m_vehicle)) - { - m_instance = instance; - m_vehicle = vehicle; - load(*source); - } - // the time stands still in the editor: the held pantographs are moved here - if (vehicle != nullptr) - { - vehicle->step_held_pantographs(ImGui::GetIO().DeltaTime); - } - if (m_path.empty() || (false == m_open)) + if (false == ImGui::BeginPopupModal(title.c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize)) { return; } - // beside the inspector, over the right of the view, and opaque: the settings of the interface may make the windows see-through - auto const *viewport{ImGui::GetMainViewport()}; - ImGui::SetNextWindowPos(ImVec2(viewport->WorkPos.x + viewport->WorkSize.x - 1100.f, viewport->WorkPos.y + 100.f), ImGuiCond_FirstUseEver); - ImGui::SetNextWindowSize(ImVec2(760, 680), ImGuiCond_FirstUseEver); - ImGui::SetNextWindowBgAlpha(0.97f); - if (std::exchange(m_tofront, false)) + auto const name{std::filesystem::path{m_path}.filename().string()}; + ImGui::TextUnformatted(std::vformat(STR("The model {} has changes which aren't saved."), std::make_format_args(name)).c_str()); + if (ImGui::Button(STR_C("Save them"))) { - // docked, it may be a tab behind the inspector - ImGui::SetNextWindowFocus(); - } - if (ImGui::Begin((std::string(STR_C("EU07M model")) + "###eu07mmodel").c_str(), &m_open, ImGuiWindowFlags_NoFocusOnAppearing)) - { - render_header(); - if (ImGui::BeginTabBar("##eu07mtabs")) + save(); + if (m_pending && (false == m_dirty)) { - if (ImGui::BeginTabItem(STR_C("Model"))) + open(*m_pending); + } + else + { + // not saved: the message says why, the model stays + m_kept = m_pending; + m_pending.reset(); + } + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button(STR_C("Throw them away"))) + { + // the model the game has is taken back to the file too + while (undo()) + { + // down to the model as the file has it + } + if (m_pending) + { + open(*m_pending); + } + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button(STR_C("Go on with this one"))) + { + m_kept = m_pending; + m_pending.reset(); + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); +} + +void eu07m_model_panel::render_bank() +{ + ImGui::SeparatorText(STR_C("Edited model")); + if (m_source == nullptr) + { + ImGui::TextWrapped("%s", STR_C("Nothing picked yet.")); + } + else + { + auto const name{m_target.vehicle != nullptr ? m_target.vehicle->name() : m_target.instance->name()}; + ImGui::TextUnformatted(name.empty() ? STR_C("(no name)") : name.c_str()); + if (m_target.vehicle != nullptr) + { + ImGui::BeginDisabled(m_target.vehicle->mdKabina == nullptr); + std::array const parts{STR_C("Body"), STR_C("Cab")}; + if (auto const clicked{choice_buttons("##part", static_cast(m_target.part), parts)}) { - render_model_tab(); - ImGui::EndTabItem(); + // the other part is shown in the next frame + m_part = static_cast(*clicked); } - if ((m_vehicle != nullptr) && (m_vehiclepart == 0) && ImGui::BeginTabItem(STR_C("Parts of the vehicle"))) - { - render_parts_tab(); - ImGui::EndTabItem(); - } - if ((instance != nullptr) && ((false == m_model.clips.empty()) || (false == instance->pModel->channels().empty())) && ImGui::BeginTabItem(STR_C("Clips and channels"))) - { - render_clips(*instance); - render_channels(*instance); - ImGui::EndTabItem(); - } - if (std::ranges::count(m_model.components, eu07m::target_kind::model, &eu07m::component_record::kind) > 0 && ImGui::BeginTabItem(STR_C("Components of the model"))) - { - render_model_components(); - ImGui::EndTabItem(); - } - ImGui::EndTabBar(); + ImGui::EndDisabled(); + } + ImGui::TextDisabled("%s", m_path.empty() ? m_source->NameGet().c_str() : std::filesystem::path{m_path}.filename().string().c_str()); + } + ImGui::SeparatorText(STR_C("A model of the scenery")); + ImGui::TextWrapped("%s", STR_C("Click a model in the view to edit it.")); + render_insert(); + if (auto const *instance{dynamic_cast(m_lastselected)}; (instance != nullptr) && (m_pickedvehicle != nullptr)) + { + auto const &name{instance->name()}; + auto const label{std::vformat(STR("Back to {}"), std::make_format_args(name))}; + if (ImGui::Button(label.c_str())) + { + m_pickedvehicle = nullptr; } } - ImGui::End(); - render_view(); + ImGui::SeparatorText(STR_C("Vehicles")); + if ((place_vehicle != nullptr) && ImGui::Button(STR_C("Put a vehicle on a track..."))) + { + place_vehicle(); + } + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("The Trainset tool of the tracks: click a track, pick the vehicle and Place it; F7 brings you back here")); + } + auto const &vehicles{simulation::Vehicles.sequence()}; + if (vehicles.empty()) + { + ImGui::TextDisabled("%s", STR_C("The scenery has no vehicles.")); + return; + } + ImGui::TextDisabled("%s", STR_C("A click picks the vehicle and takes the camera to it")); + if (false == ImGui::BeginChild("##eu07mvehicles", ImVec2(0.f, 0.f), ImGuiChildFlags_Borders)) + { + ImGui::EndChild(); + return; + } + auto const *driven{simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr}; + ImGuiListClipper clipper; + clipper.Begin(static_cast(vehicles.size())); + while (clipper.Step()) + { + for (auto idx = clipper.DisplayStart; idx < clipper.DisplayEnd; ++idx) + { + auto *vehicle{vehicles[static_cast(idx)]}; + auto label{vehicle->name()}; + if (vehicle == driven) + { + label += std::string{" "} + STR_C("(driven)"); + } + label += "##vehicle" + std::to_string(idx); + if (ImGui::Selectable(label.c_str(), vehicle == m_target.vehicle)) + { + m_pickedvehicle = vehicle; + fly_to_vehicle(*vehicle); + } + } + } + ImGui::EndChild(); +} + +void eu07m_model_panel::render_insert() +{ + if ((place_model == nullptr) || (false == ImGui::TreeNode(STR_C("Put a model in the scenery")))) + { + return; + } + auto searched{false}; + if (false == m_scanned) + { + // the folder of the models looked through once, when the list is first opened + m_scanned = true; + searched = true; + std::error_code error; + for (std::filesystem::recursive_directory_iterator entry{"models", std::filesystem::directory_options::skip_permission_denied, error}, end; entry != end; entry.increment(error)) + { + std::error_code status; + auto const extension{ToLower(entry->path().extension().string())}; + if ((false == entry->is_regular_file(status)) || ((extension != ".e3d") && (extension != ".t3d"))) + { + continue; + } + m_files.push_back(std::filesystem::relative(entry->path(), "models", status).generic_string()); + } + std::ranges::sort(m_files); + } + std::array buffer{}; + std::memcpy(buffer.data(), m_filesearch.data(), std::min(m_filesearch.size(), buffer.size() - 1)); + ImGui::SetNextItemWidth(-1.f); + if (ImGui::InputTextWithHint("##modelsearch", STR_C("Look for a model by its name, e.g. latarnia"), buffer.data(), buffer.size())) + { + m_filesearch = buffer.data(); + searched = true; + } + if (searched) + { + auto const wanted_text{lowered(m_filesearch)}; + m_found.clear(); + for (std::size_t idx = 0; idx < m_files.size(); ++idx) + { + if (lowered(m_files[idx]).find(wanted_text) != std::string::npos) + { + m_found.push_back(idx); + } + } + } + ImGui::TextDisabled("%s", STR_C("A click puts the model in front of the camera; then Whole model in the toolbar moves it")); + if (ImGui::BeginChild("##eu07mfiles", ImVec2(0.f, ImGui::GetTextLineHeightWithSpacing() * 8.f), ImGuiChildFlags_Borders)) + { + ImGuiListClipper clipper; + clipper.Begin(static_cast(m_found.size())); + while (clipper.Step()) + { + for (auto idx = clipper.DisplayStart; idx < clipper.DisplayEnd; ++idx) + { + auto const &file{m_files[m_found[static_cast(idx)]]}; + if (ImGui::Selectable((file + "##file" + std::to_string(idx)).c_str())) + { + place_model(file); + } + } + } + } + ImGui::EndChild(); + ImGui::TreePop(); +} + +bool eu07m_model_panel::import_model() +{ + if ((false == m_importable) || (m_source == nullptr)) + { + return false; + } + std::string error; + auto const written{eu07m::import_model(*m_source, error)}; + if (written.empty()) + { + m_message = std::vformat(STR("Not imported: {}"), std::make_format_args(error)); + return false; + } + open(m_target); + auto const name{std::filesystem::path{written}.filename().string()}; + m_message = std::vformat(STR("Imported to {}. Its lights and parts can be changed now"), std::make_format_args(name)); + return true; +} + +void eu07m_model_panel::render_tools() +{ + render_header(); + if (m_path.empty()) + { + return; + } + ImGui::PushItemWidth(-ImGui::GetFontSize() * label_width); + switch (m_tool) + { + case tool::lights: + render_lights_page(); + break; + case tool::parts: + render_parts_page(); + break; + case tool::elements: + render_elements_page(); + break; + case tool::animations: + render_animations_page(); + break; + } + ImGui::PopItemWidth(); } void eu07m_model_panel::render_header() { - if (m_vehicle != nullptr) + if (m_source == nullptr) { - ImGui::TextUnformatted(m_vehicle->name().c_str()); - ImGui::SameLine(); - auto part{m_vehiclepart}; - ImGui::RadioButton(STR_C("Body"), &part, 0); - ImGui::SameLine(); - ImGui::BeginDisabled(m_vehicle->mdKabina == nullptr); - ImGui::RadioButton(STR_C("Cab"), &part, 1); - ImGui::EndDisabled(); - // the other part is loaded in the next frame - m_vehiclepart = part; - ImGui::SameLine(); + ImGui::TextWrapped("%s", STR_C("No model to edit. Click a model in the scenery, or pick a vehicle in the list on the left.")); + return; } - ImGui::TextUnformatted(std::filesystem::path{m_path}.filename().string().c_str()); - if (ImGui::IsItemHovered()) + if (false == m_problem.empty()) { - auto const nodes{m_model.nodes.size()}; - auto const components{m_model.components.size()}; - auto const clips{m_model.clips.size()}; - auto const vertices{m_model.vertex_count()}; - ImGui::SetTooltip("%s\n%s", m_path.c_str(), std::vformat(STR("{} nodes, {} components, {} clips, {} vertices"), std::make_format_args(nodes, components, clips, vertices)).c_str()); + ImGui::TextWrapped("%s", m_problem.c_str()); + if (m_importable && ImGui::Button(STR_C("Import to EU07M"))) + { + import_model(); + } + if (m_importable && ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("Writes an .eu07m file beside the model, made of the model as the game has it. From then on the game loads the model from it, in every scenery")); + } + if (false == m_message.empty()) + { + ImGui::TextWrapped("%s", m_message.c_str()); + } + return; } ImGui::BeginDisabled(false == m_dirty); - if (ImGui::Button(STR_C("Save the model"))) + if (ImGui::Button(STR_C("Save the changes"))) { save(); } ImGui::EndDisabled(); - ImGui::SameLine(); - if (ImGui::Button(STR_C("Read it again")) && (m_source != nullptr)) + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) { - load(*m_source); + ImGui::SetTooltip("%s", STR_C("Writes the model to its file; until then nothing of it is changed on the disk")); } ImGui::SameLine(); - ImGui::Checkbox(STR_C("Lights marked in the view"), &m_marks); + ImGui::BeginDisabled(m_undo.empty()); + if (ImGui::Button(STR_C("Undo"))) + { + undo(); + } + ImGui::EndDisabled(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + ImGui::SetTooltip("%s", STR_C("Takes the last change of the model back (Ctrl+Z)")); + } + ImGui::SameLine(); + ImGui::BeginDisabled(m_redo.empty()); + if (ImGui::Button(STR_C("Redo"))) + { + redo(); + } + ImGui::EndDisabled(); + if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled)) + { + ImGui::SetTooltip("%s", STR_C("Makes the change taken back again (Ctrl+Y)")); + } + if (m_dirty) + { + ImGui::SameLine(); + ImGui::TextColored(ImVec4(1.f, 0.7f, 0.3f, 1.f), "%s", STR_C("Not saved")); + } if (m_submodels.empty()) { ImGui::TextWrapped("%s", STR_C("The model in the game differs from the file: the changes show once the game loads the model again")); @@ -798,27 +1295,159 @@ void eu07m_model_panel::render_header() { ImGui::TextWrapped("%s", m_message.c_str()); } + render_guide(); } -void eu07m_model_panel::render_model_tab() +void eu07m_model_panel::render_guide() const { - auto const height{ImGui::GetContentRegionAvail().y}; - if (ImGui::BeginChild("##eu07mtree", ImVec2(ImGui::GetContentRegionAvail().x * 0.42f, height), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX)) + if (false == ImGui::CollapsingHeader(STR_C("How it works"))) + { + return; + } + ImGui::Indent(); + ImGui::TextWrapped("%s", STR_C("1. Pick the model: click it in the scenery, or pick a vehicle in the list on the left.")); + ImGui::TextWrapped("%s", STR_C("2. Click a part of the model in the view. Its settings come up in the inspector.")); + ImGui::TextWrapped("%s", STR_C("3. Drag the arrows in the view to move the part picked, or the rings to turn it: Move and Turn are in the toolbar.")); + ImGui::TextWrapped("%s", STR_C("4. Ctrl+Z takes a change back. Nothing goes into the file until Save the changes.")); + ImGui::Unindent(); +} + +void eu07m_model_panel::render_lights_page() +{ + ImGui::TextWrapped("%s", STR_C("The light sources of the model. Click one to change it in the inspector; its round mark in the view does the same.")); + if (m_placing) + { + ImGui::TextColored(ImVec4(1.f, 0.85f, 0.3f, 1.f), "%s", STR_C("Click the model where the light is to be. Esc gives it up.")); + if (ImGui::Button(STR_C("Give it up"))) + { + m_placing.reset(); + } + } + else + { + ImGui::BeginDisabled(m_submodels.empty()); + if (ImGui::Button(STR_C("+ Add a bulb"))) + { + m_placing = false; + } + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("A light which shines all around, as a bulb; then a click on the model puts it there")); + } + ImGui::SameLine(); + if (ImGui::Button(STR_C("+ Add a spot"))) + { + m_placing = true; + } + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("A light which shines one way, as a headlamp; then a click on the model puts it there, shining towards the camera")); + } + ImGui::EndDisabled(); + } + ImGui::Checkbox(STR_C("Marks of the lights in the view"), &m_marks); + ImGui::SeparatorText(STR_C("Lights of the model")); + auto any{false}; + for (std::uint32_t idx = 0; idx < m_model.components.size(); ++idx) + { + auto const &record{m_model.components[idx]}; + if ((record.type != eu07m::component::light) || (record.kind != eu07m::target_kind::node) || (record.target >= m_model.nodes.size()) || + (std::size_t{record.data_offset} + sizeof(payload::light) > m_model.component_data.size())) + { + continue; + } + any = true; + payload::light light; + std::memcpy(&light, m_model.component_data.data() + record.data_offset, sizeof(light)); + ImGui::PushID(static_cast(idx)); + ImGui::ColorButton("##colour", ImVec4(light.color[0], light.color[1], light.color[2], 1.f), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoPicker); + ImGui::SameLine(); + auto const kind{light.kind == payload::light_kind::spot ? STR_C("spot") : STR_C("bulb")}; + auto const label{std::format("{} ({})", part_name(record.target), kind)}; + if (ImGui::Selectable(label.c_str(), m_selected == static_cast(record.target), ImGuiSelectableFlags_AllowDoubleClick)) + { + select(record.target); + if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + { + fly_to(record.target); + } + } + ImGui::PopID(); + } + if (false == any) + { + ImGui::TextDisabled("%s", STR_C("The model has no light sources yet.")); + } +} + +void eu07m_model_panel::render_parts_page() const +{ + if ((m_target.vehicle == nullptr) || (m_target.part != 0)) + { + ImGui::TextWrapped("%s", STR_C("The parts of a vehicle are held on its body: pick the body on the left.")); + return; + } + auto &vehicle{*m_target.vehicle}; + ImGui::TextWrapped("%s", STR_C("The vehicle keeps a part as set here until As the vehicle has it is chosen. Nothing of it goes into the file.")); + if (vehicle.pantograph_count() > 0) + { + ImGui::SeparatorText(STR_C("Pantographs")); + if (ImGui::BeginTable("##pantographs", 2, ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg)) + { + for (int idx = 0; idx < vehicle.pantograph_count(); ++idx) + { + pantograph_hold_row(vehicle, idx); + } + ImGui::EndTable(); + } + } + part_group(vehicle, STR_C("Front lights"), true, [](std::string_view const Name) { return is_lamp(Name) && is_front(Name); }); + part_group(vehicle, STR_C("Rear lights"), true, [](std::string_view const Name) { return is_lamp(Name) && (false == is_front(Name)); }); + part_group(vehicle, STR_C("Couplers and hoses"), false, [](std::string_view const Name) { return false == is_lamp(Name); }); +} + +void eu07m_model_panel::render_elements_page() +{ + ImGui::TextWrapped("%s", STR_C("All the parts of the model, as they hang one on another. A click picks one, a double click takes the camera to it.")); + std::array buffer{}; + std::memcpy(buffer.data(), m_filter.data(), std::min(m_filter.size(), buffer.size() - 1)); + ImGui::SetNextItemWidth(-1.f); + if (ImGui::InputTextWithHint("##filter", STR_C("Look for a part by its name"), buffer.data(), buffer.size())) + { + m_filter = buffer.data(); + } + if (false == ImGui::BeginChild("##eu07mtree", ImVec2(0.f, 0.f), ImGuiChildFlags_Borders)) + { + ImGui::EndChild(); + return; + } + if (m_filter.empty()) { - ImGui::TextDisabled("%s", STR_C("A click picks, a double click takes the camera there")); for (std::uint32_t idx = 0; idx < m_model.nodes.size(); idx = m_model.nodes[idx].subtree_end) { render_tree_node(idx); } + ImGui::EndChild(); + return; } - ImGui::EndChild(); - ImGui::SameLine(); - if (ImGui::BeginChild("##eu07mproperties", ImVec2(0.f, height), ImGuiChildFlags_Borders)) + // what is looked for: the parts of the name, as a list + auto const wanted_text{lowered(m_filter)}; + for (std::uint32_t idx = 0; idx < m_model.nodes.size(); ++idx) { - // the fields leave room for their labels - ImGui::PushItemWidth(-ImGui::GetFontSize() * label_width); - render_properties(); - ImGui::PopItemWidth(); + auto const name{part_name(idx)}; + if (lowered(name).find(wanted_text) == std::string::npos) + { + continue; + } + auto const label{name + "##found" + std::to_string(idx)}; + if (ImGui::Selectable(label.c_str(), m_selected == static_cast(idx), ImGuiSelectableFlags_AllowDoubleClick)) + { + select(idx); + if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + { + fly_to(idx); + } + } } ImGui::EndChild(); } @@ -871,103 +1500,194 @@ void eu07m_model_panel::render_tree_node(std::uint32_t const Index) ImGui::TreePop(); } -void eu07m_model_panel::render_properties() +void eu07m_model_panel::render_animations_page() { + auto *instance{m_target.instance}; + if (instance == nullptr) + { + ImGui::TextWrapped("%s", STR_C("The animations are tried on a model of the scenery.")); + return; + } + ImGui::TextWrapped("%s", STR_C("The animations of the model, tried on it in the view. Looped and Plays on its own go into the file.")); + render_clips(*instance); + render_channels(*instance); +} + +void eu07m_model_panel::render_selection() +{ + if (m_path.empty()) + { + ImGui::TextWrapped("%s", m_problem.empty() ? STR_C("Pick a model first: click it in the view, or pick a vehicle in the list on the left.") : m_problem.c_str()); + return; + } if ((m_selected < 0) || (m_selected >= static_cast(m_model.nodes.size()))) { - ImGui::TextWrapped("%s", STR_C("Pick a node in the tree, or a mark of a light in the view")); + ImGui::TextWrapped("%s", STR_C("Click a part of the model in the view, or pick one in the tool options, to change it here.")); return; } auto const index{static_cast(m_selected)}; - auto const name{m_model.string(m_model.nodes[index].name)}; - ImGui::SeparatorText(name.empty() ? STR_C("(no name)") : std::string{name}.c_str()); - if (ImGui::Button(STR_C("Show in the view"))) + auto const light{light_of(index)}; + ImGui::PushItemWidth(-ImGui::GetFontSize() * label_width); + ImGui::SeparatorText(part_name(index).c_str()); + if (light) + { + ImGui::TextDisabled("%s", STR_C("A light source")); + } + else + { + ImGui::TextDisabled("%s", m_model.nodes[index].mesh >= 0 ? STR_C("A part of the model") : STR_C("A point of the model, with nothing to see")); + } + if (ImGui::Button(STR_C("Show it in the view"))) { fly_to(index); } - ImGui::SameLine(); - auto mode{static_cast(m_gizmo)}; - ImGui::RadioButton(STR_C("Move"), &mode, static_cast(gizmo::move)); - ImGui::SameLine(); - ImGui::RadioButton(STR_C("Turn"), &mode, static_cast(gizmo::turn)); - ImGui::SameLine(); - ImGui::RadioButton(STR_C("No gizmo"), &mode, static_cast(gizmo::none)); - m_gizmo = static_cast(mode); - render_node_hold(index); - render_node_settings(index); - for (auto const component : node_components(m_model, index)) + // the part of the vehicle it is in + auto const *target{submodel(index)}; + if ((m_target.vehicle != nullptr) && (m_target.part == 0) && (target != nullptr)) { - render_component(component); - } -} - -void eu07m_model_panel::render_parts_tab() const -{ - ImGui::TextWrapped("%s", STR_C("Held as set here, whatever the vehicle does; Automatic gives them back to it")); - if (m_vehicle->pantograph_count() > 0) - { - ImGui::SeparatorText(STR_C("Pantographs")); - for (int idx = 0; idx < m_vehicle->pantograph_count(); ++idx) + auto const part{m_target.vehicle->part_of(target)}; + auto const pantograph{m_target.vehicle->pantograph_of(target)}; + if (((part < TDynamicObject::held_part_total) || (pantograph >= 0)) && ImGui::BeginTable("##hold", 2, ImGuiTableFlags_SizingFixedFit)) { - render_pantograph_hold(*m_vehicle, idx); + if (part < TDynamicObject::held_part_total) + { + part_hold_row(*m_target.vehicle, part); + } + if (pantograph >= 0) + { + pantograph_hold_row(*m_target.vehicle, pantograph); + } + ImGui::EndTable(); } } - render_hold_group(*m_vehicle, STR_C("Front lights"), [](std::string_view const Name) { return is_lamp(Name) && is_front(Name); }); - render_hold_group(*m_vehicle, STR_C("Rear lights"), [](std::string_view const Name) { return is_lamp(Name) && (false == is_front(Name)); }); - render_hold_group(*m_vehicle, STR_C("Couplers and hoses"), [](std::string_view const Name) { return false == is_lamp(Name); }); + if (light) + { + render_light_settings(*light); + } + render_place(index); + if (light && eu07m::node_removable(m_model, index) && ImGui::Button(STR_C("Remove this light (Del)"))) + { + remove_selected(); + ImGui::PopItemWidth(); + return; + } + render_advanced(index); + ImGui::PopItemWidth(); } -void eu07m_model_panel::render_node_hold(std::uint32_t const Index) const +void eu07m_model_panel::render_light_settings(std::uint32_t const Component) { - auto const *target{submodel(Index)}; - if ((m_vehicle == nullptr) || (m_vehiclepart != 0) || (target == nullptr)) + auto const &record{m_model.components[Component]}; + if ((record.data_size < sizeof(payload::light)) || (std::size_t{record.data_offset} + sizeof(payload::light) > m_model.component_data.size())) { return; } - auto const part{m_vehicle->part_of(target)}; - auto const pantograph{m_vehicle->pantograph_of(target)}; - if ((part >= TDynamicObject::held_part_total) && (pantograph < 0)) + payload::light light; + std::memcpy(&light, m_model.component_data.data() + record.data_offset, sizeof(light)); + auto changes{false}; + ImGui::SeparatorText(STR_C("Light")); + auto const spot{light.kind == payload::light_kind::spot}; + std::array const kinds{STR_C("Bulb: shines all around"), STR_C("Spot: shines one way")}; + if (auto const clicked{choice_buttons("##kind", spot ? 1 : 0, kinds)}; clicked && ((*clicked == 1) != spot)) + { + set_light_kind(light, *clicked == 1 ? payload::light_kind::spot : payload::light_kind::point); + changes = true; + } + changes |= ImGui::ColorEdit3(STR_C("Colour"), light.color.data()); + for (auto const &preset : colour_presets) + { + ImGui::PushID(preset.name); + if (ImGui::ColorButton(STR_C(preset.name), ImVec4(preset.colour[0], preset.colour[1], preset.colour[2], 1.f))) + { + std::ranges::copy(preset.colour, light.color.begin()); + changes = true; + } + ImGui::PopID(); + ImGui::SameLine(0.f, ImGui::GetStyle().ItemInnerSpacing.x); + } + ImGui::NewLine(); + changes |= ImGui::SliderFloat(STR_C("Brightness"), &light.hotspot_power, 0.f, 10.f, "%.2f"); + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("How strongly it lights what is around it. Ctrl+click types a value")); + } + changes |= ImGui::SliderFloat(STR_C("Glowing spot, m"), &light.radius, 0.f, 1.f, "%.2f"); + if (ImGui::IsItemHovered()) + { + ImGui::SetTooltip("%s", STR_C("The size of the glowing ball seen where the light is; 0 shows none")); + } + if (light.kind == payload::light_kind::spot) + { + changes |= edit_beam(light); + } + auto shadows{(light.flags & payload::light_flags::no_shadows) == 0}; + if (ImGui::Checkbox(STR_C("Casts shadows"), &shadows)) + { + // the box says it casts them, the flag that it doesn't + light.flags ^= payload::light_flags::no_shadows; + changes = true; + } + changes |= edit_flag(STR_C("Soft edge"), light.flags, payload::light_flags::soft_falloff); + changes |= edit_flag(STR_C("Lights this model too"), light.flags, payload::light_flags::shade_self); + if (false == changes) { return; } - ImGui::SeparatorText(STR_C("Part of the vehicle")); - if (part < TDynamicObject::held_part_total) - { - render_part_hold(*m_vehicle, part); - } - if (pantograph >= 0) - { - render_pantograph_hold(*m_vehicle, pantograph); - } + std::memcpy(m_model.component_data.data() + record.data_offset, &light, sizeof(light)); + changed(); + show_change(Component); } -void eu07m_model_panel::render_node_settings(std::uint32_t const Index) +void eu07m_model_panel::render_place(std::uint32_t const Index) { - ImGui::SeparatorText(STR_C("Settings of the node")); auto &node{m_model.nodes[Index]}; - auto *target{submodel(Index)}; + ImGui::SeparatorText(STR_C("Place")); if ((node.flags & eu07m::node_flags::matrix) != 0) { - ImGui::TextDisabled("%s", STR_C("Placed by a matrix (XFRM), not edited here")); + ImGui::TextDisabled("%s", STR_C("This part is placed in a way this window doesn't change")); } - else if (edit_place(node)) + else { - moved(Index); + ImGui::TextWrapped("%s", STR_C("Drag the arrows in the view to move it, or the rings to turn it.")); + std::array const modes{STR_C("Move"), STR_C("Turn")}; + if (auto const clicked{choice_buttons("##gizmo", m_gizmo == gizmo::turn ? 1 : 0, modes)}) + { + set_turning(*clicked == 1); + } + if (ImGui::TreeNode(STR_C("Exact values"))) + { + if (edit_place(node)) + { + moved(Index); + } + ImGui::TreePop(); + } } + ImGui::SeparatorText(STR_C("Seen from")); if (edit_range(node)) { - m_dirty = true; - if (target != nullptr) + changed(); + if (auto *target{submodel(Index)}; target != nullptr) { m_source->SetEditorRange(*target, node.range_min_sq, node.range_max_sq); } } - ImGui::SetNextItemWidth(ImGui::GetFontSize() * 6.f); - ImGui::Combo(STR_C("Kind of the light"), &m_lightkind, std::array{STR_C("point"), STR_C("spot")}.data(), 2); - ImGui::SameLine(); - if (ImGui::Button(STR_C("Add a light source here"))) +} + +void eu07m_model_panel::render_advanced(std::uint32_t const Index) +{ + if (false == ImGui::CollapsingHeader(STR_C("Advanced: the data of the file"))) { - add_light(Index); + return; + } + ImGui::TextDisabled("%s", STR_C("For those who know the EU07M format")); + if (ImGui::Button(STR_C("Add a light to this part"))) + { + add_light(Index, glm::vec3{0.f}, glm::quat{1.f, 0.f, 0.f, 0.f}, false); + } + for (auto const component : node_components(m_model, Index)) + { + render_component(component); } } @@ -975,17 +1695,36 @@ void eu07m_model_panel::render_component(std::uint32_t const Index) { auto const &record{m_model.components[Index]}; auto const label{std::format("{} ({}) #{}##component{}", component_name(record.type), fourcc_text(record.type), Index, Index)}; - if (false == ImGui::CollapsingHeader(label.c_str(), ImGuiTreeNodeFlags_DefaultOpen)) + if (false == ImGui::TreeNode(label.c_str())) { return; } ImGui::PushID(static_cast(Index)); if (edit_component(m_model, Index)) { - m_dirty = true; + changed(); show_change(Index); } ImGui::PopID(); + ImGui::TreePop(); +} + +void eu07m_model_panel::choose_tool(tool const Tool) +{ + m_tool = Tool; + m_placing.reset(); +} + +bool eu07m_model_panel::has_animations() const +{ + auto const *instance{m_target.instance}; + return (instance != nullptr) && ((false == m_model.clips.empty()) || ((instance->pModel != nullptr) && (false == instance->pModel->channels().empty()))); +} + +bool eu07m_model_panel::editable(scene::basic_node const *Node) const +{ + auto const *instance{dynamic_cast(Node)}; + return Global.modelformat_eu07m && (instance != nullptr) && (instance->pModel != nullptr) && (false == FileCased(instance->pModel->NameGet() + ".eu07m").empty()); } bool eu07m_model_panel::select_node(std::string_view const Name) @@ -1000,10 +1739,28 @@ bool eu07m_model_panel::select_node(std::string_view const Name) return true; } +bool eu07m_model_panel::add_test_light(bool const Spot) +{ + // in the middle of the geometry of the part picked, as a click there would put it + auto const where{placement()}; + // the first part when none is picked + auto const part{m_model.nodes.empty() ? std::nullopt : std::optional{static_cast(std::max(m_selected, 0))}}; + auto const *target{part ? submodel(*part) : nullptr}; + if ((false == where.has_value()) || (target == nullptr)) + { + return false; + } + auto const &bounds{m_boxes[*part]}; + auto const middle{bounds ? glm::dvec3{(bounds->first + bounds->second) * 0.5f} : glm::dvec3{0.0}}; + auto const count{m_model.nodes.size()}; + m_placing = Spot; + place_light(point_of(*where * model_space(*target), middle), part); + return m_model.nodes.size() > count; +} + void eu07m_model_panel::select(std::uint32_t const Node) { m_selected = Node; - m_box = node_box(m_model, Node); } TSubModel *eu07m_model_panel::submodel(std::uint32_t const Node) const @@ -1013,21 +1770,88 @@ TSubModel *eu07m_model_panel::submodel(std::uint32_t const Node) const std::optional eu07m_model_panel::placement() const { - if (m_vehicle != nullptr) + if (m_target.vehicle != nullptr) { - return glm::translate(glm::dmat4{1.0}, m_vehicle->GetPosition()) * m_vehicle->mMatrix; + return glm::translate(glm::dmat4{1.0}, m_target.vehicle->GetPosition()) * m_target.vehicle->mMatrix; } - if (m_instance == nullptr) + auto const *instance{m_target.instance}; + if (instance == nullptr) { return std::nullopt; } // turned about y, then x, then z, and scaled, the way the instance is drawn - auto const angles{glm::radians(glm::dvec3{m_instance->Angles()})}; - auto matrix{glm::translate(glm::dmat4{1.0}, m_instance->location())}; + auto const angles{glm::radians(glm::dvec3{instance->Angles()})}; + auto matrix{glm::translate(glm::dmat4{1.0}, instance->location())}; matrix = glm::rotate(matrix, angles.y, glm::dvec3{0.0, 1.0, 0.0}); matrix = glm::rotate(matrix, angles.x, glm::dvec3{1.0, 0.0, 0.0}); matrix = glm::rotate(matrix, angles.z, glm::dvec3{0.0, 0.0, 1.0}); - return glm::scale(matrix, glm::dvec3{m_instance->Scale()}); + return glm::scale(matrix, glm::dvec3{instance->Scale()}); +} + +std::optional eu07m_model_panel::node_at(glm::dvec3 const &Point) const +{ + auto const where{placement()}; + if (false == where.has_value()) + { + return std::nullopt; + } + std::optional best; + auto bestvolume{std::numeric_limits::max()}; + for (std::uint32_t idx = 0; (idx < m_boxes.size()) && (idx < m_submodels.size()); ++idx) + { + auto const &bounds{m_boxes[idx]}; + auto const *target{m_submodels[idx]}; + // a part hidden now, such as a lamp off, isn't what was clicked + if ((false == bounds.has_value()) || (target == nullptr) || (target->iVisible == 0)) + { + continue; + } + if (false == inside(*bounds, point_of(glm::inverse(*where * model_space(*target)), Point), pick_margin)) + { + continue; + } + auto const size{glm::dvec3{bounds->second - bounds->first} + 2.0 * pick_margin}; + if (auto const volume{size.x * size.y * size.z}; volume < bestvolume) + { + best = idx; + bestvolume = volume; + } + } + return best; +} + +std::optional eu07m_model_panel::light_of(std::uint32_t const Node) const +{ + for (std::uint32_t idx = 0; idx < m_model.components.size(); ++idx) + { + auto const &record{m_model.components[idx]}; + if ((record.type == eu07m::component::light) && (record.kind == eu07m::target_kind::node) && (record.target == Node)) + { + return idx; + } + } + return std::nullopt; +} + +std::string eu07m_model_panel::part_name(std::uint32_t const Node) const +{ + auto const name{m_model.string(m_model.nodes[Node].name)}; + std::string own{name.empty() ? std::string{STR_C("(no name)")} : std::string{name}}; + auto const *target{submodel(Node)}; + if ((m_target.vehicle == nullptr) || (m_target.part != 0) || (target == nullptr)) + { + return own; + } + if (auto const part{m_target.vehicle->part_of(target)}; part < TDynamicObject::held_part_total) + { + return std::format("{} ({})", part_text(TDynamicObject::held_part_name(part)), own); + } + if (auto const pantograph{m_target.vehicle->pantograph_of(target)}; pantograph >= 0) + { + auto const number{pantograph + 1}; + return std::format("{} ({})", std::vformat(STR("Pantograph {}"), std::make_format_args(number)), own); + } + return own; } void eu07m_model_panel::render_view() @@ -1040,64 +1864,79 @@ void eu07m_model_panel::render_view() screen_projection const projection; auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; auto const clicked{ImGui::IsMouseClicked(ImGuiMouseButton_Left) && (false == ImGui::GetIO().WantCaptureMouse)}; - auto const mouse{ImGui::GetMousePos()}; if (clicked) { m_tookpress = false; } - // the marks of the light sources; a click on one picks its node - for (auto const &record : m_model.components) + // what a click is to do now, by the cursor + if (m_placing && (false == ImGui::GetIO().WantCaptureMouse)) { - if ((false == m_marks) || (record.type != eu07m::component::light) || (record.kind != eu07m::target_kind::node) || (submodel(record.target) == nullptr) || - (std::size_t{record.data_offset} + sizeof(payload::light) > m_model.component_data.size())) - { - continue; - } - payload::light light; - std::memcpy(&light, m_model.component_data.data() + record.data_offset, sizeof(light)); - auto const space{*where * model_space(*submodel(record.target))}; - ImVec2 centre; - if (false == projection.project(point_of(space, glm::dvec3{0.0}), centre)) - { - continue; - } - auto const picked{m_selected == static_cast(record.target)}; - if (light.kind == payload::light_kind::spot) - { - // the axis of a spot is the -z of its node - projection.line(drawlist, point_of(space, glm::dvec3{0.0}), point_of(space, glm::dvec3{0.0, 0.0, -0.6}), light_colour(light, 255), 2.f); - } - drawlist->AddCircleFilled(centre, mark_radius, light_colour(light, 220)); - drawlist->AddCircle(centre, mark_radius + 1.f, picked ? overlay_color::selected : IM_COL32(0, 0, 0, 200), 0, picked ? 3.f : 1.5f); - auto const dx{mouse.x - centre.x}; - auto const dy{mouse.y - centre.y}; - if (clicked && (dx * dx + dy * dy <= (mark_radius + 3.f) * (mark_radius + 3.f))) - { - select(record.target); - m_scrolltoselected = true; - m_tookpress = true; - } + auto const mouse{ImGui::GetMousePos()}; + ImGui::GetForegroundDrawList()->AddText(ImVec2(mouse.x + 18.f, mouse.y + 4.f), IM_COL32(255, 220, 90, 255), STR_C("Click the model where the light is to be")); } - // the node picked: its frame and its axes, and the gizmo to move it + if (m_marks) + { + render_marks(*where, clicked && (false == m_placing.has_value())); + } + // the part picked: its frame and its axes, and the gizmo to move it auto const *target{m_selected >= 0 ? submodel(static_cast(m_selected)) : nullptr}; if (target == nullptr) { return; } auto const space{*where * model_space(*target)}; - if (m_box) + if (auto const &bounds{m_boxes[static_cast(m_selected)]}; bounds.has_value()) { - draw_box(drawlist, projection, space, *m_box, overlay_color::selected); + draw_box(drawlist, projection, space, *bounds, overlay_color::selected); } draw_axes(drawlist, projection, space, 0.3); render_gizmo(*where, GfxRenderer->Camera_Position()); } +void eu07m_model_panel::render_marks(glm::dmat4 const &Placement, bool const Clicked) +{ + screen_projection const projection; + auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; + auto const mouse{ImGui::GetMousePos()}; + for (auto const &record : m_model.components) + { + if ((record.type != eu07m::component::light) || (record.kind != eu07m::target_kind::node) || (submodel(record.target) == nullptr) || + (std::size_t{record.data_offset} + sizeof(payload::light) > m_model.component_data.size())) + { + continue; + } + payload::light light; + std::memcpy(&light, m_model.component_data.data() + record.data_offset, sizeof(light)); + auto const space{Placement * model_space(*submodel(record.target))}; + ImVec2 centre; + if (false == projection.project(point_of(space, glm::dvec3{0.0}), centre)) + { + continue; + } + if (light.kind == payload::light_kind::spot) + { + // the axis of a spot is the -z of its node + projection.line(drawlist, point_of(space, glm::dvec3{0.0}), point_of(space, glm::dvec3{0.0, 0.0, -0.6}), light_colour(light, 255), 2.f); + } + auto const picked{m_selected == static_cast(record.target)}; + drawlist->AddCircleFilled(centre, mark_radius, light_colour(light, 220)); + drawlist->AddCircle(centre, mark_radius + 1.f, picked ? overlay_color::selected : IM_COL32(0, 0, 0, 200), 0, picked ? 3.f : 1.5f); + auto const dx{mouse.x - centre.x}; + auto const dy{mouse.y - centre.y}; + if (Clicked && (dx * dx + dy * dy <= (mark_radius + 3.f) * (mark_radius + 3.f))) + { + select(record.target); + m_scrolltoselected = true; + m_tookpress = true; + } + } +} + void eu07m_model_panel::render_gizmo(glm::dmat4 const &Placement, glm::dvec3 const &Camera) { auto const index{static_cast(m_selected)}; auto *target{submodel(index)}; - if ((m_gizmo == gizmo::none) || (target == nullptr) || ((m_model.nodes[index].flags & eu07m::node_flags::matrix) != 0)) + if (m_placing || moves_whole() || (target == nullptr) || ((m_model.nodes[index].flags & eu07m::node_flags::matrix) != 0)) { return; } @@ -1133,7 +1972,7 @@ void eu07m_model_panel::render_gizmo(glm::dmat4 const &Placement, glm::dvec3 con void eu07m_model_panel::moved(std::uint32_t const Node) { m_model.nodes[Node].flags &= ~eu07m::node_flags::no_transform; - m_dirty = true; + changed(); if (auto *target{submodel(Node)}; target != nullptr) { m_source->SetEditorTransform(*target, eu07m::local_transform(m_model, Node)); @@ -1159,8 +1998,163 @@ void eu07m_model_panel::show_change(std::uint32_t const Index) const m_source->state_changed(); } -void eu07m_model_panel::add_light(std::uint32_t const Parent) +void eu07m_model_panel::changed() { + m_dirty = true; + // one change for a press, a drag or a typing: the model as it was before it + if (m_changing) + { + return; + } + m_changing = true; + push_change(m_before); +} + +eu07m_model_panel::snapshot eu07m_model_panel::take(bool const Whole) const +{ + snapshot result; + result.nodes = m_model.nodes; + result.components = m_model.components; + result.component_data = m_model.component_data; + result.clips = m_model.clips; + if (Whole) + { + result.whole = m_model; + } + return result; +} + +void eu07m_model_panel::restore(snapshot const &Snapshot) +{ + auto const before{m_model.nodes}; + if (Snapshot.whole) + { + m_model = *Snapshot.whole; + } + else + { + m_model.nodes = Snapshot.nodes; + m_model.components = Snapshot.components; + m_model.component_data = Snapshot.component_data; + m_model.clips = Snapshot.clips; + } + // the places and the ranges changed shown on the model the game has; a change of the tree changes nothing else + if ((before.size() == m_model.nodes.size()) && (m_source != nullptr)) + { + for (std::uint32_t idx = 0; idx < before.size(); ++idx) + { + auto *target{submodel(idx)}; + if ((target == nullptr) || same_place(before[idx], m_model.nodes[idx])) + { + continue; + } + if ((m_model.nodes[idx].flags & eu07m::node_flags::matrix) == 0) + { + m_source->SetEditorTransform(*target, eu07m::local_transform(m_model, idx)); + } + m_source->SetEditorRange(*target, m_model.nodes[idx].range_min_sq, m_model.nodes[idx].range_max_sq); + } + } +} + +void eu07m_model_panel::apply_tree(tree_change const &Change, bool const Forward) +{ + if ((Change.what == tree_change::kind::none) || (Change.submodel == nullptr) || (m_source == nullptr) || m_submodels.empty()) + { + return; + } + // a light added is taken out again when the change is taken back, one taken out is put back + if ((Change.what == tree_change::kind::added) == Forward) + { + if ((Change.parent == nullptr) || (Change.index > m_submodels.size())) + { + return; + } + m_source->LinkEditorSubmodel(*Change.submodel, *Change.parent, Change.previous); + m_submodels.insert(m_submodels.begin() + Change.index, Change.submodel); + m_boxes.insert(m_boxes.begin() + Change.index, node_box(m_model, Change.index)); + return; + } + if (Change.index >= m_submodels.size()) + { + return; + } + m_source->UnlinkEditorSubmodel(*Change.submodel); + m_submodels.erase(m_submodels.begin() + Change.index); + m_boxes.erase(m_boxes.begin() + Change.index); +} + +void eu07m_model_panel::push_change(snapshot Snapshot) +{ + m_undo.push_back(std::move(Snapshot)); + if (m_undo.size() > undo_depth) + { + m_undo.erase(m_undo.begin()); + } + m_redo.clear(); + m_dirty = true; +} + +bool eu07m_model_panel::undo() +{ + if (m_undo.empty()) + { + return false; + } + auto entry{std::move(m_undo.back())}; + m_undo.pop_back(); + auto again{take(entry.whole.has_value())}; + again.change = entry.change; + restore(entry); + apply_tree(entry.change, false); + m_redo.push_back(std::move(again)); + settled(); + return true; +} + +bool eu07m_model_panel::redo() +{ + if (m_redo.empty()) + { + return false; + } + auto entry{std::move(m_redo.back())}; + m_redo.pop_back(); + auto back{take(entry.whole.has_value())}; + back.change = entry.change; + restore(entry); + apply_tree(entry.change, true); + m_undo.push_back(std::move(back)); + settled(); + return true; +} + +void eu07m_model_panel::settled() +{ + m_dirty = true; + m_message.clear(); + m_placing.reset(); + m_before = take(false); + m_changing = false; + // the lights as they are now + for (std::uint32_t idx = 0; idx < m_model.components.size(); ++idx) + { + show_change(idx); + } + if (m_selected >= static_cast(m_model.nodes.size())) + { + m_selected = -1; + } +} + +void eu07m_model_panel::add_light(std::uint32_t const Parent, glm::vec3 const &Position, glm::quat const &Rotation, bool const Spot) +{ + auto *parent{submodel(Parent)}; + if ((parent == nullptr) || (m_source == nullptr)) + { + return; + } + auto before{take(true)}; // a name the model doesn't have yet std::string name; for (int number = 1; name.empty() || (false == eu07m::find_nodes(m_model, name).empty()); ++number) @@ -1170,28 +2164,122 @@ void eu07m_model_panel::add_light(std::uint32_t const Parent) eu07m::node_record node; node.name = m_model.intern(name); node.legacy_flags = light_node_flags; + node.translation = {Position.x, Position.y, Position.z}; + node.rotation = {Rotation.x, Rotation.y, Rotation.z, Rotation.w}; auto const index{eu07m::insert_node(m_model, static_cast(Parent), node)}; payload::light light; - light.color = {1.f, 0.95f, 0.85f, 1.f}; - set_light_kind(light, m_lightkind == 1 ? payload::light_kind::spot : payload::light_kind::point); + light.color = {1.f, 0.9f, 0.7f, 1.f}; + // without a cone yet: a spot gets the one it's given to start with + light.cos_falloff = -1.f; + set_light_kind(light, Spot ? payload::light_kind::spot : payload::light_kind::point); std::vector data(sizeof(light)); std::memcpy(data.data(), &light, sizeof(light)); eu07m::add_component(m_model, eu07m::component::light, eu07m::target_kind::node, index, data); - m_dirty = true; - // on the model the game has, under the submodel of the parent - if (auto *parent{submodel(Parent)}; parent != nullptr) + // on the model the game has, the last child of the parent as in the file + auto *previous{parent->Child}; + while ((previous != nullptr) && (previous->Next != nullptr)) { - auto &added{m_source->AddEditorLight(*parent, name, glm::mat4{1.f}, light_node_flags, light)}; - m_submodels.insert(m_submodels.begin() + index, &added); - } - else - { - m_submodels.clear(); + previous = previous->Next; } + auto &added{m_source->AddEditorLight(*parent, name, eu07m::local_transform(m_model, index), light_node_flags, light)}; + m_submodels.insert(m_submodels.begin() + index, &added); + m_boxes.insert(m_boxes.begin() + index, std::nullopt); + before.change = {tree_change::kind::added, index, &added, parent, previous}; + push_change(std::move(before)); + m_before = take(false); // the new light is picked, to be moved with the gizmo select(index); m_scrolltoselected = true; - m_message = std::vformat(STR("Added the light source {}; move it with the gizmo in the view"), std::make_format_args(name)); + m_message = std::vformat(STR("Added the light {}. Drag the arrows in the view to move it"), std::make_format_args(name)); +} + +void eu07m_model_panel::place_light(glm::dvec3 const &Point, std::optional const Part) +{ + auto const spot{m_placing.value_or(false)}; + m_placing.reset(); + // on the part clicked; a light clicked gets one beside it rather than under it + auto parent{Part.value_or(0u)}; + if (light_of(parent) && (m_model.nodes[parent].parent >= 0)) + { + parent = static_cast(m_model.nodes[parent].parent); + } + auto const *target{submodel(parent)}; + auto const where{placement()}; + if ((target == nullptr) || (false == where.has_value())) + { + return; + } + auto const inverse{glm::inverse(*where * model_space(*target))}; + glm::vec3 const position{point_of(inverse, Point)}; + // a spot shines back where it was clicked from + auto const towards{glm::dvec3{inverse * glm::dvec4{glm::dvec3{Global.pCamera.Pos} - Point, 0.0}}}; + auto const rotation{glm::length(towards) > 1e-6 ? aim(glm::normalize(glm::vec3{towards})) : glm::quat{1.f, 0.f, 0.f, 0.f}}; + add_light(parent, position, rotation, spot); +} + +bool eu07m_model_panel::pick(scene::basic_node const *Picked) +{ + if ((false == m_active) || m_submodels.empty() || (false == placement().has_value()) || (moves_whole() && (false == m_placing.has_value()))) + { + return false; + } + // a vehicle isn't a node of the scenery: a click on it hits none + auto const ours{m_target.instance != nullptr ? Picked == m_target.instance : Picked == nullptr}; + if (false == ours) + { + return false; + } + if (false == GfxRenderer->Mouse_Hit()) + { + return m_target.instance != nullptr; + } + auto const point{glm::dvec3{Global.pCamera.Pos} + GfxRenderer->Mouse_Position()}; + auto const part{node_at(point)}; + if ((m_target.vehicle != nullptr) && (false == part.has_value())) + { + return false; + } + if (m_placing) + { + place_light(point, part); + return true; + } + if (part) + { + select(*part); + m_scrolltoselected = true; + } + return true; +} + +bool eu07m_model_panel::remove_selected() +{ + if ((false == m_active) || (m_selected < 0) || (m_selected >= static_cast(m_model.nodes.size()))) + { + return false; + } + auto const index{static_cast(m_selected)}; + auto *target{submodel(index)}; + if ((false == light_of(index).has_value()) || (target == nullptr) || (target->Parent == nullptr) || (false == eu07m::node_removable(m_model, index))) + { + return false; + } + auto before{take(true)}; + auto *parent{target->Parent}; + auto const name{part_name(index)}; + if (false == eu07m::remove_node(m_model, index)) + { + return false; + } + auto *previous{m_source->UnlinkEditorSubmodel(*target)}; + m_submodels.erase(m_submodels.begin() + index); + m_boxes.erase(m_boxes.begin() + index); + before.change = {tree_change::kind::removed, index, target, parent, previous}; + push_change(std::move(before)); + m_before = take(false); + m_selected = -1; + m_message = std::vformat(STR("Removed the light {}. Ctrl+Z brings it back"), std::make_format_args(name)); + return true; } void eu07m_model_panel::fly_to(std::uint32_t const Node) const @@ -1206,14 +2294,11 @@ void eu07m_model_panel::fly_to(std::uint32_t const Node) const focus(point_of(*where, glm::dvec3{target->offset(0.01f)}), node_focus_radius); } -void eu07m_model_panel::render_model_components() +void eu07m_model_panel::fly_to_vehicle(TDynamicObject const &Vehicle) const { - for (std::uint32_t idx = 0; idx < m_model.components.size(); ++idx) + if (focus != nullptr) { - if (m_model.components[idx].kind == eu07m::target_kind::model) - { - render_component(idx); - } + focus(Vehicle.GetPosition(), std::max(5.0, Vehicle.MoverParameters->Dim.L * vehicle_focus)); } } @@ -1235,7 +2320,7 @@ void eu07m_model_panel::render_clips(TAnimModel &Instance) if (ImGui::Checkbox(STR_C("Looped"), &looped) | ImGui::Checkbox(STR_C("Plays on its own"), &autoplay)) { clip.flags = (looped ? eu07m::clip_flags::loop : 0u) | (autoplay ? eu07m::clip_flags::autoplay : 0u); - m_dirty = true; + changed(); } // the editor stops the time: the clip is held at the time picked if (ImGui::SliderFloat(STR_C("Time, s"), &m_cliptimes[idx], 0.f, std::max(clip.duration, 0.001f), "%.2f")) @@ -1281,19 +2366,19 @@ void eu07m_model_panel::save() } auto const data{eu07m::write(m_model)}; auto const temporary{m_path + ".tmp"}; - { - std::ofstream file{temporary, std::ios::binary}; - file.write(reinterpret_cast(data.data()), static_cast(data.size())); - if (false == file.good()) - { - m_message = STR("Not saved: the file can't be written"); - return; - } - } + std::ofstream file{temporary, std::ios::binary | std::ios::trunc}; + file.write(reinterpret_cast(data.data()), static_cast(data.size())); + // closed before the check: the buffer is written out there, and a fault of it (a full disk) is seen + file.close(); std::error_code error; - std::filesystem::rename(temporary, m_path, error); - if (error) + if (false == file.fail()) { + std::filesystem::rename(temporary, m_path, error); + } + if (file.fail() || error) + { + // the model stays as it was, the file cut short goes + std::filesystem::remove(temporary, error); m_message = STR("Not saved: the file can't be written"); return; } diff --git a/application/editoruimodel.h b/application/editoruimodel.h index 046fbbdab..094d89fa2 100644 --- a/application/editoruimodel.h +++ b/application/editoruimodel.h @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "model/eu07m/eu07m_model.h" +#include #include #include @@ -19,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include class TAnimModel; @@ -30,75 +32,199 @@ namespace scene class basic_node; } -// the window of an EU07M model: of the scenery instance selected in the editor, or with nothing selected, of the vehicle driven. the -// tree of its nodes beside the properties of the one picked (its place, range, components and the part of the vehicle it's in), -// the lamps, couplers, hoses and pantographs of the vehicle to hold, and the clips and the channels of a scenery model to try on -// the instance. in the 3d view the node picked is framed and moved with a gizmo, and the light sources are marked. what is edited -// shows on the model at once; the geometry, the mapping and the materials aren't edited here +// the field of work of the models in the editor: an EU07M model of a scenery model or of a vehicle, edited by someone who doesn't +// know the format. the window of the node bank says what is edited and lets a vehicle be picked, the tool options hold the page of +// the tool chosen in the toolbar (the lights, the parts of the vehicle, all the parts of the model, the animations), the inspector +// the settings of the part picked. a click on the model picks its part, a light is put where the model is clicked, and the part +// picked is moved with a gizmo in the 3d view. what is edited shows on the model at once and is taken back with Ctrl+Z; the file +// is written on Save. the geometry, the mapping and the materials aren't edited here class eu07m_model_panel { public: - void render(scene::basic_node *Node); + enum class tool : int + { + lights, + parts, + elements, + animations + }; + + // once a frame, after the windows: the model of the scenery node selected, of the vehicle picked or of the vehicle driven. Active: + // the field of work of the models is the one in use; only then is the model shown changed, and the 3d view drawn over + void update(scene::basic_node *Selected, bool Active); + // what is edited, and the vehicles to pick from: in the window of the node bank + void render_bank(); + // the page of the tool chosen: in the tool options window + void render_tools(); + // the settings of the part picked: in the inspector + void render_selection(); + // the left button in the 3d view came down on Picked (none: nothing of the scenery, or a vehicle). true when the press picked a + // part of the model shown or put a light on it, then it doesn't select anything in the scenery + bool pick(scene::basic_node const *Picked); + // the last change of the model taken back, or made again; false when there's none + bool undo(); + bool redo(); + // the part picked taken out, when it's a light source that can be (Del) + bool remove_selected(); + // a scenery model has a file of the format to edit + bool editable(scene::basic_node const *Node) const; + + tool current_tool() const { return m_tool; } + void choose_tool(tool Tool); + bool has_vehicle() const { return m_target.vehicle != nullptr; } + bool has_animations() const; + bool marks_shown() const { return m_marks; } + void show_marks(bool Shown) { m_marks = Shown; } + bool turning() const { return m_gizmo == gizmo::turn; } + void set_turning(bool Turning) { m_gizmo = Turning ? gizmo::turn : gizmo::move; } + // moves the camera to look at a point of the world, framing a sphere of the radius given std::function focus; - // the gizmo of the node picked is shown in the 3d view, in place of the one of the editor + // puts a model of the file (relative to the folder of the models) in the scenery, in front of the camera, and selects it + std::function place_model; + // takes the editor to the tool which puts a vehicle on a track + std::function place_vehicle; + // the model as a whole is moved with the gizmo of the editor, in place of its part picked + bool moves_whole() const { return m_whole && (m_target.instance != nullptr); } + void set_whole(bool Whole) { m_whole = Whole; } + // the gizmo of the part picked is shown in the 3d view, in place of the one of the editor bool gizmo_shown() const { return m_gizmoshown; } // the last press of the left button in the 3d view went to the gizmo or to a mark of a light, not to picking a node bool took_press() const { return m_tookpress; } // picks the first node of the name in the model shown; false when it has none (the self-test of the editor) bool select_node(std::string_view Name); + // a light added in the middle of the part picked, as a click there adds it (the self-test of the editor) + bool add_test_light(bool Spot); + // the model shown, without a file of the format, given one made of it as the game has it; false when it can't be + bool import_model(); private: - enum class gizmo : int { none, move, turn }; + enum class gizmo : int + { + move, + turn + }; + using box = std::pair; + // what is edited: a scenery model, or the body or the cab of a vehicle + struct target + { + TAnimModel *instance{nullptr}; + TDynamicObject *vehicle{nullptr}; + int part{0}; // of the vehicle: 0 the body, 1 the cab + bool operator==(target const &) const = default; + }; + // a change of the tree of the nodes: a light added or taken out, as the model the game has is to follow it + struct tree_change + { + enum class kind : int + { + none, + added, + removed + }; + kind what{kind::none}; + std::uint32_t index{0}; // of the node + TSubModel *submodel{nullptr}; + TSubModel *parent{nullptr}; + TSubModel *previous{nullptr}; // the child of the parent before it, none when it's the first + }; + // the model as it was before a change: the nodes and the components, or the whole of it when the tree changed + struct snapshot + { + std::vector nodes; + std::vector components; + std::vector component_data; + std::vector clips; + std::optional whole; + tree_change change; + }; + target wanted(scene::basic_node *Selected) const; + void open(target const &Target); bool load(TModel3d &Model); + void render_unsaved_popup(); + // the models of the folder of the models to put in the scenery + void render_insert(); void render_header(); - void render_model_tab(); + void render_guide() const; + void render_lights_page(); + void render_parts_page() const; + void render_elements_page(); void render_tree_node(std::uint32_t Index); - void render_properties(); - // the lamps, the coupler hooks, the hoses and the pantographs of the vehicle, held as they're set here - void render_parts_tab() const; - // the hold of the part of the vehicle the node is in, if it's in one - void render_node_hold(std::uint32_t Index) const; - void render_node_settings(std::uint32_t Index); - void render_component(std::uint32_t Index); - void render_model_components(); + void render_animations_page(); void render_clips(TAnimModel &Instance); void render_channels(TAnimModel &Instance); - // over the 3d view: the frame of the node picked, the marks of the light sources and the gizmo + void render_light_settings(std::uint32_t Component); + void render_place(std::uint32_t Index); + void render_advanced(std::uint32_t Index); + void render_component(std::uint32_t Index); + // over the 3d view: the frame of the part picked, the marks of the light sources and the gizmo void render_view(); + // the marks of the light sources; a click on one picks its node + void render_marks(glm::dmat4 const &Placement, bool Clicked); void render_gizmo(glm::dmat4 const &Placement, glm::dvec3 const &Camera); void select(std::uint32_t Node); // the submodel of the node in the model the game has, or none when that model doesn't match the file TSubModel *submodel(std::uint32_t Node) const; // where the model is drawn: its space in the world std::optional placement() const; + // the part of the model at the point of the world: the smallest box of geometry holding it + std::optional node_at(glm::dvec3 const &Point) const; + // the light source of the node, the first one when it has more + std::optional light_of(std::uint32_t Node) const; + // the name of the part in words: the part of the vehicle it is, or the name of its node + std::string part_name(std::uint32_t Node) const; // the change of a component shown on the model the game has void show_change(std::uint32_t Index) const; void moved(std::uint32_t Node); - void add_light(std::uint32_t Parent); + // a change made: the model before it kept to be taken back, once a press of the mouse or a drag + void changed(); + snapshot take(bool Whole) const; + void restore(snapshot const &Snapshot); + void apply_tree(tree_change const &Change, bool Forward); + void push_change(snapshot Snapshot); + // after a change taken back or made again: the lights shown as they are, the next change kept from here + void settled(); + void add_light(std::uint32_t Parent, glm::vec3 const &Position, glm::quat const &Rotation, bool Spot); + void place_light(glm::dvec3 const &Point, std::optional Part); void fly_to(std::uint32_t Node) const; + void fly_to_vehicle(TDynamicObject const &Vehicle) const; void save(); - bool m_open{true}; - bool m_tofront{false}; // the window is brought to the front in the next frame + bool m_active{false}; + target m_target; // shown + std::optional m_pending; // asked for while the one shown has changes not saved + std::optional m_kept; // the one shown kept although another was asked for: it isn't asked again until another one is + TDynamicObject *m_pickedvehicle{nullptr}; // in the window of the node bank + int m_part{0}; // of a vehicle, the one wanted: 0 the body, 1 the cab + scene::basic_node *m_lastselected{nullptr}; TModel3d *m_source{nullptr}; // the model shown, as the game has it - TAnimModel *m_instance{nullptr}; // the scenery instance shown, none for a vehicle - TDynamicObject *m_vehicle{nullptr}; // the vehicle shown, none for a scenery instance - int m_vehiclepart{0}; // 0: the body of the vehicle, 1: its cab std::string m_path; // of the .eu07m file, empty when the model has none + std::string m_problem; // why the model shown can't be edited eu07m::model m_model; std::vector m_submodels; // of the nodes of the file, in the model the game has; empty when they don't match + std::vector> m_boxes; // of the geometry of the nodes, each in its space bool m_dirty{false}; std::string m_message; std::int64_t m_selected{-1}; // the node picked bool m_scrolltoselected{false}; - std::optional> m_box; // of the geometry of the node picked, in its space + tool m_tool{tool::lights}; gizmo m_gizmo{gizmo::move}; bool m_marks{true}; // the light sources marked in the 3d view bool m_gizmoshown{false}; bool m_tookpress{false}; - int m_lightkind{0}; // of the light source to add: 0 a point, 1 a spot + std::optional m_placing; // a light to be put where the model is clicked: a spot or a point light + std::vector m_undo; + std::vector m_redo; + snapshot m_before; // the model when no press or drag was going on + bool m_changing{false}; // the press or the drag going on has changed the model, its change is kept + std::string m_filter; // of the parts in the list of all of them + bool m_importable{false}; // the model shown has no file of the format, one can be made of it + bool m_whole{false}; + bool m_scanned{false}; // the folder of the models was looked through + std::vector m_files; // of the models, relative to their folder + std::vector m_found; // those of them the search takes + std::string m_filesearch; std::vector m_cliptimes; // the times the clips are held at, seconds std::vector m_channels; // the values the channels were set to }; diff --git a/docs/eu07m-format.md b/docs/eu07m-format.md index 1dc56a582..63735653f 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -290,34 +290,53 @@ With `modelformat eu07m` in `eu07.ini`, a model with an `.eu07m` file beside its ### In the editor -Selecting a scenery model loaded from an `.eu07m` file opens the "EU07M model" window (`application/editoruimodel.cpp`). With -nothing selected, the window shows the model of the vehicle driven (its body or its cab), so a vehicle can be driven, the editor -opened with F11, a light changed and looked at from the cab again after F11: +The models are a field of work of the editor of their own, "Models" (F7), beside the surroundings, the tracks, the roads, the +terrain and the catenary (`application/editoruimodel.cpp`). It is made for someone who doesn't know the format: the parts are +called by what they are (a part of a vehicle by its name, such as "Left headlamp, front"), and the fields of the format are kept +under "Advanced". The model edited is the scenery model selected, a vehicle picked in the list of the vehicles, or with neither, +the vehicle driven (its body or its cab), so a vehicle can be driven, the editor opened with F11, a light changed and looked at +from the cab again after F11. "Edit this model (F7)" in the inspector of a scenery model loaded from an `.eu07m` file opens it +there. A model without an `.eu07m` file, or one which can't be read, says so and isn't edited. -- the file, and the tree of the nodes with their transforms and the components aimed at each of them, then the components of the - model; -- the fields of the common components to edit: `SOCK`, `JOIN`, `CHNL` with its bindings, `LGHT`, `LSLT`, `EMIT`, `COLL`, `MREF`; - the others are shown by their size. Strings are edited by their text. A `LGHT` changed shows at once on the model the game has - (on every instance of it), before the file is saved; -- the "Model" tab holds the tree of the nodes beside the properties of the node picked (a click picks, a double click flies the - camera to the node); the other tabs hold the parts of the vehicle, the clips and the channels, and the components of the model; -- in the 3d view the node picked is framed and shows its axes and a gizmo, which moves or turns it; the light sources are marked - with their colour (a spot with its axis, the -z of its node), and a click on a mark picks its node. A press on the gizmo or on a - mark doesn't pick a scenery node; -- the settings of a node: its position, its rotation (in degrees) and its scale, unless a matrix of `XFRM` places it, and the - distances it is drawn from and up to. "Add a light source here" puts in a new node, `light_`, as the last child of the node, - with a `LGHT` point or spot light; the references to the nodes after it move on (`eu07m::insert_node`). A change of a node or - of a light, and a light added, show on the model the game has at once (on every instance of it), when that model is the one of - the file; the spot's cones are edited as half angles in degrees; -- for the vehicle driven, "Parts of the vehicle" holds its pantographs up or down, and its lamps, coupler hooks and hoses - (`headlamp11`, `coupler1`, `cpneumatic1` and the like) in the `_off`, `_on` or `_xon` state of their submodels, whatever the - vehicle does with them, until they're set back to Automatic. A held pantograph moves at its own pace, in the editor too, up to - the wire above it when there is one (1.6 m over its rest without one). A node that is in one of those parts shows its switch in - the tree; -- the clips, with their flags to edit and a time to hold the instance at (the time stands still in the editor), and the channels of - the model, set on the instance with a slider, which tries them without changing the file; -- "Save the model" checks the model and writes the file again (the store of the family is kept); the game uses the change once it - loads the model again. "Read it again" drops the changes. +- **A model without a file of the format.** "Import to EU07M" writes `.eu07m` beside its `.e3d` (or its `.t3d`), made of + the model as the game loaded it, as `eu07 -eu07m convert` makes it (`eu07m::import_model`); for a vehicle, its body or its cab, + that is what the game writes to the `.e3d` it makes of a `.t3d`. From then on the game loads the model from it, in every + scenery. So a model of the data whose lights aren't set, such as a lamp post or a cab with its one default light, gets its light + sources here. +- **Models and vehicles in the scenery loaded.** "Put a model in the scenery" lists the `.e3d` and `.t3d` files of the folder of + the models; a click puts one in front of the camera, selected (a change of the scenery, taken back with Ctrl+Z and saved with + it). "Whole model" in the toolbar hands the gizmo of the editor the scenery model shown, to move or turn it in the scenery. + "Put a vehicle on a track..." opens the Trainset tool of the tracks. +- **The windows.** The window of the node bank says what is edited and lists the vehicles (a click picks one and takes the camera + to it). The tool options hold the page of the tool chosen in the toolbar, with "Save the changes", "Undo" and "Redo" and a short + "How it works". The inspector holds the settings of the part picked. +- **The tools.** "Lights" lists the light sources of the model; "+ Add a bulb" and "+ Add a spot" put one where the model is + clicked next, a spot shining towards the camera, as the last child of the part clicked (`light_`, a `LGHT` point or spot + light; the references to the nodes after it move on, `eu07m::insert_node`). "Parts of the vehicle" holds the pantographs of the + vehicle up or down, and its lamps, coupler hooks and hoses (`headlamp11`, `coupler1`, `cpneumatic1` and the like) in the `_on`, + `_off` or `_xon` state of their submodels, whatever the vehicle does with them, until "As the vehicle has it"; a held pantograph + moves at its own pace, in the editor too, up to the wire above it when there is one (1.6 m over its rest without one). Nothing + of these holds goes into the file. "All parts" is the tree of the nodes with a search by name. "Animations" holds the clips of a + scenery model, with their flags and a time to hold the instance at (the time stands still in the editor), and its channels, + tried on the instance without changing the file. "Move", "Turn" and "Marks of the lights" set the gizmo and the marks. +- **The 3d view.** A click on the model picks its part: the smallest box of geometry of a part shown holding the point clicked. A + click on another scenery model edits that one; a click on anything else changes nothing. The part picked is framed and shows its + axes and a gizmo, which moves or turns it. The light sources are marked with their colour (a spot with its axis, the -z of its + node), and a click on a mark picks its light. A press on the gizmo or on a mark doesn't pick a scenery node. +- **The settings of a part.** A light: a bulb or a spot, its colour (with a few common ones), its brightness, its glowing spot, + the width of the beam and its bright middle (in degrees from its axis), and whether it casts shadows, has a soft edge and lights + its own model. The place: the gizmo, and under "Exact values" the position, the rotation (in degrees) and the scale, unless a + matrix of `XFRM` places the node; and the distances it is seen from and up to. A light which nothing else points at is taken out + with "Remove this light" or Del (`eu07m::remove_node`). "Advanced" holds the fields of the common components (`SOCK`, `JOIN`, + `CHNL` with its bindings, `LGHT`, `LSLT`, `EMIT`, `COLL`, `MREF`; the others are shown by their size, strings are edited by their + text) and "Add a light to this part". +- **Changes.** A change shows at once on the model the game has (on every instance of it), when that model is the one of the file. + Ctrl+Z and Ctrl+Y take the changes of the model back and make them again, a light added or taken out among them, and then those + of the scenery (a model put in or moved as a whole); with "Whole model" chosen, those of the scenery. Del doesn't delete scenery + nodes in this field of work. "Save the changes" checks the model and writes the + file again (the store of the family is kept); the game uses the change once it loads the model again. Another model asked for + while the one edited has changes not saved asks first whether to save them, throw them away (the model the game has goes back + to the file) or go on with the one edited. The geometry, the mapping and the materials aren't edited there; that is the work of the exporter. diff --git a/editor/editorIcons.hpp b/editor/editorIcons.hpp index 7118b470f..01c55cbd2 100644 --- a/editor/editorIcons.hpp +++ b/editor/editorIcons.hpp @@ -70,6 +70,12 @@ enum class icon work_catenary, gantry, wires, + // the models, after the catenary for the same reason + work_models, + light, + pantograph, + parts_tree, + animation, count }; diff --git a/editor/icons/editor_icons.png b/editor/icons/editor_icons.png index f1305097c..57da9f95f 100644 Binary files a/editor/icons/editor_icons.png and b/editor/icons/editor_icons.png differ diff --git a/editor/icons/editor_icons.py b/editor/icons/editor_icons.py index f18774a38..a6d2ab2c3 100644 --- a/editor/icons/editor_icons.py +++ b/editor/icons/editor_icons.py @@ -476,12 +476,50 @@ def wires(d): line(d, [(4, 48), (60, 48)], W - 4) +def work_models(d): + # a box seen from a corner: the outline and the three edges meeting in the near corner + poly(d, [(32, 4), (58, 18), (58, 46), (32, 60), (6, 46), (6, 18)], outline=True, width=W - 6) + line(d, [(6, 18), (32, 32), (58, 18)], W - 6) + line(d, [(32, 32), (32, 60)], W - 6) + + +def light(d): + # a bulb: the glass, the neck and the cap + circle(d, 32, 24, 18) + rect(d, 24, 40, 40, 48) + rect(d, 27, 51, 37, 58, radius=2) + + +def pantograph(d): + # the roof, the crossed arms of the frame and the head on top + line(d, [(8, 58), (56, 58)], W - 6) + line(d, [(18, 58), (42, 34), (24, 12)], W - 8) + line(d, [(46, 58), (22, 34), (40, 12)], W - 8) + line(d, [(8, 10), (56, 10)], W - 4) + + +def parts_tree(d): + # a part and the parts under it, as a tree + rect(d, 6, 6, 24, 20, radius=2) + line(d, [(14, 20), (14, 50)], W - 10) + line(d, [(14, 32), (30, 32)], W - 10) + line(d, [(14, 50), (30, 50)], W - 10) + rect(d, 32, 25, 58, 39, radius=2) + rect(d, 32, 43, 58, 57, radius=2) + + +def animation(d): + # play in a ring + circle(d, 32, 32, 26, outline=True, width=W - 6) + poly(d, [(25, 19), (25, 45), (47, 32)]) + + ICONS = [select, insert, brush, area_fill, copy_to_bank, translate, rotate, scale, local_space, ortho, perspective, sculpt, smooth, chunks, orthophoto, road, place, lanes, lay_track, switch, straight, curve, signal, objects, vehicle, profile, speed, joints, infra, gauge, turntable, parallel, station, kilometrage, more, work_surroundings, work_tracks, work_roads, work_terrain, station_signals, line_block, hole, grass, catenary, - work_catenary, gantry, wires] + work_catenary, gantry, wires, work_models, light, pantograph, parts_tree, animation] def cutouts(name, d): diff --git a/lang/editor_pl.po b/lang/editor_pl.po index bee4f2c7c..845bbc18d 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -16434,12 +16434,6 @@ msgstr "Kolor" msgid "Intensity" msgstr "Natężenie" -msgid "Cosine of the cone" -msgstr "Cosinus stożka" - -msgid "Cosine of the hotspot" -msgstr "Cosinus plamy" - msgid "Slot" msgstr "Slot" @@ -16488,27 +16482,6 @@ msgstr "{} B, nie edytowane tutaj" msgid "Binding {}" msgstr "Powiązanie {}" -msgid "EU07M model" -msgstr "Model EU07M" - -msgid "Nodes and their components" -msgstr "Węzły i ich komponenty" - -msgid "{} nodes, {} components, {} clips, {} vertices" -msgstr "węzły: {}, komponenty: {}, klipy: {}, wierzchołki: {}" - -msgid "Save the model" -msgstr "Zapisz model" - -msgid "Read it again" -msgstr "Wczytaj ponownie" - -msgid " [{} components]" -msgstr " [komponenty: {}]" - -msgid "Components of the model" -msgstr "Komponenty modelu" - msgid "Animation clips" msgstr "Klipy animacji" @@ -16554,9 +16527,6 @@ msgstr "Pantograf {}" msgid "Parts of the vehicle" msgstr "Części pojazdu" -msgid "Held as set here, whatever the vehicle does; Automatic gives them back to it" -msgstr "Trzymane tak, jak ustawiono tutaj, cokolwiek robi pojazd; Automatycznie oddaje je pojazdowi" - msgid "Properties" msgstr "Właściwości" @@ -16680,15 +16650,6 @@ msgstr "Wąż zasilający, tył" msgid "Supply hose, rear, other side" msgstr "Wąż zasilający, tył, druga strona" -msgid "Lamp off" -msgstr "Zgaszona" - -msgid "Lamp on" -msgstr "Zapalona" - -msgid "Lamp dimmed" -msgstr "Przyciemniona" - msgid "Disconnected" msgstr "Rozłączony" @@ -16698,12 +16659,6 @@ msgstr "Połączony" msgid "Other position" msgstr "Inne położenie" -msgid "Pantograph down" -msgstr "Opuszczony" - -msgid "Pantograph up" -msgstr "Podniesiony" - msgid "Pantographs" msgstr "Pantografy" @@ -16728,27 +16683,9 @@ msgstr "Widoczny od, m" msgid "Visible up to, m (0: no limit)" msgstr "Widoczny do, m (0: bez limitu)" -msgid "Settings of the node" -msgstr "Ustawienia węzła" - -msgid "Placed by a matrix (XFRM), not edited here" -msgstr "Położony macierzą (XFRM), nie edytuje się go tutaj" - -msgid "Kind of the light" -msgstr "Rodzaj światła" - -msgid "Add a light source here" -msgstr "Dodaj tu źródło światła" - -msgid "Added the light source {}; place it in the settings of its node" -msgstr "Dodano źródło światła {}; ustaw je w ustawieniach jego węzła" - msgid "The model in the game differs from the file: the changes show once the game loads the model again" msgstr "Model w grze różni się od pliku: zmiany będą widoczne po ponownym wczytaniu modelu" -msgid "A double click on a name takes the camera there" -msgstr "Dwuklik na nazwie przenosi tam kamerę" - msgid "Glowing sphere radius, m" msgstr "Promień świecącej kuli, m" @@ -16761,26 +16698,362 @@ msgstr "Plama, połowa kąta w stopniach" msgid "Model" msgstr "Model" -msgid "Clips and channels" -msgstr "Klipy i kanały" - -msgid "Lights marked in the view" -msgstr "Znaczniki świateł w widoku" - -msgid "A click picks, a double click takes the camera there" -msgstr "Klik zaznacza, dwuklik przenosi tam kamerę" - -msgid "Pick a node in the tree, or a mark of a light in the view" -msgstr "Zaznacz węzeł w drzewie albo znacznik światła w widoku" - msgid "Move" msgstr "Przesuwaj" msgid "Turn" msgstr "Obracaj" -msgid "Part of the vehicle" -msgstr "Część pojazdu" +msgid "Lit" +msgstr "Zapalona" -msgid "Added the light source {}; move it with the gizmo in the view" -msgstr "Dodano źródło światła {}; przesuń je uchwytem w widoku" +msgid "Dimmed" +msgstr "Przyciemniona" + +msgid "As the vehicle has it" +msgstr "Jak w pojeździe" + +msgid "Light them all" +msgstr "Zapal wszystkie" + +msgid "Connect them all" +msgstr "Podłącz wszystkie" + +msgid "Put them all out" +msgstr "Zgaś wszystkie" + +msgid "Disconnect them all" +msgstr "Odłącz wszystkie" + +msgid "All as the vehicle has them" +msgstr "Wszystkie jak w pojeździe" + +msgid "The models of the EU07M format are turned off (modelformat in eu07.ini)" +msgstr "Modele w formacie EU07M są wyłączone (modelformat w eu07.ini)" + +msgid "This model has no EU07M file, so it can't be edited here. The command eu07 -eu07m convert makes one of its E3D or T3D file" +msgstr "Ten model nie ma pliku EU07M, więc nie da się go tu zmieniać. Polecenie eu07 -eu07m convert zrobi go z pliku E3D albo T3D" + +msgid "The EU07M file of the model can't be read: {}" +msgstr "Nie da się odczytać pliku EU07M tego modelu: {}" + +msgid "Changes not saved" +msgstr "Niezapisane zmiany" + +msgid "The model {} has changes which aren't saved." +msgstr "Model {} ma zmiany, które nie są zapisane." + +msgid "Save them" +msgstr "Zapisz je" + +msgid "Throw them away" +msgstr "Odrzuć je" + +msgid "Go on with this one" +msgstr "Zostań przy tym modelu" + +msgid "Edited model" +msgstr "Edytowany model" + +msgid "Nothing picked yet." +msgstr "Jeszcze nic nie wybrano." + +msgid "A model of the scenery" +msgstr "Model ze scenerii" + +msgid "Click a model in the view to edit it." +msgstr "Kliknij model w widoku, żeby go edytować." + +msgid "Back to {}" +msgstr "Wróć do {}" + +msgid "Vehicles" +msgstr "Pojazdy" + +msgid "The scenery has no vehicles." +msgstr "W scenerii nie ma pojazdów." + +msgid "A click picks the vehicle and takes the camera to it" +msgstr "Kliknięcie wybiera pojazd i przenosi do niego kamerę" + +msgid "(driven)" +msgstr "(prowadzony)" + +msgid "No model to edit. Click a model in the scenery, or pick a vehicle in the list on the left." +msgstr "Nie ma modelu do edycji. Kliknij model w scenerii albo wybierz pojazd z listy po lewej." + +msgid "Save the changes" +msgstr "Zapisz zmiany" + +msgid "Writes the model to its file; until then nothing of it is changed on the disk" +msgstr "Zapisuje model do jego pliku; do tego czasu nic nie zmienia się na dysku" + +msgid "Takes the last change of the model back (Ctrl+Z)" +msgstr "Cofa ostatnią zmianę modelu (Ctrl+Z)" + +msgid "Makes the change taken back again (Ctrl+Y)" +msgstr "Przywraca cofniętą zmianę (Ctrl+Y)" + +msgid "Not saved" +msgstr "Niezapisane" + +msgid "How it works" +msgstr "Jak to działa" + +msgid "1. Pick the model: click it in the scenery, or pick a vehicle in the list on the left." +msgstr "1. Wybierz model: kliknij go w scenerii albo wybierz pojazd z listy po lewej." + +msgid "2. Click a part of the model in the view. Its settings come up in the inspector." +msgstr "2. Kliknij część modelu w widoku. Jej ustawienia pojawią się w inspektorze." + +msgid "3. Drag the arrows in the view to move the part picked, or the rings to turn it: Move and Turn are in the toolbar." +msgstr "3. Przeciągnij strzałki w widoku, żeby przesunąć wybraną część, albo pierścienie, żeby ją obrócić: Przesuwaj i Obracaj są na pasku narzędzi." + +msgid "4. Ctrl+Z takes a change back. Nothing goes into the file until Save the changes." +msgstr "4. Ctrl+Z cofa zmianę. Nic nie trafia do pliku przed kliknięciem Zapisz zmiany." + +msgid "The light sources of the model. Click one to change it in the inspector; its round mark in the view does the same." +msgstr "Źródła światła modelu. Kliknij jedno, żeby zmienić je w inspektorze; to samo robi kliknięcie jego kółka w widoku." + +msgid "Click the model where the light is to be. Esc gives it up." +msgstr "Kliknij model w miejscu, gdzie ma być światło. Esc rezygnuje." + +msgid "Give it up" +msgstr "Zrezygnuj" + +msgid "+ Add a bulb" +msgstr "+ Dodaj żarówkę" + +msgid "A light which shines all around, as a bulb; then a click on the model puts it there" +msgstr "Światło świecące dookoła, jak żarówka; potem kliknięcie modelu stawia je w tym miejscu" + +msgid "+ Add a spot" +msgstr "+ Dodaj reflektor" + +msgid "A light which shines one way, as a headlamp; then a click on the model puts it there, shining towards the camera" +msgstr "Światło świecące w jedną stronę, jak reflektor; potem kliknięcie modelu stawia je w tym miejscu, świecące w stronę kamery" + +msgid "Marks of the lights in the view" +msgstr "Kółka świateł w widoku" + +msgid "Lights of the model" +msgstr "Światła modelu" + +msgid "bulb" +msgstr "żarówka" + +msgid "The model has no light sources yet." +msgstr "Model nie ma jeszcze źródeł światła." + +msgid "The parts of a vehicle are held on its body: pick the body on the left." +msgstr "Części pojazdu ustawia się na nadwoziu: wybierz nadwozie po lewej." + +msgid "The vehicle keeps a part as set here until As the vehicle has it is chosen. Nothing of it goes into the file." +msgstr "Pojazd trzyma część tak, jak ją tu ustawisz, dopóki nie wybierzesz Jak w pojeździe. Nic z tego nie trafia do pliku." + +msgid "All the parts of the model, as they hang one on another. A click picks one, a double click takes the camera to it." +msgstr "Wszystkie części modelu, tak jak jedna wisi na drugiej. Kliknięcie wybiera część, dwuklik przenosi do niej kamerę." + +msgid "Look for a part by its name" +msgstr "Szukaj części po nazwie" + +msgid "The animations are tried on a model of the scenery." +msgstr "Animacje sprawdza się na modelu ze scenerii." + +msgid "The animations of the model, tried on it in the view. Looped and Plays on its own go into the file." +msgstr "Animacje modelu, sprawdzane na nim w widoku. Zapętlony i Gra sam trafiają do pliku." + +msgid "Pick a model first: click it in the view, or pick a vehicle in the list on the left." +msgstr "Najpierw wybierz model: kliknij go w widoku albo wybierz pojazd z listy po lewej." + +msgid "Click a part of the model in the view, or pick one in the tool options, to change it here." +msgstr "Kliknij część modelu w widoku albo wybierz ją w opcjach narzędzia, żeby ją tu zmienić." + +msgid "A light source" +msgstr "Źródło światła" + +msgid "A part of the model" +msgstr "Część modelu" + +msgid "A point of the model, with nothing to see" +msgstr "Punkt modelu, bez niczego do zobaczenia" + +msgid "Show it in the view" +msgstr "Pokaż w widoku" + +msgid "Remove this light (Del)" +msgstr "Usuń to światło (Del)" + +msgid "Light" +msgstr "Światło" + +msgid "Bulb: shines all around" +msgstr "Żarówka: świeci dookoła" + +msgid "Spot: shines one way" +msgstr "Reflektor: świeci w jedną stronę" + +msgid "Brightness" +msgstr "Jasność" + +msgid "How strongly it lights what is around it. Ctrl+click types a value" +msgstr "Jak mocno oświetla otoczenie. Ctrl+klik pozwala wpisać wartość" + +msgid "Glowing spot, m" +msgstr "Świecąca plamka, m" + +msgid "The size of the glowing ball seen where the light is; 0 shows none" +msgstr "Wielkość świecącej kuli widocznej w miejscu światła; 0 – bez kuli" + +msgid "Width of the beam, degrees" +msgstr "Szerokość snopu, stopnie" + +msgid "From the axis of the beam to its edge" +msgstr "Od osi snopu do jego krawędzi" + +msgid "Bright middle, degrees" +msgstr "Jasny środek, stopnie" + +msgid "The middle of the beam lit fully; from there to the edge it fades" +msgstr "Środek snopu świeci w pełni; dalej do krawędzi światło słabnie" + +msgid "Casts shadows" +msgstr "Rzuca cienie" + +msgid "Soft edge" +msgstr "Miękka krawędź" + +msgid "Lights this model too" +msgstr "Oświetla też ten model" + +msgid "This part is placed in a way this window doesn't change" +msgstr "Ta część jest ustawiona w sposób, którego to okno nie zmienia" + +msgid "Drag the arrows in the view to move it, or the rings to turn it." +msgstr "Przeciągnij strzałki w widoku, żeby ją przesunąć, albo pierścienie, żeby ją obrócić." + +msgid "Seen from" +msgstr "Widoczność" + +msgid "Advanced: the data of the file" +msgstr "Zaawansowane: dane pliku" + +msgid "For those who know the EU07M format" +msgstr "Dla znających format EU07M" + +msgid "Add a light to this part" +msgstr "Dodaj światło do tej części" + +msgid "Click the model where the light is to be" +msgstr "Kliknij model w miejscu, gdzie ma być światło" + +msgid "Added the light {}. Drag the arrows in the view to move it" +msgstr "Dodano światło {}. Przeciągnij strzałki w widoku, żeby je przesunąć" + +msgid "Removed the light {}. Ctrl+Z brings it back" +msgstr "Usunięto światło {}. Ctrl+Z je przywróci" + +msgid "Models" +msgstr "Modele" + +msgid "The models of the vehicles and of the scenery: their lights, the parts of a vehicle, moving and turning their parts" +msgstr "Modele pojazdów i scenerii: ich światła, części pojazdu, przesuwanie i obracanie ich części" + +msgid "The light sources of the model: change them, add them by a click on the model" +msgstr "Źródła światła modelu: zmieniaj je i dodawaj kliknięciem w model" + +msgid "Pantographs up or down, lamps lit or off, couplers and hoses connected or not" +msgstr "Pantografy w górze lub w dole, lampy zapalone lub zgaszone, sprzęgi i węże podłączone lub nie" + +msgid "All parts" +msgstr "Wszystkie części" + +msgid "All the parts of the model as a tree, with a search by name" +msgstr "Wszystkie części modelu jako drzewo, z wyszukiwaniem po nazwie" + +msgid "Animations" +msgstr "Animacje" + +msgid "The animations of the model, tried in the view" +msgstr "Animacje modelu, sprawdzane w widoku" + +msgid "The arrows in the view move the part picked" +msgstr "Strzałki w widoku przesuwają wybraną część" + +msgid "The rings in the view turn the part picked" +msgstr "Pierścienie w widoku obracają wybraną część" + +msgid "Marks of the lights" +msgstr "Kółka świateł" + +msgid "The round marks of the light sources in the view; a click on one picks the light" +msgstr "Okrągłe znaczniki źródeł światła w widoku; kliknięcie znacznika wybiera światło" + +msgid "Edit this model (F7)" +msgstr "Edytuj ten model (F7)" + +msgid "Warm white" +msgstr "Ciepła biel" + +msgid "White" +msgstr "Biel" + +msgid "Cold white" +msgstr "Zimna biel" + +msgid "Red" +msgstr "Czerwony" + +msgid "Yellow" +msgstr "Żółty" + +msgid "Green" +msgstr "Zielony" + +msgid "Blue" +msgstr "Niebieski" + +msgid "This model has no EU07M file yet. Import it to change its lights and parts." +msgstr "Ten model nie ma jeszcze pliku EU07M. Zaimportuj go, żeby zmieniać jego światła i części." + +msgid "Put a vehicle on a track..." +msgstr "Postaw pojazd na torze..." + +msgid "The Trainset tool of the tracks: click a track, pick the vehicle and Place it; F7 brings you back here" +msgstr "Narzędzie Skład w torach: kliknij tor, wybierz pojazd i postaw go; F7 wraca tutaj" + +msgid "Put a model in the scenery" +msgstr "Wstaw model do scenerii" + +msgid "Look for a model by its name, e.g. latarnia" +msgstr "Szukaj modelu po nazwie, np. latarnia" + +msgid "A click puts the model in front of the camera; then Whole model in the toolbar moves it" +msgstr "Kliknięcie stawia model przed kamerą; potem Cały model na pasku narzędzi pozwala go przestawić" + +msgid "Not imported: {}" +msgstr "Nie zaimportowano: {}" + +msgid "Imported to {}. Its lights and parts can be changed now" +msgstr "Zaimportowano do {}. Teraz można zmieniać jego światła i części" + +msgid "Import to EU07M" +msgstr "Importuj do EU07M" + +msgid "Writes an .eu07m file beside the model, made of the model as the game has it. From then on the game loads the model from it, in every scenery" +msgstr "Zapisuje plik .eu07m obok modelu, zrobiony z modelu wczytanego w grze. Od tej chwili gra wczytuje model z tego pliku, w każdej scenerii" + +msgid "Click a track, pick the vehicle and Place it; F7 goes back to the models" +msgstr "Kliknij tor, wybierz pojazd i postaw go; F7 wraca do modeli" + +msgid "The model %s couldn't be put in, the log says why" +msgstr "Nie udało się wstawić modelu %s, powód jest w logu" + +msgid "%s stands in the scenery; Whole model in the toolbar moves it" +msgstr "%s stoi w scenerii; Cały model na pasku narzędzi pozwala go przestawić" + +msgid "Whole model" +msgstr "Cały model" + +msgid "The gizmo moves or turns the whole model in the scenery, not its part; the change is one of the scenery, saved with it" +msgstr "Uchwyt przesuwa albo obraca cały model w scenerii, a nie jego część; to zmiana scenerii, zapisywana razem z nią" diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 072168fc0..21f52b2b9 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -821,9 +821,10 @@ bool TAnimModel::play_clip( std::string_view const Name, float const Speed, floa if( found == clips.end() ) { return false; } auto const index { static_cast( std::distance( clips.begin(), found ) ) }; std::erase_if( m_clips, [ index ]( clip_playing const &Playing ) { return Playing.clip == index; } ); - // started as long before now as From takes at the pace - auto const pace { std::max( Speed, 1e-3f ) }; - m_clips.push_back( { index, Timer::GetTime() - static_cast( From / pace ), pace } ); + // started as long before now as From takes at the pace; a pace of 0 holds the clip at its start and a negative one runs it + // backwards, as before, From counted only for a clip going forwards + auto const ahead { Speed > 0.f ? static_cast( From / Speed ) : 0.0 }; + m_clips.push_back( { index, Timer::GetTime() - ahead, Speed } ); m_autoplaystarted = true; return true; } diff --git a/model/AnimModel.h b/model/AnimModel.h index 66ecad0b6..b39e4d927 100644 --- a/model/AnimModel.h +++ b/model/AnimModel.h @@ -192,8 +192,8 @@ public: glm::mat4 const &rotation_scale(); void RaAnimate( unsigned int const Framestamp ); // przeliczenie animacji egzemplarza // starts the animation clip of the model (EU07M) with the name at From seconds of it (its beginning by default), at Speed times its - // pace; a clip already playing starts over. with the time stopped (the editor) it holds the pose of From. false when the model has - // no clip of the name + // pace; a clip already playing starts over. with the time stopped (the editor) it holds the pose of From. From is counted only for + // a positive Speed: 0 holds the clip at its start, a negative Speed runs it backwards. false when the model has no clip of the name bool play_clip( std::string_view Name, float Speed = 1.f, float From = 0.f ); // stops the clips playing: each is held at the moment it was stopped, so the nodes stay where they were put, till a clip // started on them or an animation event of the scenery moves them diff --git a/model/Model3d.h b/model/Model3d.h index da92b2ce2..743274cb6 100644 --- a/model/Model3d.h +++ b/model/Model3d.h @@ -388,6 +388,11 @@ public: void SetEditorTransform(TSubModel &Submodel, glm::mat4 const &Local); // the squared distances from which and up to which the submodel is drawn; 0 as the upper one is the default of a submodel void SetEditorRange(TSubModel &Submodel, float MinSq, float MaxSq); + // for the editor: the submodel taken out of the children of its parent, where it's no longer drawn; it stays where it's kept. + // returns the child before it, none when it was the first one or has no parent (then it isn't taken out) + TSubModel *UnlinkEditorSubmodel(TSubModel &Submodel); + // for the editor: the submodel put back among the children of Parent, after Previous, or as the first child when Previous is none + void LinkEditorSubmodel(TSubModel &Submodel, TSubModel &Parent, TSubModel *Previous); bool LoadFromFile(std::string const &FileName, bool dynamic); TSubModel *AppendChildFromGeometry(const std::string &name, const std::string &parent, const gfx::vertex_array &vertices, const gfx::index_array &indices); void SaveToBinFile(std::string const &FileName); diff --git a/model/eu07m/eu07m_build.cpp b/model/eu07m/eu07m_build.cpp index 7875996b3..880cebc0e 100644 --- a/model/eu07m/eu07m_build.cpp +++ b/model/eu07m/eu07m_build.cpp @@ -317,11 +317,26 @@ void compute_bounds(model &Model) { namespace { -// a node of the model after one put in at At moves one place on -void shift_node(std::uint32_t &Node, std::uint32_t const At) { - if (Node != no_index && Node >= At) - ++Node; -} +// how the indices of the nodes change: after a node put in at At, those from At on move one place on; after the node At taken +// out, those after it move one place back and At itself is gone +struct node_shift { + std::uint32_t at{0}; + bool removal{false}; + + void operator()(std::uint32_t &Node) const { + if (Node == no_index) + return; + if (false == removal) { + if (Node >= at) + ++Node; + return; + } + if (Node == at) + Node = no_index; + else if (Node > at) + --Node; + } +}; template bool read_at(std::span const Data, std::size_t const Offset, Type_ &Value) { if (Offset + sizeof(Type_) > Data.size()) @@ -334,19 +349,19 @@ template void write_at(std::span const Data, std::si std::memcpy(Data.data() + Offset, &Value, sizeof(Type_)); } -// Count node indices from Offset of the data -void shift_node_list(std::span const Data, std::size_t const Offset, std::size_t const Count, std::uint32_t const At) { +// Count indices from Offset of the data, each given to Visit, which may change it +template void visit_index_list(std::span const Data, std::size_t const Offset, std::size_t const Count, Visit_ const &Visit) { for (std::size_t idx = 0; idx < Count; ++idx) { auto const offset{Offset + idx * sizeof(std::uint32_t)}; - std::uint32_t node{0}; - if (false == read_at(Data, offset, node)) + std::uint32_t index{0}; + if (false == read_at(Data, offset, index)) return; - shift_node(node, At); - write_at(Data, offset, node); + Visit(index); + write_at(Data, offset, index); } } -void shift_properties(std::span const Data, std::uint32_t const At) { +template void visit_properties(std::span const Data, Visit_ const &Visit) { std::uint32_t count{0}; if (false == read_at(Data, 0, count)) return; @@ -357,26 +372,26 @@ void shift_properties(std::span const Data, std::uint32_t const At) { return; if (property.type != payload::value_type::node) continue; - shift_node(property.value[0], At); + Visit(property.value[0]); write_at(Data, offset, property); } } -void shift_spring(std::span const Data, std::uint32_t const At) { +template void visit_spring(std::span const Data, Visit_ const &Visit) { payload::spring spring; if (false == read_at(Data, 0, spring)) return; - shift_node(spring.anchor_a, At); - shift_node(spring.anchor_b, At); + Visit(spring.anchor_a); + Visit(spring.anchor_b); write_at(Data, 0, spring); } -void shift_chain(std::span const Data, std::uint32_t const At) { +template void visit_chain(std::span const Data, Visit_ const &Visit) { if (payload::chain chain; read_at(Data, 0, chain)) - shift_node_list(Data, sizeof(chain), chain.joint_count, At); + visit_index_list(Data, sizeof(chain), chain.joint_count, Visit); } -void shift_variants(std::span const Data, std::uint32_t const At) { +template void visit_variants(std::span const Data, Visit_ const &Visit) { payload::variants variants; if (false == read_at(Data, 0, variants)) return; @@ -385,29 +400,77 @@ void shift_variants(std::span const Data, std::uint32_t const At) { if (payload::variant_state state; read_at(Data, sizeof(variants) + idx * sizeof(state), state)) listsize = std::max(listsize, std::size_t{state.node_first} + state.node_count); } - shift_node_list(Data, sizeof(variants) + variants.state_count * sizeof(payload::variant_state), listsize, At); + visit_index_list(Data, sizeof(variants) + variants.state_count * sizeof(payload::variant_state), listsize, Visit); } -void shift_light_slot(std::span const Data, std::uint32_t const At) { +template void visit_light_slot(std::span const Data, Visit_ const &Visit) { if (payload::light_slot slot; read_at(Data, 0, slot)) - shift_node_list(Data, sizeof(slot), std::size_t{slot.on_count} + slot.off_count, At); + visit_index_list(Data, sizeof(slot), std::size_t{slot.on_count} + slot.off_count, Visit); } -// the nodes in the data of the component -void shift_payload(model &Model, component_record const &Record, std::uint32_t const At) { +// the data of the component, none when it runs past the data of the model +std::span payload_of(model &Model, component_record const &Record) { if (std::size_t{Record.data_offset} + Record.data_size > Model.component_data.size()) - return; - std::span const data{Model.component_data.data() + Record.data_offset, Record.data_size}; + return {}; + return {Model.component_data.data() + Record.data_offset, Record.data_size}; +} + +// the nodes in the data of the component, each given to Visit, which may change it +template void visit_payload_nodes(model &Model, component_record const &Record, Visit_ const &Visit) { + auto const data{payload_of(Model, Record)}; switch (Record.type) { - case component::properties: shift_properties(data, At); break; - case component::spring: shift_spring(data, At); break; - case component::chain: shift_chain(data, At); break; - case component::variants: shift_variants(data, At); break; - case component::light_slot: shift_light_slot(data, At); break; + case component::properties: visit_properties(data, Visit); break; + case component::spring: visit_spring(data, Visit); break; + case component::chain: visit_chain(data, Visit); break; + case component::variants: visit_variants(data, Visit); break; + case component::light_slot: visit_light_slot(data, Visit); break; default: break; } } +// the components the data of the component points at, each given to Visit, which may change it: the targets of the bindings of a +// channel other than clips, and the light sources of a light slot +template void visit_payload_components(model &Model, component_record const &Record, Visit_ const &Visit) { + auto const data{payload_of(Model, Record)}; + if (Record.type == component::light_slot) { + if (payload::light_slot slot; read_at(data, 0, slot)) + visit_index_list(data, sizeof(slot) + (std::size_t{slot.on_count} + slot.off_count) * sizeof(std::uint32_t), slot.light_count, Visit); + return; + } + payload::channel channel; + if ((Record.type != component::channel) || (false == read_at(data, 0, channel))) + return; + for (std::uint16_t idx = 0; idx < channel.binding_count; ++idx) { + auto const offset{sizeof(channel) + idx * sizeof(payload::channel_binding)}; + payload::channel_binding binding; + if (false == read_at(data, offset, binding)) + return; + if (binding.kind == payload::binding_kind::clip) + continue; + Visit(binding.target); + write_at(data, offset, binding); + } +} + +// each place but the tree itself where the model points at a node, given to Visit, which may change it: the transforms, the +// primitives, the joints of the skins, the tracks of the clips, the targets of the components and the nodes in their data. the +// roots of the skins are signed, the callers see to them +template void visit_node_references(model &Model, Visit_ const &Visit) { + for (auto &transform : Model.transforms) + Visit(transform.node); + for (auto &primitive : Model.primitives) + Visit(primitive.node); + for (auto &joint : Model.skin_joints) + Visit(joint.node); + for (auto &track : Model.clip_tracks) + Visit(track.node); + for (auto &record : Model.components) { + if (record.kind == target_kind::node) + Visit(record.target); + visit_payload_nodes(Model, record, Visit); + } +} + // the subtrees which end at At and hold Parent take the new node in; the others after it move on void shift_subtrees(model &Model, std::int32_t const Parent, std::uint32_t const At) { std::vector holding(Model.nodes.size(), false); @@ -422,29 +485,78 @@ void shift_subtrees(model &Model, std::int32_t const Parent, std::uint32_t const } } +// something other than its own components points at the node: the geometry, a transform, a skin, a clip, the data of a component +bool node_referenced(model &Model, std::uint32_t const Node) { + auto found{false}; + auto const check = [Node, &found](std::uint32_t const &Index) { found |= (Index == Node); }; + for (auto const &transform : Model.transforms) + check(transform.node); + for (auto const &primitive : Model.primitives) + check(primitive.node); + for (auto const &joint : Model.skin_joints) + check(joint.node); + for (auto const &track : Model.clip_tracks) + check(track.node); + for (auto const &record : Model.components) + visit_payload_nodes(Model, record, check); + found |= std::ranges::any_of(Model.skins, [Node](skin_record const &Skin) { return Skin.root == static_cast(Node); }); + return found; +} + +// the data of another component points at the component: a binding of a channel, the light sources of a light slot +bool component_referenced(model &Model, std::uint32_t const Component) { + auto found{false}; + auto const check = [Component, &found](std::uint32_t const &Index) { found |= (Index == Component); }; + for (auto const &record : Model.components) + visit_payload_components(Model, record, check); + return found; +} + +// a range of components after the component taken out of the table +void close_range(std::uint32_t &First, std::uint32_t &Count, std::uint32_t const Component) { + if (First > Component) + --First; + else if (std::size_t{Component} < std::size_t{First} + Count) + --Count; +} + +// the component taken out of the table: the ranges of the nodes and the vertex groups and the references in the data of the others +// close up. its data stays where it is, nothing points at it any more +void erase_component(model &Model, std::uint32_t const Component) { + Model.components.erase(Model.components.begin() + Component); + for (auto &node : Model.nodes) + close_range(node.component_first, node.component_count, Component); + for (auto &group : Model.vertex_groups) + close_range(group.component_first, group.component_count, Component); + auto const close = [Component](std::uint32_t &Index) { + if ((Index != no_index) && (Index > Component)) + --Index; + }; + for (auto const &record : Model.components) + visit_payload_components(Model, record, close); +} + +// the components aimed at the node +std::vector components_of(model const &Model, std::uint32_t const Node) { + std::vector components; + for (std::uint32_t idx = 0; idx < Model.components.size(); ++idx) { + if ((Model.components[idx].kind == target_kind::node) && (Model.components[idx].target == Node)) + components.push_back(idx); + } + return components; +} + } // namespace std::uint32_t insert_node(model &Model, std::int32_t const Parent, node_record Node) { auto const valid_parent{Parent >= 0 && Parent < static_cast(Model.nodes.size())}; auto const at{valid_parent ? Model.nodes[Parent].subtree_end : static_cast(Model.nodes.size())}; shift_subtrees(Model, valid_parent ? Parent : -1, at); - for (auto &transform : Model.transforms) - shift_node(transform.node, at); - for (auto &primitive : Model.primitives) - shift_node(primitive.node, at); + visit_node_references(Model, node_shift{at, false}); for (auto &skin : Model.skins) { if (skin.root >= static_cast(at)) ++skin.root; } - for (auto &joint : Model.skin_joints) - shift_node(joint.node, at); - for (auto &track : Model.clip_tracks) - shift_node(track.node, at); - for (auto &record : Model.components) { - if (record.kind == target_kind::node) - shift_node(record.target, at); - shift_payload(Model, record, at); - } Node.parent = valid_parent ? Parent : -1; Node.subtree_end = at + 1; Model.nodes.insert(Model.nodes.begin() + at, Node); @@ -455,6 +567,40 @@ std::uint32_t insert_node(model &Model, std::int32_t const Parent, node_record N return at; } +bool node_removable(model &Model, std::uint32_t const Node) { + if ((Node >= Model.nodes.size()) || (Model.nodes[Node].subtree_end != Node + 1) || (Model.nodes[Node].mesh >= 0) || node_referenced(Model, Node)) + return false; + auto const components{components_of(Model, Node)}; + return std::ranges::none_of(components, [&Model](std::uint32_t const Component) { return component_referenced(Model, Component); }); +} + +bool remove_node(model &Model, std::uint32_t const Node) { + if (false == node_removable(Model, Node)) + return false; + // its components first, the last of them first so the indices of the others hold + auto const components{components_of(Model, Node)}; + for (auto component{components.rbegin()}; component != components.rend(); ++component) + erase_component(Model, *component); + visit_node_references(Model, node_shift{Node, true}); + for (auto &skin : Model.skins) { + if (skin.root > static_cast(Node)) + --skin.root; + } + // the subtrees which held it, and those after it, end one place sooner + for (auto &node : Model.nodes) { + if (node.subtree_end > Node) + --node.subtree_end; + if (node.parent > static_cast(Node)) + --node.parent; + } + Model.nodes.erase(Model.nodes.begin() + Node); + if (false == Model.name_index.empty()) + build_name_index(Model); + if (false == Model.bounds.empty()) + compute_bounds(Model); + return true; +} + std::uint32_t add_component(model &Model, std::uint32_t const Type, target_kind const Kind, std::uint32_t const Target, std::span const Data) { // the data of each component starts at a multiple of 4 Model.component_data.resize((Model.component_data.size() + 3) & ~std::size_t{3}); diff --git a/model/eu07m/eu07m_build.h b/model/eu07m/eu07m_build.h index c73412995..c141fd01d 100644 --- a/model/eu07m/eu07m_build.h +++ b/model/eu07m/eu07m_build.h @@ -57,6 +57,13 @@ void compute_bounds(model &Model); // the subtrees, the transforms, the primitives, the skins, the tracks of the clips, the targets of the components and the nodes // in their data. the index of the names and the bounds, where the model has them, are built again. returns the index of the node std::uint32_t insert_node(model &Model, std::int32_t Parent, node_record Node); +// the node can be taken out: a leaf without geometry which nothing points at but its own components, and those components aren't +// pointed at by the data of others (the bindings of a channel, the light sources of a light slot) +bool node_removable(model &Model, std::uint32_t Node); +// takes out the node, which node_removable() allows, with its components; each reference to the nodes and the components after +// them moves back by one, the data of the components taken out stays unreferenced. the index of the names and the bounds, where +// the model has them, are built again. false, and nothing changed, when the node can't be taken out +bool remove_node(model &Model, std::uint32_t Node); // appends a component of the type aimed at the target, with its data; returns its index. a node or a vertex group without // components lists it as its range std::uint32_t add_component(model &Model, std::uint32_t Type, target_kind Kind, std::uint32_t Target, std::span Data); diff --git a/model/eu07m/eu07m_convert.cpp b/model/eu07m/eu07m_convert.cpp index 6b5b358a4..7243f1c1e 100644 --- a/model/eu07m/eu07m_convert.cpp +++ b/model/eu07m/eu07m_convert.cpp @@ -27,6 +27,9 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include +#include +#include #include #include #include @@ -574,6 +577,47 @@ model convert(TModel3d &Source, std::vector &Faults) { return converter{Source, Faults}.run(); } +std::string import_model(TModel3d &Source, std::string &Error) { + auto const stem{Source.NameGet()}; + auto input{FileCased(stem + ".e3d")}; + if (input.empty()) + input = FileCased(stem + ".t3d"); + if (input.empty()) { + Error = "the model has no .e3d or .t3d file"; + return {}; + } + std::vector faults; + auto converted{convert(Source, faults)}; + if (false == faults.empty()) { + Error = faults.front(); + return {}; + } + auto const file{read_whole_file(input)}; + converted.source_hash = hash_bytes(std::as_bytes(std::span{file.data.get(), file.size})); + converted.edit.push_back({converted.intern(input), converted.intern("editor import"), {}}); + if (auto const problems{validate(converted)}; false == problems.empty()) { + Error = problems.front(); + return {}; + } + auto const output{stem + ".eu07m"}; + auto const temporary{output + ".tmp"}; + auto const bytes{write(converted)}; + std::ofstream stream{temporary, std::ios::binary | std::ios::trunc}; + stream.write(reinterpret_cast(bytes.data()), static_cast(bytes.size())); + // closed before the check: the buffer is written out there, and a fault of it (a full disk) is seen + stream.close(); + std::error_code error; + if (false == stream.fail()) + std::filesystem::rename(temporary, output, error); + if (stream.fail() || error) { + std::filesystem::remove(temporary, error); + Error = std::format("can't write \"{}\"", output); + return {}; + } + WriteLog(std::format("EU07M: {} imported to {}, {} nodes", input, output, converted.nodes.size())); + return output; +} + int run_command_line(int const Argc, char *Argv[]) { std::string_view const command{Argc > 2 ? Argv[2] : ""}; if (command == "convert") diff --git a/model/eu07m/eu07m_convert.h b/model/eu07m/eu07m_convert.h index 904bc8372..6f44147ef 100644 --- a/model/eu07m/eu07m_convert.h +++ b/model/eu07m/eu07m_convert.h @@ -25,6 +25,10 @@ namespace eu07m { // leave the result invalid, are added to Faults, each naming its submodel model convert(TModel3d &Source, std::vector &Faults); +// the EU07M file of the loaded model written beside the file it was loaded from (its .e3d, or else its .t3d), as the convert +// command writes it. returns the path of the file written, or empty with Error saying why +std::string import_model(TModel3d &Source, std::string &Error); + // the -eu07m commands: convert, dump, validate. returns the exit code of the program int run_command_line(int Argc, char *Argv[]); diff --git a/model/eu07m/eu07m_load.cpp b/model/eu07m/eu07m_load.cpp index 130b611c5..ba8f45765 100644 --- a/model/eu07m/eu07m_load.cpp +++ b/model/eu07m/eu07m_load.cpp @@ -631,6 +631,40 @@ void TModel3d::SetEditorRange(TSubModel &Submodel, float const MinSq, float cons submodels_changed(); } +TSubModel *TModel3d::UnlinkEditorSubmodel(TSubModel &Submodel) { + auto *parent{Submodel.Parent}; + if (parent == nullptr) + return nullptr; + TSubModel *previous{nullptr}; + auto *child{parent->Child}; + while ((child != nullptr) && (child != &Submodel)) { + previous = child; + child = child->Next; + } + if (child == nullptr) + return nullptr; + if (previous == nullptr) + parent->Child = Submodel.Next; + else + previous->Next = Submodel.Next; + Submodel.Next = nullptr; + submodels_changed(); + return previous; +} + +void TModel3d::LinkEditorSubmodel(TSubModel &Submodel, TSubModel &Parent, TSubModel *Previous) { + Submodel.Parent = &Parent; + if (Previous == nullptr) { + Submodel.Next = Parent.Child; + Parent.Child = &Submodel; + } + else { + Submodel.Next = Previous->Next; + Previous->Next = &Submodel; + } + submodels_changed(); +} + void TModel3d::submodels_changed() { if (Root != nullptr) iFlags |= Root->FlagsCheck(); diff --git a/tests/unit/test_eu07m_edit.cpp b/tests/unit/test_eu07m_edit.cpp index 92dfc1cc5..9017dfcc1 100644 --- a/tests/unit/test_eu07m_edit.cpp +++ b/tests/unit/test_eu07m_edit.cpp @@ -111,3 +111,49 @@ TEST_CASE("eu07m: a node put in without a parent goes last, and a component adde CHECK(read.nodes.size() == 5); CHECK(read.components.size() == 3); } + +TEST_CASE("eu07m: a light put in and taken out again leaves the model as it was") { + auto model{lamp_model()}; + auto const before{model.nodes}; + eu07m::node_record light; + light.name = model.intern("light_3"); + auto const index{eu07m::insert_node(model, 0, light)}; + eu07m::payload::light payload; + std::vector data(sizeof(payload)); + std::memcpy(data.data(), &payload, sizeof(payload)); + eu07m::add_component(model, eu07m::component::light, eu07m::target_kind::node, index, data); + REQUIRE(eu07m::node_removable(model, index)); + REQUIRE(eu07m::remove_node(model, index)); + REQUIRE(model.nodes.size() == before.size()); + for (std::size_t idx = 0; idx < before.size(); ++idx) { + CHECK(model.nodes[idx].parent == before[idx].parent); + CHECK(model.nodes[idx].subtree_end == before[idx].subtree_end); + CHECK(model.nodes[idx].name == before[idx].name); + } + // the components of the light are gone, the others point where they did + REQUIRE(model.components.size() == 2); + CHECK(model.components[1].target == 3); + CHECK(model.clip_tracks[0].node == 3); + CHECK(listed_node(model, 0, 0) == 2); + CHECK(listed_node(model, 0, 1) == 3); + CHECK(eu07m::find_nodes(model, "rear") == std::vector{3}); + CHECK(eu07m::validate(model).empty()); +} + +TEST_CASE("eu07m: a node with children, or one something points at, isn't taken out") { + auto model{lamp_model()}; + auto const nodes{model.nodes.size()}; + // the root has children, the door is listed by the light slot, the rear node is moved by a clip + CHECK_FALSE(eu07m::remove_node(model, 0)); + CHECK_FALSE(eu07m::remove_node(model, 2)); + CHECK_FALSE(eu07m::remove_node(model, 3)); + CHECK_FALSE(eu07m::remove_node(model, 9)); + CHECK(model.nodes.size() == nodes); + // the lamp is a leaf nothing points at + CHECK(eu07m::remove_node(model, 1)); + CHECK(model.nodes.size() == nodes - 1); + CHECK(model.nodes[0].subtree_end == 2); + CHECK(listed_node(model, 0, 0) == 1); + CHECK(listed_node(model, 0, 1) == 2); + CHECK(eu07m::validate(model).empty()); +}