18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-01 10:37:07 +01:00
Files
maszyna/application/editoruimodel.cpp
T
maj00r 107cc3c927 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_<n> 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 <name>.
2026-11-29 18:11:38 +01:00

1303 lines
46 KiB
C++

/*
This Source Code Form is subject to the
terms of the Mozilla Public License, v.
2.0. If a copy of the MPL was not
distributed with this file, You can
obtain one at
http://mozilla.org/MPL/2.0/.
*/
#include "stdafx.h"
#include "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 <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <algorithm>
#include <array>
#include <cmath>
#include <cstring>
#include <filesystem>
#include <format>
#include <fstream>
#include <string_view>
#include <utility>
namespace
{
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<TSubModel *> &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)
{
std::string result(4, ' ');
for (std::size_t idx = 0; idx < 4; ++idx)
{
result[idx] = static_cast<char>((Type >> (8 * idx)) & 0xFF);
}
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<type_name, 16> 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<part_label, 24> 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)
{
std::array<char, 128> buffer{};
auto const text{Model.string(Id)};
std::memcpy(buffer.data(), text.data(), std::min(text.size(), buffer.size() - 1));
ImGui::InputText(Label, buffer.data(), buffer.size());
if (false == ImGui::IsItemDeactivatedAfterEdit())
{
return false;
}
std::string_view const edited{buffer.data()};
Id = edited.empty() ? eu07m::no_index : Model.intern(edited);
return true;
}
// an enumeration of the format picked from the names of its values
template <typename Enum_> bool edit_enum(char const *Label, Enum_ &Value, std::initializer_list<char const *> Names)
{
std::vector<char const *> const names{Names};
auto index{static_cast<int>(Value)};
if (false == ImGui::Combo(Label, &index, names.data(), static_cast<int>(names.size())))
{
return false;
}
Value = static_cast<Enum_>(index);
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 <typename Pick_> void render_hold_group(TDynamicObject &Vehicle, char const *Title, Pick_ &&Pick)
{
std::vector<std::size_t> 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};
if (false == ImGui::Checkbox(Label, &set))
{
return false;
}
Flags = static_cast<std::uint8_t>(set ? (Flags | Bit) : (Flags & ~Bit));
return true;
}
// a rotation as a quaternion x y z w, edited as angles in degrees
bool edit_rotation(char const *Label, std::array<float, 4> &Rotation)
{
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 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 <typename Payload_, typename Edit_> bool edit_payload(eu07m::model &Model, std::uint32_t const Index, std::size_t const Offset, Edit_ &&Edit)
{
auto const &record{Model.components[Index]};
auto const at{std::size_t{record.data_offset} + Offset};
if ((Offset + sizeof(Payload_) > record.data_size) || (at + sizeof(Payload_) > Model.component_data.size()))
{
ImGui::TextDisabled("%s", STR_C("The data of the component is cut short"));
return false;
}
Payload_ value;
std::memcpy(&value, Model.component_data.data() + at, sizeof(value));
if (false == Edit(value))
{
return false;
}
std::memcpy(Model.component_data.data() + at, &value, sizeof(value));
return true;
}
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, m"), Socket.position.data(), 0.001f, 0.f, 0.f, "%.4f");
changed |= edit_rotation(STR_C("Rotation, degrees"), Socket.rotation);
return changed;
}
bool edit_joint(eu07m::model &Model, payload::joint &Joint)
{
auto changed{edit_enum(STR_C("Kind"), Joint.kind, {STR_C("fixed"), STR_C("hinge"), STR_C("ball"), STR_C("slider"), STR_C("screw")})};
auto limited{Joint.limited != 0};
if (ImGui::Checkbox(STR_C("Limited"), &limited))
{
Joint.limited = limited ? 1 : 0;
changed = true;
}
changed |= edit_string(STR_C("Role"), Model, Joint.role);
changed |= ImGui::DragFloat3(STR_C("Axis"), Joint.axis.data(), 0.01f, -1.f, 1.f, "%.3f");
changed |= ImGui::DragFloat(STR_C("Minimum"), &Joint.minimum, 0.01f);
changed |= ImGui::DragFloat(STR_C("Maximum"), &Joint.maximum, 0.01f);
changed |= ImGui::DragFloat(STR_C("Rest"), &Joint.rest, 0.01f);
if (Joint.kind == payload::joint_kind::screw)
{
changed |= ImGui::DragFloat(STR_C("Pitch, m a turn"), &Joint.pitch, 0.0005f, 0.f, 1.f, "%.4f");
}
return changed;
}
bool edit_channel(eu07m::model &Model, payload::channel &Channel)
{
auto changed{edit_string(STR_C("Name"), Model, Channel.name)};
changed |= ImGui::DragFloat(STR_C("Minimum"), &Channel.minimum, 0.01f);
changed |= ImGui::DragFloat(STR_C("Maximum"), &Channel.maximum, 0.01f);
changed |= ImGui::DragFloat(STR_C("Initial value"), &Channel.initial, 0.01f);
return changed;
}
bool edit_binding(payload::channel_binding &Binding)
{
auto changed{edit_enum(STR_C("Bound to"), Binding.kind, {STR_C("joint"), STR_C("clip"), STR_C("variants"), STR_C("light slot")})};
auto target{Binding.target == eu07m::no_index ? -1 : static_cast<int>(Binding.target)};
if (ImGui::InputInt(STR_C("Target (component or clip, -1 none)"), &target))
{
Binding.target = target < 0 ? eu07m::no_index : static_cast<std::uint32_t>(target);
changed = true;
}
changed |= ImGui::DragFloat(STR_C("Scale"), &Binding.scale, 0.01f);
changed |= ImGui::DragFloat(STR_C("Offset"), &Binding.offset, 0.01f);
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 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);
return changed;
}
bool edit_light_slot(payload::light_slot &Slot)
{
auto changed{ImGui::InputScalar(STR_C("Slot"), ImGuiDataType_U16, &Slot.slot)};
changed |= ImGui::DragFloat(STR_C("Initial state"), &Slot.initial, 0.01f, 0.f, 10.f);
changed |= ImGui::ColorEdit3(STR_C("Colour (negative: of the sources)"), Slot.color.data(), ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR);
return changed;
}
bool edit_emitter(payload::emitter &Emitter)
{
auto changed{edit_enum(STR_C("Kind"), Emitter.kind, {STR_C("smoke"), STR_C("steam"), STR_C("sparks")})};
changed |= ImGui::DragFloat3(STR_C("Direction"), Emitter.direction.data(), 0.01f, -1.f, 1.f, "%.3f");
return changed;
}
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, degrees"), Collision.rotation);
changed |= ImGui::DragFloat3(STR_C("Half extents"), Collision.size.data(), 0.001f, 0.f, 1000.f, "%.4f");
return changed;
}
bool edit_reference(eu07m::model &Model, payload::model_reference &Reference)
{
auto changed{edit_string(STR_C("Model path"), Model, Reference.path)};
changed |= edit_string(STR_C("Skin"), Model, Reference.skin);
return changed;
}
bool edit_channel_component(eu07m::model &Model, std::uint32_t const Index)
{
payload::channel channel;
auto changed{edit_payload<payload::channel>(Model, Index, 0, [&Model, &channel](payload::channel &Value) {
auto const result{edit_channel(Model, Value)};
channel = Value;
return result;
})};
for (std::uint32_t binding = 0; binding < channel.binding_count; ++binding)
{
ImGui::PushID(static_cast<int>(binding));
auto const number{binding + 1};
ImGui::SeparatorText(std::vformat(STR("Binding {}"), std::make_format_args(number)).c_str());
changed |= edit_payload<payload::channel_binding>(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<payload::socket>(Model, Index, 0, [&Model](payload::socket &Value) { return edit_socket(Model, Value); });
case component::joint: return edit_payload<payload::joint>(Model, Index, 0, [&Model](payload::joint &Value) { return edit_joint(Model, Value); });
case component::light: return edit_payload<payload::light>(Model, Index, 0, [](payload::light &Value) { return edit_light(Value); });
case component::light_slot: return edit_payload<payload::light_slot>(Model, Index, 0, [](payload::light_slot &Value) { return edit_light_slot(Value); });
case component::emitter: return edit_payload<payload::emitter>(Model, Index, 0, [](payload::emitter &Value) { return edit_emitter(Value); });
case component::collision: return edit_payload<payload::collision>(Model, Index, 0, [&Model](payload::collision &Value) { return edit_collision(Model, Value); });
case component::model_reference:
return edit_payload<payload::model_reference>(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<std::uint32_t> node_components(eu07m::model const &Model, std::uint32_t const Node)
{
std::vector<std::uint32_t> 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<std::uint32_t> 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<char const *> 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
namespace
{
using box = std::pair<glm::vec3, glm::vec3>;
// the box of the geometry of the node, in its space; none for a node without geometry
std::optional<box> node_box(eu07m::model const &Model, std::uint32_t const Node)
{
auto const mesh{Model.nodes[Node].mesh};
if ((mesh < 0) || (static_cast<std::size_t>(mesh) >= Model.meshes.size()))
{
return std::nullopt;
}
auto const &record{Model.meshes[mesh]};
std::optional<box> result;
auto const last{std::min<std::size_t>(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>(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<int>(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 (false == Global.modelformat_eu07m)
{
return false;
}
auto const path{FileCased(Model.NameGet() + ".eu07m")};
if (path.empty())
{
return false;
}
std::ifstream file{path, std::ios::binary | std::ios::ate};
std::vector<std::byte> data(file.good() ? static_cast<std::size_t>(file.tellg()) : 0);
file.seekg(0);
file.read(reinterpret_cast<char *>(data.data()), static_cast<std::streamsize>(data.size()));
eu07m::read_options options;
options.blocks = eu07m::store_source(eu07m::family_store(path));
if (auto const result{eu07m::read(data, m_model, options)}; false == result.ok)
{
m_message = result.error;
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 : Model.channels())
{
m_channels.push_back(channel.initial);
}
return true;
}
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<TAnimModel *>(Node)};
auto *vehicle{(Node == nullptr) && (simulation::Train != nullptr) ? simulation::Train->Dynamic() : nullptr};
auto *source{instance != nullptr ? instance->pModel : vehicle_model(vehicle, m_vehiclepart)};
if ((source == nullptr) && (vehicle != nullptr) && (m_vehiclepart != 0))
{
// 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 ((source != m_source) || (instance != m_instance) || (vehicle != m_vehicle))
{
m_instance = instance;
m_vehicle = vehicle;
load(*source);
}
// the time stands still in the editor: the held pantographs are moved here
if (vehicle != nullptr)
{
vehicle->step_held_pantographs(ImGui::GetIO().DeltaTime);
}
if (m_path.empty() || (false == m_open))
{
return;
}
// beside the inspector, over the right of the view, and opaque: the settings of the interface may make the windows see-through
auto const *viewport{ImGui::GetMainViewport()};
ImGui::SetNextWindowPos(ImVec2(viewport->WorkPos.x + viewport->WorkSize.x - 1100.f, viewport->WorkPos.y + 100.f), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(760, 680), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowBgAlpha(0.97f);
if (std::exchange(m_tofront, false))
{
// docked, it may be a tab behind the inspector
ImGui::SetNextWindowFocus();
}
if (ImGui::Begin((std::string(STR_C("EU07M model")) + "###eu07mmodel").c_str(), &m_open, ImGuiWindowFlags_NoFocusOnAppearing))
{
render_header();
if (ImGui::BeginTabBar("##eu07mtabs"))
{
if (ImGui::BeginTabItem(STR_C("Model")))
{
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();
}
}
ImGui::End();
render_view();
}
void eu07m_model_panel::render_header()
{
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")))
{
save();
}
ImGui::EndDisabled();
ImGui::SameLine();
if (ImGui::Button(STR_C("Read it again")) && (m_source != nullptr))
{
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())
{
ImGui::TextWrapped("%s", m_message.c_str());
}
}
void eu07m_model_panel::render_model_tab()
{
auto const height{ImGui::GetContentRegionAvail().y};
if (ImGui::BeginChild("##eu07mtree", ImVec2(ImGui::GetContentRegionAvail().x * 0.42f, height), ImGuiChildFlags_Borders | ImGuiChildFlags_ResizeX))
{
ImGui::TextDisabled("%s", STR_C("A click picks, a double click takes the camera there"));
for (std::uint32_t idx = 0; idx < m_model.nodes.size(); idx = m_model.nodes[idx].subtree_end)
{
render_tree_node(idx);
}
}
ImGui::EndChild();
ImGui::SameLine();
if (ImGui::BeginChild("##eu07mproperties", ImVec2(0.f, height), ImGuiChildFlags_Borders))
{
// the fields leave room for their labels
ImGui::PushItemWidth(-ImGui::GetFontSize() * label_width);
render_properties();
ImGui::PopItemWidth();
}
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<std::int64_t>(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<std::int64_t>(Index) && m_selected < static_cast<std::int64_t>(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;
}
for (auto child = Index + 1; child < node.subtree_end; child = m_model.nodes[child].subtree_end)
{
render_tree_node(child);
}
ImGui::TreePop();
}
void eu07m_model_panel::render_properties()
{
if ((m_selected < 0) || (m_selected >= static_cast<std::int64_t>(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<std::uint32_t>(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<int>(m_gizmo)};
ImGui::RadioButton(STR_C("Move"), &mode, static_cast<int>(gizmo::move));
ImGui::SameLine();
ImGui::RadioButton(STR_C("Turn"), &mode, static_cast<int>(gizmo::turn));
ImGui::SameLine();
ImGui::RadioButton(STR_C("No gizmo"), &mode, static_cast<int>(gizmo::none));
m_gizmo = static_cast<gizmo>(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 &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;
}
ImGui::PushID(static_cast<int>(Index));
if (edit_component(m_model, Index))
{
m_dirty = true;
show_change(Index);
}
ImGui::PopID();
}
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<glm::dmat4> 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<std::int64_t>(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<std::uint32_t>(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<std::uint32_t>(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<std::int32_t>(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<std::byte> 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()
{
for (std::uint32_t idx = 0; idx < m_model.components.size(); ++idx)
{
if (m_model.components[idx].kind == eu07m::target_kind::model)
{
render_component(idx);
}
}
}
void eu07m_model_panel::render_clips(TAnimModel &Instance)
{
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<int>(idx));
auto const name{std::string{m_model.string(clip.name)}};
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))
{
clip.flags = (looped ? eu07m::clip_flags::loop : 0u) | (autoplay ? eu07m::clip_flags::autoplay : 0u);
m_dirty = true;
}
// the editor stops the time: the clip is held at the time picked
if (ImGui::SliderFloat(STR_C("Time, s"), &m_cliptimes[idx], 0.f, std::max(clip.duration, 0.001f), "%.2f"))
{
Instance.play_clip(name, 1.f, m_cliptimes[idx]);
}
ImGui::PopID();
}
if (ImGui::Button(STR_C("Stop the clips")))
{
Instance.stop_clips();
}
}
void eu07m_model_panel::render_channels(TAnimModel &Instance)
{
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)
{
auto const &channel{channels[idx]};
ImGui::PushID(static_cast<int>(idx));
if (ImGui::SliderFloat(channel.name.c_str(), &m_channels[idx], std::min(channel.minimum, channel.maximum), std::max(channel.minimum, channel.maximum), "%.3f"))
{
Instance.set_channel(channel.name, m_channels[idx]);
}
ImGui::PopID();
}
ImGui::TextDisabled("%s", STR_C("The channels and the clips are tried on the instance; the model as the file had it when it was loaded"));
}
void eu07m_model_panel::save()
{
if (auto const faults{eu07m::validate(m_model, 1)}; false == faults.empty())
{
m_message = std::vformat(STR("Not saved: {}"), std::make_format_args(faults.front()));
return;
}
auto const data{eu07m::write(m_model)};
auto const temporary{m_path + ".tmp"};
{
std::ofstream file{temporary, std::ios::binary};
file.write(reinterpret_cast<char const *>(data.data()), static_cast<std::streamsize>(data.size()));
if (false == file.good())
{
m_message = STR("Not saved: the file can't be written");
return;
}
}
std::error_code error;
std::filesystem::rename(temporary, m_path, error);
if (error)
{
m_message = STR("Not saved: the file can't be written");
return;
}
m_dirty = false;
m_message = STR("Saved. The game uses the change once it loads the model again");
}