18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-12-01 09:27:10 +01:00
Files
maszyna/application/editoruimodel.cpp
T
maj00r 56756ddb8e feat(model): .ng3d and .ng3p in what this branch adds, as below it
The model files are .ng3d and the family store .ng3p, selected with modelformat ng3d (8637101d9 on feat/e4d-compact).
2026-11-30 22:27:05 +01:00

2527 lines
84 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_convert.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 <cctype>
#include <cmath>
#include <cstring>
#include <filesystem>
#include <format>
#include <fstream>
#include <limits>
#include <span>
#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 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;
}
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
namespace
{
using part_hold = TDynamicObject::part_hold;
using pantograph_hold = TDynamicObject::pantograph_hold;
// the buttons of a lamp, a coupler or a hose, and of a pantograph, in the order of these holds
constexpr std::array part_holds{part_hold::on, part_hold::off, part_hold::xon, part_hold::none};
constexpr std::array pantograph_holds{pantograph_hold::up, pantograph_hold::down, pantograph_hold::none};
// the most changes taken back
constexpr std::size_t undo_depth{50};
// how far from the box of the geometry of a part a click still picks it, metres
constexpr double pick_margin{0.03};
// the radius of the sphere the camera frames around a vehicle, in its lengths
constexpr double vehicle_focus{0.6};
struct colour_preset
{
char const *name;
std::array<float, 3> colour;
};
// the colours a light is often given
constexpr std::array<colour_preset, 7> colour_presets{{{"Warm white", {1.f, 0.85f, 0.6f}},
{"White", {1.f, 1.f, 1.f}},
{"Cold white", {0.8f, 0.9f, 1.f}},
{"Red", {1.f, 0.08f, 0.04f}},
{"Yellow", {1.f, 0.75f, 0.1f}},
{"Green", {0.1f, 1.f, 0.3f}},
{"Blue", {0.2f, 0.45f, 1.f}}}};
// a row of buttons of which one is chosen, as a switch of a few positions; the position clicked, none when none was
std::optional<std::size_t> choice_buttons(char const *Id, std::size_t const Chosen, std::span<char const *const> const Labels)
{
std::optional<std::size_t> clicked;
ImGui::PushID(Id);
for (std::size_t idx = 0; idx < Labels.size(); ++idx)
{
if (idx > 0)
{
ImGui::SameLine(0.f, ImGui::GetStyle().ItemInnerSpacing.x);
}
auto const chosen{idx == Chosen};
if (chosen)
{
ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyleColorVec4(ImGuiCol_HeaderActive));
}
if (ImGui::Button(Labels[idx]))
{
clicked = idx;
}
if (chosen)
{
ImGui::PopStyleColor();
}
}
ImGui::PopID();
return clicked;
}
template <typename Value_, std::size_t Size_> std::size_t position_of(std::array<Value_, Size_> const &Values, Value_ const Value)
{
return static_cast<std::size_t>(std::ranges::find(Values, Value) - Values.begin());
}
// the name of a part in the first column of a table, the tooltip on it
void part_cell(char const *Text, char const *Tooltip)
{
ImGui::TableNextRow();
ImGui::TableNextColumn();
ImGui::AlignTextToFramePadding();
ImGui::TextUnformatted(Text);
if ((Tooltip != nullptr) && ImGui::IsItemHovered())
{
ImGui::SetTooltip("%s", Tooltip);
}
ImGui::TableNextColumn();
}
// a row of a table: how the editor holds a part of the vehicle
void part_hold_row(TDynamicObject &Vehicle, std::size_t const Part)
{
auto const *name{TDynamicObject::held_part_name(Part)};
auto const variants{std::format("{0}_on / {0}_off / {0}_xon", name)};
part_cell(part_text(name), variants.c_str());
std::array const lamp{STR_C("Lit"), STR_C("Off"), STR_C("Dimmed"), STR_C("As the vehicle has it")};
std::array const coupler{STR_C("Connected"), STR_C("Disconnected"), STR_C("Other position"), STR_C("As the vehicle has it")};
if (auto const clicked{choice_buttons(name, position_of(part_holds, Vehicle.held_part(Part)), is_lamp(name) ? lamp : coupler)})
{
Vehicle.hold_part(Part, part_holds[*clicked]);
}
}
// a row of a table: how the editor holds a pantograph
void pantograph_hold_row(TDynamicObject &Vehicle, int const Pantograph)
{
auto const number{Pantograph + 1};
auto const label{std::vformat(STR("Pantograph {}"), std::make_format_args(number))};
part_cell(label.c_str(), nullptr);
std::array const labels{STR_C("Up"), STR_C("Down"), STR_C("As the vehicle has it")};
if (auto const clicked{choice_buttons(label.c_str(), position_of(pantograph_holds, Vehicle.held_pantograph(Pantograph)), labels)})
{
Vehicle.hold_pantograph(Pantograph, pantograph_holds[*clicked]);
}
}
// the parts of the vehicle Pick takes, those the model has, in a table under the title, with buttons to hold them all at once
template <typename Pick_> void part_group(TDynamicObject &Vehicle, char const *Title, bool const Lamps, Pick_ const &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);
ImGui::PushID(Title);
auto const all = [&Vehicle, &parts](part_hold const Hold) {
for (auto const part : parts)
{
Vehicle.hold_part(part, Hold);
}
};
if (ImGui::SmallButton(Lamps ? STR_C("Light them all") : STR_C("Connect them all")))
{
all(part_hold::on);
}
ImGui::SameLine();
if (ImGui::SmallButton(Lamps ? STR_C("Put them all out") : STR_C("Disconnect them all")))
{
all(part_hold::off);
}
ImGui::SameLine();
if (ImGui::SmallButton(STR_C("All as the vehicle has them")))
{
all(part_hold::none);
}
if (ImGui::BeginTable("##parts", 2, ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg))
{
for (auto const part : parts)
{
part_hold_row(Vehicle, part);
}
ImGui::EndTable();
}
ImGui::PopID();
}
// the vehicle is still in the simulation
bool vehicle_exists(TDynamicObject const *Vehicle)
{
return std::ranges::find(simulation::Vehicles.sequence(), Vehicle) != simulation::Vehicles.sequence().end();
}
// the scenery model is still in the scenery
bool instance_exists(TAnimModel const *Instance)
{
return std::ranges::find(simulation::Instances.sequence(), Instance) != simulation::Instances.sequence().end();
}
// the place of the node, its range and its flags as another record has them
bool same_place(eu07m::node_record const &Left, eu07m::node_record const &Right)
{
return (Left.translation == Right.translation) && (Left.rotation == Right.rotation) && (Left.scale == Right.scale) && (Left.flags == Right.flags) &&
(Left.range_min_sq == Right.range_min_sq) && (Left.range_max_sq == Right.range_max_sq);
}
// the point lies in the box, or within the margin of it
bool inside(std::pair<glm::vec3, glm::vec3> const &Box, glm::dvec3 const &Point, double const Margin)
{
auto const low{glm::dvec3{Box.first} - Margin};
auto const high{glm::dvec3{Box.second} + Margin};
return (Point.x >= low.x) && (Point.y >= low.y) && (Point.z >= low.z) && (Point.x <= high.x) && (Point.y <= high.y) && (Point.z <= high.z);
}
// the turn which brings -z, the axis of a spot, onto the direction
glm::quat aim(glm::vec3 const &Direction)
{
glm::vec3 const axis{0.f, 0.f, -1.f};
auto const cosine{glm::dot(axis, Direction)};
if (cosine < -0.9999f)
{
// the other way round: half a turn about y
return glm::quat{0.f, 0.f, 1.f, 0.f};
}
auto const cross{glm::cross(axis, Direction)};
return glm::normalize(glm::quat{1.f + cosine, cross.x, cross.y, cross.z});
}
// a text with no case, to look for another in it
std::string lowered(std::string_view const Text)
{
std::string result{Text};
std::ranges::transform(result, result.begin(), [](unsigned char const Character) { return static_cast<char>(std::tolower(Character)); });
return result;
}
// the half angle of a cone in degrees, from its cosine
float cone_degrees(float const Cosine)
{
return glm::degrees(std::acos(std::clamp(Cosine, -1.f, 1.f)));
}
// the width of the beam of a spot and its bright middle, in degrees from its axis
bool edit_beam(payload::light &Light)
{
auto changes{false};
auto width{cone_degrees(Light.cos_falloff)};
auto middle{std::min(cone_degrees(Light.cos_hotspot), width)};
if (ImGui::SliderFloat(STR_C("Width of the beam, degrees"), &width, 1.f, 89.f, "%.0f"))
{
Light.cos_falloff = std::cos(glm::radians(width));
Light.cos_hotspot = std::cos(glm::radians(std::min(middle, width)));
changes = true;
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("%s", STR_C("From the axis of the beam to its edge"));
}
if (ImGui::SliderFloat(STR_C("Bright middle, degrees"), &middle, 0.f, width, "%.0f"))
{
Light.cos_hotspot = std::cos(glm::radians(middle));
changes = true;
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("%s", STR_C("The middle of the beam lit fully; from there to the edge it fades"));
}
return changes;
}
} // namespace
void eu07m_model_panel::update(scene::basic_node *Selected, bool const Active)
{
m_gizmoshown = false;
m_active = Active;
if ((m_pickedvehicle != nullptr) && (false == vehicle_exists(m_pickedvehicle)))
{
m_pickedvehicle = nullptr;
}
if ((m_target.vehicle != nullptr) && (false == vehicle_exists(m_target.vehicle)))
{
open(target{});
}
// the time stands still in the editor: the held pantographs are moved here
if (m_target.vehicle != nullptr)
{
m_target.vehicle->step_held_pantographs(ImGui::GetIO().DeltaTime);
}
if (false == Active)
{
m_placing.reset();
m_tookpress = false;
return;
}
if ((m_target.instance != nullptr) && (false == instance_exists(m_target.instance)))
{
open(target{});
}
if (Selected != m_lastselected)
{
// a scenery model clicked is edited in place of the vehicle picked
m_lastselected = Selected;
if (dynamic_cast<TAnimModel *>(Selected) != nullptr)
{
m_pickedvehicle = nullptr;
}
}
auto const next{wanted(Selected)};
if (next == m_target)
{
m_kept.reset();
}
else if (false == m_dirty)
{
open(next);
}
else if ((false == m_kept.has_value()) || (*m_kept != next))
{
m_pending = next;
}
render_unsaved_popup();
if (m_placing && ImGui::IsKeyPressed(ImGuiKey_Escape, false))
{
m_placing.reset();
}
if ((m_source == nullptr) || m_path.empty())
{
return;
}
// the model as it is between the presses and the drags: a change made by the next one takes it back to this
if ((false == ImGui::IsAnyItemActive()) && (false == ImGuizmo::IsUsing()))
{
m_before = take(false);
m_changing = false;
}
render_view();
}
eu07m_model_panel::target eu07m_model_panel::wanted(scene::basic_node *Selected) const
{
target result;
if (m_pickedvehicle != nullptr)
{
result.vehicle = m_pickedvehicle;
}
else if (auto *instance{dynamic_cast<TAnimModel *>(Selected)}; instance != nullptr)
{
result.instance = instance;
return result;
}
else if (simulation::Train != nullptr)
{
result.vehicle = simulation::Train->Dynamic();
}
// the cab isn't loaded while the driver is outside
if ((result.vehicle != nullptr) && (m_part == 1) && (result.vehicle->mdKabina != nullptr))
{
result.part = 1;
}
return result;
}
void eu07m_model_panel::release_holds() const
{
if ((m_target.vehicle != nullptr) && vehicle_exists(m_target.vehicle))
{
m_target.vehicle->release_holds();
}
}
void eu07m_model_panel::open(target const &Target)
{
// the vehicle shown before has its parts and pantographs back: a hold is only for the vehicle in the panel
if (Target.vehicle != m_target.vehicle)
{
release_holds();
}
m_target = Target;
m_pending.reset();
m_kept.reset();
m_undo.clear();
m_redo.clear();
m_placing.reset();
m_source = nullptr;
m_path.clear();
m_problem.clear();
m_importable = false;
m_model = eu07m::model{};
m_submodels.clear();
m_boxes.clear();
m_selected = -1;
m_dirty = false;
m_message.clear();
auto *source{Target.instance != nullptr ? Target.instance->pModel : vehicle_model(Target.vehicle, Target.part)};
if (source != nullptr)
{
load(*source);
}
}
bool eu07m_model_panel::load(TModel3d &Model)
{
m_source = &Model;
if (false == Global.modelformat_eu07m)
{
m_problem = STR("The models of the EU07M format are turned off (modelformat in eu07.ini)");
return false;
}
auto const path{FileCased(Model.NameGet() + ".ng3d")};
if (path.empty())
{
// one is made of the model as the game loaded it: for a vehicle, its body or its cab, that is what the game writes to the
// .e3d it makes of a .t3d (convertmodels)
m_importable = (false == FileCased(Model.NameGet() + ".e3d").empty()) || (false == FileCased(Model.NameGet() + ".t3d").empty());
m_problem = m_importable ? STR("This model has no EU07M file yet. Import it to change its lights and parts.")
: STR("This model has no EU07M file, so it can't be edited here. The command eu07 -eu07m convert makes one of its E3D or T3D file");
return false;
}
std::ifstream file{path, std::ios::binary | std::ios::ate};
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_problem = std::vformat(STR("The EU07M file of the model can't be read: {}"), std::make_format_args(result.error));
return false;
}
m_path = path;
// 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();
}
for (std::uint32_t idx = 0; idx < m_model.nodes.size(); ++idx)
{
m_boxes.push_back(node_box(m_model, idx));
}
m_cliptimes.assign(m_model.clips.size(), 0.f);
m_channels.clear();
for (auto const &channel : Model.channels())
{
m_channels.push_back(channel.initial);
}
m_before = take(false);
return true;
}
void eu07m_model_panel::render_unsaved_popup()
{
auto const title{std::string{STR_C("Changes not saved")} + "###eu07munsaved"};
if (m_pending && (false == ImGui::IsPopupOpen(title.c_str())))
{
ImGui::OpenPopup(title.c_str());
}
if (false == ImGui::BeginPopupModal(title.c_str(), nullptr, ImGuiWindowFlags_AlwaysAutoResize))
{
return;
}
auto const name{std::filesystem::path{m_path}.filename().string()};
ImGui::TextUnformatted(std::vformat(STR("The model {} has changes which aren't saved."), std::make_format_args(name)).c_str());
if (ImGui::Button(STR_C("Save them")))
{
save();
if (m_pending && (false == m_dirty))
{
open(*m_pending);
}
else
{
// not saved: the message says why, the model stays
m_kept = m_pending;
m_pending.reset();
}
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button(STR_C("Throw them away")))
{
// the model the game has is taken back to the file too
while (undo())
{
// down to the model as the file has it
}
if (m_pending)
{
open(*m_pending);
}
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button(STR_C("Go on with this one")))
{
m_kept = m_pending;
m_pending.reset();
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
void eu07m_model_panel::render_bank()
{
ImGui::SeparatorText(STR_C("Edited model"));
if (m_source == nullptr)
{
ImGui::TextWrapped("%s", STR_C("Nothing picked yet."));
}
else
{
auto const name{m_target.vehicle != nullptr ? m_target.vehicle->name() : m_target.instance->name()};
ImGui::TextUnformatted(name.empty() ? STR_C("(no name)") : name.c_str());
if (m_target.vehicle != nullptr)
{
render_vehicle_part();
}
ImGui::TextDisabled("%s", m_path.empty() ? m_source->NameGet().c_str() : std::filesystem::path{m_path}.filename().string().c_str());
}
ImGui::SeparatorText(STR_C("A model of the scenery"));
ImGui::TextWrapped("%s", STR_C("Click a model in the view to edit it."));
render_insert();
if (auto const *instance{dynamic_cast<TAnimModel *>(m_lastselected)}; (instance != nullptr) && (m_pickedvehicle != nullptr))
{
auto const &name{instance->name()};
auto const label{std::vformat(STR("Back to {}"), std::make_format_args(name))};
if (ImGui::Button(label.c_str()))
{
m_pickedvehicle = nullptr;
}
}
ImGui::SeparatorText(STR_C("Vehicles"));
if ((place_vehicle != nullptr) && ImGui::Button(STR_C("Put a vehicle on a track...")))
{
place_vehicle();
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("%s", STR_C("The Trainset tool of the tracks: click a track, pick the vehicle and Place it; F7 brings you back here"));
}
auto const &vehicles{simulation::Vehicles.sequence()};
if (vehicles.empty())
{
ImGui::TextDisabled("%s", STR_C("The scenery has no vehicles."));
return;
}
ImGui::TextDisabled("%s", STR_C("A click picks the vehicle and takes the camera to it"));
if (false == ImGui::BeginChild("##eu07mvehicles", ImVec2(0.f, 0.f), ImGuiChildFlags_Borders))
{
ImGui::EndChild();
return;
}
auto const *driven{simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr};
ImGuiListClipper clipper;
clipper.Begin(static_cast<int>(vehicles.size()));
while (clipper.Step())
{
for (auto idx = clipper.DisplayStart; idx < clipper.DisplayEnd; ++idx)
{
auto *vehicle{vehicles[static_cast<std::size_t>(idx)]};
auto label{vehicle->name()};
if (vehicle == driven)
{
label += std::string{" "} + STR_C("(driven)");
}
label += "##vehicle" + std::to_string(idx);
if (ImGui::Selectable(label.c_str(), vehicle == m_target.vehicle))
{
m_pickedvehicle = vehicle;
fly_to_vehicle(*vehicle);
}
}
}
ImGui::EndChild();
}
void eu07m_model_panel::render_vehicle_part()
{
auto *vehicle{m_target.vehicle};
auto const cab{(vehicle->mdKabina != nullptr) && (vehicle->mdKabina != vehicle->mdModel)};
if (false == cab)
{
// the cab is loaded only by getting in: the button does what the game does then
if (ImGui::Button(STR_C("Get in the cab")))
{
open_cab();
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("%s", STR_C("Loads the cab of the vehicle as the game does when you get in, and puts the camera in the seat of the driver"));
}
return;
}
std::array const parts{STR_C("Body"), STR_C("Cab")};
if (auto const clicked{choice_buttons("##part", static_cast<std::size_t>(m_target.part), parts)})
{
// the other part is shown in the next frame; from the cab the camera goes out to look at the body
m_part = static_cast<int>(*clicked);
if ((m_part == 1) && (enter_cab != nullptr))
{
enter_cab(*vehicle);
}
else if (m_part == 0)
{
fly_to_vehicle(*vehicle);
}
}
}
bool eu07m_model_panel::open_cab()
{
auto *vehicle{m_target.vehicle != nullptr ? m_target.vehicle : m_pickedvehicle};
if ((vehicle == nullptr) || (enter_cab == nullptr))
{
return false;
}
m_pickedvehicle = vehicle;
if (false == enter_cab(*vehicle))
{
m_message = STR("The vehicle has no cab of its own to get in");
return false;
}
m_part = 1;
return true;
}
void eu07m_model_panel::render_insert()
{
if ((place_model == nullptr) || (false == ImGui::TreeNode(STR_C("Put a model in the scenery"))))
{
return;
}
auto searched{false};
if (false == m_scanned)
{
// the folder of the models looked through once, when the list is first opened
m_scanned = true;
searched = true;
std::error_code error;
for (std::filesystem::recursive_directory_iterator entry{"models", std::filesystem::directory_options::skip_permission_denied, error}, end; entry != end; entry.increment(error))
{
std::error_code status;
auto const extension{ToLower(entry->path().extension().string())};
if ((false == entry->is_regular_file(status)) || ((extension != ".e3d") && (extension != ".t3d")))
{
continue;
}
m_files.push_back(std::filesystem::relative(entry->path(), "models", status).generic_string());
}
std::ranges::sort(m_files);
}
std::array<char, 64> buffer{};
std::memcpy(buffer.data(), m_filesearch.data(), std::min(m_filesearch.size(), buffer.size() - 1));
ImGui::SetNextItemWidth(-1.f);
if (ImGui::InputTextWithHint("##modelsearch", STR_C("Look for a model by its name, e.g. latarnia"), buffer.data(), buffer.size()))
{
m_filesearch = buffer.data();
searched = true;
}
if (searched)
{
auto const wanted_text{lowered(m_filesearch)};
m_found.clear();
for (std::size_t idx = 0; idx < m_files.size(); ++idx)
{
if (lowered(m_files[idx]).find(wanted_text) != std::string::npos)
{
m_found.push_back(idx);
}
}
}
ImGui::TextDisabled("%s", STR_C("A click puts the model in front of the camera; then Whole model in the toolbar moves it"));
if (ImGui::BeginChild("##eu07mfiles", ImVec2(0.f, ImGui::GetTextLineHeightWithSpacing() * 8.f), ImGuiChildFlags_Borders))
{
ImGuiListClipper clipper;
clipper.Begin(static_cast<int>(m_found.size()));
while (clipper.Step())
{
for (auto idx = clipper.DisplayStart; idx < clipper.DisplayEnd; ++idx)
{
auto const &file{m_files[m_found[static_cast<std::size_t>(idx)]]};
if (ImGui::Selectable((file + "##file" + std::to_string(idx)).c_str()))
{
place_model(file);
}
}
}
}
ImGui::EndChild();
ImGui::TreePop();
}
bool eu07m_model_panel::import_model()
{
if ((false == m_importable) || (m_source == nullptr))
{
return false;
}
std::string error;
auto const written{eu07m::import_model(*m_source, error)};
if (written.empty())
{
m_message = std::vformat(STR("Not imported: {}"), std::make_format_args(error));
return false;
}
open(m_target);
auto const name{std::filesystem::path{written}.filename().string()};
m_message = std::vformat(STR("Imported to {}. Its lights and parts can be changed now"), std::make_format_args(name));
return true;
}
void eu07m_model_panel::render_tools()
{
render_header();
if (m_path.empty())
{
return;
}
ImGui::PushItemWidth(-ImGui::GetFontSize() * label_width);
switch (m_tool)
{
case tool::lights:
render_lights_page();
break;
case tool::parts:
render_parts_page();
break;
case tool::elements:
render_elements_page();
break;
case tool::animations:
render_animations_page();
break;
}
ImGui::PopItemWidth();
}
void eu07m_model_panel::render_header()
{
if (m_source == nullptr)
{
ImGui::TextWrapped("%s", STR_C("No model to edit. Click a model in the scenery, or pick a vehicle in the list on the left."));
return;
}
if (false == m_problem.empty())
{
ImGui::TextWrapped("%s", m_problem.c_str());
if (m_importable && ImGui::Button(STR_C("Import to EU07M")))
{
import_model();
}
if (m_importable && ImGui::IsItemHovered())
{
ImGui::SetTooltip("%s", STR_C("Writes an .ng3d file beside the model, made of the model as the game has it. From then on the game loads the model from it, in every scenery"));
}
// the game doesn't compare the .ng3d with the file it was made of: an update of that one is shadowed by it
if (m_importable)
{
ImGui::TextDisabled("%s", STR_C("While the .ng3d is there, a later update of the .e3d or .t3d doesn't reach the game: import it again, or delete the .ng3d"));
}
if (false == m_message.empty())
{
ImGui::TextWrapped("%s", m_message.c_str());
}
return;
}
ImGui::BeginDisabled(false == m_dirty);
if (ImGui::Button(STR_C("Save the changes")))
{
save();
}
ImGui::EndDisabled();
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))
{
ImGui::SetTooltip("%s", STR_C("Writes the model to its file; until then nothing of it is changed on the disk"));
}
ImGui::SameLine();
ImGui::BeginDisabled(m_undo.empty());
if (ImGui::Button(STR_C("Undo")))
{
undo();
}
ImGui::EndDisabled();
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))
{
ImGui::SetTooltip("%s", STR_C("Takes the last change of the model back (Ctrl+Z)"));
}
ImGui::SameLine();
ImGui::BeginDisabled(m_redo.empty());
if (ImGui::Button(STR_C("Redo")))
{
redo();
}
ImGui::EndDisabled();
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))
{
ImGui::SetTooltip("%s", STR_C("Makes the change taken back again (Ctrl+Y)"));
}
if (m_dirty)
{
ImGui::SameLine();
ImGui::TextColored(ImVec4(1.f, 0.7f, 0.3f, 1.f), "%s", STR_C("Not saved"));
}
if (m_submodels.empty())
{
ImGui::TextWrapped("%s", STR_C("The model in the game differs from the file: the changes show once the game loads the model again"));
}
if (false == m_message.empty())
{
ImGui::TextWrapped("%s", m_message.c_str());
}
render_guide();
}
void eu07m_model_panel::render_guide() const
{
if (false == ImGui::CollapsingHeader(STR_C("How it works")))
{
return;
}
ImGui::Indent();
ImGui::TextWrapped("%s", STR_C("1. Pick the model: click it in the scenery, or pick a vehicle in the list on the left."));
ImGui::TextWrapped("%s", STR_C("2. Click a part of the model in the view. Its settings come up in the inspector."));
ImGui::TextWrapped("%s", STR_C("3. Drag the arrows in the view to move the part picked, or the rings to turn it: Move and Turn are in the toolbar."));
ImGui::TextWrapped("%s", STR_C("4. Ctrl+Z takes a change back. Nothing goes into the file until Save the changes."));
ImGui::Unindent();
}
void eu07m_model_panel::render_lights_page()
{
ImGui::TextWrapped("%s", STR_C("The light sources of the model. Click one to change it in the inspector; its round mark in the view does the same."));
if (m_placing)
{
ImGui::TextColored(ImVec4(1.f, 0.85f, 0.3f, 1.f), "%s", STR_C("Click the model where the light is to be. Esc gives it up."));
if (ImGui::Button(STR_C("Give it up")))
{
m_placing.reset();
}
}
else
{
ImGui::BeginDisabled(m_submodels.empty());
if (ImGui::Button(STR_C("+ Add a bulb")))
{
m_placing = false;
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("%s", STR_C("A light which shines all around, as a bulb; then a click on the model puts it there"));
}
ImGui::SameLine();
if (ImGui::Button(STR_C("+ Add a spot")))
{
m_placing = true;
}
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("%s", STR_C("A light which shines one way, as a headlamp; then a click on the model puts it there, shining towards the camera"));
}
ImGui::EndDisabled();
}
ImGui::Checkbox(STR_C("Marks of the lights in the view"), &m_marks);
ImGui::SeparatorText(STR_C("Lights of the model"));
auto any{false};
for (std::uint32_t idx = 0; idx < m_model.components.size(); ++idx)
{
auto const &record{m_model.components[idx]};
if ((record.type != eu07m::component::light) || (record.kind != eu07m::target_kind::node) || (record.target >= m_model.nodes.size()) ||
(std::size_t{record.data_offset} + sizeof(payload::light) > m_model.component_data.size()))
{
continue;
}
any = true;
payload::light light;
std::memcpy(&light, m_model.component_data.data() + record.data_offset, sizeof(light));
ImGui::PushID(static_cast<int>(idx));
ImGui::ColorButton("##colour", ImVec4(light.color[0], light.color[1], light.color[2], 1.f), ImGuiColorEditFlags_NoTooltip | ImGuiColorEditFlags_NoPicker);
ImGui::SameLine();
auto const kind{light.kind == payload::light_kind::spot ? STR_C("spot") : STR_C("bulb")};
auto const label{std::format("{} ({})", part_name(record.target), kind)};
if (ImGui::Selectable(label.c_str(), m_selected == static_cast<std::int64_t>(record.target), ImGuiSelectableFlags_AllowDoubleClick))
{
select(record.target);
if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))
{
fly_to(record.target);
}
}
ImGui::PopID();
}
if (false == any)
{
ImGui::TextDisabled("%s", STR_C("The model has no light sources yet."));
}
}
void eu07m_model_panel::render_parts_page() const
{
if ((m_target.vehicle == nullptr) || (m_target.part != 0))
{
ImGui::TextWrapped("%s", STR_C("The parts of a vehicle are held on its body: pick the body on the left."));
return;
}
auto &vehicle{*m_target.vehicle};
ImGui::TextWrapped("%s", STR_C("The vehicle keeps a part as set here until As the vehicle has it is chosen. Nothing of it goes into the file."));
if (vehicle.pantograph_count() > 0)
{
ImGui::SeparatorText(STR_C("Pantographs"));
if (ImGui::BeginTable("##pantographs", 2, ImGuiTableFlags_SizingFixedFit | ImGuiTableFlags_RowBg))
{
for (int idx = 0; idx < vehicle.pantograph_count(); ++idx)
{
pantograph_hold_row(vehicle, idx);
}
ImGui::EndTable();
}
}
part_group(vehicle, STR_C("Front lights"), true, [](std::string_view const Name) { return is_lamp(Name) && is_front(Name); });
part_group(vehicle, STR_C("Rear lights"), true, [](std::string_view const Name) { return is_lamp(Name) && (false == is_front(Name)); });
part_group(vehicle, STR_C("Couplers and hoses"), false, [](std::string_view const Name) { return false == is_lamp(Name); });
}
void eu07m_model_panel::render_elements_page()
{
ImGui::TextWrapped("%s", STR_C("All the parts of the model, as they hang one on another. A click picks one, a double click takes the camera to it."));
std::array<char, 64> buffer{};
std::memcpy(buffer.data(), m_filter.data(), std::min(m_filter.size(), buffer.size() - 1));
ImGui::SetNextItemWidth(-1.f);
if (ImGui::InputTextWithHint("##filter", STR_C("Look for a part by its name"), buffer.data(), buffer.size()))
{
m_filter = buffer.data();
}
if (false == ImGui::BeginChild("##eu07mtree", ImVec2(0.f, 0.f), ImGuiChildFlags_Borders))
{
ImGui::EndChild();
return;
}
if (m_filter.empty())
{
for (std::uint32_t idx = 0; idx < m_model.nodes.size(); idx = m_model.nodes[idx].subtree_end)
{
render_tree_node(idx);
}
ImGui::EndChild();
return;
}
// what is looked for: the parts of the name, as a list
auto const wanted_text{lowered(m_filter)};
for (std::uint32_t idx = 0; idx < m_model.nodes.size(); ++idx)
{
auto const name{part_name(idx)};
if (lowered(name).find(wanted_text) == std::string::npos)
{
continue;
}
auto const label{name + "##found" + std::to_string(idx)};
if (ImGui::Selectable(label.c_str(), m_selected == static_cast<std::int64_t>(idx), ImGuiSelectableFlags_AllowDoubleClick))
{
select(idx);
if (ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left))
{
fly_to(idx);
}
}
}
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_animations_page()
{
auto *instance{m_target.instance};
if (instance == nullptr)
{
ImGui::TextWrapped("%s", STR_C("The animations are tried on a model of the scenery."));
return;
}
ImGui::TextWrapped("%s", STR_C("The animations of the model, tried on it in the view. Looped and Plays on its own go into the file."));
render_clips(*instance);
render_channels(*instance);
}
void eu07m_model_panel::render_selection()
{
if (m_path.empty())
{
ImGui::TextWrapped("%s", m_problem.empty() ? STR_C("Pick a model first: click it in the view, or pick a vehicle in the list on the left.") : m_problem.c_str());
return;
}
if ((m_selected < 0) || (m_selected >= static_cast<std::int64_t>(m_model.nodes.size())))
{
ImGui::TextWrapped("%s", STR_C("Click a part of the model in the view, or pick one in the tool options, to change it here."));
return;
}
auto const index{static_cast<std::uint32_t>(m_selected)};
auto const light{light_of(index)};
ImGui::PushItemWidth(-ImGui::GetFontSize() * label_width);
ImGui::SeparatorText(part_name(index).c_str());
if (light)
{
ImGui::TextDisabled("%s", STR_C("A light source"));
}
else
{
ImGui::TextDisabled("%s", m_model.nodes[index].mesh >= 0 ? STR_C("A part of the model") : STR_C("A point of the model, with nothing to see"));
}
if (ImGui::Button(STR_C("Show it in the view")))
{
fly_to(index);
}
// the part of the vehicle it is in
auto const *target{submodel(index)};
if ((m_target.vehicle != nullptr) && (m_target.part == 0) && (target != nullptr))
{
auto const part{m_target.vehicle->part_of(target)};
auto const pantograph{m_target.vehicle->pantograph_of(target)};
if (((part < TDynamicObject::held_part_total) || (pantograph >= 0)) && ImGui::BeginTable("##hold", 2, ImGuiTableFlags_SizingFixedFit))
{
if (part < TDynamicObject::held_part_total)
{
part_hold_row(*m_target.vehicle, part);
}
if (pantograph >= 0)
{
pantograph_hold_row(*m_target.vehicle, pantograph);
}
ImGui::EndTable();
}
}
if (light)
{
render_light_settings(*light);
}
render_place(index);
if (render_remove(index, light.has_value()))
{
ImGui::PopItemWidth();
return;
}
render_advanced(index);
ImGui::PopItemWidth();
}
bool eu07m_model_panel::render_remove(std::uint32_t const Index, bool const Light)
{
auto const *target{submodel(Index)};
auto const removable{(target != nullptr) && (target->Parent != nullptr) && eu07m::node_removable(m_model, Index)};
ImGui::Separator();
ImGui::BeginDisabled(false == removable);
auto const clicked{ImGui::Button(Light ? STR_C("Remove this light (Del)") : STR_C("Remove this part (Del)"))};
ImGui::EndDisabled();
if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled))
{
ImGui::SetTooltip("%s", removable ? STR_C("Takes it out of the model, with what it draws; Ctrl+Z brings it back")
: STR_C("This part can't be taken out: it has parts under it, or something else in the model points at it (an animation, a light slot, a skin)"));
}
return clicked && remove_selected();
}
void eu07m_model_panel::render_light_settings(std::uint32_t const Component)
{
auto const &record{m_model.components[Component]};
if ((record.data_size < sizeof(payload::light)) || (std::size_t{record.data_offset} + sizeof(payload::light) > m_model.component_data.size()))
{
return;
}
payload::light light;
std::memcpy(&light, m_model.component_data.data() + record.data_offset, sizeof(light));
auto changes{false};
ImGui::SeparatorText(STR_C("Light"));
auto const spot{light.kind == payload::light_kind::spot};
std::array const kinds{STR_C("Bulb: shines all around"), STR_C("Spot: shines one way")};
if (auto const clicked{choice_buttons("##kind", spot ? 1 : 0, kinds)}; clicked && ((*clicked == 1) != spot))
{
set_light_kind(light, *clicked == 1 ? payload::light_kind::spot : payload::light_kind::point);
changes = true;
}
changes |= ImGui::ColorEdit3(STR_C("Colour"), light.color.data());
for (auto const &preset : colour_presets)
{
ImGui::PushID(preset.name);
if (ImGui::ColorButton(STR_C(preset.name), ImVec4(preset.colour[0], preset.colour[1], preset.colour[2], 1.f)))
{
std::ranges::copy(preset.colour, light.color.begin());
changes = true;
}
ImGui::PopID();
ImGui::SameLine(0.f, ImGui::GetStyle().ItemInnerSpacing.x);
}
ImGui::NewLine();
changes |= ImGui::SliderFloat(STR_C("Brightness"), &light.hotspot_power, 0.f, 10.f, "%.2f");
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("%s", STR_C("How strongly it lights what is around it. Ctrl+click types a value"));
}
changes |= ImGui::SliderFloat(STR_C("Glowing spot, m"), &light.radius, 0.f, 1.f, "%.2f");
if (ImGui::IsItemHovered())
{
ImGui::SetTooltip("%s", STR_C("The size of the glowing ball seen where the light is; 0 shows none"));
}
if (light.kind == payload::light_kind::spot)
{
changes |= edit_beam(light);
}
auto shadows{(light.flags & payload::light_flags::no_shadows) == 0};
if (ImGui::Checkbox(STR_C("Casts shadows"), &shadows))
{
// the box says it casts them, the flag that it doesn't
light.flags ^= payload::light_flags::no_shadows;
changes = true;
}
changes |= edit_flag(STR_C("Soft edge"), light.flags, payload::light_flags::soft_falloff);
changes |= edit_flag(STR_C("Lights this model too"), light.flags, payload::light_flags::shade_self);
if (false == changes)
{
return;
}
std::memcpy(m_model.component_data.data() + record.data_offset, &light, sizeof(light));
changed();
show_change(Component);
}
void eu07m_model_panel::render_place(std::uint32_t const Index)
{
auto &node{m_model.nodes[Index]};
ImGui::SeparatorText(STR_C("Place"));
if ((node.flags & eu07m::node_flags::matrix) != 0)
{
ImGui::TextDisabled("%s", STR_C("This part is placed in a way this window doesn't change"));
}
else
{
ImGui::TextWrapped("%s", STR_C("Drag the arrows in the view to move it, or the rings to turn it."));
std::array const modes{STR_C("Move"), STR_C("Turn")};
if (auto const clicked{choice_buttons("##gizmo", m_gizmo == gizmo::turn ? 1 : 0, modes)})
{
set_turning(*clicked == 1);
}
if (ImGui::TreeNode(STR_C("Exact values")))
{
if (edit_place(node))
{
moved(Index);
}
ImGui::TreePop();
}
}
ImGui::SeparatorText(STR_C("Seen from"));
if (edit_range(node))
{
changed();
if (auto *target{submodel(Index)}; target != nullptr)
{
m_source->SetEditorRange(*target, node.range_min_sq, node.range_max_sq);
}
}
}
void eu07m_model_panel::render_advanced(std::uint32_t const Index)
{
if (false == ImGui::CollapsingHeader(STR_C("Advanced: the data of the file")))
{
return;
}
ImGui::TextDisabled("%s", STR_C("For those who know the EU07M format"));
if (ImGui::Button(STR_C("Add a light to this part")))
{
add_light(Index, glm::vec3{0.f}, glm::quat{1.f, 0.f, 0.f, 0.f}, false);
}
for (auto const component : node_components(m_model, Index))
{
render_component(component);
}
}
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::TreeNode(label.c_str()))
{
return;
}
ImGui::PushID(static_cast<int>(Index));
if (edit_component(m_model, Index))
{
changed();
show_change(Index);
}
ImGui::PopID();
ImGui::TreePop();
}
void eu07m_model_panel::choose_tool(tool const Tool)
{
m_tool = Tool;
m_placing.reset();
}
bool eu07m_model_panel::has_animations() const
{
auto const *instance{m_target.instance};
return (instance != nullptr) && ((false == m_model.clips.empty()) || ((instance->pModel != nullptr) && (false == instance->pModel->channels().empty())));
}
bool eu07m_model_panel::editable(scene::basic_node const *Node) const
{
auto const *instance{dynamic_cast<TAnimModel const *>(Node)};
return Global.modelformat_eu07m && (instance != nullptr) && (instance->pModel != nullptr) && (false == FileCased(instance->pModel->NameGet() + ".ng3d").empty());
}
bool eu07m_model_panel::pick_vehicle(std::string_view const Name, int const Part)
{
auto const &vehicles{simulation::Vehicles.sequence()};
auto const wanted_name{lowered(Name)};
auto const found{std::ranges::find_if(vehicles, [&wanted_name](TDynamicObject const *Vehicle) { return lowered(Vehicle->name()) == wanted_name; })};
if (found == vehicles.end())
{
return false;
}
m_pickedvehicle = *found;
m_part = Part;
if (Part == 1)
{
return (enter_cab != nullptr) && enter_cab(**found);
}
fly_to_vehicle(**found);
return true;
}
bool eu07m_model_panel::save_model()
{
if (m_path.empty())
{
return false;
}
save();
return false == m_dirty;
}
bool eu07m_model_panel::set_brightness(float const Brightness)
{
auto const light{m_selected >= 0 ? light_of(static_cast<std::uint32_t>(m_selected)) : std::nullopt};
if (false == light.has_value())
{
return false;
}
auto const &record{m_model.components[*light]};
if (std::size_t{record.data_offset} + sizeof(payload::light) > m_model.component_data.size())
{
return false;
}
payload::light value;
std::memcpy(&value, m_model.component_data.data() + record.data_offset, sizeof(value));
value.hotspot_power = Brightness;
std::memcpy(m_model.component_data.data() + record.data_offset, &value, sizeof(value));
changed();
show_change(*light);
return true;
}
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;
}
bool eu07m_model_panel::add_test_light(bool const Spot)
{
// in the middle of the geometry of the part picked, as a click there would put it
auto const where{placement()};
// the first part when none is picked
auto const part{m_model.nodes.empty() ? std::nullopt : std::optional<std::uint32_t>{static_cast<std::uint32_t>(std::max<std::int64_t>(m_selected, 0))}};
auto const *target{part ? submodel(*part) : nullptr};
if ((false == where.has_value()) || (target == nullptr))
{
return false;
}
auto const &bounds{m_boxes[*part]};
auto const middle{bounds ? glm::dvec3{(bounds->first + bounds->second) * 0.5f} : glm::dvec3{0.0}};
auto const count{m_model.nodes.size()};
m_placing = Spot;
place_light(point_of(*where * model_space(*target), middle), part);
return m_model.nodes.size() > count;
}
void eu07m_model_panel::select(std::uint32_t const Node)
{
m_selected = Node;
}
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_target.vehicle != nullptr)
{
return glm::translate(glm::dmat4{1.0}, m_target.vehicle->GetPosition()) * m_target.vehicle->mMatrix;
}
auto const *instance{m_target.instance};
if (instance == nullptr)
{
return std::nullopt;
}
// turned about y, then x, then z, and scaled, the way the instance is drawn
auto const angles{glm::radians(glm::dvec3{instance->Angles()})};
auto matrix{glm::translate(glm::dmat4{1.0}, instance->location())};
matrix = glm::rotate(matrix, angles.y, glm::dvec3{0.0, 1.0, 0.0});
matrix = glm::rotate(matrix, angles.x, glm::dvec3{1.0, 0.0, 0.0});
matrix = glm::rotate(matrix, angles.z, glm::dvec3{0.0, 0.0, 1.0});
return glm::scale(matrix, glm::dvec3{instance->Scale()});
}
std::optional<std::uint32_t> eu07m_model_panel::node_at(glm::dvec3 const &Point) const
{
auto const where{placement()};
if (false == where.has_value())
{
return std::nullopt;
}
std::optional<std::uint32_t> best;
auto bestvolume{std::numeric_limits<double>::max()};
for (std::uint32_t idx = 0; (idx < m_boxes.size()) && (idx < m_submodels.size()); ++idx)
{
auto const &bounds{m_boxes[idx]};
auto const *target{m_submodels[idx]};
// a part hidden now, such as a lamp off, isn't what was clicked
if ((false == bounds.has_value()) || (target == nullptr) || (target->iVisible == 0))
{
continue;
}
if (false == inside(*bounds, point_of(glm::inverse(*where * model_space(*target)), Point), pick_margin))
{
continue;
}
auto const size{glm::dvec3{bounds->second - bounds->first} + 2.0 * pick_margin};
if (auto const volume{size.x * size.y * size.z}; volume < bestvolume)
{
best = idx;
bestvolume = volume;
}
}
return best;
}
std::optional<std::uint32_t> eu07m_model_panel::light_of(std::uint32_t const Node) const
{
for (std::uint32_t idx = 0; idx < m_model.components.size(); ++idx)
{
auto const &record{m_model.components[idx]};
if ((record.type == eu07m::component::light) && (record.kind == eu07m::target_kind::node) && (record.target == Node))
{
return idx;
}
}
return std::nullopt;
}
std::string eu07m_model_panel::part_name(std::uint32_t const Node) const
{
auto const name{m_model.string(m_model.nodes[Node].name)};
std::string own{name.empty() ? std::string{STR_C("(no name)")} : std::string{name}};
auto const *target{submodel(Node)};
if ((m_target.vehicle == nullptr) || (m_target.part != 0) || (target == nullptr))
{
return own;
}
if (auto const part{m_target.vehicle->part_of(target)}; part < TDynamicObject::held_part_total)
{
return std::format("{} ({})", part_text(TDynamicObject::held_part_name(part)), own);
}
if (auto const pantograph{m_target.vehicle->pantograph_of(target)}; pantograph >= 0)
{
auto const number{pantograph + 1};
return std::format("{} ({})", std::vformat(STR("Pantograph {}"), std::make_format_args(number)), own);
}
return own;
}
void eu07m_model_panel::render_view()
{
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)};
if (clicked)
{
m_tookpress = false;
}
// what a click is to do now, by the cursor
if (m_placing && (false == ImGui::GetIO().WantCaptureMouse))
{
auto const mouse{ImGui::GetMousePos()};
ImGui::GetForegroundDrawList()->AddText(ImVec2(mouse.x + 18.f, mouse.y + 4.f), IM_COL32(255, 220, 90, 255), STR_C("Click the model where the light is to be"));
}
if (m_marks)
{
render_marks(*where, clicked && (false == m_placing.has_value()));
}
// the part picked: its frame and its axes, and the gizmo to move it
auto const *target{m_selected >= 0 ? submodel(static_cast<std::uint32_t>(m_selected)) : nullptr};
if (target == nullptr)
{
return;
}
auto const space{*where * model_space(*target)};
if (auto const &bounds{m_boxes[static_cast<std::size_t>(m_selected)]}; bounds.has_value())
{
draw_box(drawlist, projection, space, *bounds, overlay_color::selected);
}
draw_axes(drawlist, projection, space, 0.3);
render_gizmo(*where, GfxRenderer->Camera_Position());
}
void eu07m_model_panel::render_marks(glm::dmat4 const &Placement, bool const Clicked)
{
screen_projection const projection;
auto *drawlist{ImGui::GetBackgroundDrawList(ImGui::GetMainViewport())};
auto const mouse{ImGui::GetMousePos()};
for (auto const &record : m_model.components)
{
if ((record.type != eu07m::component::light) || (record.kind != eu07m::target_kind::node) || (submodel(record.target) == nullptr) ||
(std::size_t{record.data_offset} + sizeof(payload::light) > m_model.component_data.size()))
{
continue;
}
payload::light light;
std::memcpy(&light, m_model.component_data.data() + record.data_offset, sizeof(light));
auto const space{Placement * model_space(*submodel(record.target))};
ImVec2 centre;
if (false == projection.project(point_of(space, glm::dvec3{0.0}), centre))
{
continue;
}
if (light.kind == payload::light_kind::spot)
{
// the axis of a spot is the -z of its node
projection.line(drawlist, point_of(space, glm::dvec3{0.0}), point_of(space, glm::dvec3{0.0, 0.0, -0.6}), light_colour(light, 255), 2.f);
}
auto const picked{m_selected == static_cast<std::int64_t>(record.target)};
drawlist->AddCircleFilled(centre, mark_radius, light_colour(light, 220));
drawlist->AddCircle(centre, mark_radius + 1.f, picked ? overlay_color::selected : IM_COL32(0, 0, 0, 200), 0, picked ? 3.f : 1.5f);
auto const dx{mouse.x - centre.x};
auto const dy{mouse.y - centre.y};
if (Clicked && (dx * dx + dy * dy <= (mark_radius + 3.f) * (mark_radius + 3.f)))
{
select(record.target);
m_scrolltoselected = true;
m_tookpress = true;
}
}
}
void eu07m_model_panel::render_gizmo(glm::dmat4 const &Placement, glm::dvec3 const &Camera)
{
auto const index{static_cast<std::uint32_t>(m_selected)};
auto *target{submodel(index)};
if (m_placing || moves_whole() || (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;
changed();
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::changed()
{
m_dirty = true;
// one change for a press, a drag or a typing: the model as it was before it
if (m_changing)
{
return;
}
m_changing = true;
push_change(m_before);
}
eu07m_model_panel::snapshot eu07m_model_panel::take(bool const Whole) const
{
snapshot result;
result.nodes = m_model.nodes;
result.components = m_model.components;
result.component_data = m_model.component_data;
result.clips = m_model.clips;
if (Whole)
{
result.whole = m_model;
}
return result;
}
void eu07m_model_panel::restore(snapshot const &Snapshot)
{
auto const before{m_model.nodes};
if (Snapshot.whole)
{
m_model = *Snapshot.whole;
}
else
{
m_model.nodes = Snapshot.nodes;
m_model.components = Snapshot.components;
m_model.component_data = Snapshot.component_data;
m_model.clips = Snapshot.clips;
}
// the places and the ranges changed shown on the model the game has; a change of the tree changes nothing else
if ((before.size() == m_model.nodes.size()) && (m_source != nullptr))
{
for (std::uint32_t idx = 0; idx < before.size(); ++idx)
{
auto *target{submodel(idx)};
if ((target == nullptr) || same_place(before[idx], m_model.nodes[idx]))
{
continue;
}
if ((m_model.nodes[idx].flags & eu07m::node_flags::matrix) == 0)
{
m_source->SetEditorTransform(*target, eu07m::local_transform(m_model, idx));
}
m_source->SetEditorRange(*target, m_model.nodes[idx].range_min_sq, m_model.nodes[idx].range_max_sq);
}
}
}
void eu07m_model_panel::apply_tree(tree_change const &Change, bool const Forward)
{
if ((Change.what == tree_change::kind::none) || (Change.submodel == nullptr) || (m_source == nullptr) || m_submodels.empty())
{
return;
}
// a light added is taken out again when the change is taken back, one taken out is put back
if ((Change.what == tree_change::kind::added) == Forward)
{
if ((Change.parent == nullptr) || (Change.index > m_submodels.size()))
{
return;
}
m_source->LinkEditorSubmodel(*Change.submodel, *Change.parent, Change.previous);
m_submodels.insert(m_submodels.begin() + Change.index, Change.submodel);
m_boxes.insert(m_boxes.begin() + Change.index, node_box(m_model, Change.index));
// the part back is picked again, as it was when it was taken out
m_pick_after = Change.index;
return;
}
if (Change.index >= m_submodels.size())
{
return;
}
m_source->UnlinkEditorSubmodel(*Change.submodel);
m_submodels.erase(m_submodels.begin() + Change.index);
m_boxes.erase(m_boxes.begin() + Change.index);
if (m_selected == static_cast<std::int64_t>(Change.index))
{
m_selected = -1;
}
}
void eu07m_model_panel::push_change(snapshot Snapshot)
{
m_undo.push_back(std::move(Snapshot));
if (m_undo.size() > undo_depth)
{
m_undo.erase(m_undo.begin());
}
m_redo.clear();
m_dirty = true;
}
bool eu07m_model_panel::undo()
{
if (m_undo.empty())
{
return false;
}
auto entry{std::move(m_undo.back())};
m_undo.pop_back();
auto again{take(entry.whole.has_value())};
again.change = entry.change;
restore(entry);
apply_tree(entry.change, false);
m_redo.push_back(std::move(again));
settled();
return true;
}
bool eu07m_model_panel::redo()
{
if (m_redo.empty())
{
return false;
}
auto entry{std::move(m_redo.back())};
m_redo.pop_back();
auto back{take(entry.whole.has_value())};
back.change = entry.change;
restore(entry);
apply_tree(entry.change, true);
m_undo.push_back(std::move(back));
settled();
return true;
}
void eu07m_model_panel::settled()
{
m_dirty = true;
m_message.clear();
m_placing.reset();
m_before = take(false);
m_changing = false;
// the lights as they are now
for (std::uint32_t idx = 0; idx < m_model.components.size(); ++idx)
{
show_change(idx);
}
if (m_selected >= static_cast<std::int64_t>(m_model.nodes.size()))
{
m_selected = -1;
}
if (auto const part{std::exchange(m_pick_after, std::nullopt)}; part && (*part < m_model.nodes.size()))
{
select(*part);
m_scrolltoselected = true;
}
}
void eu07m_model_panel::add_light(std::uint32_t const Parent, glm::vec3 const &Position, glm::quat const &Rotation, bool const Spot)
{
auto *parent{submodel(Parent)};
if ((parent == nullptr) || (m_source == nullptr))
{
return;
}
auto before{take(true)};
// a name the model doesn't have yet
std::string name;
for (int number = 1; name.empty() || (false == eu07m::find_nodes(m_model, name).empty()); ++number)
{
name = std::format("light_{}", number);
}
eu07m::node_record node;
node.name = m_model.intern(name);
node.legacy_flags = light_node_flags;
node.translation = {Position.x, Position.y, Position.z};
node.rotation = {Rotation.x, Rotation.y, Rotation.z, Rotation.w};
auto const index{eu07m::insert_node(m_model, static_cast<std::int32_t>(Parent), node)};
payload::light light;
light.color = {1.f, 0.9f, 0.7f, 1.f};
// without a cone yet: a spot gets the one it's given to start with
light.cos_falloff = -1.f;
set_light_kind(light, Spot ? payload::light_kind::spot : payload::light_kind::point);
std::vector<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);
// on the model the game has, the last child of the parent as in the file
auto *previous{parent->Child};
while ((previous != nullptr) && (previous->Next != nullptr))
{
previous = previous->Next;
}
auto &added{m_source->AddEditorLight(*parent, name, eu07m::local_transform(m_model, index), light_node_flags, light)};
m_submodels.insert(m_submodels.begin() + index, &added);
m_boxes.insert(m_boxes.begin() + index, std::nullopt);
before.change = {tree_change::kind::added, index, &added, parent, previous};
push_change(std::move(before));
m_before = take(false);
// the new light is picked, to be moved with the gizmo
select(index);
m_scrolltoselected = true;
m_message = std::vformat(STR("Added the light {}. Drag the arrows in the view to move it"), std::make_format_args(name));
}
void eu07m_model_panel::place_light(glm::dvec3 const &Point, std::optional<std::uint32_t> const Part)
{
auto const spot{m_placing.value_or(false)};
m_placing.reset();
// on the part clicked; a light clicked gets one beside it rather than under it
auto parent{Part.value_or(0u)};
if (light_of(parent) && (m_model.nodes[parent].parent >= 0))
{
parent = static_cast<std::uint32_t>(m_model.nodes[parent].parent);
}
auto const *target{submodel(parent)};
auto const where{placement()};
if ((target == nullptr) || (false == where.has_value()))
{
return;
}
auto const inverse{glm::inverse(*where * model_space(*target))};
glm::vec3 const position{point_of(inverse, Point)};
// a spot shines back where it was clicked from
auto const towards{glm::dvec3{inverse * glm::dvec4{glm::dvec3{Global.pCamera.Pos} - Point, 0.0}}};
auto const rotation{glm::length(towards) > 1e-6 ? aim(glm::normalize(glm::vec3{towards})) : glm::quat{1.f, 0.f, 0.f, 0.f}};
add_light(parent, position, rotation, spot);
}
bool eu07m_model_panel::pick(scene::basic_node const *Picked)
{
if ((false == m_active) || m_submodels.empty() || (false == placement().has_value()) || (moves_whole() && (false == m_placing.has_value())))
{
return false;
}
// a vehicle isn't a node of the scenery: a click on it hits none
auto const ours{m_target.instance != nullptr ? Picked == m_target.instance : Picked == nullptr};
if (false == ours)
{
return false;
}
if (false == GfxRenderer->Mouse_Hit())
{
return m_target.instance != nullptr;
}
auto const point{glm::dvec3{Global.pCamera.Pos} + GfxRenderer->Mouse_Position()};
auto const part{node_at(point)};
if ((m_target.vehicle != nullptr) && (false == part.has_value()))
{
return false;
}
if (m_placing)
{
place_light(point, part);
return true;
}
if (part)
{
select(*part);
m_scrolltoselected = true;
}
return true;
}
bool eu07m_model_panel::remove_selected()
{
if ((false == m_active) || (m_selected < 0) || (m_selected >= static_cast<std::int64_t>(m_model.nodes.size())))
{
return false;
}
auto const index{static_cast<std::uint32_t>(m_selected)};
auto *target{submodel(index)};
if ((target == nullptr) || (target->Parent == nullptr) || (false == eu07m::node_removable(m_model, index)))
{
return false;
}
auto before{take(true)};
auto *parent{target->Parent};
auto const name{part_name(index)};
auto const light{light_of(index).has_value()};
if (false == eu07m::remove_node(m_model, index))
{
return false;
}
auto *previous{m_source->UnlinkEditorSubmodel(*target)};
m_submodels.erase(m_submodels.begin() + index);
m_boxes.erase(m_boxes.begin() + index);
before.change = {tree_change::kind::removed, index, target, parent, previous};
push_change(std::move(before));
m_before = take(false);
m_selected = -1;
m_message = light ? std::vformat(STR("Removed the light {}. Ctrl+Z brings it back"), std::make_format_args(name))
: std::vformat(STR("Removed {}. Ctrl+Z brings it back"), std::make_format_args(name));
return true;
}
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::fly_to_vehicle(TDynamicObject const &Vehicle) const
{
if (focus != nullptr)
{
focus(Vehicle.GetPosition(), std::max(5.0, Vehicle.GetLength() * vehicle_focus));
}
}
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);
changed();
}
// the editor stops the time: the clip is held at the time picked
if (ImGui::SliderFloat(STR_C("Time, s"), &m_cliptimes[idx], 0.f, std::max(clip.duration, 0.001f), "%.2f"))
{
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 | std::ios::trunc};
file.write(reinterpret_cast<char const *>(data.data()), static_cast<std::streamsize>(data.size()));
// closed before the check: the buffer is written out there, and a fault of it (a full disk) is seen
file.close();
std::error_code error;
if (false == file.fail())
{
std::filesystem::rename(temporary, m_path, error);
}
if (file.fail() || error)
{
// the model stays as it was, the file cut short goes
std::filesystem::remove(temporary, error);
m_message = STR("Not saved: the file can't be written");
return;
}
m_dirty = false;
m_message = STR("Saved. The game uses the change once it loads the model again");
}