fix(plot,render,gl): live streaming measurements, handed-back GL state

Final whole-branch review fixes.

1 (Important). Plot::measurement() cached on (series pointer, sample count)
only, so a saturated StreamSeries -- whose size() stays pinned while x0()
advances every acquire() -- froze its readout on the first saturated frame
until a cursor moved. The cache key now carries the series' x0() (new
MeasureSlot::last_x0), so a sliding window recomputes and a static series
still does not: asserted with a new macro-gated counter hook
(plot/detail/measure_count.hpp, PLOT_COUNT_MEASURE_RECOMPUTES, wired like the
pyramid and ring counters, absent from the release library). New case
saturated_stream_measurement_tracks_the_sliding_window: saturated ring,
stationary cursors, ramp in absolute x -- zero recomputes for repeated reads
with nothing moving, one per acquire while it slides.

2-3, 9. Spec: 4.3 described a GL_LINE_STRIP path that does not exist (there is
one rasteriser -- instanced anti-aliased quads -- and dense_threshold_spp
selects the gather level, not a primitive); 8 named a PLOT_GL_CHECK() macro
that exists nowhere, and stated no exception policy. The table, the field's
comment and 8 now describe the real gather-level threshold, the real
glGetError() drain plus the stores' drop-to-orphan fallbacks, and the real
policy: library failures return Status/bool, allocating entry points propagate
std::bad_alloc.

4. The frame handed back neither GL_UNPACK_ALIGNMENT (init() sets 1 for the
atlas) nor the clear colour (queried once with a new glGetFloatv entry).
end_frame() restores both and renderer.hpp lists them in the residue
contract.

5. draw() kept a host TextBackend for layout while drawing with its own font.
The renderer now installs its font unconditionally -- strips and labels measure
and draw with one backend -- with a debug-build diagnostic if a different one
was set, and Plot::set_text_backend() is documented as the no-renderer path.
New case renderer_measures_the_labels_it_draws asserts layout, measuring and
the drawn label's ink agree.

6-10. draw()'s style overwrite stated at the call site; the load-sensitive
wall-clock bound in test_measure.cpp replaced by a counter assertion (same
interval, same fold count over a 512x length ratio); dump_frame_ppm drops
noexcept and says why it may allocate; error.txt ignored (not this project's,
not generated here) rather than deleted.

Verified: debug and release build clean (-Wall -Wextra -Wpedantic -Wconversion
-Wshadow), 4/4 ctest entries pass, 130 cases pass (was 127), umbrella and
header self-containment checks pass, and no counter symbol in the release
archive.
This commit is contained in:
Martino Ferrari committed 2026-09-28 03:42:34 +02:00
1 parent f363523195
commit a08b184481
15 files changed
+478 -54

No files matched your search

+2 -1
View File
@@ -69,7 +69,8 @@ target_include_directories(plot_tests PRIVATE "${CMAKE_SOURCE_DIR}/adapters")
# behind them (see include/plot/data/detail/{cover,merge}_count.hpp).
target_compile_definitions(plot_tests PRIVATE PLOT_PYRAMID_COUNT_COVERS
PLOT_PYRAMID_COUNT_MERGES
PLOT_RING_STATS)
PLOT_RING_STATS
PLOT_COUNT_MEASURE_RECOMPUTES)
plot_apply_warnings(plot_tests)
add_test(NAME plot_tests COMMAND plot_tests)
+31 -10
View File
@@ -1,8 +1,9 @@
#include "harness.hpp"
#include <plot/plot/measure.hpp>
#include <plot/data/array_series.hpp>
#include <plot/data/detail/cover_count.hpp>
#include <algorithm>
#include <chrono>
#include <atomic>
#include <cmath>
#include <vector>
@@ -25,15 +26,35 @@ PLOT_TEST(measurement_over_interval_matches_direct_computation) {
PLOT_CHECK_NEAR(m.dx, 699.0, 1e-9);
}
PLOT_TEST(measurement_uses_pyramid_not_scan) {
// Guard against a future regression that linear-scans the series: a huge
// series must evaluate a 1-sample-wide interval in well under a millisecond.
std::vector<f32> y(1u << 22, 1.0f); // 4M samples
plot::data::ArraySeries s(std::move(y), 0.0, 1.0);
const auto t0 = std::chrono::steady_clock::now();
for (int i = 0; i < 1000; ++i) (void)plot::Measure::evaluate(s, 1'000'000, 1'000'001);
const auto us = std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now() - t0).count();
PLOT_CHECK(us < 50'000); // 1000 evals in < 50 ms
// Guard against a future regression that linear-scans the series, counted rather
// than timed: a query's cost is the pyramid's covering decomposition -- at most
// two entries per level -- so the entry count must depend on the *interval* and
// never on the series length. The wall-clock bound this replaced (1000 evals in
// < 50 ms) failed on a loaded machine and passed vacuously on a fast one, while
// saying nothing about the shape of the work.
std::vector<f32> big(1u << 22, 1.0f); // 4M samples
plot::data::ArraySeries s_big(std::move(big), 0.0, 1.0);
std::vector<f32> small(1u << 13, 1.0f); // 8k samples: 512x shorter
plot::data::ArraySeries s_small(std::move(small), 0.0, 1.0);
auto covers = [](const plot::data::Series& s, u64 begin, u64 end) {
plot::data::detail::cover_entry_count().store(0, std::memory_order_relaxed);
(void)plot::Measure::evaluate(s, begin, end);
return plot::data::detail::cover_entry_count().load(std::memory_order_relaxed);
};
// The same absolute interval over both series walks the same run of level-0
// buckets, so it must fold the same entries: a decomposition that degenerated
// with series length -- one bucket at a time, or a scan -- shows up here.
const u64 big_covers = covers(s_big, 1024, 7000);
PLOT_CHECK(big_covers == covers(s_small, 1024, 7000));
PLOT_CHECK(big_covers > 0u); // the interior came from the pyramid
PLOT_CHECK(big_covers <= 32u); // ~2 entries per level, few levels here
// A 1-sample interval needs no whole bucket at all: its answer is the two partial
// edge buckets a pyramid of complete buckets cannot cover (at most 2 * kBucket raw
// samples through copy_raw), so it folds nothing whatever the series holds.
PLOT_CHECK(covers(s_big, 1'000'000, 1'000'001) == 0u);
}
PLOT_TEST(empty_and_single_sample_intervals_are_valid_false) {
std::vector<f32> y{3.0f};
+66
View File
@@ -1,5 +1,6 @@
#include "harness.hpp"
#include <plot/plot/plot.hpp>
#include <plot/plot/detail/measure_count.hpp>
#include <plot/data/array_series.hpp>
#include <plot/data/stream_series.hpp>
#include <plot/render/bitmap_font.hpp>
@@ -310,6 +311,71 @@ PLOT_TEST(measurement_recomputes_when_the_series_grows) {
PLOT_CHECK_NEAR(p.measurement(m).dx, 18.0, 1e-9);
}
/// A saturated ring pins size() at capacity while x0() advances every acquire(),
/// so a cache keyed on (pointer, sample count) alone would freeze this measurement
/// on the first saturated frame -- the one case the demos never reach, because they
/// move their cursors (and therefore `dirty`) every frame.
///
/// The signal is a ramp in absolute x, so the value a cursor names once the window
/// has slid past it is the current window's oldest sample: a live cache tracks
/// x0(), a frozen one keeps reporting the first frame's numbers. The counter is the
/// other half of the contract -- a frame in which nothing moved is still a cache
/// hit, or the fix would have traded a stale readout for a per-frame recompute.
PLOT_TEST(saturated_stream_measurement_tracks_the_sliding_window) {
constexpr u64 kCapacity = 64;
plot::data::StreamSeries s(kCapacity, 0.0, 1.0);
for (u64 i = 0; i < kCapacity; ++i) s.push(f32(i)); // y == absolute x
s.acquire();
PLOT_CHECK(s.size() == kCapacity); // published window is full
plot::Plot p;
p.set_viewport({0.0f, 0.0f, 800.0f, 400.0f});
const u32 ax = p.add_x_axis({"t", {0.0, 100.0}, false, plot::AxisPlace::Bottom, false});
const u32 ay = p.add_y_axis({"v", {0.0, 100.0}, false, plot::AxisPlace::Left, false});
p.add_trace({&s, plot::Color::hex(0xFFFFFF), 1.0f, ax, ay});
const u32 a = p.add_cursor(10.0, plot::Color::hex(0xFFB020));
const u32 b = p.add_cursor(60.0, plot::Color::hex(0xFFB020));
const u32 m = p.add_measure(a, b);
// First window, both cursors inside it: y over absolute x 10..60.
PLOT_CHECK(p.measurement(m).valid);
PLOT_CHECK_NEAR(p.measurement(m).ymin, 10.0, 1e-9);
PLOT_CHECK_NEAR(p.measurement(m).ymax, 60.0, 1e-9);
PLOT_CHECK_NEAR(p.measurement(m).mean, 35.0, 1e-9);
PLOT_CHECK_NEAR(p.measurement(m).dx, 50.0, 1e-9);
auto counter = [] {
return plot::detail::measure_recomputes().load(std::memory_order_relaxed);
};
plot::detail::measure_recomputes().store(0, std::memory_order_relaxed);
// Neither cursor moves and neither does the window: eight reads, no recompute.
for (int i = 0; i < 8; ++i) (void)p.measurement(m);
PLOT_CHECK(counter() == 0u);
// Slide the window past cursor `a` -- 40 more samples and an acquire, with the
// sample count unchanged (still capacity) and neither cursor touched.
for (u64 i = kCapacity; i < kCapacity + 40; ++i) s.push(f32(i));
s.acquire();
PLOT_CHECK(s.size() == kCapacity); // size() cannot be the key
PLOT_CHECK_NEAR(s.x0(), 40.0, 1e-9); // x0() moved under it
const plot::Measurement& slid = p.measurement(m); // one acquire, one recompute
PLOT_CHECK(counter() == 1u);
PLOT_CHECK(slid.valid);
PLOT_CHECK_NEAR(slid.ymin, 40.0, 1e-9); // `a` clamped onto the new x0()
PLOT_CHECK_NEAR(slid.ymax, 60.0, 1e-9);
PLOT_CHECK_NEAR(slid.mean, 50.0, 1e-9);
PLOT_CHECK_NEAR(slid.dx, 20.0, 1e-9);
// And it keeps tracking, one recompute per acquire with the cursors still.
for (u64 i = 0; i < 5; ++i) {
s.push(f32(kCapacity + 40 + static_cast<f64>(i)));
s.acquire();
PLOT_CHECK_NEAR(p.measurement(m).ymin, 41.0 + static_cast<f64>(i), 1e-9);
PLOT_CHECK(counter() == 2u + i);
}
}
PLOT_TEST(inverted_and_out_of_range_measurements_are_invalid) {
plot::data::ArraySeries s(ramp(10), 0.0, 1.0);
plot::Plot p;
+162
View File
@@ -115,6 +115,50 @@ bool pixel_is(const plot::u8 px[4], plot::Color c) {
return near(px[0], c.r) && near(px[1], c.g) && near(px[2], c.b);
}
/// A host's `TextBackend` that measures one pixel per string, when the labels the
/// renderer draws are tens of pixels wide: installed on a plot, it asks for a label
/// strip far too narrow for anything the text pipeline draws.
class OnePxPerStringBackend final : public plot::render::TextBackend {
public:
plot::f32 measure(const char*) const override { return 1.0f; }
plot::f32 height() const override { return 1.0f; }
plot::f32 ascent() const override { return 1.0f; }
};
/// No column held ink.
constexpr plot::u32 kNoColumn = 0xFFFFFFFFu;
/// What a text strip's pixels say: the leftmost column holding ink, and the widest
/// run of ink columns any single row holds -- one drawn label's extent, since a
/// label has a row band to itself.
struct TextInk {
plot::u32 leftmost = kNoColumn;
plot::u32 widest_row_run = 0;
};
/// Scans the top-down pixels of [x0, x1) x [y, y + rows) for fully covered text
/// pixels in `text`.
TextInk scan_text_ink(plottest::HeadlessContext& ctx, plot::u32 x0, plot::u32 x1, plot::u32 y,
plot::u32 rows, plot::Color text) {
TextInk ink;
for (plot::u32 r = 0; r < rows; ++r) {
plot::u32 first = kNoColumn;
plot::u32 last = 0;
for (plot::u32 x = x0; x < x1; ++x) {
plot::u8 px[4] = {};
PLOT_CHECK(ctx.read_pixel(x, ctx.height - 1u - (y + r), px));
if (!pixel_is(px, text)) continue;
if (first == kNoColumn) first = x;
last = x;
if (ink.leftmost == kNoColumn) ink.leftmost = x;
}
if (first != kNoColumn && last - first + 1u > ink.widest_row_run) {
ink.widest_row_run = last - first + 1u;
}
}
return ink;
}
/// Holds one GL entry point at a stub for as long as it lives. The entry points
/// are the library's own function pointers (`plot/gl/api.hpp`), so a driver
/// refusal -- a map or a fence that fails while the caps still advertise support
@@ -336,6 +380,124 @@ PLOT_TEST(clears_only_the_viewport_region) {
ctx.destroy();
}
// A host embeds the plot in its own frame loop, so the two pieces of global state
// the renderer has to change must come back as the host left them: the unpack
// alignment `init()` sets for the glyph atlas (whose single-channel rows are
// 1-byte aligned), and the clear colour the frame paints its background with.
PLOT_TEST(frame_hands_back_the_hosts_clear_colour_and_unpack_alignment) {
plottest::HeadlessContext ctx(kW, kH);
plot::Status st;
PLOT_CHECK(ctx.create(&st));
PLOT_CHECK(plot::gl::load(nullptr));
plot::Renderer r;
PLOT_CHECK(r.init(&st));
// The host's clear colour, set before the first frame. Nothing touches the
// unpack alignment: the context starts at GL's default of 4, and that is what
// the frame has to leave behind -- with the atlas' 1 still in place, a host's
// next padded RGBA upload would read the wrong rows.
plot::gl::glClearColor(0.5f, 0.25f, 0.75f, 1.0f);
plot::data::ArraySeries s(sine_samples(), 0.0, 1.0);
plot::Plot p;
p.set_viewport({0, 0, static_cast<plot::f32>(kW), static_cast<plot::f32>(kH)});
const plot::u32 ax = p.add_x_axis({"t", s.x_bounds(), true, plot::AxisPlace::Bottom, false});
const plot::u32 ay = p.add_y_axis({"v", {-1.0, 1.0}, false, plot::AxisPlace::Left, false});
p.add_trace({&s, plot::Color::hex(0x40C0FF), 1.5f, ax, ay});
r.begin_frame(kW, kH, {0, 0, static_cast<plot::f32>(kW), static_cast<plot::f32>(kH)});
r.draw(p);
r.end_frame();
PLOT_CHECK(!r.last_frame_had_gl_error());
plot::f32 clear[4] = {};
plot::gl::glGetFloatv(plot::gl::GL_COLOR_CLEAR_VALUE, clear);
PLOT_CHECK_NEAR(clear[0], 0.5, 1e-6);
PLOT_CHECK_NEAR(clear[1], 0.25, 1e-6);
PLOT_CHECK_NEAR(clear[2], 0.75, 1e-6);
PLOT_CHECK_NEAR(clear[3], 1.0, 1e-6);
plot::gl::GLint alignment = 0;
plot::gl::glGetIntegerv(plot::gl::GL_UNPACK_ALIGNMENT, &alignment);
PLOT_CHECK(alignment == 4);
// Not vacuous: the frame really did clear to its own background rather than the
// host's grey, so the value above is a restoration and not an untouched leftover.
plot::u8 px[4] = {};
PLOT_CHECK(ctx.read_pixel(2, kH - 3u, px));
PLOT_CHECK(px[0] + px[1] + px[2] < 200);
ctx.destroy();
}
// The renderer draws every label with its own bitmap font, so it has to lay the
// strips out with that font's metrics. A host backend whose metrics are nothing
// like the artwork's would otherwise reserve a strip too narrow for the labels the
// text pipeline then draws -- here, one pixel per string against ~40px labels.
PLOT_TEST(renderer_measures_the_labels_it_draws) {
plottest::HeadlessContext ctx(kW, kH);
plot::Status st;
PLOT_CHECK(ctx.create(&st));
PLOT_CHECK(plot::gl::load(nullptr));
plot::Renderer r;
PLOT_CHECK(r.init(&st));
plot::data::ArraySeries s(sine_samples(), 0.0, 1.0);
plot::Plot p;
// The sub-rect viewport the adapters use, so the label strip's left edge is not
// the framebuffer edge: with a narrower strip than the labels need, the renderer
// stages them left of the viewport, where GL's own clip removes all but their
// last few pixels.
const plot::Rect vp{60.0f, 0.0f, 500.0f, 300.0f};
p.set_viewport(vp);
const plot::u32 ax = p.add_x_axis({"t", s.x_bounds(), true, plot::AxisPlace::Bottom, false});
// No y title: the title strip sits left of the label strip, and this test reads
// the label strip's own columns for ink.
const plot::u32 ay = p.add_y_axis({"", {-1000.0, 1000.0}, false, plot::AxisPlace::Left, false});
p.add_trace({&s, plot::Color::hex(0x40C0FF), 1.5f, ax, ay});
OnePxPerStringBackend host_font;
p.set_text_backend(&host_font);
// With the host's metrics the strip is 1px of label: what the frame must replace.
PLOT_CHECK_NEAR(p.layout().y_label_area.w, 1.0f + 2.0f * p.style().grid_label_pad, 1e-6);
plot::gl::glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
plot::gl::glClear(plot::gl::GL_COLOR_BUFFER_BIT);
r.begin_frame(kW, kH, vp);
r.draw(p);
r.end_frame();
PLOT_CHECK(!r.last_frame_had_gl_error());
// Layout and drawing measure with one backend: the renderer's font, at the size
// the text pipeline draws (whole multiples of the glyph cell -- see AxisFont).
const plot::render::TextBackend* back = p.text_backend();
PLOT_CHECK(back != nullptr);
PLOT_CHECK(back != &host_font);
PLOT_CHECK_NEAR(back->height(), r.axis_font_px(), 1e-6);
plot::f32 widest = 0.0f;
for (const plot::Tick& tick : p.y_axis(ay).ticks) {
if (!tick.major || tick.label.empty()) continue;
widest = std::max(widest, back->measure(tick.label.c_str()));
}
PLOT_CHECK(widest > 8.0f); // real labels in the real font, not the host's 1px
const plot::Rect labels = p.layout().y_label_area;
PLOT_CHECK_NEAR(labels.w, widest + 2.0f * p.style().grid_label_pad, 1e-3);
// And the pixels agree with the strip: the drawn labels occupy the width the
// layout reserved and stay inside it. Kept on the host's 1px metrics the strip is
// ~9px wide while the renderer right-aligns its ~40px label against it, so all
// but the label's last few pixels land left of the viewport and are clipped --
// the ink run collapses instead of filling the width that was reserved.
const plot::Color text = r.style().axis_text;
const plot::u32 y = static_cast<plot::u32>(labels.y);
const plot::u32 rows = static_cast<plot::u32>(labels.h);
const plot::u32 strip_x = static_cast<plot::u32>(labels.x);
const TextInk ink =
scan_text_ink(ctx, strip_x, strip_x + static_cast<plot::u32>(labels.w) + 16u, y, rows, text);
PLOT_CHECK(ink.leftmost != kNoColumn); // labels were drawn
PLOT_CHECK(ink.leftmost >= strip_x); // inside their strip
PLOT_CHECK(static_cast<plot::f32>(ink.widest_row_run) >= 0.6f * widest); // full width drawn
PLOT_CHECK(static_cast<plot::f32>(ink.widest_row_run) <= widest + 1.0f); // and no wider
ctx.destroy();
}
// The overlay layer: cursor markers in their own colours, the shaded measurement
// band and its readout, and an annotation pin. These are the pixels the adapters'
// demos are read for, and none of them goes through the trace path.