From 107cc3c92761b6b214384144f77ab9d02dbd5b02 Mon Sep 17 00:00:00 2001 From: maj00r <73280030+maj00r@users.noreply.github.com> Date: Sun, 29 Nov 2026 18:11:38 +0100 Subject: [PATCH] feat(editor): the EU07M window edits in 3D, holds vehicle parts and adds lights The window of an EU07M model gets tabs: the tree of the nodes beside the properties of the node picked, the parts of the vehicle, the clips and channels, and the components of the model. The texts are Polish in lang/editor_pl.po. - With nothing selected, it shows the model of the vehicle driven (its body or its cab). - In the 3D view the node picked is framed and shows its axes and a gizmo to move or turn it. The light sources are marked in their colour, a spot with its axis, and a click on a mark picks its node. A press on the gizmo or a mark doesn't pick a scenery node, and the editor's own gizmo gives way. A double click in the tree flies the camera there. - The settings of a node: its position, rotation (degrees) and scale, and the distances it is drawn from and up to. - "Add a light source here" puts in a node light_ with a point or spot LGHT as the last child of the node. eu07m::insert_node moves every reference to the nodes after it, and eu07m::add_component appends a component; both have unit tests. - Changes show at once on the model the game has, through new TModel3d methods for the editor (ApplyEU07MLight, AddEditorLight, SetEditorTransform, SetEditorRange). The spot's cones are edited as half angles in degrees. - Parts of the vehicle: the editor holds the lamps, coupler hooks and hoses in their _off/_on/_xon state, and the pantographs up or down, whatever the vehicle does. A held pantograph moves at its own pace, in the editor too, up to the wire above it. Only the look changes: the electrics of the vehicle don't. - Neither the empty-scenery line nor the no-tracks hint shows in a scenery of models alone. - New editor self-test command: modelnode . --- application/editormode.cpp | 16 +- application/editormode.h | 2 + application/editormodenmt.cpp | 3 + application/editormodeselftestscene.cpp | 9 + application/editormodetrack.cpp | 4 + application/editoruilayer.h | 6 + application/editoruimodel.cpp | 998 +++++++++++++++++++++--- application/editoruimodel.h | 69 +- docs/eu07m-format.md | 22 +- lang/editor_pl.po | 246 ++++++ model/Model3d.h | 18 + model/eu07m/eu07m_build.cpp | 167 ++++ model/eu07m/eu07m_build.h | 10 + model/eu07m/eu07m_load.cpp | 48 +- tests/unit/test_eu07m_edit.cpp | 113 +++ vehicle/AirCoupler.h | 5 + vehicle/DynObj.cpp | 136 ++++ vehicle/DynObj.h | 33 + 18 files changed, 1777 insertions(+), 128 deletions(-) create mode 100644 tests/unit/test_eu07m_edit.cpp diff --git a/application/editormode.cpp b/application/editormode.cpp index 132c61dfd..a0cddd9b3 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -583,6 +583,7 @@ editor_mode::editor_mode() { ui()->set_new_scenery([this]() { m_newscenery_asked = true; }); ui()->set_open_scenery([this]() { m_openscenery_asked = true; }); ui()->set_memcell_focus([this](scene::basic_node *Node) { start_focus(Node); }); + ui()->set_model_focus([this](glm::dvec3 const &Point, double const Radius) { focus_sphere(Point, Radius); }); ui()->set_edit_menu([this]() { render_edit_menu(); }); ui()->set_tools_menu([this]() { render_track_presets_menu(); @@ -753,10 +754,12 @@ void editor_mode::start_focus(scene::basic_node *node, double duration) if (!node) return; - glm::dvec3 const center = node->location(); + focus_sphere(node->location(), std::max(1.0, static_cast(node->radius())), duration); +} +void editor_mode::focus_sphere(glm::dvec3 const ¢er, double const radius, double const duration) +{ // distance that frames the object's bounding sphere within the vertical FOV, with some margin - double const radius = std::max(1.0, static_cast(node->radius())); double const fovy = glm::radians(static_cast(Global.FieldOfView) / std::max(0.01, static_cast(Global.ZoomFactor))); double distance = radius / std::tan(fovy * 0.5) * 1.6; distance = std::clamp(distance, radius * 1.5, static_cast(kMaxPlacementDistance)); @@ -7121,8 +7124,9 @@ void editor_mode::render_gizmo() return; } - // the transform gizmo is suppressed while editing terrain, so the brush/chunk tool owns the mouse - if (!gizmo_shown() || terrain_brush() || terrain_clicking()) + // the transform gizmo is suppressed while editing terrain, so the brush/chunk tool owns the mouse; the window of an EU07M + // model shows the gizmo of a node of the model instead + if (!gizmo_shown() || terrain_brush() || terrain_clicking() || ui()->model_gizmo_shown()) { m_gizmo_using = false; m_track_gizmo_using = false; @@ -8361,8 +8365,8 @@ void editor_mode::on_mouse_button(int const Button, int const Action, int const auto const additive{mode == nodebank_panel::MODIFY && (Mods & GLFW_MOD_SHIFT) != 0}; GfxRenderer->Pick_Node_Callback( [this, mode, rotation_mode, fixed_rotation_value, additive](scene::basic_node *node) { - // the press turned out to be meant for the UI - if (!viewport_click()) + // 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; auto *const previous{m_node}; diff --git a/application/editormode.h b/application/editormode.h index ad09e9d5e..73041034d 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -344,6 +344,8 @@ class editor_mode : public application_mode, private editor_track::observer, pri // focus camera smoothly on specified node void start_focus(scene::basic_node *node, double duration = 0.6); + // the camera flown to look at a sphere of the world, from the side it views it from now + void focus_sphere(glm::dvec3 const &Center, double Radius, double Duration = 0.6); // drops the node straight down onto the nearest surface below (terrain or another object). its group goes along with it, // unless Alone: then the node goes by itself. Joined: undone together with the change before diff --git a/application/editormodenmt.cpp b/application/editormodenmt.cpp index 1b83a96ef..fc51970af 100644 --- a/application/editormodenmt.cpp +++ b/application/editormodenmt.cpp @@ -2293,6 +2293,9 @@ void editor_mode::render_empty_scenery_hint() auto const &tracks{simulation::Paths.sequence()}; if (std::any_of(tracks.begin(), tracks.end(), [](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved && rail(*Track); })) return; + // a scenery of models alone, such as one put up to look at a model, isn't empty either + if (std::ranges::any_of(simulation::Instances.sequence(), [](TAnimModel const *Instance) { return Instance != nullptr; })) + return; auto const low{editor_ui::view_min()}; auto const high{editor_ui::view_max()}; auto *list{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; diff --git a/application/editormodeselftestscene.cpp b/application/editormodeselftestscene.cpp index becfafa8a..6763b1c27 100644 --- a/application/editormodeselftestscene.cpp +++ b/application/editormodeselftestscene.cpp @@ -368,6 +368,15 @@ 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 == "modelnode") + { + // a node picked in the window of the EU07M model shown + std::string name; + words >> name; + auto const found{ui()->select_model_node(name)}; + WriteLog("SELFTEST modelnode " + name + (found ? "" : ": no such node")); + return selftest_result::handled; + } if (command == "selectmodel") { glm::dvec3 point{0.0}; diff --git a/application/editormodetrack.cpp b/application/editormodetrack.cpp index 95f3062b2..8da1413b3 100644 --- a/application/editormodetrack.cpp +++ b/application/editormodetrack.cpp @@ -28,6 +28,7 @@ http: #include "scene/scene.h" #include "scene/scenelayers.h" #include "simulation/simulation.h" +#include "model/AnimModel.h" #include "utilities/Logs.h" #include "utilities/translation.h" @@ -2284,6 +2285,9 @@ void editor_mode::draw_empty_scenery_hint() auto const &paths{simulation::Paths.sequence()}; if (std::any_of(paths.begin(), paths.end(), [](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved; })) return; + // a scenery of models alone, such as one put up to look at a model, isn't one to lay tracks in + if (std::ranges::any_of(simulation::Instances.sequence(), [](TAnimModel const *Instance) { return Instance != nullptr; })) + return; // the line of the empty scenery in the middle of the view says the same: it gives way to this one m_empty_hint_frame = ImGui::GetFrameCount(); auto *list{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())}; diff --git a/application/editoruilayer.h b/application/editoruilayer.h index 2b9c990b8..2f408c60a 100644 --- a/application/editoruilayer.h +++ b/application/editoruilayer.h @@ -116,6 +116,12 @@ class editor_ui : public ui_layer void set_new_scenery(std::function New) { m_newscenery = std::move(New); } void set_open_scenery(std::function Open) { m_openscenery = std::move(Open); } void set_memcell_focus(std::function Focus) { m_memcellspanel.focus = std::move(Focus); } + void set_model_focus(std::function Focus) { m_modelpanel.focus = std::move(Focus); } + // the window of an EU07M model shows its own gizmo, of the node picked in it, in place of the one of the editor + bool model_gizmo_shown() const { return m_modelpanel.gizmo_shown(); } + // 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); } // 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() diff --git a/application/editoruimodel.cpp b/application/editoruimodel.cpp index 590835d95..4e172c363 100644 --- a/application/editoruimodel.cpp +++ b/application/editoruimodel.cpp @@ -10,21 +10,35 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "application/editoruimodel.h" +#include "application/editorprojection.h" + #include "model/AnimModel.h" #include "model/Model3d.h" +#include "model/eu07m/eu07m_build.h" #include "model/eu07m/eu07m_dump.h" #include "model/eu07m/eu07m_io.h" #include "model/eu07m/eu07m_store.h" #include "scene/scenenode.h" +#include "simulation/simulation.h" #include "utilities/Globals.h" #include "utilities/translation.h" #include "utilities/utilities.h" +#include "vehicle/DynObj.h" +#include "vehicle/Train.h" +#include +#include +#include + +#include #include +#include #include #include #include #include +#include +#include namespace { @@ -34,6 +48,39 @@ namespace payload = eu07m::payload; // the nodes of a model the panel shows open at once constexpr std::size_t small_model{32}; +// the radius of the sphere around a node the camera frames, metres: close enough to see a lamp +constexpr double node_focus_radius{1.0}; + +// the flags of a node of a light source added here, as those of the light points converted from E3D: a transform of its own +// (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}; + +// the model of the part of the vehicle: 0 the body, 1 the cab +TModel3d *vehicle_model(TDynamicObject const *Vehicle, int const Part) +{ + if (Vehicle == nullptr) + { + return nullptr; + } + return Part == 1 ? Vehicle->mdKabina : Vehicle->mdModel; +} + +// the submodels of the model in the order of the nodes of its file: the tree the game has, walked depth first +void collect_submodels(TSubModel *Submodel, std::vector &Submodels) +{ + for (auto *submodel{Submodel}; submodel != nullptr; submodel = submodel->NextGet()) + { + Submodels.push_back(submodel); + collect_submodels(submodel->ChildGet(), Submodels); + } +} + // the name of a component type, its four characters std::string fourcc_text(std::uint32_t const Type) { @@ -45,6 +92,86 @@ std::string fourcc_text(std::uint32_t const Type) return result; } +struct type_name +{ + std::uint32_t type; + char const *name; +}; + +// what a component is, in words +char const *component_name(std::uint32_t const Type) +{ + namespace component = eu07m::component; + static std::array const names{{{component::properties, "Properties"}, + {component::socket, "Socket"}, + {component::joint, "Joint"}, + {component::spring, "Spring"}, + {component::chain, "Chain"}, + {component::variants, "Variants"}, + {component::channel, "Channel"}, + {component::light_slot, "Light slot"}, + {component::light, "Light source"}, + {component::emitter, "Emitter"}, + {component::model_reference, "Attached model"}, + {component::collision, "Collision shape"}, + {component::legacy_animation, "Animation (E3D)"}, + {component::legacy_text, "Text (E3D)"}, + {component::legacy_stars, "Stars (E3D)"}, + {component::legacy_material, "Material (E3D)"}}}; + auto const found{std::ranges::find(names, Type, &type_name::type)}; + return found != names.end() ? STR_C(found->name) : STR_C("Component"); +} + +struct part_label +{ + char const *name; + char const *text; +}; + +// what a part of the vehicle is, in words; its own name when it isn't known +char const *part_text(char const *Name) +{ + static std::array const labels{{{"headlamp11", "Upper headlamp, front"}, + {"headlamp12", "Right headlamp, front"}, + {"headlamp13", "Left headlamp, front"}, + {"highbeam12", "Right high beam, front"}, + {"highbeam13", "Left high beam, front"}, + {"headsignal12", "Right signal lamp, front"}, + {"headsignal13", "Left signal lamp, front"}, + {"headlamp21", "Upper headlamp, rear"}, + {"headlamp22", "Right headlamp, rear"}, + {"headlamp23", "Left headlamp, rear"}, + {"highbeam22", "Right high beam, rear"}, + {"highbeam23", "Left high beam, rear"}, + {"headsignal22", "Right signal lamp, rear"}, + {"headsignal23", "Left signal lamp, rear"}, + {"coupler1", "Coupler hook, front"}, + {"coupler2", "Coupler hook, rear"}, + {"cpneumatic1", "Brake hose, front"}, + {"cpneumatic1r", "Brake hose, front, other side"}, + {"cpneumatic2", "Brake hose, rear"}, + {"cpneumatic2r", "Brake hose, rear, other side"}, + {"pneumatic1", "Supply hose, front"}, + {"pneumatic1r", "Supply hose, front, other side"}, + {"pneumatic2", "Supply hose, rear"}, + {"pneumatic2r", "Supply hose, rear, other side"}}}; + std::string_view const name{Name}; + auto const found{std::ranges::find_if(labels, [name](part_label const &Label) { return name == Label.name; })}; + return found != labels.end() ? STR_C(found->text) : Name; +} + +// the lamps are named head... and high... +bool is_lamp(std::string_view const Name) +{ + return Name.starts_with("head") || Name.starts_with("high"); +} + +// the lamps of the front end have 1 before their last digit, those of the rear 2 +bool is_front(std::string_view const Name) +{ + return (Name.size() >= 2) && (Name[Name.size() - 2] == '1'); +} + // a string of the model edited by its text; an empty text is no string bool edit_string(char const *Label, eu07m::model &Model, std::uint32_t &Id) { @@ -74,6 +201,59 @@ 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}; @@ -85,24 +265,60 @@ bool edit_flag(char const *Label, std::uint8_t &Flags, std::uint8_t const Bit) return true; } -// a rotation as a quaternion x y z w, kept of unit length +// a rotation as a quaternion x y z w, edited as angles in degrees bool edit_rotation(char const *Label, std::array &Rotation) { - if (false == ImGui::DragFloat4(Label, Rotation.data(), 0.01f, -1.f, 1.f, "%.3f")) + glm::quat const turn{Rotation[3], Rotation[0], Rotation[1], Rotation[2]}; + auto angles{glm::degrees(glm::eulerAngles(turn))}; + if (false == ImGui::DragFloat3(Label, glm::value_ptr(angles), 0.5f, 0.f, 0.f, "%.1f")) { return false; } - auto const length{std::sqrt(Rotation[0] * Rotation[0] + Rotation[1] * Rotation[1] + Rotation[2] * Rotation[2] + Rotation[3] * Rotation[3])}; - if (length > 0.f) - { - for (auto &component : Rotation) - { - component /= length; - } - } + auto const turned{glm::normalize(glm::quat{glm::radians(angles)})}; + Rotation = {turned.x, turned.y, turned.z, turned.w}; return true; } +// the half angle of a cone in degrees, for the cosine the format keeps +bool edit_cone(char const *Label, float &Cosine) +{ + auto angle{glm::degrees(std::acos(std::clamp(Cosine, -1.f, 1.f)))}; + if (false == ImGui::DragFloat(Label, &angle, 0.25f, 0.f, 180.f, "%.1f")) + { + return false; + } + Cosine = std::cos(glm::radians(angle)); + return true; +} + +// the place of the node in the space of its parent +bool edit_place(eu07m::node_record &Node) +{ + auto changed{ImGui::DragFloat3(STR_C("Position, m"), Node.translation.data(), 0.005f, 0.f, 0.f, "%.3f")}; + changed |= edit_rotation(STR_C("Rotation, degrees"), Node.rotation); + changed |= ImGui::DragFloat3(STR_C("Scale"), Node.scale.data(), 0.01f, 0.f, 0.f, "%.3f"); + return changed; +} + +// the distances from which and up to which the node is drawn, kept squared +bool edit_range(eu07m::node_record &Node) +{ + auto from{std::sqrt(std::max(Node.range_min_sq, 0.f))}; + auto to{std::sqrt(std::max(Node.range_max_sq, 0.f))}; + auto changed{false}; + if (ImGui::DragFloat(STR_C("Visible from, m"), &from, 0.5f, 0.f, 100000.f, "%.1f")) + { + Node.range_min_sq = from * from; + changed = true; + } + if (ImGui::DragFloat(STR_C("Visible up to, m (0: no limit)"), &to, 0.5f, 0.f, 100000.f, "%.1f")) + { + Node.range_max_sq = to * to; + changed = true; + } + return changed; +} + // the payload of the component at Offset of its data, edited by Edit; written back when it changed template bool edit_payload(eu07m::model &Model, std::uint32_t const Index, std::size_t const Offset, Edit_ &&Edit) { @@ -128,8 +344,8 @@ bool edit_socket(eu07m::model &Model, payload::socket &Socket) auto changed{edit_string(STR_C("Role"), Model, Socket.role)}; changed |= edit_enum(STR_C("End of the vehicle"), Socket.end, {STR_C("none"), STR_C("front"), STR_C("rear")}); changed |= ImGui::InputScalar(STR_C("Index"), ImGuiDataType_U16, &Socket.index); - changed |= ImGui::DragFloat3(STR_C("Position"), Socket.position.data(), 0.001f, 0.f, 0.f, "%.4f"); - changed |= edit_rotation(STR_C("Rotation"), Socket.rotation); + changed |= ImGui::DragFloat3(STR_C("Position, m"), Socket.position.data(), 0.001f, 0.f, 0.f, "%.4f"); + changed |= edit_rotation(STR_C("Rotation, degrees"), Socket.rotation); return changed; } @@ -177,18 +393,42 @@ bool edit_binding(payload::channel_binding &Binding) return changed; } +// a point light shines all around (the cone of -1); a spot made of one gets a cone to start with +void set_light_kind(payload::light &Light, payload::light_kind const Kind) +{ + Light.kind = Kind; + if (Kind == payload::light_kind::point) + { + Light.cos_falloff = -1.f; + Light.cos_hotspot = -1.f; + } + else if (Light.cos_falloff <= -1.f) + { + Light.cos_falloff = std::cos(glm::radians(30.f)); + Light.cos_hotspot = std::cos(glm::radians(20.f)); + } +} + bool edit_light(payload::light &Light) { - auto changed{edit_enum(STR_C("Kind"), Light.kind, {STR_C("point"), STR_C("spot")})}; + auto kind{Light.kind}; + auto changed{edit_enum(STR_C("Kind"), kind, {STR_C("point"), STR_C("spot")})}; + if (changed) + { + set_light_kind(Light, kind); + } + changed |= ImGui::ColorEdit3(STR_C("Colour"), Light.color.data()); + changed |= ImGui::DragFloat(STR_C("Intensity"), &Light.hotspot_power, 0.01f, 0.f, 100.f, "%.2f"); + changed |= ImGui::DragFloat(STR_C("Glowing sphere radius, m"), &Light.radius, 0.005f, 0.f, 10.f, "%.3f"); + if (Light.kind == payload::light_kind::spot) + { + changed |= edit_cone(STR_C("Cone, half angle in degrees"), Light.cos_falloff); + changed |= edit_cone(STR_C("Hotspot, half angle in degrees"), Light.cos_hotspot); + } changed |= edit_flag(STR_C("Lights itself"), Light.flags, payload::light_flags::shade_self); changed |= edit_flag(STR_C("No shadows"), Light.flags, payload::light_flags::no_shadows); changed |= edit_flag(STR_C("Soft falloff"), Light.flags, payload::light_flags::soft_falloff); changed |= edit_flag(STR_C("Light only"), Light.flags, payload::light_flags::light_only); - changed |= ImGui::ColorEdit4(STR_C("Colour"), Light.color.data()); - changed |= ImGui::DragFloat(STR_C("Intensity"), &Light.hotspot_power, 0.01f, 0.f, 100.f); - changed |= ImGui::DragFloat(STR_C("Radius"), &Light.radius, 0.1f, 0.f, 10000.f); - changed |= ImGui::DragFloat(STR_C("Cosine of the cone"), &Light.cos_falloff, 0.005f, -1.f, 1.f); - changed |= ImGui::DragFloat(STR_C("Cosine of the hotspot"), &Light.cos_hotspot, 0.005f, -1.f, 1.f); return changed; } @@ -212,7 +452,7 @@ bool edit_collision(eu07m::model &Model, payload::collision &Collision) auto changed{edit_enum(STR_C("Shape"), Collision.kind, {STR_C("box"), STR_C("sphere"), STR_C("capsule")})}; changed |= edit_string(STR_C("Role"), Model, Collision.role); changed |= ImGui::DragFloat3(STR_C("Centre"), Collision.centre.data(), 0.001f, 0.f, 0.f, "%.4f"); - changed |= edit_rotation(STR_C("Rotation"), Collision.rotation); + changed |= edit_rotation(STR_C("Rotation, degrees"), Collision.rotation); changed |= ImGui::DragFloat3(STR_C("Half extents"), Collision.size.data(), 0.001f, 0.f, 1000.f, "%.4f"); return changed; } @@ -224,30 +464,8 @@ bool edit_reference(eu07m::model &Model, payload::model_reference &Reference) return changed; } -// the components the panel edits field by field; the others are shown by their size -bool edit_component(eu07m::model &Model, std::uint32_t const Index) +bool edit_channel_component(eu07m::model &Model, std::uint32_t const Index) { - namespace component = eu07m::component; - auto const type{Model.components[Index].type}; - if (type == component::socket) - return edit_payload(Model, Index, 0, [&Model](payload::socket &Value) { return edit_socket(Model, Value); }); - if (type == component::joint) - return edit_payload(Model, Index, 0, [&Model](payload::joint &Value) { return edit_joint(Model, Value); }); - if (type == component::light) - return edit_payload(Model, Index, 0, [](payload::light &Value) { return edit_light(Value); }); - if (type == component::light_slot) - return edit_payload(Model, Index, 0, [](payload::light_slot &Value) { return edit_light_slot(Value); }); - if (type == component::emitter) - return edit_payload(Model, Index, 0, [](payload::emitter &Value) { return edit_emitter(Value); }); - if (type == component::collision) - return edit_payload(Model, Index, 0, [&Model](payload::collision &Value) { return edit_collision(Model, Value); }); - if (type == component::model_reference) - return edit_payload(Model, Index, 0, [&Model](payload::model_reference &Value) { return edit_reference(Model, Value); }); - if (type != component::channel) - { - ImGui::TextDisabled("%s", std::vformat(STR("{} bytes, not edited here"), std::make_format_args(Model.components[Index].data_size)).c_str()); - return false; - } payload::channel channel; auto changed{edit_payload(Model, Index, 0, [&Model, &channel](payload::channel &Value) { auto const result{edit_channel(Model, Value)}; @@ -257,28 +475,174 @@ bool edit_component(eu07m::model &Model, std::uint32_t const Index) for (std::uint32_t binding = 0; binding < channel.binding_count; ++binding) { ImGui::PushID(static_cast(binding)); - ImGui::SeparatorText(std::vformat(STR("Binding {}"), std::make_format_args(binding)).c_str()); + auto const number{binding + 1}; + ImGui::SeparatorText(std::vformat(STR("Binding {}"), std::make_format_args(number)).c_str()); changed |= edit_payload(Model, Index, sizeof(payload::channel) + binding * sizeof(payload::channel_binding), [](payload::channel_binding &Value) { return edit_binding(Value); }); ImGui::PopID(); } return changed; } +// the components the panel edits field by field; the others are shown by their size +bool edit_component(eu07m::model &Model, std::uint32_t const Index) +{ + namespace component = eu07m::component; + switch (Model.components[Index].type) + { + case component::socket: return edit_payload(Model, Index, 0, [&Model](payload::socket &Value) { return edit_socket(Model, Value); }); + case component::joint: return edit_payload(Model, Index, 0, [&Model](payload::joint &Value) { return edit_joint(Model, Value); }); + case component::light: return edit_payload(Model, Index, 0, [](payload::light &Value) { return edit_light(Value); }); + case component::light_slot: return edit_payload(Model, Index, 0, [](payload::light_slot &Value) { return edit_light_slot(Value); }); + case component::emitter: return edit_payload(Model, Index, 0, [](payload::emitter &Value) { return edit_emitter(Value); }); + case component::collision: return edit_payload(Model, Index, 0, [&Model](payload::collision &Value) { return edit_collision(Model, Value); }); + case component::model_reference: + return edit_payload(Model, Index, 0, [&Model](payload::model_reference &Value) { return edit_reference(Model, Value); }); + case component::channel: return edit_channel_component(Model, Index); + default: break; + } + ImGui::TextDisabled("%s", std::vformat(STR("{} bytes, not edited here"), std::make_format_args(Model.components[Index].data_size)).c_str()); + return false; +} + +// the components aimed at the node, whether its range lists them or not +std::vector node_components(eu07m::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 == eu07m::target_kind::node) && (Model.components[idx].target == Node)) + { + components.push_back(idx); + } + } + return components; +} + +// the name of the node and what its components are, in words +std::string node_label(eu07m::model const &Model, std::uint32_t const Node, std::vector const &Components) +{ + auto const name{Model.string(Model.nodes[Node].name)}; + auto label{name.empty() ? std::string{STR_C("(no name)")} : std::string{name}}; + std::vector kinds; + for (auto const component : Components) + { + auto const *kind{component_name(Model.components[component].type)}; + if (std::ranges::find(kinds, kind) == kinds.end()) + { + kinds.push_back(kind); + } + } + for (std::size_t idx = 0; idx < kinds.size(); ++idx) + { + label += (idx == 0 ? " [" : ", "); + label += kinds[idx]; + } + if (false == kinds.empty()) + { + label += "]"; + } + return label; +} + } // namespace -bool eu07m_model_panel::load(TAnimModel &Instance) +namespace { - m_instance = &Instance; + +using box = std::pair; + +// the box of the geometry of the node, in its space; none for a node without geometry +std::optional node_box(eu07m::model const &Model, std::uint32_t const Node) +{ + auto const mesh{Model.nodes[Node].mesh}; + if ((mesh < 0) || (static_cast(mesh) >= Model.meshes.size())) + { + return std::nullopt; + } + auto const &record{Model.meshes[mesh]}; + std::optional result; + auto const last{std::min(std::size_t{record.primitive_first} + record.primitive_count, Model.primitives.size())}; + for (auto idx = std::size_t{record.primitive_first}; idx < last; ++idx) + { + auto const &primitive{Model.primitives[idx]}; + auto const end{std::min(std::size_t{primitive.base_vertex} + primitive.vertex_count, Model.positions.size())}; + for (auto vertex = std::size_t{primitive.base_vertex}; vertex < end; ++vertex) + { + glm::vec3 const point{Model.positions[vertex][0], Model.positions[vertex][1], Model.positions[vertex][2]}; + result = result ? box{glm::min(result->first, point), glm::max(result->second, point)} : box{point, point}; + } + } + return result; +} + +// the space of the submodel in the space of the model, as it stands in the file (not as an animation turned it) +glm::dmat4 model_space(TSubModel const &Submodel) +{ + float4x4 matrix; + Submodel.ParentMatrix(&matrix); + return glm::dmat4{glm::make_mat4(matrix.readArray())}; +} + +glm::dvec3 point_of(glm::dmat4 const &Matrix, glm::dvec3 const &Point) +{ + return glm::dvec3{Matrix * glm::dvec4{Point, 1.0}}; +} + +// the twelve edges of the box in the space of Matrix +void draw_box(ImDrawList *Drawlist, screen_projection const &Projection, glm::dmat4 const &Matrix, box const &Box, ImU32 const Color) +{ + auto const corner = [&Matrix, &Box](int const Index) { + return point_of(Matrix, glm::dvec3{(Index & 1) ? Box.second.x : Box.first.x, (Index & 2) ? Box.second.y : Box.first.y, (Index & 4) ? Box.second.z : Box.first.z}); + }; + for (int idx = 0; idx < 8; ++idx) + { + for (int const axis : {1, 2, 4}) + { + if ((idx & axis) == 0) + { + Projection.line(Drawlist, corner(idx), corner(idx | axis), Color, 2.f); + } + } + } +} + +// the axes of the space of Matrix from its origin: x red, y green, z blue +void draw_axes(ImDrawList *Drawlist, screen_projection const &Projection, glm::dmat4 const &Matrix, double const Length) +{ + auto const origin{point_of(Matrix, glm::dvec3{0.0})}; + Projection.line(Drawlist, origin, point_of(Matrix, glm::dvec3{Length, 0.0, 0.0}), IM_COL32(230, 60, 60, 255), 2.f); + Projection.line(Drawlist, origin, point_of(Matrix, glm::dvec3{0.0, Length, 0.0}), IM_COL32(60, 210, 60, 255), 2.f); + Projection.line(Drawlist, origin, point_of(Matrix, glm::dvec3{0.0, 0.0, Length}), IM_COL32(70, 120, 255, 255), 2.f); +} + +ImU32 light_colour(payload::light const &Light, int const Alpha) +{ + auto const channel = [](float const Value) { return static_cast(std::clamp(Value, 0.f, 1.f) * 255.f); }; + return IM_COL32(channel(Light.color[0]), channel(Light.color[1]), channel(Light.color[2]), Alpha); +} + +// the radius of the mark of a light source, pixels +constexpr float mark_radius{7.f}; + +} // namespace + +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 ((Instance.pModel == nullptr) || (false == Global.modelformat_eu07m)) + if (false == Global.modelformat_eu07m) { return false; } - auto const path{FileCased(Instance.pModel->NameGet() + ".eu07m")}; + auto const path{FileCased(Model.NameGet() + ".eu07m")}; if (path.empty()) { return false; @@ -295,9 +659,15 @@ bool eu07m_model_panel::load(TAnimModel &Instance) return false; } m_path = path; + // the submodels of the nodes, when the model the game has is the one of the file + collect_submodels(Model.GetSMRoot(), m_submodels); + if (m_submodels.size() != m_model.nodes.size()) + { + m_submodels.clear(); + } m_cliptimes.assign(m_model.clips.size(), 0.f); m_channels.clear(); - for (auto const &channel : Instance.pModel->channels()) + for (auto const &channel : Model.channels()) { m_channels.push_back(channel.initial); } @@ -306,15 +676,34 @@ bool eu07m_model_panel::load(TAnimModel &Instance) void eu07m_model_panel::render(scene::basic_node *Node) { + m_gizmoshown = false; + // a scenery model selected, or with nothing selected, the vehicle driven auto *instance{dynamic_cast(Node)}; - if (instance == nullptr) + 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)) { + // the cab isn't loaded while the driver is outside + m_vehiclepart = 0; + source = vehicle_model(vehicle, 0); + } + if (source == nullptr) + { + m_source = nullptr; m_instance = nullptr; + m_vehicle = nullptr; return; } - if (instance != m_instance) + if ((source != m_source) || (instance != m_instance) || (vehicle != m_vehicle)) { - load(*instance); + 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)) { @@ -322,34 +711,72 @@ void eu07m_model_panel::render(scene::basic_node *Node) } // 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 - 900.f, viewport->WorkPos.y + 120.f), ImGuiCond_FirstUseEver); - ImGui::SetNextWindowSize(ImVec2(440, 560), ImGuiCond_FirstUseEver); + 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)) + { + // 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_file(); - if (ImGui::CollapsingHeader(STR_C("Nodes and their components"), ImGuiTreeNodeFlags_DefaultOpen)) + render_header(); + if (ImGui::BeginTabBar("##eu07mtabs")) { - for (std::uint32_t idx = 0; idx < m_model.nodes.size(); idx = m_model.nodes[idx].subtree_end) + if (ImGui::BeginTabItem(STR_C("Model"))) { - render_node(idx); + render_model_tab(); + ImGui::EndTabItem(); } + 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(); } - render_model_components(); - render_clips(*instance); - render_channels(*instance); } ImGui::End(); + render_view(); } -void eu07m_model_panel::render_file() +void eu07m_model_panel::render_header() { - ImGui::TextWrapped("%s", m_path.c_str()); - 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::TextDisabled("%s", std::vformat(STR("{} nodes, {} components, {} clips, {} vertices"), std::make_format_args(nodes, components, clips, vertices)).c_str()); + if (m_vehicle != 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::TextUnformatted(std::filesystem::path{m_path}.filename().string().c_str()); + if (ImGui::IsItemHovered()) + { + 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::BeginDisabled(false == m_dirty); if (ImGui::Button(STR_C("Save the model"))) { @@ -357,9 +784,15 @@ void eu07m_model_panel::render_file() } ImGui::EndDisabled(); ImGui::SameLine(); - if (ImGui::Button(STR_C("Read it again")) && (m_instance != nullptr)) + if (ImGui::Button(STR_C("Read it again")) && (m_source != nullptr)) { - load(*const_cast(m_instance)); + load(*m_source); + } + ImGui::SameLine(); + ImGui::Checkbox(STR_C("Lights marked in the view"), &m_marks); + 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")); } if (false == m_message.empty()) { @@ -367,51 +800,182 @@ void eu07m_model_panel::render_file() } } -void eu07m_model_panel::render_node(std::uint32_t const Index) +void eu07m_model_panel::render_model_tab() { - auto const &node{m_model.nodes[Index]}; - auto const name{m_model.string(node.name)}; - // the components aimed at the node, whether its range lists them or not - std::vector components; - for (std::uint32_t idx = 0; idx < m_model.components.size(); ++idx) + auto const height{ImGui::GetContentRegionAvail().y}; + if (ImGui::BeginChild("##eu07mtree", ImVec2(ImGui::GetContentRegionAvail().x * 0.42f, height), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX)) { - if ((m_model.components[idx].kind == eu07m::target_kind::node) && (m_model.components[idx].target == Index)) + 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) { - components.push_back(idx); + render_tree_node(idx); } } - auto const leaf{(node.subtree_end == Index + 1) && components.empty()}; - auto label{name.empty() ? std::string{STR_C("(no name)")} : std::string{name}}; - if (false == components.empty()) + ImGui::EndChild(); + ImGui::SameLine(); + if (ImGui::BeginChild("##eu07mproperties", ImVec2(0.f, height), ImGuiChildFlags_Borders)) { - auto const count{components.size()}; - label += std::vformat(STR(" [{} components]"), std::make_format_args(count)); + // the fields leave room for their labels + ImGui::PushItemWidth(-ImGui::GetFontSize() * label_width); + render_properties(); + ImGui::PopItemWidth(); } - label += "##node" + std::to_string(Index); - // a small model shows its whole tree at once - auto const open{m_model.nodes.size() <= small_model ? ImGuiTreeNodeFlags_DefaultOpen : ImGuiTreeNodeFlags_None}; - if (false == ImGui::TreeNodeEx(label.c_str(), leaf ? ImGuiTreeNodeFlags_Leaf : open)) + ImGui::EndChild(); +} + +void eu07m_model_panel::render_tree_node(std::uint32_t const Index) +{ + auto const &node{m_model.nodes[Index]}; + auto const components{node_components(m_model, Index)}; + auto const label{node_label(m_model, Index, components) + "##node" + std::to_string(Index)}; + auto flags{ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth}; + if (node.subtree_end == Index + 1) + { + flags |= ImGuiTreeNodeFlags_Leaf; + } + if (m_model.nodes.size() <= small_model) + { + flags |= ImGuiTreeNodeFlags_DefaultOpen; + } + if (m_selected == static_cast(Index)) + { + flags |= ImGuiTreeNodeFlags_Selected; + // picked in the view: the tree opens down to it + if (m_scrolltoselected) + { + ImGui::SetScrollHereY(); + m_scrolltoselected = false; + } + } + if (m_selected > static_cast(Index) && m_selected < static_cast(node.subtree_end) && m_scrolltoselected) + { + ImGui::SetNextItemOpen(true); + } + auto const opened{ImGui::TreeNodeEx(label.c_str(), flags)}; + if (ImGui::IsItemClicked(ImGuiMouseButton_Left) && (false == ImGui::IsItemToggledOpen())) + { + select(Index); + } + if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) + { + fly_to(Index); + } + if (false == opened) { return; } - ImGui::TextDisabled("t %.3f %.3f %.3f r %.3f %.3f %.3f %.3f s %.3f %.3f %.3f", node.translation[0], node.translation[1], node.translation[2], node.rotation[0], node.rotation[1], - node.rotation[2], node.rotation[3], node.scale[0], node.scale[1], node.scale[2]); - for (auto const component : components) - { - render_component(component); - } for (auto child = Index + 1; child < node.subtree_end; child = m_model.nodes[child].subtree_end) { - render_node(child); + render_tree_node(child); } ImGui::TreePop(); } +void eu07m_model_panel::render_properties() +{ + 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")); + 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"))) + { + 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)) + { + 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) + { + render_pantograph_hold(*m_vehicle, idx); + } + } + 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); }); +} + +void eu07m_model_panel::render_node_hold(std::uint32_t const Index) const +{ + auto const *target{submodel(Index)}; + if ((m_vehicle == nullptr) || (m_vehiclepart != 0) || (target == nullptr)) + { + 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)) + { + 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); + } +} + +void eu07m_model_panel::render_node_settings(std::uint32_t const Index) +{ + ImGui::SeparatorText(STR_C("Settings of the node")); + auto &node{m_model.nodes[Index]}; + auto *target{submodel(Index)}; + if ((node.flags & eu07m::node_flags::matrix) != 0) + { + ImGui::TextDisabled("%s", STR_C("Placed by a matrix (XFRM), not edited here")); + } + else if (edit_place(node)) + { + moved(Index); + } + if (edit_range(node)) + { + m_dirty = true; + if (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"))) + { + add_light(Index); + } +} + void eu07m_model_panel::render_component(std::uint32_t const Index) { - auto const label{std::format("{} [{}]##component{}", fourcc_text(m_model.components[Index].type), Index, Index)}; - auto const open{m_model.components.size() <= small_model / 4 ? ImGuiTreeNodeFlags_DefaultOpen : ImGuiTreeNodeFlags_None}; - if (false == ImGui::TreeNodeEx(label.c_str(), open)) + 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)) { return; } @@ -419,42 +983,253 @@ void eu07m_model_panel::render_component(std::uint32_t const Index) if (edit_component(m_model, Index)) { m_dirty = true; + show_change(Index); } ImGui::PopID(); - ImGui::TreePop(); +} + +bool eu07m_model_panel::select_node(std::string_view const Name) +{ + auto const nodes{eu07m::find_nodes(m_model, Name)}; + if (nodes.empty()) + { + return false; + } + select(nodes.front()); + m_scrolltoselected = true; + return true; +} + +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 +{ + return Node < m_submodels.size() ? m_submodels[Node] : nullptr; +} + +std::optional eu07m_model_panel::placement() const +{ + if (m_vehicle != nullptr) + { + return glm::translate(glm::dmat4{1.0}, m_vehicle->GetPosition()) * m_vehicle->mMatrix; + } + if (m_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())}; + 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()}); +} + +void eu07m_model_panel::render_view() +{ + auto const where{placement()}; + if ((false == where.has_value()) || m_submodels.empty()) + { + return; + } + 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) + { + 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; + } + } + // the node 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) + { + draw_box(drawlist, projection, space, *m_box, overlay_color::selected); + } + draw_axes(drawlist, projection, space, 0.3); + render_gizmo(*where, GfxRenderer->Camera_Position()); +} + +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)) + { + return; + } + m_gizmoshown = true; + ImGuizmo::BeginFrame(); + ImGuizmo::SetOrthographic(Global.EditorOrtho); + ImGuiIO const &io{ImGui::GetIO()}; + ImGuizmo::SetRect(0.f, 0.f, io.DisplaySize.x, io.DisplaySize.y); + auto const view{GfxRenderer->Camera_View_Matrix()}; + auto const projection{editor_mode::projection_matrix(io.DisplaySize.y > 0.f ? io.DisplaySize.x / io.DisplaySize.y : 1.f)}; + // the model in the space of the camera, its position taken off, as the gizmo of the editor works + auto const model{glm::translate(glm::dmat4{1.0}, -Camera) * Placement}; + auto matrix{glm::mat4{model * model_space(*target)}}; + auto const operation{m_gizmo == gizmo::turn ? ImGuizmo::ROTATE : ImGuizmo::TRANSLATE}; + ImGuizmo::Manipulate(glm::value_ptr(view), glm::value_ptr(projection), operation, ImGuizmo::LOCAL, glm::value_ptr(matrix)); + if (ImGui::IsMouseClicked(ImGuiMouseButton_Left) && ImGuizmo::IsOver()) + { + m_tookpress = true; + } + if (false == ImGuizmo::IsUsing()) + { + return; + } + // back to the space of the parent of the node + auto const parent{target->Parent != nullptr ? model_space(*target->Parent) : glm::dmat4{1.0}}; + auto const local{glm::mat4{glm::inverse(model * parent) * glm::dmat4{matrix}}}; + if (eu07m::set_transform(m_model.nodes[index], local, 1e-3f)) + { + moved(index); + } +} + +void eu07m_model_panel::moved(std::uint32_t const Node) +{ + m_model.nodes[Node].flags &= ~eu07m::node_flags::no_transform; + m_dirty = true; + if (auto *target{submodel(Node)}; target != nullptr) + { + m_source->SetEditorTransform(*target, eu07m::local_transform(m_model, Node)); + } +} + +void eu07m_model_panel::show_change(std::uint32_t const Index) const +{ + auto const &record{m_model.components[Index]}; + if ((m_source == nullptr) || (record.type != eu07m::component::light) || (record.kind != eu07m::target_kind::node) || (record.data_size < sizeof(payload::light)) || + (std::size_t{record.data_offset} + sizeof(payload::light) > m_model.component_data.size())) + { + return; + } + auto *target{submodel(record.target)}; + if ((target == nullptr) || (target->eType != TP_FREESPOTLIGHT)) + { + return; + } + payload::light light; + std::memcpy(&light, m_model.component_data.data() + record.data_offset, sizeof(light)); + TModel3d::ApplyEU07MLight(*target, light); + m_source->state_changed(); +} + +void eu07m_model_panel::add_light(std::uint32_t const Parent) +{ + // 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) + { + name = std::format("light_{}", number); + } + eu07m::node_record node; + node.name = m_model.intern(name); + node.legacy_flags = light_node_flags; + 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); + 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) + { + 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(); + } + // 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)); +} + +void eu07m_model_panel::fly_to(std::uint32_t const Node) const +{ + auto const where{placement()}; + auto const *target{submodel(Node)}; + if ((focus == nullptr) || (target == nullptr) || (false == where.has_value())) + { + return; + } + // the node in the model, or the middle of its geometry when it has no offset of its own + focus(point_of(*where, glm::dvec3{target->offset(0.01f)}), node_focus_radius); } void eu07m_model_panel::render_model_components() { - auto const count{std::ranges::count(m_model.components, eu07m::target_kind::model, &eu07m::component_record::kind)}; - if (count == 0) + for (std::uint32_t idx = 0; idx < m_model.components.size(); ++idx) { - return; - } - if (ImGui::CollapsingHeader(STR_C("Components of the model"), m_model.nodes.size() <= small_model ? ImGuiTreeNodeFlags_DefaultOpen : ImGuiTreeNodeFlags_None)) - { - for (std::uint32_t idx = 0; idx < m_model.components.size(); ++idx) + if (m_model.components[idx].kind == eu07m::target_kind::model) { - if (m_model.components[idx].kind == eu07m::target_kind::model) - { - render_component(idx); - } + render_component(idx); } } } void eu07m_model_panel::render_clips(TAnimModel &Instance) { - if (m_model.clips.empty() || (false == ImGui::CollapsingHeader(STR_C("Animation clips")))) + if (m_model.clips.empty()) { return; } + ImGui::SeparatorText(STR_C("Animation clips")); for (std::size_t idx = 0; idx < m_model.clips.size(); ++idx) { auto &clip{m_model.clips[idx]}; ImGui::PushID(static_cast(idx)); auto const name{std::string{m_model.string(clip.name)}}; - ImGui::SeparatorText(name.c_str()); + ImGui::TextUnformatted(name.c_str()); auto looped{(clip.flags & eu07m::clip_flags::loop) != 0}; auto autoplay{(clip.flags & eu07m::clip_flags::autoplay) != 0}; if (ImGui::Checkbox(STR_C("Looped"), &looped) | ImGui::Checkbox(STR_C("Plays on its own"), &autoplay)) @@ -477,10 +1252,11 @@ void eu07m_model_panel::render_clips(TAnimModel &Instance) void eu07m_model_panel::render_channels(TAnimModel &Instance) { - if ((Instance.pModel == nullptr) || Instance.pModel->channels().empty() || (false == ImGui::CollapsingHeader(STR_C("Channels")))) + if ((Instance.pModel == nullptr) || Instance.pModel->channels().empty()) { return; } + ImGui::SeparatorText(STR_C("Channels")); auto const &channels{Instance.pModel->channels()}; m_channels.resize(channels.size(), 0.f); for (std::size_t idx = 0; idx < channels.size(); ++idx) diff --git a/application/editoruimodel.h b/application/editoruimodel.h index 22d24bab6..046fbbdab 100644 --- a/application/editoruimodel.h +++ b/application/editoruimodel.h @@ -11,41 +11,94 @@ http://mozilla.org/MPL/2.0/. #include "model/eu07m/eu07m_model.h" +#include +#include + #include +#include +#include #include +#include #include class TAnimModel; +class TDynamicObject; +class TModel3d; +class TSubModel; namespace scene { class basic_node; } -// the window of the EU07M model of the scenery instance selected in the editor: the tree of its nodes with their components, the fields -// of the common components to edit and save to the file, and the clips and the channels of the model to try on the instance. the -// geometry, the mapping and the materials aren't edited here +// 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 class eu07m_model_panel { public: - // shown while the selected node is a model instance loaded from an EU07M file void render(scene::basic_node *Node); + // 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 + 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); private: - bool load(TAnimModel &Instance); - void render_file(); - void render_node(std::uint32_t Index); + enum class gizmo : int { none, move, turn }; + + bool load(TModel3d &Model); + void render_header(); + void render_model_tab(); + 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_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_view(); + 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 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); + void fly_to(std::uint32_t Node) const; void save(); bool m_open{true}; - TAnimModel const *m_instance{nullptr}; + bool m_tofront{false}; // the window is brought to the front in the next frame + 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 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 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 + 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::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 be99933b4..8da6b5a37 100644 --- a/docs/eu07m-format.md +++ b/docs/eu07m-format.md @@ -286,12 +286,30 @@ 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`): +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 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; + 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 diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 0eb29e1ab..bee4f2c7c 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -16538,3 +16538,249 @@ msgstr "Nie zapisano: nie można zapisać pliku" msgid "Saved. The game uses the change once it loads the model again" msgstr "Zapisano. Gra użyje zmiany, gdy wczyta model ponownie" + +msgid "Body" +msgstr "Pudło" + +msgid "Cab" +msgstr "Kabina" + +msgid "Automatic" +msgstr "Automatycznie" + +msgid "Pantograph {}" +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" + +msgid "Socket" +msgstr "Gniazdo" + +msgid "Joint" +msgstr "Przegub" + +msgid "Spring" +msgstr "Sprężyna" + +msgid "Chain" +msgstr "Łańcuch" + +msgid "Variants" +msgstr "Warianty" + +msgid "Channel" +msgstr "Kanał" + +msgid "Light slot" +msgstr "Slot światła" + +msgid "Light source" +msgstr "Źródło światła" + +msgid "Emitter" +msgstr "Emiter" + +msgid "Attached model" +msgstr "Dołączony model" + +msgid "Collision shape" +msgstr "Bryła kolizji" + +msgid "Animation (E3D)" +msgstr "Animacja (E3D)" + +msgid "Text (E3D)" +msgstr "Tekst (E3D)" + +msgid "Stars (E3D)" +msgstr "Gwiazdy (E3D)" + +msgid "Material (E3D)" +msgstr "Materiał (E3D)" + +msgid "Component" +msgstr "Komponent" + +msgid "Upper headlamp, front" +msgstr "Reflektor górny, przód" + +msgid "Right headlamp, front" +msgstr "Reflektor prawy, przód" + +msgid "Left headlamp, front" +msgstr "Reflektor lewy, przód" + +msgid "Right high beam, front" +msgstr "Światło drogowe prawe, przód" + +msgid "Left high beam, front" +msgstr "Światło drogowe lewe, przód" + +msgid "Right signal lamp, front" +msgstr "Lampa sygnałowa prawa, przód" + +msgid "Left signal lamp, front" +msgstr "Lampa sygnałowa lewa, przód" + +msgid "Upper headlamp, rear" +msgstr "Reflektor górny, tył" + +msgid "Right headlamp, rear" +msgstr "Reflektor prawy, tył" + +msgid "Left headlamp, rear" +msgstr "Reflektor lewy, tył" + +msgid "Right high beam, rear" +msgstr "Światło drogowe prawe, tył" + +msgid "Left high beam, rear" +msgstr "Światło drogowe lewe, tył" + +msgid "Right signal lamp, rear" +msgstr "Lampa sygnałowa prawa, tył" + +msgid "Left signal lamp, rear" +msgstr "Lampa sygnałowa lewa, tył" + +msgid "Coupler hook, front" +msgstr "Hak sprzęgu, przód" + +msgid "Coupler hook, rear" +msgstr "Hak sprzęgu, tył" + +msgid "Brake hose, front" +msgstr "Wąż hamulcowy, przód" + +msgid "Brake hose, front, other side" +msgstr "Wąż hamulcowy, przód, druga strona" + +msgid "Brake hose, rear" +msgstr "Wąż hamulcowy, tył" + +msgid "Brake hose, rear, other side" +msgstr "Wąż hamulcowy, tył, druga strona" + +msgid "Supply hose, front" +msgstr "Wąż zasilający, przód" + +msgid "Supply hose, front, other side" +msgstr "Wąż zasilający, przód, druga strona" + +msgid "Supply hose, rear" +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" + +msgid "Connected" +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" + +msgid "Front lights" +msgstr "Światła przednie" + +msgid "Rear lights" +msgstr "Światła tylne" + +msgid "Couplers and hoses" +msgstr "Sprzęgi i węże" + +msgid "Position, m" +msgstr "Położenie, m" + +msgid "Rotation, degrees" +msgstr "Obrót, stopnie" + +msgid "Visible from, m" +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" + +msgid "Cone, half angle in degrees" +msgstr "Stożek, połowa kąta w stopniach" + +msgid "Hotspot, half angle in degrees" +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 "Added the light source {}; move it with the gizmo in the view" +msgstr "Dodano źródło światła {}; przesuń je uchwytem w widoku" diff --git a/model/Model3d.h b/model/Model3d.h index e540207b0..ffcd1446a 100644 --- a/model/Model3d.h +++ b/model/Model3d.h @@ -17,7 +17,9 @@ http://mozilla.org/MPL/2.0/. #include "model/skinning.h" #include "model/clip.h" +#include #include +#include #define EU07_USE_GEOMETRYINDEXING @@ -55,6 +57,9 @@ class shape_node; } class TModel3d; +namespace eu07m::payload { +struct light; +} using nameoffset_sequence = std::vector>; class TSubModel @@ -330,6 +335,10 @@ private: std::vector m_channels; // of an EU07M model void finish_binary( bool dynamic, bool hastangents ); + // the flags of the submodel tree worked out again after the editor changed it, and the renderer told + void submodels_changed(); + std::vector> m_editorsubmodels; // added by the editor, linked into the tree + std::vector> m_editormatrices; // given by the editor to submodels which had none public: TModel3d() = default; @@ -367,6 +376,15 @@ public: // the model from an EU07M file (model/eu07m/eu07m_load.cpp), as LoadFromBinFile builds it from E3D. returns false, with the reason // in the log and nothing loaded, when the file can't be read or isn't valid bool LoadFromEU07M(std::string const &FileName, bool dynamic); + // the light of the submodel as the loading of an EU07M model sets it from Light (model/eu07m/eu07m_load.cpp) + static void ApplyEU07MLight(TSubModel &Submodel, eu07m::payload::light const &Light); + // for the editor, which shows a change of an EU07M file on the model at once. a new submodel of a light, the last child of + // Parent, placed by Local in its space and kept by the model + TSubModel &AddEditorLight(TSubModel &Parent, std::string const &Name, glm::mat4 const &Local, std::uint32_t Flags, eu07m::payload::light const &Light); + // the transform of the submodel in the space of its parent; a submodel without one of its own gets one, kept by the model + 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); 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 c1865d247..3d5519be3 100644 --- a/model/eu07m/eu07m_build.cpp +++ b/model/eu07m/eu07m_build.cpp @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include #include +#include #include #include #include @@ -316,4 +317,170 @@ void compute_bounds(model &Model) { Model.bounds.push_back(to_bounds(whole, whole.empty() ? 0.f : glm::length(whole.max - whole.centre()))); } +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; +} + +template bool read_at(std::span const Data, std::size_t const Offset, Type_ &Value) { + if (Offset + sizeof(Type_) > Data.size()) + return false; + std::memcpy(&Value, Data.data() + Offset, sizeof(Type_)); + return true; +} + +template void write_at(std::span const Data, std::size_t const Offset, Type_ const &Value) { + 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) { + 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)) + return; + shift_node(node, At); + write_at(Data, offset, node); + } +} + +void shift_properties(std::span const Data, std::uint32_t const At) { + std::uint32_t count{0}; + if (false == read_at(Data, 0, count)) + return; + for (std::uint32_t idx = 0; idx < count; ++idx) { + auto const offset{sizeof(std::uint32_t) + idx * sizeof(payload::property)}; + payload::property property; + if (false == read_at(Data, offset, property)) + return; + if (property.type != payload::value_type::node) + continue; + shift_node(property.value[0], At); + write_at(Data, offset, property); + } +} + +void shift_spring(std::span const Data, std::uint32_t const At) { + payload::spring spring; + if (false == read_at(Data, 0, spring)) + return; + shift_node(spring.anchor_a, At); + shift_node(spring.anchor_b, At); + write_at(Data, 0, spring); +} + +void shift_chain(std::span const Data, std::uint32_t const At) { + if (payload::chain chain; read_at(Data, 0, chain)) + shift_node_list(Data, sizeof(chain), chain.joint_count, At); +} + +void shift_variants(std::span const Data, std::uint32_t const At) { + payload::variants variants; + if (false == read_at(Data, 0, variants)) + return; + std::size_t listsize{0}; + for (std::uint32_t idx = 0; idx < variants.state_count; ++idx) { + 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); +} + +void shift_light_slot(std::span const Data, std::uint32_t const At) { + 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); +} + +// the nodes in the data of the component +void shift_payload(model &Model, component_record const &Record, std::uint32_t const At) { + 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}; + 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; + default: break; + } +} + +// 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); + for (auto node{Parent}; node >= 0 && node < static_cast(Model.nodes.size()); node = Model.nodes[node].parent) + holding[node] = true; + for (std::uint32_t idx = 0; idx < Model.nodes.size(); ++idx) { + auto &node{Model.nodes[idx]}; + if (holding[idx] || node.subtree_end > At) + ++node.subtree_end; + if (node.parent >= static_cast(At)) + ++node.parent; + } +} + +} // 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); + 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); + if (false == Model.name_index.empty()) + build_name_index(Model); + if (false == Model.bounds.empty()) + compute_bounds(Model); + return at; +} + +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}); + component_record record; + record.type = Type; + record.kind = Kind; + record.target = Target; + record.data_offset = static_cast(Model.component_data.size()); + record.data_size = static_cast(Data.size()); + Model.component_data.insert(Model.component_data.end(), Data.begin(), Data.end()); + auto const index{static_cast(Model.components.size())}; + Model.components.push_back(record); + auto const list = [index](std::uint32_t &First, std::uint32_t &Count) { + if (Count == 0) { + First = index; + Count = 1; + } + }; + if (Kind == target_kind::node && Target < Model.nodes.size()) + list(Model.nodes[Target].component_first, Model.nodes[Target].component_count); + if (Kind == target_kind::vertex_group && Target < Model.vertex_groups.size()) + list(Model.vertex_groups[Target].component_first, Model.vertex_groups[Target].component_count); + return index; +} + + } // namespace eu07m diff --git a/model/eu07m/eu07m_build.h b/model/eu07m/eu07m_build.h index 1a4e27435..c73412995 100644 --- a/model/eu07m/eu07m_build.h +++ b/model/eu07m/eu07m_build.h @@ -16,6 +16,8 @@ http://mozilla.org/MPL/2.0/. #include +#include + namespace eu07m { struct tangent_frame { @@ -51,4 +53,12 @@ std::vector find_nodes(model const &Model, std::string_view Name) // the bounds of every node (its own geometry, in its space) and of the whole model, and the spheres of the primitives void compute_bounds(model &Model); +// puts Node in as the last child of Parent (-1: as the last root) and moves each reference to the nodes after it: the parents and +// 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); +// 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); + } // namespace eu07m diff --git a/model/eu07m/eu07m_load.cpp b/model/eu07m/eu07m_load.cpp index 4f0d29026..b8538f826 100644 --- a/model/eu07m/eu07m_load.cpp +++ b/model/eu07m/eu07m_load.cpp @@ -107,12 +107,12 @@ class submodel_builder { void build(std::uint32_t Index, TSubModel &Submodel); // the vertices and the indices of all the submodels, on several threads for a big model void fill_geometry(); + static void light(eu07m::payload::light const &Light, TSubModel &Submodel); private: void links(std::uint32_t Index, TSubModel &Submodel) const; void transform(std::uint32_t Index, TSubModel &Submodel); void material(std::uint32_t Material, TSubModel &Submodel); - static void light(eu07m::payload::light const &Light, TSubModel &Submodel); void geometry(eu07m::primitive_record const &Primitive, legacy_parts const &Parts, TSubModel &Submodel); void fill(geometry_job const &Job) const; void indices(eu07m::primitive_record const &Primitive, TSubModel &Submodel) const; @@ -536,3 +536,49 @@ bool TModel3d::LoadFromEU07M(std::string const &FileName, bool const dynamic) { WriteLog("Finished loading EU07M model data from \"" + FileName + "\"", logtype::model); return true; } + +void TModel3d::ApplyEU07MLight(TSubModel &Submodel, eu07m::payload::light const &Light) { + submodel_builder::light(Light, Submodel); +} + +TSubModel &TModel3d::AddEditorLight(TSubModel &Parent, std::string const &Name, glm::mat4 const &Local, std::uint32_t const Flags, eu07m::payload::light const &Light) { + auto &submodel{*m_editorsubmodels.emplace_back(std::make_unique())}; + submodel.eType = TP_FREESPOTLIGHT; + submodel.iFlags = Flags; + submodel.pName = Name; + submodel_builder::light(Light, submodel); + submodel.Parent = &Parent; + // the last child, as the node is the last child of its parent in the file + if (Parent.Child == nullptr) { + Parent.Child = &submodel; + } + else { + auto *last{Parent.Child}; + while (last->Next != nullptr) + last = last->Next; + last->Next = &submodel; + } + SetEditorTransform(submodel, Local); + return submodel; +} + +void TModel3d::SetEditorTransform(TSubModel &Submodel, glm::mat4 const &Local) { + if (Submodel.fMatrix == nullptr) + Submodel.fMatrix = m_editormatrices.emplace_back(std::make_unique()).get(); + *Submodel.fMatrix = float4x4(glm::value_ptr(Local)); + Submodel.iFlags |= 0x8000; + submodels_changed(); +} + +void TModel3d::SetEditorRange(TSubModel &Submodel, float const MinSq, float const MaxSq) { + Submodel.fSquareMinDist = MinSq; + Submodel.fSquareMaxDist = MaxSq > 0.f ? MaxSq : TSubModel{}.fSquareMaxDist; + submodels_changed(); +} + +void TModel3d::submodels_changed() { + if (Root != nullptr) + iFlags |= Root->FlagsCheck(); + m_lodboundsfound = false; + state_changed(); +} diff --git a/tests/unit/test_eu07m_edit.cpp b/tests/unit/test_eu07m_edit.cpp new file mode 100644 index 000000000..92dfc1cc5 --- /dev/null +++ b/tests/unit/test_eu07m_edit.cpp @@ -0,0 +1,113 @@ +#include "stdafx.h" + +#include "doctest.h" + +#include "model/eu07m/eu07m_build.h" +#include "model/eu07m/eu07m_io.h" + +#include +#include + +namespace { + +// root (0) { lamp (1), door (2) }, rear (3); a light slot of the root lists the door and the rear node, a joint is aimed at the +// rear node and a clip moves it +eu07m::model lamp_model() { + eu07m::model model; + auto const node = [&model](std::string_view const Name, std::int32_t const Parent, std::uint32_t const End) { + eu07m::node_record record; + record.name = model.intern(Name); + record.parent = Parent; + record.subtree_end = End; + model.nodes.push_back(record); + }; + node("root", -1, 3); + node("lamp", 0, 2); + node("door", 0, 3); + node("rear", -1, 4); + eu07m::payload::light_slot slot; + slot.on_count = 1; + slot.off_count = 1; + std::vector data(sizeof(slot) + 2 * sizeof(std::uint32_t)); + std::memcpy(data.data(), &slot, sizeof(slot)); + std::uint32_t const lit{2}; + std::uint32_t const dark{3}; + std::memcpy(data.data() + sizeof(slot), &lit, sizeof(lit)); + std::memcpy(data.data() + sizeof(slot) + sizeof(lit), &dark, sizeof(dark)); + eu07m::add_component(model, eu07m::component::light_slot, eu07m::target_kind::node, 0, data); + eu07m::payload::joint joint; + std::vector jointdata(sizeof(joint)); + std::memcpy(jointdata.data(), &joint, sizeof(joint)); + eu07m::add_component(model, eu07m::component::joint, eu07m::target_kind::node, 3, jointdata); + eu07m::clip_record clip; + clip.name = model.intern("open"); + clip.track_first = 0; + clip.track_count = 1; + model.clips.push_back(clip); + eu07m::track_record track; + track.node = 3; + track.key_count = 1; + model.clip_tracks.push_back(track); + model.key_times.push_back(0.f); + model.key_vectors.push_back({0.f, 0.f, 0.f}); + eu07m::build_name_index(model); + return model; +} + +std::uint32_t listed_node(eu07m::model const &Model, std::uint32_t const Component, std::size_t const Item) { + std::uint32_t node{0}; + std::memcpy(&node, Model.component_data.data() + Model.components[Component].data_offset + sizeof(eu07m::payload::light_slot) + Item * sizeof(node), sizeof(node)); + return node; +} + +} // namespace + +TEST_CASE("eu07m: a node put in under a parent moves the references to the nodes after it") { + auto model{lamp_model()}; + REQUIRE(eu07m::validate(model).empty()); + eu07m::node_record light; + light.name = model.intern("light_1"); + auto const index{eu07m::insert_node(model, 0, light)}; + CHECK(index == 3); + REQUIRE(model.nodes.size() == 5); + // the root holds it, the lamp and the door keep their subtrees, the rear node moves on + CHECK(model.nodes[0].subtree_end == 4); + CHECK(model.nodes[1].subtree_end == 2); + CHECK(model.nodes[2].subtree_end == 3); + CHECK(model.nodes[3].parent == 0); + CHECK(model.nodes[3].subtree_end == 4); + CHECK(model.string(model.nodes[4].name) == "rear"); + CHECK(model.nodes[4].parent == -1); + CHECK(model.nodes[4].subtree_end == 5); + // the joint, the track and the light slot follow the rear node; the door stays + CHECK(model.components[1].target == 4); + CHECK(model.clip_tracks[0].node == 4); + CHECK(listed_node(model, 0, 0) == 2); + CHECK(listed_node(model, 0, 1) == 4); + CHECK(eu07m::find_nodes(model, "light_1") == std::vector{3}); + CHECK(eu07m::find_nodes(model, "rear") == std::vector{4}); + CHECK(eu07m::validate(model).empty()); +} + +TEST_CASE("eu07m: a node put in without a parent goes last, and a component added is listed by it") { + auto model{lamp_model()}; + eu07m::node_record light; + light.name = model.intern("light_2"); + auto const index{eu07m::insert_node(model, -1, light)}; + CHECK(index == 4); + CHECK(model.nodes[3].subtree_end == 4); + CHECK(model.nodes[4].subtree_end == 5); + eu07m::payload::light payload; + std::vector data(sizeof(payload)); + std::memcpy(data.data(), &payload, sizeof(payload)); + auto const component{eu07m::add_component(model, eu07m::component::light, eu07m::target_kind::node, index, data)}; + CHECK(model.nodes[index].component_first == component); + CHECK(model.nodes[index].component_count == 1); + CHECK(model.components[component].data_offset % 4 == 0); + CHECK(eu07m::validate(model).empty()); + // the file written and read again holds the same + eu07m::model read; + REQUIRE(eu07m::read(eu07m::write(model), read).ok); + CHECK(read.nodes.size() == 5); + CHECK(read.components.size() == 3); +} diff --git a/vehicle/AirCoupler.h b/vehicle/AirCoupler.h index 2de380fad..1587935f2 100644 --- a/vehicle/AirCoupler.h +++ b/vehicle/AirCoupler.h @@ -31,6 +31,11 @@ public: ///Loads info about coupler. void Load(cParser *Parser, TModel3d *Model); int GetStatus() const; + // whether the submodel is one of those the coupler shows + bool is_part(TSubModel const *Submodel) const + { + return (Submodel != nullptr) && ((Submodel == ModelOn) || (Submodel == ModelOff) || (Submodel == ModelxOn)); + } inline void TurnOn() ///Turns on straight coupler. { On = true; diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp index fb28557a0..b7acdc262 100644 --- a/vehicle/DynObj.cpp +++ b/vehicle/DynObj.cpp @@ -1462,6 +1462,10 @@ void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) else m_highbeam22.TurnOff(); } + // the parts the editor holds, over what the vehicle has set + if( apply_held_parts() ) { + btnOn = true; + } // interior light levels auto sectionlightcolor { glm::vec4( 1.f ) }; bool cabsection{ true }; @@ -4613,6 +4617,12 @@ bool TDynamicObject::Update(double dt, double dt1) ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantFrontVolt * fPantCurrent * dt1 / 3600000.0; break; } // pozostałe na razie nie obsługiwane + // held by the editor, the pantograph goes where it was put, whatever the air and the switches + if( ( i < static_cast( m_heldpantographs.size() ) ) + && ( m_heldpantographs[ i ] != pantograph_hold::none ) ) { + move_pantograph( *p, m_heldpantographs[ i ] == pantograph_hold::up, dt1 ); + continue; + } if( MoverParameters->PantPress > ( MoverParameters->TrainType == dt_EZT ? 2.45 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 @@ -10473,3 +10483,129 @@ vehicle_table::erase_disabled() { return true; } + +std::array const &TDynamicObject::held_part_table() { + static std::array const table { { + { "coupler1", &TDynamicObject::btCoupler1 }, + { "coupler2", &TDynamicObject::btCoupler2 }, + { "cpneumatic1", &TDynamicObject::btCPneumatic1 }, + { "cpneumatic1r", &TDynamicObject::btCPneumatic1r }, + { "cpneumatic2", &TDynamicObject::btCPneumatic2 }, + { "cpneumatic2r", &TDynamicObject::btCPneumatic2r }, + { "pneumatic1", &TDynamicObject::btPneumatic1 }, + { "pneumatic1r", &TDynamicObject::btPneumatic1r }, + { "pneumatic2", &TDynamicObject::btPneumatic2 }, + { "pneumatic2r", &TDynamicObject::btPneumatic2r }, + { "headlamp11", &TDynamicObject::m_headlamp11 }, + { "headlamp12", &TDynamicObject::m_headlamp12 }, + { "headlamp13", &TDynamicObject::m_headlamp13 }, + { "highbeam12", &TDynamicObject::m_highbeam12 }, + { "highbeam13", &TDynamicObject::m_highbeam13 }, + { "headsignal12", &TDynamicObject::m_headsignal12 }, + { "headsignal13", &TDynamicObject::m_headsignal13 }, + { "headlamp21", &TDynamicObject::m_headlamp21 }, + { "headlamp22", &TDynamicObject::m_headlamp22 }, + { "headlamp23", &TDynamicObject::m_headlamp23 }, + { "highbeam22", &TDynamicObject::m_highbeam22 }, + { "highbeam23", &TDynamicObject::m_highbeam23 }, + { "headsignal22", &TDynamicObject::m_headsignal22 }, + { "headsignal23", &TDynamicObject::m_headsignal23 } } }; + return table; +} + +char const *TDynamicObject::held_part_name( std::size_t const Part ) { + return held_part_table()[ Part ].name; +} + +bool TDynamicObject::held_part_present( std::size_t const Part ) const { + return ( this->*( held_part_table()[ Part ].part ) ).Active(); +} + +std::size_t TDynamicObject::part_of( TSubModel const *Submodel ) const { + auto const &table { held_part_table() }; + for( auto const *submodel { Submodel }; submodel != nullptr; submodel = submodel->Parent ) { + auto const found { std::ranges::find_if( table, [ this, submodel ]( held_part_entry const &Entry ) { return ( this->*( Entry.part ) ).is_part( submodel ); } ) }; + if( found != table.end() ) { + return static_cast( std::distance( table.begin(), found ) ); + } + } + return held_part_total; +} + +bool TDynamicObject::apply_held_parts() { + auto held { false }; + auto const &table { held_part_table() }; + for( std::size_t idx = 0; idx < table.size(); ++idx ) { + auto &part { this->*( table[ idx ].part ) }; + switch( m_heldparts[ idx ] ) { + case part_hold::off: { part.TurnOff(); break; } + case part_hold::on: { part.TurnOn(); break; } + case part_hold::xon: { part.TurnxOn(); break; } + default: { continue; } + } + held = true; + } + return held; +} + +int TDynamicObject::pantograph_count() const { + return std::min( iAnimType[ ANIM_PANTS ], static_cast( m_heldpantographs.size() ) ); +} + +void TDynamicObject::hold_pantograph( int const Pantograph, pantograph_hold const Hold ) { + if( ( Pantograph < 0 ) || ( Pantograph >= pantograph_count() ) ) { + return; + } + m_heldpantographs[ Pantograph ] = Hold; +} + +void TDynamicObject::step_held_pantographs( double const Timedelta ) { + if( pants == nullptr ) { + return; + } + for( int idx = 0; idx < pantograph_count(); ++idx ) { + if( ( m_heldpantographs[ idx ] != pantograph_hold::none ) && ( pants[ idx ].fParamPants != nullptr ) ) { + move_pantograph( *pants[ idx ].fParamPants, m_heldpantographs[ idx ] == pantograph_hold::up, Timedelta ); + } + } +} + +int TDynamicObject::pantograph_of( TSubModel const *Submodel ) const { + if( pants == nullptr ) { + return -1; + } + for( auto const *submodel { Submodel }; submodel != nullptr; submodel = submodel->Parent ) { + for( int idx = 0; idx < pantograph_count(); ++idx ) { + auto const *arms { pants[ idx ].smElement }; + if( ( arms != nullptr ) && std::ranges::find( arms, arms + 5, submodel ) != arms + 5 ) { + return idx; + } + } + } + return -1; +} + +void TDynamicObject::move_pantograph( TAnimPant &Pantograph, bool const Up, double const Timedelta ) { + // the upper arm follows the lower one, and the height follows both, as the pantograph moves in Update() + auto const upper = [ &Pantograph ]( double const Lower ) { + return std::acos( std::clamp( ( Pantograph.fLenL1 * std::cos( Lower ) + Pantograph.fHoriz ) / Pantograph.fLenU1, -1.0, 1.0 ) ); }; + auto const height = [ &Pantograph, &upper ]( double const Lower ) { + return Pantograph.fLenL1 * std::sin( Lower ) + Pantograph.fLenU1 * std::sin( upper( Lower ) ) + Pantograph.fHeight; }; + // the angle of the lower arm it goes to: down at rest, up at the wire it has, or without one 1.6 m over its rest, and no + // further than the arms reach + auto target { Pantograph.fAngleL0 }; + if( Up ) { + auto const top { Pantograph.hvPowerWire != nullptr ? Pantograph.PantTraction : height( target ) + 1.6 }; + constexpr double step { 0.002 }; + while( ( height( target ) < top ) && ( target + step + upper( target + step ) < std::numbers::pi ) ) { + target += step; + } + } + // a few seconds from the rest to the wire, a little slower down, as the air moves it + auto const pace { ( Up ? 0.3 : 0.2 ) * std::max( 0.0, Timedelta ) }; + auto lower { Pantograph.fAngleL }; + lower = lower < target ? std::min( lower + pace, target ) : std::max( lower - pace, target ); + Pantograph.fAngleL = lower; + Pantograph.fAngleU = upper( lower ); + Pantograph.PantWys = height( lower ); +} diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index ca82a0950..2b9edb861 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -895,6 +895,39 @@ public: void SetLightDimmings(); void RaLightsSet(int head, int rear); int LightList( end const Side ) const { return iInventory[ Side ]; } + // the hold of the editor on parts of the vehicle (the EU07M model window): the lamps, the coupler hooks and the hoses shown in + // a state of its choice, and the pantographs held up or down, whatever the vehicle does with them. nothing is held at first + enum class part_hold : std::uint8_t { none, off, on, xon }; + enum class pantograph_hold : std::uint8_t { none, down, up }; + static constexpr std::size_t held_part_total{ 24 }; + // the name of the part, as its submodels are named in the model (headlamp11 for headlamp11_on and the like) + static char const *held_part_name( std::size_t Part ); + // whether the model of the vehicle has the part + bool held_part_present( std::size_t Part ) const; + part_hold held_part( std::size_t Part ) const { return m_heldparts[ Part ]; } + void hold_part( std::size_t Part, part_hold Hold ) { m_heldparts[ Part ] = Hold; } + // the part the submodel is, or is in; held_part_total when it's none of them + std::size_t part_of( TSubModel const *Submodel ) const; + int pantograph_count() const; + pantograph_hold held_pantograph( int Pantograph ) const { return m_heldpantographs[ Pantograph ]; } + // held up or down, the pantograph goes there at its own pace, to the wire above it if there's one + void hold_pantograph( int Pantograph, pantograph_hold Hold ); + // moves the held pantographs on by the time, where the simulation stands still (the editor) + void step_held_pantographs( double Timedelta ); + // the pantograph the submodel is an arm of, or is in; -1 when it's none + int pantograph_of( TSubModel const *Submodel ) const; + private: + struct held_part_entry { + char const *name; + AirCoupler TDynamicObject::*part; + }; + static std::array const &held_part_table(); + // the parts held by the editor shown as it holds them, after the vehicle has set them; true when any is held + bool apply_held_parts(); + static void move_pantograph( TAnimPant &Pantograph, bool Up, double Timedelta ); + std::array m_heldparts {}; + std::array m_heldpantographs {}; + public: bool has_signal_pc1_on() const; bool has_signal_pc2_on() const; bool has_signal_pc5_on() const;