web_server 初步改

This commit is contained in:
2026-08-21 12:52:27 +08:00
parent d1aa763fcd
commit c41a8ff62d
14 changed files with 792 additions and 421 deletions
+214 -3
View File
@@ -1,6 +1,217 @@
#include "Plot.hpp"
#include "Renderable_Adapter.hpp"
#include <asio/co_spawn.hpp>
#include <asio/error_code.hpp>
#include <asio/experimental/concurrent_channel.hpp>
#include <asio/redirect_error.hpp>
#include <asio/strand.hpp>
#include <asio/use_awaitable.hpp>
#include <render_2D/plottable/Plottables.hpp>
#include <render_2D/scene/Render_Scene_2D.hpp>
#include <render_3D/Render_3D.hpp>
#include <algorithm>
#include <array>
#include <atomic>
#include <cmath>
#include <cstring>
#include <mutex>
#include <numbers>
#include <span>
#include <stdexcept>
#include <unordered_map>
#include <utility>
#include <variant>
namespace aethera::web {
Plot::Plot(std::string key_value, std::shared_ptr<Graph_WebSocket> websocket_value) : websocket(std::move(websocket_value)), key(std::move(key_value)) { websocket->register_callback(key, [this](std::string_view event) { on_event(event); }); }
Plot::~Plot() { websocket->unregister_callback(key); }
void Plot::send_frame(std::string_view frame) { websocket->send(key, frame); }
namespace {
using namespace render_2d;
using namespace render_3d;
using Scene_2D = Impl<Render_Scene_2D>;
using Frequency_Axis_Object = Impl<Frequency_Axis>;
using Numeric_Axis_Object = Impl<Numeric_Axis>;
using Time_Axis_Object = Impl<Time_Axis>;
template <typename Object, typename... Arguments>
std::unique_ptr<Object> build(Arguments&&... arguments) { typename Object::Builder builder(std::forward<Arguments>(arguments)...); auto result = builder.build(); if (!result) throw std::logic_error("gallery graph dependency graph is invalid"); return std::move(result).value(); }
template <typename Axis>
void configure_axis(Axis* axis, Axis_Orientation orientation, Point_F position, Axis_Pixel_Length length, Size canvas) { axis->template set<&Abs_Axis::Prop::orientation>(orientation); axis->template set<&Abs_Axis::Prop::position>(position); axis->template set<&Abs_Axis::Prop::pixel_length>(length); axis->template set<&Abs_Axis::Prop::canvas_size>(canvas); }
template <typename Integer>
void append_binary(std::string& output, Integer value) { const auto start = output.size(); output.resize(start + sizeof(Integer)); std::memcpy(output.data() + start, &value, sizeof(Integer)); }
std::string encode_frame(Image_View image, std::uint64_t sequence) { std::string output; output.reserve(24 + static_cast<std::size_t>(image.width) * image.height * 4); append_binary(output, std::uint32_t{0x41544852}); append_binary(output, std::uint16_t{1}); append_binary(output, std::uint16_t{}); append_binary(output, static_cast<std::uint32_t>(image.width)); append_binary(output, static_cast<std::uint32_t>(image.height)); append_binary(output, sequence); for (int y = 0; y < image.height; ++y) { const auto* row = reinterpret_cast<const std::uint8_t*>(image.data + static_cast<std::ptrdiff_t>(y) * image.stride); for (int x = 0; x < image.width; ++x) { const auto* pixel = row + x * 4; output.push_back(static_cast<char>(pixel[2])); output.push_back(static_cast<char>(pixel[1])); output.push_back(static_cast<char>(pixel[0])); output.push_back(static_cast<char>(pixel[3])); } } return output; }
std::string encode_frame(const render_3d::Pixel_Frame& frame, std::uint64_t sequence) { std::string output; output.reserve(24 + frame.rgba8.size()); append_binary(output, std::uint32_t{0x41544852}); append_binary(output, std::uint16_t{1}); append_binary(output, std::uint16_t{}); append_binary(output, frame.extent.width); append_binary(output, frame.extent.height); append_binary(output, sequence); output.append(reinterpret_cast<const char*>(frame.rgba8.data()), frame.rgba8.size()); return output; }
struct Schema_Query { Plot::Json_Handler handler{}; };
struct Prop_Write { std::string key{}; nlohmann::json value{}; Plot::Json_Handler handler{}; };
using Plot_Input = std::variant<Plot_Event, Schema_Query, Prop_Write>;
struct Plot_2D {
std::unique_ptr<Scene_2D> scene{}; /* 鏈€缁堜簩缁?Scene銆?*/
std::unique_ptr<Frequency_Axis_Object> frequency{}; /* 棰戠巼杞达紱涓嶇敤鏃朵粛涓虹┖銆?*/
std::unique_ptr<Numeric_Axis_Object> horizontal{}; /* 鏄熷骇鍥炬按骞虫暟鍊艰酱銆?*/
std::unique_ptr<Numeric_Axis_Object> vertical{}; /* 鍔熺巼鎴栨槦搴у浘鍨傜洿杞淬€?*/
std::unique_ptr<Time_Axis_Object> time{}; /* 鏃堕棿杞达紱涓嶇敤鏃朵负绌恒€?*/
std::unique_ptr<Root> plot{}; /* 鍏蜂綋 Plottable 鐨勫敮涓€鎵€鏈夋潈銆?*/
std::function<void(double)> update{}; /* 鏍规嵁娴忚鍣ㄦ椂閽熸洿鏂版潈濞?Prop銆?*/
std::unique_ptr<detail::Renderable_Descriptor> descriptor{}; /* 鐩存帴璇诲啓 plot 鐨?Structive 鍗忚瑙嗗浘銆?*/
};
template <typename Definition, typename... Fields, typename Holder, typename Object>
void bind_renderable_adapter(Holder& plot, Object& object) {
using Tag = typename Definition::Base_Tag;
using State = typename Definition::State;
using Adapter = detail::Renderable_Adapter<Object, Fields...,
detail::State_Field<Tag, &State::prepare_dirty, "prepare_dirty">,
detail::State_Field<Tag, &State::paint_dirty, "paint_dirty">,
detail::State_Field<Tag, &State::prepare_executed, "prepare_executed">,
detail::State_Field<Tag, &State::paint_executed, "paint_executed">,
detail::State_Field<Tag, &State::prepare_graph_rebuilt, "prepare_graph_rebuilt">,
detail::State_Field<Tag, &State::paint_graph_rebuilt, "paint_graph_rebuilt">,
detail::State_Field<Tag, &State::prepare_task_count, "prepare_task_count">,
detail::State_Field<Tag, &State::paint_task_count, "paint_task_count">,
detail::State_Field<Tag, &State::prepare_execution_time_ns, "prepare_execution_time_ns">,
detail::State_Field<Tag, &State::paint_execution_time_ns, "paint_execution_time_ns">>;
plot.descriptor = detail::make_renderable_descriptor(Adapter{object});
}
#define AETHERA_PROP(Type, Name) detail::Prop_Field<&Type::Prop::Name, #Name>
#define AETHERA_STATE(Type, Name) detail::State_Field<typename Type::Base_Tag, &Type::State::Name, #Name>
template <typename Definition>
Plot_2D make_plot_2d() {
Plot_2D result;
const Size canvas{720, 420};
result.scene = build<Scene_2D>();
result.scene->set<&Render_Scene_2D::Prop::viewport>(canvas);
result.scene->set<&Render_Scene_2D::Prop::background>(Color{7, 13, 24, 255});
result.scene->activate_view();
auto make_frequency = [&] { result.frequency = build<Frequency_Axis_Object>(); configure_axis(result.frequency.get(), Axis_Orientation::horizontal, Point_F{64.0, 370.0}, 620.0, canvas); result.frequency->set<&Numeric_Axis::Prop::coordinate_range>(Axis_Range{0.0, 100.0}); };
auto make_vertical = [&](Axis_Range range) {
result.vertical = build<Numeric_Axis_Object>();
configure_axis(result.vertical.get(), Axis_Orientation::vertical, {64.0, 370.0}, -320.0, canvas); result.vertical->set<&Numeric_Axis::Prop::coordinate_range>(range);
};
if constexpr (std::same_as<Definition, Spectrum>) {
make_frequency(); make_vertical({-110.0, 0.0}); auto object = build<Impl<Spectrum>>(result.scene.get(), result.frequency.get(), result.vertical.get()); object->set<&Spectrum::Prop::frequency_range>(Axis_Range{0.0, 100.0}); object->set<&Spectrum::Prop::max_hold_visible>(true); auto* raw = object.get(); raw->mark_dirty<Prepare_Data_Tag>(); raw->mark_dirty<Paint_Tag>(); bind_renderable_adapter<Spectrum, AETHERA_PROP(Spectrum, center_frequency), AETHERA_PROP(Spectrum, partition_count), AETHERA_PROP(Spectrum, max_hold_visible), AETHERA_PROP(Spectrum, min_hold_visible), AETHERA_PROP(Spectrum, max_marker_visible), AETHERA_PROP(Spectrum, min_marker_visible), AETHERA_PROP(Spectrum, sweep_region_visible), AETHERA_PROP(Spectrum, visible_range_only), AETHERA_PROP(Spectrum, frequency_range), AETHERA_PROP(Spectrum, sweep_frequency_range), AETHERA_PROP(Spectrum, partition_mode), AETHERA_PROP(Spectrum, interpolation_mode), AETHERA_PROP(Spectrum, max_brush), AETHERA_PROP(Spectrum, current_brush), AETHERA_PROP(Spectrum, min_brush), AETHERA_PROP(Spectrum, max_pen), AETHERA_PROP(Spectrum, current_pen), AETHERA_PROP(Spectrum, min_pen), AETHERA_PROP(Spectrum, selected_marker_pen), AETHERA_PROP(Spectrum, marker_pen), AETHERA_PROP(Spectrum, middle_frequency_pen), AETHERA_PROP(Spectrum, sweep_region_brush), AETHERA_PROP(Spectrum, custom_markers), AETHERA_PROP(Spectrum, selected_marker), AETHERA_STATE(Spectrum, sample_count), AETHERA_STATE(Spectrum, rendered_point_count), AETHERA_STATE(Spectrum, selectable_marker_count)>(result, *raw); result.update = [raw](double time) { std::array<double, 256> samples{}; for (std::size_t i = 0; i < samples.size(); ++i) { const double x = static_cast<double>(i) / samples.size(); samples[i] = -92.0 + 54.0 * std::exp(-180.0 * std::pow(x - 0.28 - 0.03 * std::sin(time * 0.001), 2.0)) + 42.0 * std::exp(-260.0 * std::pow(x - 0.68, 2.0)) + 2.5 * std::sin(i * 0.31 + time * 0.004); } raw->update_samples(samples); }; result.plot = std::move(object);
} else if constexpr (std::same_as<Definition, Frequency_Trace>) {
result.time = build<Time_Axis_Object>(); configure_axis(result.time.get(), Axis_Orientation::horizontal, {64.0, 370.0}, 620.0, canvas); make_vertical({-1.2, 1.2}); auto object = build<Impl<Frequency_Trace>>(result.scene.get(), result.time.get(), result.vertical.get()); auto* raw = object.get(); raw->mark_dirty<Prepare_Data_Tag>(); raw->mark_dirty<Paint_Tag>(); bind_renderable_adapter<Frequency_Trace, AETHERA_PROP(Frequency_Trace, partition_count), AETHERA_PROP(Frequency_Trace, pen), AETHERA_PROP(Frequency_Trace, partition_mode), AETHERA_PROP(Frequency_Trace, samples), AETHERA_STATE(Frequency_Trace, sample_count), AETHERA_STATE(Frequency_Trace, rendered_point_count)>(result, *raw); auto tick = std::make_shared<std::uint64_t>(); result.update = [raw, tick](double time) { raw->append_sample((*tick)++, std::sin(time * 0.0025) * 0.8 + std::sin(time * 0.0007) * 0.2); }; result.plot = std::move(object);
} else if constexpr (std::same_as<Definition, Sweep_Spectrum>) {
make_frequency(); make_vertical({-110.0, 0.0}); auto object = build<Impl<Sweep_Spectrum>>(result.scene.get(), result.frequency.get(), result.vertical.get()); object->set<&Sweep_Spectrum::Prop::frequency_range>(Axis_Range{0.0, 100.0}); auto* raw = object.get(); raw->mark_dirty<Prepare_Data_Tag>(); raw->mark_dirty<Paint_Tag>(); bind_renderable_adapter<Sweep_Spectrum, AETHERA_PROP(Sweep_Spectrum, bins_per_block), AETHERA_PROP(Sweep_Spectrum, block_count), AETHERA_PROP(Sweep_Spectrum, partition_count), AETHERA_PROP(Sweep_Spectrum, visible_range_only), AETHERA_PROP(Sweep_Spectrum, frequency_range), AETHERA_PROP(Sweep_Spectrum, partition_mode), AETHERA_PROP(Sweep_Spectrum, pen), AETHERA_PROP(Sweep_Spectrum, current_frequency_pen), AETHERA_PROP(Sweep_Spectrum, interpolation_mode), AETHERA_PROP(Sweep_Spectrum, blocks), AETHERA_STATE(Sweep_Spectrum, stored_block_count), AETHERA_STATE(Sweep_Spectrum, stored_point_count), AETHERA_STATE(Sweep_Spectrum, rendered_point_count)>(result, *raw); result.update = [raw](double time) { std::array<double, 64> values{}; for (std::size_t i = 0; i < values.size(); ++i) values[i] = -90.0 + 35.0 * std::sin(i * 0.08 + time * 0.002); raw->append_block(values); }; result.plot = std::move(object);
} else if constexpr (std::same_as<Definition, Afterglow>) {
make_frequency(); make_vertical({-110.0, 0.0}); auto object = build<Impl<Afterglow>>(result.scene.get(), result.frequency.get(), result.vertical.get()); object->set<&Afterglow::Prop::frequency_range>(Axis_Range{0.0, 100.0}); object->set<&Afterglow::Prop::power_range>(Axis_Range{-110.0, 0.0}); object->set<&Afterglow::Prop::power_point_size>(96); auto* raw = object.get(); raw->mark_dirty<Prepare_Data_Tag>(); raw->mark_dirty<Paint_Tag>(); bind_renderable_adapter<Afterglow, AETHERA_PROP(Afterglow, frequency_point_size), AETHERA_PROP(Afterglow, power_point_size), AETHERA_PROP(Afterglow, partition_count), AETHERA_PROP(Afterglow, interpolate), AETHERA_PROP(Afterglow, attenuation_rate), AETHERA_PROP(Afterglow, frequency_range), AETHERA_PROP(Afterglow, power_range), AETHERA_PROP(Afterglow, partition_mode), AETHERA_PROP(Afterglow, color_map), AETHERA_PROP(Afterglow, spectra), AETHERA_STATE(Afterglow, history_count), AETHERA_STATE(Afterglow, latest_spectrum_point_count), AETHERA_STATE(Afterglow, rendered_cell_count)>(result, *raw); result.update = [raw](double time) { std::array<double, 192> values{}; for (std::size_t i = 0; i < values.size(); ++i) values[i] = -95.0 + 62.0 * std::exp(-220.0 * std::pow(static_cast<double>(i) / values.size() - 0.5 - 0.18 * std::sin(time * 0.0008), 2.0)); raw->append_spectrum(values); }; result.plot = std::move(object);
} else if constexpr (std::same_as<Definition, Waterfall>) {
make_frequency(); result.time = build<Time_Axis_Object>(); configure_axis(result.time.get(), Axis_Orientation::vertical, {64.0, 370.0}, -320.0, canvas); auto object = build<Impl<Waterfall>>(result.scene.get(), result.frequency.get(), result.time.get()); object->set<&Waterfall::Prop::frequency_range>(Axis_Range{0.0, 100.0}); object->set<&Waterfall::Prop::power_range>(Axis_Range{-110.0, 0.0}); auto* raw = object.get(); raw->mark_dirty<Prepare_Data_Tag>(); raw->mark_dirty<Paint_Tag>(); bind_renderable_adapter<Waterfall, AETHERA_PROP(Waterfall, tooltip_enabled), AETHERA_PROP(Waterfall, tooltip_font), AETHERA_PROP(Waterfall, tooltip_text_pen), AETHERA_PROP(Waterfall, tooltip_background_brush), AETHERA_PROP(Waterfall, frequency_bin_count), AETHERA_PROP(Waterfall, partition_count), AETHERA_PROP(Waterfall, visible_range_only), AETHERA_PROP(Waterfall, frequency_range), AETHERA_PROP(Waterfall, power_range), AETHERA_PROP(Waterfall, partition_mode), AETHERA_PROP(Waterfall, interpolation_mode), AETHERA_PROP(Waterfall, color_map), AETHERA_PROP(Waterfall, rows), AETHERA_STATE(Waterfall, row_count), AETHERA_STATE(Waterfall, stored_point_count), AETHERA_STATE(Waterfall, rendered_cell_count)>(result, *raw); auto tick = std::make_shared<std::uint64_t>(); result.update = [raw, tick](double time) { std::array<double, 192> values{}; for (std::size_t i = 0; i < values.size(); ++i) values[i] = -100.0 + 70.0 * std::exp(-240.0 * std::pow(static_cast<double>(i) / values.size() - 0.5 - 0.22 * std::sin(time * 0.0006), 2.0)); raw->append_row((*tick)++, values); }; result.plot = std::move(object);
} else if constexpr (std::same_as<Definition, Constellation_Diagram>) {
result.horizontal = build<Numeric_Axis_Object>(); configure_axis(result.horizontal.get(), Axis_Orientation::horizontal, {64.0, 370.0}, 620.0, canvas); result.horizontal->set<&Numeric_Axis::Prop::coordinate_range>(Axis_Range{-1.2, 1.2}); make_vertical({-1.2, 1.2}); auto object = build<Impl<Constellation_Diagram>>(result.scene.get(), result.horizontal.get(), result.vertical.get()); object->set<&Constellation_Diagram::Prop::i_range>(Axis_Range{-1.2, 1.2}); object->set<&Constellation_Diagram::Prop::q_range>(Axis_Range{-1.2, 1.2}); auto* raw = object.get(); raw->mark_dirty<Prepare_Data_Tag>(); raw->mark_dirty<Paint_Tag>(); bind_renderable_adapter<Constellation_Diagram, AETHERA_PROP(Constellation_Diagram, point_lifetime_ms), AETHERA_PROP(Constellation_Diagram, type), AETHERA_PROP(Constellation_Diagram, phase_offset_radians), AETHERA_PROP(Constellation_Diagram, i_range), AETHERA_PROP(Constellation_Diagram, q_range), AETHERA_PROP(Constellation_Diagram, point_color), AETHERA_PROP(Constellation_Diagram, anchor_color), AETHERA_PROP(Constellation_Diagram, points), AETHERA_STATE(Constellation_Diagram, point_count)>(result, *raw); result.update = [raw](double time) { const double phase = time * 0.003; raw->append_point({std::cos(phase) * 0.82 + 0.04 * std::sin(phase * 7.0), std::sin(phase) * 0.82 + 0.04 * std::cos(phase * 5.0)}); }; result.plot = std::move(object);
} else if constexpr (std::same_as<Definition, Selection_Rectangle_Overlay>) {
result.horizontal = build<Numeric_Axis_Object>(); configure_axis(result.horizontal.get(), Axis_Orientation::horizontal, {64.0, 370.0}, 620.0, canvas); result.horizontal->set<&Numeric_Axis::Prop::coordinate_range>(Axis_Range{0.0, 100.0}); make_vertical({0.0, 100.0}); auto object = build<Impl<Selection_Rectangle_Overlay>>(result.scene.get(), result.horizontal.get(), result.vertical.get()); auto* raw = object.get(); raw->mark_dirty<Prepare_Data_Tag>(); raw->mark_dirty<Paint_Tag>(); bind_renderable_adapter<Selection_Rectangle_Overlay, AETHERA_PROP(Selection_Rectangle_Overlay, label_font), AETHERA_PROP(Selection_Rectangle_Overlay, label_pen), AETHERA_PROP(Selection_Rectangle_Overlay, selection_brush), AETHERA_PROP(Selection_Rectangle_Overlay, selection_border_pen), AETHERA_PROP(Selection_Rectangle_Overlay, selected_regions), AETHERA_STATE(Selection_Rectangle_Overlay, selected_region_count)>(result, *raw); result.update = [](double) {}; result.plot = std::move(object);
} else {
static_assert(std::same_as<Definition, void>, "unsupported 2D Plot definition");
}
return result;
}
struct Plot_3D {
std::unique_ptr<Impl<Point_Visual>> visual{}; /* 鐐瑰浘鍏冩潈濞佸璞°€?*/
std::unique_ptr<Impl<Render_Scene_3D>> scene{}; /* 寮傛 Datoviz Scene銆?*/
std::unique_ptr<detail::Renderable_Descriptor> descriptor{}; /* 鐩存帴璇诲啓 visual 鐨?Structive 鍗忚瑙嗗浘銆?*/
};
Plot_3D make_plot_3d() { Plot_3D result; result.visual = build<Impl<Point_Visual>>(); static_cast<void>(result.visual->update_items({render_3d::Point{.position = {-0.55F, -0.2F, 0.0F}, .color = Color::red_color(), .diameter_px = 24.0F}, render_3d::Point{.position = {0.0F, 0.5F, 0.0F}, .color = Color::green_color(), .diameter_px = 30.0F}, render_3d::Point{.position = {0.55F, -0.1F, 0.0F}, .color = Color{42, 120, 255, 255}, .diameter_px = 26.0F}})); bind_renderable_adapter<Point_Visual, AETHERA_PROP(Point_Visual, transform), AETHERA_PROP(Point_Visual, visible), AETHERA_PROP(Point_Visual, depth_test), AETHERA_PROP(Point_Visual, items), AETHERA_STATE(Point_Visual, item_count), AETHERA_STATE(Point_Visual, prepared_item_count), AETHERA_STATE(Point_Visual, prepared_revision)>(result, *result.visual); result.visual->advance(); result.scene = build<Impl<Render_Scene_3D>>(result.visual.get()); result.scene->activate_view(); return result; }
using Plot_Engine = std::variant<Plot_2D, Plot_3D>;
template <typename Definition>
Plot_Engine make_plot_engine_2d() { return Plot_Engine{std::in_place_type<Plot_2D>, make_plot_2d<Definition>()}; }
Plot_Engine make_plot_engine_3d() { return Plot_Engine{std::in_place_type<Plot_3D>, make_plot_3d()}; }
#undef AETHERA_STATE
#undef AETHERA_PROP
}
namespace {
struct Plot_Catalog_Entry {
std::string_view id; /* URL 与 WebSocket 共用的稳定标识。 */
std::string_view title; /* Gallery 展示名称。 */
std::string_view category; /* Gallery 分类。 */
std::string_view description; /* Gallery 用途说明。 */
std::string_view dimension; /* Gallery 维度标签。 */
Plot_Engine (*build)(); /* 直接构造完整 Scene/Renderable/descriptor 的 typed factory。 */
};
constexpr std::array plot_catalog{
Plot_Catalog_Entry{"spectrum", "Spectrum", "Curves", "Current, maximum and minimum spectrum curves with markers.", "2D", &make_plot_engine_2d<Spectrum>},
Plot_Catalog_Entry{"frequency_trace", "Frequency trace", "Curves", "Time ordered frequency samples rendered as a partitioned curve.", "2D", &make_plot_engine_2d<Frequency_Trace>},
Plot_Catalog_Entry{"sweep_spectrum", "Sweep spectrum", "Curves", "Incremental sweep blocks composed into one frequency curve.", "2D", &make_plot_engine_2d<Sweep_Spectrum>},
Plot_Catalog_Entry{"afterglow", "Afterglow", "Raster", "Persistent spectrum energy rendered as reusable color blocks.", "2D", &make_plot_engine_2d<Afterglow>},
Plot_Catalog_Entry{"waterfall", "Waterfall", "Raster", "Time ordered spectrum rows rendered as a color raster.", "2D", &make_plot_engine_2d<Waterfall>},
Plot_Catalog_Entry{"constellation", "Constellation", "Signals", "I/Q samples and modulation anchors.", "2D", &make_plot_engine_2d<Constellation_Diagram>},
Plot_Catalog_Entry{"selection_overlay", "Selection overlay", "Interaction", "Direct-paint selection rectangle over numeric axes.", "2D", &make_plot_engine_2d<Selection_Rectangle_Overlay>},
Plot_Catalog_Entry{"datoviz_point", "Datoviz point", "3D", "Asynchronous Vulkan point visual with GPU readback.", "3D", &make_plot_engine_3d}
};
const Plot_Catalog_Entry* find_plot(std::string_view id) {
const auto found = std::ranges::find(plot_catalog, id, &Plot_Catalog_Entry::id);
return found == plot_catalog.end() ? nullptr : &*found;
}
}
struct Plot::Private {
asio::strand<asio::any_io_executor> strand; /* 寮曟搸鍙?descriptor 鐨勪覆琛岃闂煙銆?*/
asio::experimental::concurrent_channel<void(asio::error_code, Plot_Input)> inputs; /* UI 杈撳叆闃熷垪銆?*/
Plot_Engine engine; /* Builder 已完成的 Scene、Renderable 与 adapter 唯一所有权。 */
std::mutex handlers_mutex; /* 淇濇姢璺?Drogon 绾跨▼鐨勫抚璁㈤槄闆嗗悎銆?*/
std::unordered_map<const void*, Frame_Handler> handlers; /* 褰撳墠 WebSocket 甯ф秷璐硅€呫€?*/
std::atomic_uint64_t frame_sequence{}; /* 浜岃繘鍒跺抚鍗忚搴忓彿銆?*/
explicit Private(asio::any_io_executor executor, Plot_Engine value) : strand(asio::make_strand(std::move(executor))), inputs(strand, 32), engine(std::move(value)) {}
void publish(std::string pixels) { std::vector<Frame_Handler> outputs; { std::lock_guard lock(handlers_mutex); outputs.reserve(handlers.size()); for (const auto& [owner, handler] : handlers) outputs.push_back(handler); } for (auto& output : outputs) output(pixels); }
detail::Renderable_Descriptor& descriptor() { return std::visit([](auto& value) -> detail::Renderable_Descriptor& { return *value.descriptor; }, engine); }
};
Plot::Plot(std::unique_ptr<Private> private_data) : d(std::move(private_data)) {}
Plot::~Plot() { d->inputs.close(); }
void Plot::start() {
auto self = shared_from_this();
if (auto* engine_2d = std::get_if<Plot_2D>(&d->engine)) {
engine_2d->scene->set_frame_callback([weak = weak_from_this()](Image_View image) {
if (auto owner = weak.lock()) {
const auto sequence = owner->d->frame_sequence.fetch_add(1, std::memory_order_acq_rel) + 1;
owner->d->publish(encode_frame(image, sequence));
}
});
} else {
std::get<Plot_3D>(d->engine).scene->set_frame_callback([weak = weak_from_this()](std::shared_ptr<const render_3d::Pixel_Frame> frame) {
if (auto owner = weak.lock()) {
const auto sequence = owner->d->frame_sequence.fetch_add(1, std::memory_order_acq_rel) + 1;
owner->d->publish(encode_frame(*frame, sequence));
}
});
}
asio::co_spawn(d->strand, [self]() -> asio::awaitable<void> {
for (;;) {
asio::error_code error;
auto input = co_await self->d->inputs.async_receive(asio::redirect_error(asio::use_awaitable, error));
if (error) co_return;
if (auto* query = std::get_if<Schema_Query>(&input)) {
query->handler(self->d->descriptor().schema());
continue;
}
if (auto* write = std::get_if<Prop_Write>(&input)) {
write->handler(self->d->descriptor().write_prop(write->key, write->value));
continue;
}
const auto value = std::get<Plot_Event>(input);
if (auto* engine_2d = std::get_if<Plot_2D>(&self->d->engine)) {
const Size viewport{static_cast<int>(std::clamp(value.width, 160U, 1920U)), static_cast<int>(std::clamp(value.height, 120U, 1080U))};
engine_2d->scene->set<&Render_Scene_2D::Prop::viewport>(viewport);
if (engine_2d->frequency) engine_2d->frequency->set<&Abs_Axis::Prop::canvas_size>(viewport);
if (engine_2d->horizontal) engine_2d->horizontal->set<&Abs_Axis::Prop::canvas_size>(viewport);
if (engine_2d->vertical) engine_2d->vertical->set<&Abs_Axis::Prop::canvas_size>(viewport);
if (engine_2d->time) engine_2d->time->set<&Abs_Axis::Prop::canvas_size>(viewport);
engine_2d->update(value.time_milliseconds);
engine_2d->scene->render();
} else {
auto& engine_3d = std::get<Plot_3D>(self->d->engine);
engine_3d.scene->set<&Render_Scene_3D::Prop::viewport>(render_3d::Extent{std::clamp(value.width, 160U, 1920U), std::clamp(value.height, 120U, 1080U)});
engine_3d.scene->render();
}
}
}, [](std::exception_ptr exception) {
if (exception) std::rethrow_exception(exception);
});
}
void Plot::attach(const void* owner, Frame_Handler handler) { { std::lock_guard lock(d->handlers_mutex); d->handlers.insert_or_assign(owner, std::move(handler)); } submit({}); }
void Plot::detach(const void* owner) { std::lock_guard lock(d->handlers_mutex); d->handlers.erase(owner); }
void Plot::submit(Plot_Event event) { static_cast<void>(d->inputs.try_send(asio::error_code{}, Plot_Input{event})); }
void Plot::async_schema(Json_Handler handler) { if (!d->inputs.try_send(asio::error_code{}, Plot_Input{Schema_Query{std::move(handler)}})) throw std::runtime_error("plot input queue is unavailable"); }
void Plot::async_write_prop(std::string key, nlohmann::json value, Json_Handler handler) { if (!d->inputs.try_send(asio::error_code{}, Plot_Input{Prop_Write{std::move(key), std::move(value), std::move(handler)}})) throw std::runtime_error("plot input queue is unavailable"); }
struct Plot_Registry::Private { asio::any_io_executor executor; std::mutex mutex; std::unordered_map<std::string, std::shared_ptr<Plot>> plots; explicit Private(asio::any_io_executor value) : executor(std::move(value)) {} };
Plot_Registry::Plot_Registry(asio::any_io_executor executor) : d(std::make_unique<Private>(std::move(executor))) {}
Plot_Registry::~Plot_Registry() = default;
std::shared_ptr<Plot> Plot_Registry::acquire(std::string_view plot_id) { const auto* entry = find_plot(plot_id); if (!entry) return {}; std::lock_guard lock(d->mutex); auto& plot = d->plots[std::string(plot_id)]; if (!plot) { plot = std::shared_ptr<Plot>(new Plot(std::make_unique<Plot::Private>(d->executor, entry->build()))); plot->start(); } return plot; }
nlohmann::json Plot_Registry::catalog() const { nlohmann::json result = nlohmann::json::array(); for (const auto& entry : plot_catalog) result.push_back({{"id", entry.id}, {"title", entry.title}, {"category", entry.category}, {"description", entry.description}, {"dimension", entry.dimension}, {"websocket", "/ws/plot/" + std::string(entry.id)}, {"schema", "/plot/" + std::string(entry.id) + "/schema"}}); return result; }
}