diff --git a/CMakeLists.txt b/CMakeLists.txt index 9e9b55d86..c69cbc5d1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -223,6 +223,7 @@ set(SOURCES "editor/editorGroundFollow.cpp" "editor/editorAlignmentStore.cpp" "editor/editorSwitchStore.cpp" +"editor/editorFillStore.cpp" "editor/editorSwitchCurve.cpp" "editor/editorKilometrage.cpp" "editor/editorStation.cpp" diff --git a/application/editormode.cpp b/application/editormode.cpp index 93498a58d..21c8be086 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -548,6 +548,7 @@ void editor_mode::editormode_input::poll() editor_mode::editor_mode() { alignment_store::reset(); switch_store::reset(); + fill_store::reset(); kilometrage::reset(); m_userinterface = std::make_shared(); // the area fill settings live in the node bank window, in the tab of the fill mode @@ -962,9 +963,7 @@ void editor_mode::nullify_history_pointers(scene::basic_node *node) s.infra.erase(std::remove_if(s.infra.begin(), s.infra.end(), followed), s.infra.end()); } - // deleted nodes also drop out of the "undo last fill" set - m_fill_last.erase(std::remove(m_fill_last.begin(), m_fill_last.end(), node), m_fill_last.end()); - // and out of the selection and their group + // deleted nodes drop out of the selection and their group m_selection.erase(std::remove(m_selection.begin(), m_selection.end(), node), m_selection.end()); scene::Groups.remove(node); @@ -4801,16 +4800,44 @@ void editor_mode::add_area_fill_point() m_fill_points.push_back(placement_on_ground(world)); } -void editor_mode::undo_last_area_fill() +fill_store::area editor_mode::fill_settings() const { - // nullify_history_pointers() removes deleted nodes from m_fill_last, so work on a copy - auto const created = std::move(m_fill_last); - m_fill_last.clear(); + fill_store::area area; + area.set_kind = static_cast(m_fill_source.kind); + area.set_id = m_fill_source.id; + area.density = std::max(0.0f, m_fill_density); + area.spacing = std::max(0.0f, m_fill_min_spacing); + area.scale_min = std::max(0.01f, std::min(m_fill_scale_min, m_fill_scale_max)); + area.scale_max = std::max(0.01f, std::max(m_fill_scale_min, m_fill_scale_max)); + area.random_rotation = m_fill_random_rotation; + // without the random rotation the one of the Functions panel goes with the area, a fixed one or none + area.rotation = (false == m_fill_random_rotation && ui()->rot_mode() == functions_panel::FIXED) ? ui()->rot_val() : 0.0f; + area.models_as_ground = m_fill_models_as_ground; + if (m_fill_source.kind == model_set_ref::source::manual) + area.templates = m_fill_custom; + else + for (auto const *entry : ui()->nodebank().set_entries(m_fill_source)) + area.templates.push_back(*entry); + area.templates.erase(std::remove_if(area.templates.begin(), area.templates.end(), [](std::string const &Template) { return Template.empty(); }), area.templates.end()); + return area; +} - for (TAnimModel *model : created) +std::vector editor_mode::fill_area_models(std::string const &Id) const +{ + std::vector models; + if (Id.empty()) + return models; + for (auto *model : simulation::Instances.sequence()) + if (model != nullptr && fill_store::owns(Id, model->name())) + models.push_back(model); + return models; +} + +std::size_t editor_mode::erase_fill_area_models(std::string const &Id) +{ + auto const models{fill_area_models(Id)}; + for (auto *model : models) { - if (model == nullptr) - continue; if (m_node == model) { m_node = nullptr; @@ -4818,66 +4845,58 @@ void editor_mode::undo_last_area_fill() } erase_model(model); } - m_fill_status = format(STR_C("Removed %zu objects of the last fill"), created.size()); + return models.size(); } -void editor_mode::run_area_fill() +std::size_t editor_mode::place_fill_area(fill_store::area const &Area, std::size_t &Target, std::size_t &Unsupported) { // limits keeping a single click from freezing the editor for too long std::size_t constexpr max_objects = 20000; + // the models go to the layer of the area, whichever is active (on an undo, on a change): the area and its models are saved together; + // the active one if the area's is gone + auto layer{scene::Layers.resolve(Area.layer)}; + if (false == scene::Layers.listed(layer)) + layer = null_handle; // large model instances (e.g. terrain tiles) are treated as ground, smaller ones (houses, trees) are not float constexpr terrain_model_radius = 50.0f; // ground is searched up to this far above the height interpolated from the outline points, // so hills inside the outline are found but bridges or roofs high above it are not double constexpr height_tolerance = 50.0; - if (m_fill_points.size() < 3) - { - m_fill_status = STR("Outline needs at least 3 points"); - return; - } + Target = 0; + Unsupported = 0; + auto const &outline{Area.outline}; + if (outline.size() < 3 || Area.templates.empty()) + return 0; - // model package - std::vector package; - if (m_fill_source.kind == model_set_ref::source::manual) - package = m_fill_custom; - else - for (auto const *entry : ui()->nodebank().set_entries(m_fill_source)) - package.push_back(*entry); - package.erase(std::remove_if(package.begin(), package.end(), [](std::string const &Template) { return Template.empty(); }), package.end()); - if (package.empty()) - { - m_fill_status = STR("Selected model package is empty"); - return; - } + // every random number of the fill comes from its seed, so the area filled again with the same settings gets the same objects + std::mt19937 random{Area.seed}; // NOSONAR(cpp:S2245) the placement of models, not security: it must repeat from the seed + auto const uniform = [&](double const Low, double const High) { return std::uniform_real_distribution{Low, High}(random); }; // area bounds glm::dvec2 bmin(std::numeric_limits::max()); glm::dvec2 bmax(-std::numeric_limits::max()); - for (auto const &p : m_fill_points) + for (auto const &p : outline) { bmin = glm::min(bmin, glm::dvec2(p.x, p.z)); bmax = glm::max(bmax, glm::dvec2(p.x, p.z)); } - double const area = polygon_area_xz(m_fill_points); - auto const target = static_cast(std::min(std::round(area / 10000.0 * std::max(0.0f, m_fill_density)), max_objects)); - if (target == 0) - { - m_fill_status = STR("Density too low for this area, nothing to place"); - return; - } + double const area = polygon_area_xz(outline); + Target = static_cast(std::min(std::round(area / 10000.0 * std::max(0.0f, Area.density)), max_objects)); + if (Target == 0) + return 0; // scatter points: random samples inside the outline, rejecting the ones closer than the minimal spacing // to an already accepted point (checked on a hashed grid with cell size == spacing) - double const spacing = std::max(0.0f, m_fill_min_spacing); + double const spacing = std::max(0.0f, Area.spacing); std::unordered_map> occupancy; auto const cell_key = [](std::int64_t const X, std::int64_t const Z) { return (X << 32) ^ (Z & 0xffffffff); }; std::vector points; - points.reserve(target); - for (std::size_t attempt = 0; attempt < target * 30 && points.size() < target; ++attempt) + points.reserve(Target); + for (std::size_t attempt = 0; attempt < Target * 30 && points.size() < Target; ++attempt) { - glm::dvec2 const p(LocalRandom(bmin.x, bmax.x), LocalRandom(bmin.y, bmax.y)); - if (false == point_in_polygon_xz(m_fill_points, p.x, p.y)) + glm::dvec2 const p(uniform(bmin.x, bmax.x), uniform(bmin.y, bmax.y)); + if (false == point_in_polygon_xz(outline, p.x, p.y)) continue; if (spacing > 0.0) { @@ -4906,23 +4925,22 @@ void editor_mode::run_area_fill() // ground geometry within the area std::vector triangles; - gather_ground_triangles(bmin, bmax, m_fill_models_as_ground, terrain_model_radius, triangles); + gather_ground_triangles(bmin, bmax, Area.models_as_ground, terrain_model_radius, triangles); triangle_grid const ground(std::move(triangles), bmin, bmax); auto const terrains = active_terrains(); - auto const rotation_mode = m_fill_random_rotation ? functions_panel::RANDOM : ui()->rot_mode(); - auto const fixed_rotation_value = ui()->rot_val(); - float const scalemin = std::max(0.01f, std::min(m_fill_scale_min, m_fill_scale_max)); - float const scalemax = std::max(0.01f, std::max(m_fill_scale_min, m_fill_scale_max)); - - std::vector created; - created.reserve(points.size()); - std::size_t unsupported = 0; + std::size_t placed{0}; + std::size_t number{0}; for (auto const &p : points) { + // the random numbers of the point are drawn before anything can skip it, so the points after it get the same ones + auto const pick{uniform(0.0, 1.0)}; + auto const yaw{uniform(0.0, 360.0)}; + auto const scale{uniform(0.0, 1.0)}; + // reference height: the outline points, weighted by inverse squared distance double weights = 0.0, reference = 0.0; - for (auto const &v : m_fill_points) + for (auto const &v : outline) { double const w = 1.0 / std::max(1e-6, glm::length2(glm::dvec2(v.x, v.z) - p)); weights += w; @@ -4947,40 +4965,210 @@ void editor_mode::run_area_fill() if (!found) { y = reference; - ++unsupported; + ++Unsupported; } glm::dvec3 const location(p.x, y, p.y); if (!simulation::Region->point_inside(location)) continue; - auto const &src = package[package.size() > 1 ? std::min(package.size() - 1, static_cast(LocalRandom(0.0, static_cast(package.size())))) : 0]; - // NOTE: no names here either, same as with the brush - TAnimModel *cloned = simulation::State.create_model(src, std::string{}, location); + auto const &src = Area.templates[std::min(Area.templates.size() - 1, static_cast(pick * static_cast(Area.templates.size())))]; + // named after the area, so its models are found again in a scenery loaded later + TAnimModel *cloned = simulation::State.create_model(src, fill_store::model_name(Area.id, number++), location, layer); if (!cloned) continue; - apply_rotation_for_new_node(cloned, rotation_mode, fixed_rotation_value); - if (scalemin != 1.0f || scalemax != 1.0f) - cloned->Scale(static_cast(LocalRandom(scalemin, scalemax))); - created.push_back(cloned); + if (Area.random_rotation) + m_editor.rotate(cloned, glm::vec3{0.0f, static_cast(yaw), 0.0f}, 1); + else if (Area.rotation != 0.0f) + m_editor.rotate(cloned, glm::vec3{0.0f, Area.rotation, 0.0f}, 0); + if (Area.scale_min != 1.0f || Area.scale_max != 1.0f) + cloned->Scale(static_cast(Area.scale_min + (Area.scale_max - Area.scale_min) * scale)); + ++placed; } + return placed; +} - // a new fill replaces the "last fill" undo set; the previous objects stay in the scene - m_fill_last = std::move(created); +void editor_mode::finish_area_fill() +{ + if (m_fill_points.size() < 3) + { + m_fill_status = STR("Outline needs at least 3 points"); + return; + } + auto area{fill_settings()}; + if (area.templates.empty()) + { + m_fill_status = STR("Selected model package is empty"); + return; + } + area.outline = m_fill_points; + if (std::round(polygon_area_xz(area.outline) / 10000.0 * area.density) < 1.0) + { + m_fill_status = STR("Density too low for this area, nothing to place"); + return; + } + // a changed area keeps its name and the names of its models, a new one gets them + auto const *before{m_fill_editing.empty() ? nullptr : fill_store::find(m_fill_editing)}; + fill_undo undo; + if (before != nullptr) + { + undo.what = fill_undo::kind::changed; + undo.before = *before; + area.id = before->id; + area.label = before->label; + // its own rotation, unless the rotation of the Functions panel was changed since it was picked up + if (false == area.random_rotation && false == before->random_rotation && static_cast(ui()->rot_mode()) == m_fill_editing_panel_mode && + ui()->rot_val() == m_fill_editing_panel_value) + area.rotation = m_fill_editing_rotation; + erase_fill_area_models(area.id); + } + else + { + undo.what = fill_undo::kind::added; + area.id = fill_store::next_id(); + area.label = format(STR_C("Area %zu"), fill_store::areas().size() + 1); + } + undo.id = area.id; + area.seed = static_cast(LocalRandom(0.0, 4294967295.0)); + // a changed area stays in its layer, with its models; a new one goes to the active layer + area.layer = before != nullptr ? undo.before.layer : scene::Layers.active(); - m_fill_status = format(STR_C("Placed %zu of %zu objects"), m_fill_last.size(), static_cast(target)); - if (points.size() < target) + std::size_t target{0}; + std::size_t unsupported{0}; + area.objects = place_fill_area(area, target, unsupported); + fill_store::put(area); + m_fill_undo = std::move(undo); + m_fill_points.clear(); + m_fill_editing.clear(); + + m_fill_status = format(STR_C("%s: placed %zu of %zu objects"), area.label.c_str(), area.objects, target); + if (area.objects < target) m_fill_status += STR_C(" (limited by min. spacing)"); if (unsupported > 0) m_fill_status += format(STR_C(", without ground under them (height from the outline): %zu"), unsupported); WriteLog("Editor: area fill - " + m_fill_status, logtype::generic); } +void editor_mode::cancel_area_fill() +{ + if (false == m_fill_editing.empty()) + { + if (auto const *area{fill_store::find(m_fill_editing)}) + m_fill_status = format(STR_C("%s left as it was"), area->label.c_str()); + m_fill_editing.clear(); + } + m_fill_points.clear(); +} + +void editor_mode::edit_fill_area(std::string const &Id) +{ + auto const *area{fill_store::find(Id)}; + if (area == nullptr) + return; + m_fill_editing = Id; + m_fill_points = area->outline; + m_fill_density = area->density; + m_fill_min_spacing = area->spacing; + m_fill_scale_min = area->scale_min; + m_fill_scale_max = area->scale_max; + m_fill_random_rotation = area->random_rotation; + m_fill_editing_rotation = area->rotation; + m_fill_editing_panel_mode = static_cast(ui()->rot_mode()); + m_fill_editing_panel_value = ui()->rot_val(); + m_fill_models_as_ground = area->models_as_ground; + // the set the models came from, while it still holds the same templates; otherwise the templates of the area themselves + model_set_ref source; + source.kind = static_cast(std::clamp(area->set_kind, 0, 2)); + source.id = area->set_id; + std::vector entries; + if (source.kind != model_set_ref::source::manual) + for (auto const *entry : ui()->nodebank().set_entries(source)) + if (false == entry->empty()) + entries.push_back(*entry); + if (source.kind != model_set_ref::source::manual && entries == area->templates) + m_fill_source = source; + else + { + m_fill_source = model_set_ref{}; + m_fill_custom = area->templates; + m_fill_custom_idx = -1; + } + m_fill_status = format(STR_C("%s picked up: change the outline or the settings, Enter fills it anew, Esc leaves it as it was"), area->label.c_str()); +} + +void editor_mode::remove_fill_area(std::string const &Id) +{ + auto const *area{fill_store::find(Id)}; + if (area == nullptr) + return; + if (m_fill_editing == Id) + { + m_fill_editing.clear(); + m_fill_points.clear(); + } + fill_undo undo; + undo.what = fill_undo::kind::removed; + undo.id = Id; + undo.before = *area; + auto const removed{erase_fill_area_models(Id)}; + m_fill_status = format(STR_C("%s removed with its %zu objects"), undo.before.label.c_str(), removed); + fill_store::forget(Id); + m_fill_undo = std::move(undo); +} + +void editor_mode::show_fill_area(std::string const &Id) +{ + auto const *area{fill_store::find(Id)}; + if (area == nullptr || area->outline.empty()) + return; + glm::dvec3 low{std::numeric_limits::max()}; + glm::dvec3 high{-std::numeric_limits::max()}; + for (auto const &point : area->outline) + { + low = glm::min(low, point); + high = glm::max(high, point); + } + auto const centre{(low + high) * 0.5}; + auto const extent{std::max(30.0, std::max(high.x - low.x, high.z - low.z))}; + // from the south-east, high enough to see the whole outline + Camera.Pos = centre + glm::dvec3{-0.5 * extent, 0.8 * extent, 0.5 * extent}; + auto const look{glm::normalize(centre - Camera.Pos)}; + Camera.Angle = glm::vec3(static_cast(std::asin(std::clamp(look.y, -1.0, 1.0))), static_cast(std::atan2(-look.x, -look.z)), 0.0f); + Camera.Velocity = {}; + Camera.m_owner = nullptr; + m_focus_active = false; + Global.pCamera = Camera; +} + +void editor_mode::undo_last_area_fill() +{ + if (false == m_fill_undo.has_value()) + return; + auto const undo{std::move(*m_fill_undo)}; + m_fill_undo.reset(); + if (m_fill_editing == undo.id) + { + m_fill_editing.clear(); + m_fill_points.clear(); + } + auto const removed{erase_fill_area_models(undo.id)}; + if (undo.what == fill_undo::kind::added) + { + fill_store::forget(undo.id); + m_fill_status = format(STR_C("Removed %zu objects of the last fill"), removed); + return; + } + // changed or removed: the area as it was, filled again from its seed, which gives the same objects + std::size_t target{0}; + std::size_t unsupported{0}; + auto before{undo.before}; + before.objects = place_fill_area(before, target, unsupported); + fill_store::put(before); + m_fill_status = format(STR_C("%s back as it was, %zu objects"), before.label.c_str(), before.objects); +} + void editor_mode::draw_area_fill_outline() const { - if (m_fill_points.empty()) - return; - // same camera-relative view and clean perspective the transform gizmo uses ImGuiIO const &io = ImGui::GetIO(); glm::mat4 const view = GfxRenderer->Camera_View_Matrix(); @@ -4995,27 +5183,42 @@ void editor_mode::draw_area_fill_outline() const float constexpr nearw = 0.1f; ImDrawList *drawlist = ImGui::GetBackgroundDrawList(ImGui::GetMainViewport()); + auto const draw_edges = [&](std::vector const &Points, bool const Open, ImU32 const Color, ImU32 const Closing, float const Thickness) { + std::size_t const count = Points.size(); + for (std::size_t i = 0; i < count; ++i) + { + bool const closing = (i + 1 == count); + if (closing && (count < 3 || (Open && Closing == 0))) + break; + glm::vec4 a = to_clip(Points[i]); + glm::vec4 b = to_clip(Points[(i + 1) % count]); + // clip the edge against the near plane, so points behind the camera don't flip across the screen + if (a.w < nearw && b.w < nearw) + continue; + if (a.w < nearw) + a = glm::mix(a, b, (nearw - a.w) / (b.w - a.w)); + else if (b.w < nearw) + b = glm::mix(b, a, (nearw - b.w) / (a.w - b.w)); + drawlist->AddLine(to_screen(a), to_screen(b), closing && Open ? Closing : Color, Thickness); + } + }; + + // the areas on the list, the one under the cursor in the list brighter; the one being changed is drawn as the outline + for (auto const &area : fill_store::areas()) + { + if (area.id == m_fill_editing) + continue; + auto const hovered{area.id == m_fill_hover}; + draw_edges(area.outline, false, hovered ? IM_COL32(120, 230, 255, 255) : IM_COL32(120, 200, 255, 110), 0, hovered ? 3.0f : 1.5f); + } + + if (m_fill_points.empty()) + return; ImU32 const edgecolor = IM_COL32(255, 200, 40, 230); ImU32 const closingcolor = IM_COL32(255, 200, 40, 110); - + draw_edges(m_fill_points, true, edgecolor, closingcolor, 2.0f); std::size_t const count = m_fill_points.size(); for (std::size_t i = 0; i < count; ++i) - { - bool const closing = (i + 1 == count); - if (closing && count < 3) - break; - glm::vec4 a = to_clip(m_fill_points[i]); - glm::vec4 b = to_clip(m_fill_points[(i + 1) % count]); - // clip the edge against the near plane, so points behind the camera don't flip across the screen - if (a.w < nearw && b.w < nearw) - continue; - if (a.w < nearw) - a = glm::mix(a, b, (nearw - a.w) / (b.w - a.w)); - else if (b.w < nearw) - b = glm::mix(b, a, (nearw - b.w) / (a.w - b.w)); - drawlist->AddLine(to_screen(a), to_screen(b), closing ? closingcolor : edgecolor, 2.0f); - } - for (std::size_t i = 0; i < count; ++i) { glm::vec4 const c = to_clip(m_fill_points[i]); if (c.w < nearw) @@ -5026,7 +5229,10 @@ void editor_mode::draw_area_fill_outline() const void editor_mode::render_area_fill() { - ImGui::TextDisabled(STR_C("LMB: add outline point Backspace: remove last point")); + ImGui::TextDisabled(STR_C("LMB: add outline point Backspace: remove last point Enter: fill and finish Esc: drop the outline")); + if (false == m_fill_editing.empty()) + if (auto const *editing{fill_store::find(m_fill_editing)}) + ImGui::TextColored(ImVec4(0.47f, 0.9f, 1.0f, 1.0f), STR_C("Changing: %s"), editing->label.c_str()); double const area = polygon_area_xz(m_fill_points); // the square sign written as its utf-8 bytes: the game is built without /utf-8 where it has the debug symbols ImGui::Text(STR_C("Points: %zu Area: %.0f m\xC2\xB2 (%.2f ha)"), m_fill_points.size(), area, area / 10000.0); @@ -5034,7 +5240,7 @@ void editor_mode::render_area_fill() m_fill_points.pop_back(); ImGui::SameLine(); if (ImGui::Button(STR_C("Clear outline"))) - m_fill_points.clear(); + cancel_area_fill(); ImGui::Separator(); @@ -5069,15 +5275,102 @@ void editor_mode::render_area_fill() ImGui::Text(STR_C("Estimated objects: %.0f"), std::round(area / 10000.0 * m_fill_density)); - if (ImGui::Button(STR_C("Fill area"))) - run_area_fill(); + if (ImGui::Button(m_fill_editing.empty() ? STR_C("Fill area (Enter)") : STR_C("Fill again (Enter)"))) + finish_area_fill(); ImGui::SameLine(); - std::string const undolabel = format(STR_C("Undo last fill (%zu)"), m_fill_last.size()); - if (ImGui::Button(undolabel.c_str()) && !m_fill_last.empty()) - undo_last_area_fill(); + if (m_fill_undo.has_value()) + { + if (ImGui::Button(STR_C("Undo last fill"))) + undo_last_area_fill(); + } + else + ImGui::TextDisabled("%s", STR_C("Undo last fill")); if (!m_fill_status.empty()) - ImGui::TextUnformatted(m_fill_status.c_str()); + ImGui::TextWrapped("%s", m_fill_status.c_str()); + + render_fill_area_list(); +} + +void editor_mode::render_fill_area_list() +{ + ImGui::Separator(); + auto const &areas{fill_store::areas()}; + ImGui::Text(STR_C("Filled areas: %zu"), areas.size()); + m_fill_hover.clear(); + if (areas.empty()) + { + ImGui::TextDisabled("%s", STR_C("None yet. Enter fills the outline and puts the area here, to be changed later")); + return; + } + // the buttons act after the list is drawn: they change the list + std::string edit, remove, show; + if (ImGui::BeginTable("fillareas", 4, ImGuiTableFlags_RowBg | ImGuiTableFlags_BordersInnerH | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY, ImVec2(0.0f, std::min(10, static_cast(areas.size()) + 1) * ImGui::GetFrameHeightWithSpacing()))) + { + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn(STR_C("Name"), ImGuiTableColumnFlags_WidthStretch, 3.0f); + ImGui::TableSetupColumn(STR_C("Objects"), ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn(STR_C("ha"), ImGuiTableColumnFlags_WidthFixed); + ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed); + ImGui::TableHeadersRow(); + for (auto const &area : areas) + { + ImGui::PushID(area.id.c_str()); + ImGui::TableNextRow(); + if (area.id == m_fill_editing) + ImGui::TableSetBgColor(ImGuiTableBgTarget_RowBg1, IM_COL32(60, 120, 150, 120)); + ImGui::TableNextColumn(); + // the name, changed in place and kept with the area once the field is left + std::array name{}; + std::snprintf(name.data(), name.size(), "%s", area.label.c_str()); + ImGui::SetNextItemWidth(-1.0f); + ImGui::InputText("##name", name.data(), name.size()); + if (ImGui::IsItemDeactivatedAfterEdit()) + { + auto changed{area}; + changed.label = name.data(); + fill_store::put(std::move(changed)); + ImGui::PopID(); + break; // the list changed under the loop + } + auto hovered{ImGui::IsItemHovered()}; + ImGui::TableNextColumn(); + ImGui::Text("%zu", area.objects); + hovered = hovered || ImGui::IsItemHovered(); + ImGui::TableNextColumn(); + ImGui::Text("%.2f", polygon_area_xz(area.outline) / 10000.0); + hovered = hovered || ImGui::IsItemHovered(); + ImGui::TableNextColumn(); + if (ImGui::SmallButton(STR_C("Change"))) + edit = area.id; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("Its outline and settings back in the tool: move the points, change the models or the density, Enter fills it anew")); + hovered = hovered || ImGui::IsItemHovered(); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Show"))) + show = area.id; + hovered = hovered || ImGui::IsItemHovered(); + ImGui::SameLine(); + if (ImGui::SmallButton(STR_C("Remove"))) + remove = area.id; + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The area and its models removed; Undo last fill brings them back")); + hovered = hovered || ImGui::IsItemHovered(); + if (hovered) + m_fill_hover = area.id; + ImGui::PopID(); + } + ImGui::EndTable(); + } + if (false == show.empty()) + show_fill_area(show); + if (false == edit.empty()) + { + edit_fill_area(edit); + show_fill_area(edit); + } + if (false == remove.empty()) + remove_fill_area(remove); } glm::vec3 editor_mode::array_size(TAnimModel const &Base) @@ -7353,7 +7646,7 @@ void editor_mode::exit() g_redo.clear(); m_history.clear(); m_orphans.clear(); - m_fill_last.clear(); + m_fill_undo.reset(); m_orthophoto.cancel_pending(); m_orthophoto.detach_scene(); // the layer is an editor aid, keep it out of the other modes for (auto &layer : m_wms) @@ -7691,6 +7984,12 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in area_finish(false); break; } + // area fill: the outline dropped, an area picked up for a change left as it was + if (is_press(Action) && ui()->mode() == nodebank_panel::FILL && false == ImGui::GetIO().WantTextInput && (false == m_fill_points.empty() || false == m_fill_editing.empty())) + { + cancel_area_fill(); + break; + } if (is_press(Action)) { road_cancel(); @@ -7781,6 +8080,12 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in area_finish(true); break; } + // area fill: the outline filled and put on the list, the next one can be started + if (is_press(Action) && ui()->mode() == nodebank_panel::FILL && false == ImGui::GetIO().WantTextInput && false == m_fill_points.empty()) + { + finish_area_fill(); + break; + } if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK && m_lay.active) lay_enter(); if (is_press(Action) && m_route.trace.active && route_active()) diff --git a/application/editormode.h b/application/editormode.h index 60da345e4..988dc590c 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -38,6 +38,7 @@ http://mozilla.org/MPL/2.0/. #include "editor/editorAlignment.hpp" #include "editor/editorAlignmentStore.hpp" #include "editor/editorSwitchStore.hpp" +#include "editor/editorFillStore.hpp" #include "editor/editorSwitchCurve.hpp" #include "editor/editorKilometrage.hpp" #include "editor/editorSpeed.hpp" @@ -1008,14 +1009,47 @@ class editor_mode : public application_mode, private editor_track::observer, pri void render_change_history(); void render_settings(); - // area fill: scatters models from a package over a polygon outlined in the viewport + // area fill: scatters models from a package over a polygon outlined in the viewport. a filled area goes on the list of the + // panel (fill_store, kept in the scenery), to be picked up again later: its outline and settings back in the tool, filled anew void render_area_fill(); + void render_fill_area_list(); void draw_area_fill_outline() const; void add_area_fill_point(); - void run_area_fill(); + // Enter: the outline filled and put on the list, the tool ready for the next one + void finish_area_fill(); + // Esc: the outline dropped; an area picked up for a change stays as it was + void cancel_area_fill(); + void edit_fill_area(std::string const &Id); + void remove_fill_area(std::string const &Id); + void show_fill_area(std::string const &Id); void undo_last_area_fill(); + // the settings of the tool as an area, without its outline, id and label + fill_store::area fill_settings() const; + // the models the area is filled with, from its seed: the same each time for the same area. returns how many were placed + std::size_t place_fill_area(fill_store::area const &Area, std::size_t &Target, std::size_t &Unsupported); + std::vector fill_area_models(std::string const &Id) const; + std::size_t erase_fill_area_models(std::string const &Id); std::vector m_fill_points; // outline vertices (world space) in click order - std::vector m_fill_last; // instances created by the most recent fill, for "Undo last fill" + std::string m_fill_editing; // the listed area whose outline is in m_fill_points, empty for a new one + // the rotation of the area picked up and the one of the Functions panel then: the area keeps its own unless it's changed in the tool + float m_fill_editing_rotation{0.0f}; + int m_fill_editing_panel_mode{-1}; + float m_fill_editing_panel_value{0.0f}; + std::string m_fill_hover; // the area under the cursor in the list, drawn brighter + // what "Undo last fill" takes back: the area filled, changed or removed last, and how it was before + struct fill_undo + { + enum class kind + { + added, + changed, + removed + }; + kind what{kind::added}; + std::string id; + fill_store::area before; + }; + std::optional m_fill_undo; std::vector m_fill_custom; // user-assembled package of node templates int m_fill_custom_idx{-1}; model_set_ref m_fill_source; // manual = m_fill_custom, otherwise a user set or node bank group diff --git a/editor/editorFillStore.cpp b/editor/editorFillStore.cpp new file mode 100644 index 000000000..9cfe4097e --- /dev/null +++ b/editor/editorFillStore.cpp @@ -0,0 +1,220 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#include "stdafx.h" +#include "editor/editorFillStore.hpp" +#include "editor/editorFormat.hpp" + +#include "model/AnimModel.h" +#include "simulation/simulation.h" +#include "utilities/Logs.h" + +#include +#include +#include +#include + +namespace fill_store +{ + +namespace +{ + +std::string const kMark{"//$u"}; + +std::vector g_areas; +bool g_loaded{false}; + +// format of the lines, coordinates in the space of the file: +// area seed density spacing scale rotation ground <0|1> +// set objects label +// outline ... +// template +// end + +std::string trimmed(std::string Text) +{ + auto const first{Text.find_first_not_of(" \t")}; + if (first == std::string::npos) + return {}; + auto const last{Text.find_last_not_of(" \t\r\n")}; + return Text.substr(first, last - first + 1); +} + +void mark(scene::layer_handle const Layer) +{ + if (false == scene::Layers.valid(Layer)) + return; + auto const &context{scene::Layers.layer(Layer).context_insert()}; + std::vector lines; + for (auto const &entry : g_areas) + { + if (entry.layer != Layer) + continue; + if (lines.empty()) + lines.emplace_back("# areas filled with models in the editor, the simulation skips these lines"); + auto header{format("area %s seed %u density %.3f spacing %.3f", entry.id.c_str(), static_cast(entry.seed), entry.density, entry.spacing)}; + header += format(" scale %.3f %.3f rotation %s %.3f", entry.scale_min, entry.scale_max, entry.random_rotation ? "random" : "fixed", entry.rotation); + header += format(" ground %d set %d %d objects %zu label %s", entry.models_as_ground ? 1 : 0, entry.set_kind, entry.set_id, entry.objects, entry.label.c_str()); + lines.push_back(std::move(header)); + auto outline{format("outline %zu", entry.outline.size())}; + for (auto const &point : entry.outline) + { + auto const local{context.to_local(point)}; + outline += format(" %.4f %.4f %.4f", local.x, local.y, local.z); + } + lines.push_back(std::move(outline)); + for (auto const &entry_template : entry.templates) + lines.push_back("template " + entry_template); + lines.emplace_back("end"); + } + scene::Layers.mark(Layer, kMark, std::move(lines)); +} + +} // namespace + +void reset() +{ + g_areas.clear(); + g_loaded = false; +} + +void load() +{ + if (g_loaded || scene::Layers.empty()) + return; + g_loaded = true; + g_areas.clear(); + for (auto const layer : scene::Layers.marked_layers(kMark)) + { + auto const &context{scene::Layers.layer(layer).context_insert()}; + area entry; + bool open{false}; + for (auto const &text : scene::Layers.marked(layer, kMark)) + { + std::istringstream line{text}; + std::string keyword; + line >> keyword; + if (keyword == "area") + { + entry = area{}; + entry.layer = layer; + std::string seed, density, spacing, scale, rotation, rotationkind, ground, set, objects, label; + int groundvalue{1}; + unsigned seedvalue{0}; + line >> entry.id >> seed >> seedvalue >> density >> entry.density >> spacing >> entry.spacing >> scale >> entry.scale_min >> entry.scale_max; + line >> rotation >> rotationkind >> entry.rotation >> ground >> groundvalue >> set >> entry.set_kind >> entry.set_id >> objects >> entry.objects >> label; + open = (false == line.fail()) && (false == entry.id.empty()) && label == "label"; + if (false == open) + continue; + entry.seed = seedvalue; + entry.random_rotation = (rotationkind != "fixed"); + entry.models_as_ground = (groundvalue != 0); + std::string rest; + std::getline(line, rest); + entry.label = trimmed(rest); + } + else if (keyword == "outline" && open) + { + std::size_t count{0}; + line >> count; + for (std::size_t i = 0; i < count && i < 100000; ++i) + { + glm::dvec3 point{0.0}; + line >> point.x >> point.y >> point.z; + if (line.fail()) + break; + entry.outline.push_back(context.to_world(point)); + } + } + else if (keyword == "template" && open) + { + std::string rest; + std::getline(line, rest); + rest = trimmed(rest); + if (false == rest.empty()) + entry.templates.push_back(std::move(rest)); + } + else if (keyword == "end" && open) + { + open = false; + if (entry.outline.size() >= 3) + g_areas.push_back(std::move(entry)); + } + } + } + if (false == g_areas.empty()) + WriteLog("Editor: " + std::to_string(g_areas.size()) + " filled area(s) read from the scenery", logtype::generic); +} + +std::vector const &areas() +{ + load(); + return g_areas; +} + +area const *find(std::string const &Id) +{ + load(); + auto const lookup{std::find_if(g_areas.begin(), g_areas.end(), [&](area const &Entry) { return Entry.id == Id; })}; + return lookup != g_areas.end() ? &(*lookup) : nullptr; +} + +std::string next_id() +{ + load(); + for (std::size_t number = g_areas.size() + 1;; ++number) + { + auto const id{"fill" + std::to_string(number)}; + if (find(id) == nullptr && simulation::Instances.find(model_name(id, 0)) == nullptr) + return id; + } +} + +void put(area Entry) +{ + load(); + std::set layers{Entry.layer}; + auto const existing{std::find_if(g_areas.begin(), g_areas.end(), [&](area const &Other) { return Other.id == Entry.id; })}; + if (existing != g_areas.end()) + { + layers.insert(existing->layer); + *existing = std::move(Entry); + } + else + g_areas.push_back(std::move(Entry)); + for (auto const layer : layers) + mark(layer); +} + +void forget(std::string const &Id) +{ + load(); + std::set layers; + for (auto const &entry : g_areas) + if (entry.id == Id) + layers.insert(entry.layer); + g_areas.erase(std::remove_if(g_areas.begin(), g_areas.end(), [&](area const &Entry) { return Entry.id == Id; }), g_areas.end()); + for (auto const layer : layers) + mark(layer); +} + +std::string model_name(std::string const &Id, std::size_t const Number) +{ + return Id + "_" + std::to_string(Number); +} + +bool owns(std::string const &Id, std::string const &Name) +{ + if (Name.size() <= Id.size() + 1 || Name.compare(0, Id.size(), Id) != 0 || Name[Id.size()] != '_') + return false; + return std::all_of(Name.begin() + static_cast(Id.size()) + 1, Name.end(), [](char const Character) { return Character >= '0' && Character <= '9'; }); +} + +} // namespace fill_store diff --git a/editor/editorFillStore.hpp b/editor/editorFillStore.hpp new file mode 100644 index 000000000..03f31661f --- /dev/null +++ b/editor/editorFillStore.hpp @@ -0,0 +1,59 @@ +/* +This Source Code Form is subject to the +terms of the Mozilla Public License, v. +2.0. If a copy of the MPL was not +distributed with this file, You can +obtain one at +http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include +#include +#include +#include + +#include "scene/scenelayers.h" + +// areas filled with models in the editor, kept in the scenery files as "//$u" comment lines: the outline, the models and the +// settings of the fill and the seed of its random numbers, so the area can be picked up again, changed and filled anew. the +// models of an area are named after it, _, which is how they're found again in a scenery loaded later +namespace fill_store +{ + +struct area +{ + std::string id; // fill, the prefix of the names of its models + std::string label; // given by the user, shown in the list + scene::layer_handle layer{null_handle}; + std::vector outline; // world space, in the order it was clicked + std::vector templates; // the node templates the models were drawn from + int set_kind{0}; // the model set the templates came from (model_set_ref): 0 the list of the tool, 1 a user set, 2 a node bank group + int set_id{-1}; + float density{200.0f}; // objects per hectare + float spacing{2.0f}; // minimal distance between the objects, m + float scale_min{1.0f}; + float scale_max{1.0f}; + bool random_rotation{true}; + float rotation{0.0f}; // yaw of all objects without the random rotation, degrees + bool models_as_ground{true}; + std::uint32_t seed{0}; // of the random numbers of the fill: the same seed and settings make the same objects + std::size_t objects{0}; // placed by the last fill +}; + +void reset(); +void load(); +std::vector const &areas(); +area const *find(std::string const &Id); +// an id no area has and no model is named after yet +std::string next_id(); +// the area of the id is replaced, or added; it's kept in the file of its layer +void put(area Entry); +void forget(std::string const &Id); +// the name of the model of the area with the number +std::string model_name(std::string const &Id, std::size_t const Number); +// whether the model name is one of the models of the area +bool owns(std::string const &Id, std::string const &Name); + +} // namespace fill_store diff --git a/lang/editor_pl.po b/lang/editor_pl.po index 719e51337..bf36eae0e 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -3309,6 +3309,57 @@ msgstr "Szacowana liczba obiektów: %.0f" msgid "Fill area" msgstr "Wypełnij obszar" +msgid "LMB: add outline point Backspace: remove last point Enter: fill and finish Esc: drop the outline" +msgstr "LPM: dodaj punkt obrysu Backspace: usuń ostatni punkt Enter: wypełnij i zakończ Esc: porzuć obrys" + +msgid "Changing: %s" +msgstr "Zmieniasz: %s" + +msgid "Fill area (Enter)" +msgstr "Wypełnij obszar (Enter)" + +msgid "Fill again (Enter)" +msgstr "Wypełnij od nowa (Enter)" + +msgid "Undo last fill" +msgstr "Cofnij ostatnie wypełnienie" + +msgid "Area %zu" +msgstr "Obszar %zu" + +msgid "%s: placed %zu of %zu objects" +msgstr "%s: postawiono %zu z %zu obiektów" + +msgid "%s left as it was" +msgstr "%s zostaje bez zmian" + +msgid "%s picked up: change the outline or the settings, Enter fills it anew, Esc leaves it as it was" +msgstr "%s do zmiany: popraw obrys albo ustawienia, Enter wypełnia od nowa, Esc zostawia bez zmian" + +msgid "%s removed with its %zu objects" +msgstr "Usunięto %s razem z obiektami (%zu)" + +msgid "%s back as it was, %zu objects" +msgstr "%s przywrócony, obiektów: %zu" + +msgid "Filled areas: %zu" +msgstr "Wypełnione obszary: %zu" + +msgid "None yet. Enter fills the outline and puts the area here, to be changed later" +msgstr "Jeszcze żadnego. Enter wypełnia obrys i dopisuje obszar tutaj, do późniejszej zmiany" + +msgid "ha" +msgstr "ha" + +msgid "Change" +msgstr "Zmień" + +msgid "Its outline and settings back in the tool: move the points, change the models or the density, Enter fills it anew" +msgstr "Obrys i ustawienia wracają do narzędzia: przesuń punkty, zmień modele albo gęstość, Enter wypełnia od nowa" + +msgid "The area and its models removed; Undo last fill brings them back" +msgstr "Usuwa obszar i jego modele; Cofnij ostatnie wypełnienie przywraca je" + msgid "Copies of the selected model, set out in a row" msgstr "Kopie zaznaczonego modelu, ustawione w rzędzie" diff --git a/scene/scenelayers.cpp b/scene/scenelayers.cpp index 2484e048f..9e075d063 100644 --- a/scene/scenelayers.cpp +++ b/scene/scenelayers.cpp @@ -858,7 +858,8 @@ namespace { // marks of the lines the editor keeps track of. The letters the starters read in a scenery file are left to them: the title //$n, // the description //$d, the attachments //$f, the image //$i, the id //$l and the old scenery //$a, in the trainsets //$o and //$r -std::array const editormarks{"//$p", "//$h", "//$r", "//$b", "//$c", "//$o", "//$s", "//$k", "//$z", "//$w", "//$t"}; +// the filled areas of the area fill //$u +std::array const editormarks{"//$p", "//$h", "//$r", "//$b", "//$c", "//$o", "//$s", "//$k", "//$z", "//$w", "//$t", "//$u"}; // the marks some of these had before, on the letters of the starters: the download area //$z was //$a, the shared grade lines //$w // were //$n, the fitted tracks //$t were //$f. Their lines are read only by the word the editor wrote in them, or by the start of @@ -894,7 +895,7 @@ bool editor_line(std::string_view const Mark, std::string const &Text) std::string on, state, next; return words >> on >> state && on == "on" && (state == "0" || state == "1") && (false == static_cast(words >> next) || next == "origin" || next == "year"); } - static std::array>, 7> const words{{ + static std::array>, 8> const words{{ {"//$h", {"#", "alignment", "source", "ends", "norms", "pieces", "kept", "vertex", "click", "element", "end"}}, {"//$r", {"#", "switch", "slip", "crossing", "double", "connection"}}, {"//$s", {"#", "station"}}, @@ -902,6 +903,7 @@ bool editor_line(std::string_view const Mark, std::string const &Text) {"//$z", {"#", "point"}}, {"//$w", {"#", "gradeline"}}, {"//$t", {"#", "fitted"}}, + {"//$u", {"#", "area", "outline", "template", "end"}}, }}; auto const lookup{std::find_if(words.begin(), words.end(), [&](auto const &Entry) { return Entry.first == Mark; })}; if (lookup == words.end()) diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index bb804734a..c6b150cf4 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -545,8 +545,8 @@ void state_manager::process_commands() { } } -TAnimModel * state_manager::create_model(const std::string &src, const std::string &name, const glm::dvec3 &position) { - return m_serializer.create_model(src, name, position); +TAnimModel * state_manager::create_model(const std::string &src, const std::string &name, const glm::dvec3 &position, scene::layer_handle const Layer) { + return m_serializer.create_model(src, name, position, Layer); } std::vector state_manager::insert_trainset(std::string const &Name, TTrack *Path, double const Offset, std::string const &Vehicles, bool const Reversed) { diff --git a/simulation/simulation.h b/simulation/simulation.h index 04349ee81..02bef0ffd 100644 --- a/simulation/simulation.h +++ b/simulation/simulation.h @@ -39,7 +39,7 @@ public: process_commands(); // create model from node string TAnimModel * - create_model(const std::string &src, const std::string &name, const glm::dvec3 &position); + create_model(const std::string &src, const std::string &name, const glm::dvec3 &position, scene::layer_handle Layer = null_handle); // places the vehicles, given as their node statements, as a trainset on the path. returns: the vehicles made std::vector insert_trainset(std::string const &Name, TTrack *Path, double const Offset, std::string const &Vehicles, bool const Reversed = false); diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 1b09c0b80..2d8541d7f 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -1939,7 +1939,7 @@ state_serializer::export_nodes_to_stream(std::ostream &scmfile, bool Dirty) cons } } -TAnimModel *state_serializer::create_model(const std::string &src, const std::string &name, const glm::dvec3 &position) { +TAnimModel *state_serializer::create_model(const std::string &src, const std::string &name, const glm::dvec3 &position, scene::layer_handle const Layer) { cParser parser(src); parser.getTokens(); // "node" parser.getTokens(2); // ranges @@ -1950,7 +1950,8 @@ TAnimModel *state_serializer::create_model(const std::string &src, const std::st parser.getTokens(2); // name, type nodedata.name = name; nodedata.type = "model"; - nodedata.layer = scene::Layers.active(); // null_handle unless the scenery was opened for editing + // null_handle unless the scenery was opened for editing + nodedata.layer = Layer != null_handle ? Layer : scene::Layers.active(); scene::scratch_data scratch; diff --git a/simulation/simulationstateserializer.h b/simulation/simulationstateserializer.h index 95da529fe..dc01d53dc 100644 --- a/simulation/simulationstateserializer.h +++ b/simulation/simulationstateserializer.h @@ -43,7 +43,8 @@ public: void export_as_text( std::string const &Scenariofile ) const; // create new model from node stirng - TAnimModel * create_model(std::string const &src, std::string const &name, const glm::dvec3 &position); + // the model goes to the layer given, or to the active one with none given + TAnimModel * create_model(std::string const &src, std::string const &name, const glm::dvec3 &position, scene::layer_handle Layer = null_handle); // places the vehicles, given as their node statements, as a trainset on the path, while the simulation runs. returns: the vehicles made std::vector insert_trainset(std::string const &Name, TTrack *Path, double const Offset, std::string const &Vehicles, bool const Reversed = false); // create new eventlauncher from node stirng