Breaking: Series::gather emits x relative to x0() and takes a GatherMode; consumers reconstruct absolute x in f64 before mapping (series.hpp documents the contract). Bugs, each pinned by a fail-before regression test: - render: f32 staging quantised epoch-time x into 128 px columns; every data-space draw now stages to_space(x) - to_space(origin) with the origin folded into the offset uniform in f64 (epoch/zero-origin twins rasterise identically) - ticks: major test was ULP-fragile and blanked epoch axes; majors are an integer-index test and are never truncated by the minor cap - gather: LOD envelope emitted buckets straddling [begin,end); ceil/floor bucket edges + raw lead/trail spans - live follow: log x axes held a linear span and zoomed every frame; span and offset now live in axis space (plot + both figure link-group paths) - input: a zero-notch wheel disarmed auto_scale on every axis; dy==0 pans x, factor == 1 / inf refused in wheel and drag zoom - render: the single text flush painted legend names over the crosshair readout panel; two batches, under flushed before the panel - data: NaN dropped from min/max unless it seeded the fold; non-finite samples are now excluded from every aggregate and from cached bounds Robustness: viewport normalisation (no clamp UB), non-finite range refusal, pyramid level cap at 57 (no shift/div UB through public gather), rounded ring capacity documented + pre-sized, GL blend func and UNPACK_ALIGNMENT save/restore, Renderer::release_gl() teardown, u64 buffer epochs, annotation captions clamped, button-aware GLFW row capture, cached figure row rects (no per-event layout), ruler-pair measurement refused, span-nonfinite guards in axis_ends. Features: XY series (sorted x, binary-search neighbours/snap, LOD over sample index); StreamSeries::freeze(); ArraySeries::push(); per-trace dash and markers (scatter at width 0) with auto or literal stride; GatherMode Envelope/Nearest/Mean via bucket_sum/sumsq; Style::line_aa_px; per-glyph text colour (readout values in trace colour); wheel-dx x pan; arrow-key pan; Escape cancels a drag and restores captured ranges; modifier-masked box zoom (Shift both, Ctrl x, Alt y); double-click reset via PointerEvent::time_s; ImGui key repeat unified; pinch gestures on Qt and GTK; pixelDelta wheel path and DevicePixelRatioChange handling; GNUInstallDirs, SOVERSION, SameMinorVersion, generated plot/version.hpp, relocatable plot.pc, licence install, FILES_MATCHING, GitHub Actions CI (debug/coverage/asan). Suite 283 -> 350 cases, 0 failed; coverage 93.9% (3730/3971) over 24 files, floor 80/90 held; ASAN preset suite green; all four demos run headless (the GTK scripted-resize check needs a window manager and fails identically on the parent commit); readme_main.cpp committed and compiles with the README command; pkg-config and find_package consumption verified from a relocated install prefix.
225 lines
11 KiB
C++
225 lines
11 KiB
C++
// SPDX-License-Identifier: MIT
|
|
// SPDX-FileCopyrightText: 2026 Martino Ferrari
|
|
|
|
#pragma once
|
|
#include <plot/core/status.hpp>
|
|
#include <plot/core/types.hpp>
|
|
#include <plot/gl/handle.hpp>
|
|
|
|
namespace plot::render {
|
|
|
|
/// Per-instance payload of the line pipeline: one segment in data space. It
|
|
/// mirrors the interleaved floats `LineBatch::data()` produces, which is why the
|
|
/// attribute offsets in vertex_array.cpp come from `offsetof` rather than from
|
|
/// hand-written numbers.
|
|
struct LineInstance {
|
|
f32 x0;
|
|
f32 y0;
|
|
f32 x1;
|
|
f32 y1;
|
|
};
|
|
|
|
/// Per-instance payload of the text pipeline: one glyph cell.
|
|
///
|
|
/// - `(x, y)` is the cell's top-left corner in Rect pixels, top-left origin like
|
|
/// `plot::Rect`. `TextBatch` already applied the glyph's bearing along the
|
|
/// basis, so this is the corner the shader grows the cell from.
|
|
/// - `(u, v)` is the glyph rect's **normalised top-left** in the atlas, with `v`
|
|
/// increasing *downward* -- the convention `Glyph` states, so `(u, v)` is the
|
|
/// rect's top-left texel and the cell spans `(u, v)..(u + w, v + h)`, where
|
|
/// `(w, h)` is the glyph cell's normalised size (a per-draw uniform: every
|
|
/// glyph a batch stages comes from one atlas and occupies a cell of one size).
|
|
/// - `(ax, ay)` is the glyph's local +x axis -- the direction the run advances
|
|
/// in -- as a **unit vector in pixels**. It is what rotates the cell: the
|
|
/// shader builds it from `(ax, ay)` and its perpendicular, and maps the glyph's
|
|
/// rect onto the two the same way round, so a cell is never mirrored. `(1, 0)`
|
|
/// is unrotated text, and `(0, -1)` is a run advancing up the screen, i.e. a
|
|
/// 90 degree counter-clockwise label such as a y-axis title.
|
|
/// - `(r, g, b, a)` is the run's tint, straight alpha. Per instance rather than
|
|
/// a uniform, so one draw can carry a readout whose values are coloured per
|
|
/// row (each row's own trace) while its labels stay the axis text colour.
|
|
///
|
|
/// Ten floats, still one instanced draw call per frame.
|
|
struct TextInstance {
|
|
f32 x;
|
|
f32 y;
|
|
f32 u;
|
|
f32 v;
|
|
f32 ax;
|
|
f32 ay;
|
|
f32 r;
|
|
f32 g;
|
|
f32 b;
|
|
f32 a;
|
|
};
|
|
|
|
static_assert(sizeof(LineInstance) == 4 * sizeof(f32), "line instance must stay 4 floats");
|
|
static_assert(sizeof(TextInstance) == 10 * sizeof(f32), "text instance must stay 10 floats");
|
|
|
|
/// How a store's staged instances reach the GPU. Semantics are identical either
|
|
/// way -- only the transfer differs, and `Renderer::init()` picks one from
|
|
/// `plot::gl::caps()`:
|
|
///
|
|
/// - `Orphan`: the GL 3.3 baseline. Every upload re-specifies the store with a
|
|
/// null `glBufferData` (orphaning it, so the driver never has to wait for the
|
|
/// draw that is still reading the previous one) and then refills it.
|
|
/// - `PersistentMapped`: GL 4.4 / ARB_buffer_storage. Immutable storage is mapped
|
|
/// once and written directly, one slot per upload. A slot is never written
|
|
/// twice within a frame, one fence is recorded after the frame's last draw, and
|
|
/// the only wait is at the start of the next frame -- so the render thread
|
|
/// never synchronises with GPU work it has just issued. The vertex array's
|
|
/// attribute pointers move with the slot.
|
|
enum class UploadMode { Orphan, PersistentMapped };
|
|
|
|
namespace detail {
|
|
|
|
/// The growth half of an instance buffer, shared by both pipelines so neither
|
|
/// duplicates the GL ownership or the transfer strategy. This is the one place
|
|
/// vertex data is handed to the GPU: `LineBuffer::upload` and
|
|
/// `TextBuffer::upload` both land here, and no caller of either can tell which
|
|
/// `UploadMode` is live.
|
|
class InstanceStore {
|
|
public:
|
|
/// Slots the persistent ring starts with. The floor, not the ring's size: it
|
|
/// grows to cover the uploads a frame actually performs (see `upload()`), and
|
|
/// never shrinks, so a steady workload grows it at most a logarithmic number of
|
|
/// times over the life of the store.
|
|
static constexpr u32 kInitialSlots = 3;
|
|
/// Upper bound on the wait for the previous frame's draws to retire: a driver
|
|
/// that has stopped making progress must not stall the render thread forever.
|
|
static constexpr u64 kFenceWaitNs = 1'000'000'000ull;
|
|
|
|
/// Creates the vertex buffer in `mode`. Reports `ErrorCode::Unsupported` while
|
|
/// the GL entry points are unresolved and `GLFailure` if the driver hands out
|
|
/// no name. A caller asking for `PersistentMapped` must already have checked
|
|
/// that the context and the entry points can do it (see Renderer::init): a
|
|
/// store created that way on a machine without them would never draw.
|
|
bool create(UploadMode mode, Status* st = nullptr) noexcept;
|
|
|
|
/// Starts a frame: waits, once, for the frame before it to retire the draws
|
|
/// that read the ring, so no slot about to be written can still be being read.
|
|
/// False when that wait timed out -- or when a slot was written without a fence
|
|
/// ever being recorded for it -- in which case the store has dropped to the
|
|
/// baseline path, which has no such hazard, and the caller reports it (see
|
|
/// `Renderer::begin_frame`).
|
|
///
|
|
/// One wait covers every slot because no slot is written twice within a frame
|
|
/// (`upload()` grows the ring rather than wrapping it), so each slot this frame
|
|
/// touches was last written in the previous frame or earlier -- and the
|
|
/// previous frame's fence sits behind every draw that read one.
|
|
bool begin_frame() noexcept;
|
|
|
|
/// Uploads `count` instances of `instance_bytes`. `Orphan` mode orphans and
|
|
/// refills; `PersistentMapped` mode writes the next slot of the ring, growing
|
|
/// the ring first when the frame has already written all of its slots.
|
|
void upload(const void* data, u32 count, usize instance_bytes) noexcept;
|
|
|
|
/// Records the frame's single fence, behind every draw that read the ring, so
|
|
/// the next `begin_frame()` can wait for them. Called once per frame, after the
|
|
/// last draw that consumes the store. True in `Orphan` mode, where nothing
|
|
/// reads the store after the orphan, and true when the frame drew nothing from
|
|
/// the ring.
|
|
///
|
|
/// False when the driver refused the fence: the slots written this frame would
|
|
/// stay unsynchronised, so the store drops the mapped ring for the orphan path
|
|
/// instead of rotating through it (the caller reports the failure -- see
|
|
/// `Renderer::end_frame`).
|
|
bool mark_drawn() noexcept;
|
|
|
|
/// Byte offset the current slot's instances start at: 0 in `Orphan` mode,
|
|
/// `slot * slot_bytes` in `PersistentMapped` mode. The vertex array re-points
|
|
/// its attribute pointers whenever `epoch()` changes.
|
|
usize slot_offset() const noexcept {
|
|
return mode_ == UploadMode::PersistentMapped ? usize(slot_) * slot_bytes_ : 0u;
|
|
}
|
|
|
|
/// Changes whenever the staged instances moved (a new slot) or the GL buffer
|
|
/// was recreated, i.e. whenever attribute pointers into this store went stale.
|
|
///
|
|
/// Derived from the two things that can make them stale rather than bumped by
|
|
/// hand at every site that replaces the buffer object: `gl::Buffer::generation()`
|
|
/// advances on every allocation and deletion (so a fallback that re-creates the
|
|
/// buffer cannot leave the vertex array bound to a deleted one), and `slot_epoch_`
|
|
/// advances on every upload that lands in a new slot. Both counters only ever
|
|
/// increase, so their sum changes whenever either does, and never repeats.
|
|
/// 64-bit: the sum of two counters that advance every upload of a streaming
|
|
/// frame loop must not be able to wrap into a stale value.
|
|
u64 epoch() const noexcept { return buffer_.generation() + slot_epoch_; }
|
|
|
|
void bind() const noexcept { buffer_.bind(); }
|
|
bool persistent() const noexcept { return mode_ == UploadMode::PersistentMapped; }
|
|
|
|
private:
|
|
/// (Re)allocates the mapped ring with `slots` slots of `bytes` each. False when
|
|
/// the driver refuses the storage or the map, in which case the store has fallen
|
|
/// back to a fresh `Orphan` buffer and the frame still draws.
|
|
bool grow_persistent(usize bytes, u32 slots) noexcept;
|
|
/// Deletes the frame fence, unmaps and releases the GL buffer. `slot_bytes_`
|
|
/// drops to 0 so the next upload regrows.
|
|
void release_storage() noexcept;
|
|
/// Abandons the mapped ring for the baseline path and re-creates the empty
|
|
/// buffer that path needs. Used wherever the ring can no longer be guarded.
|
|
void drop_to_orphan() noexcept;
|
|
|
|
gl::Buffer buffer_;
|
|
UploadMode mode_ = UploadMode::Orphan;
|
|
u32 capacity_ = 0; ///< instances the orphan store can hold
|
|
usize slot_bytes_ = 0; ///< bytes per slot of the persistent ring
|
|
u32 slot_count_ = kInitialSlots; ///< slots the ring has; grows, never shrinks
|
|
u32 slot_ = 0; ///< slot the last upload wrote
|
|
/// Slots written since this frame began, and the index the next upload takes.
|
|
/// It is the ring index itself, which is what keeps a frame's slots distinct.
|
|
u32 frame_uploads_ = 0;
|
|
/// Times an upload landed in a new slot. Kept apart from the buffer's own
|
|
/// identity (see `epoch()`) so neither has to know about the other.
|
|
u64 slot_epoch_ = 0;
|
|
u8* mapped_ = nullptr; ///< base of the mapped ring, null in `Orphan` mode
|
|
/// Guards every slot the frame just ended wrote. Recorded once, after its last
|
|
/// draw; waited on once, at the start of the next frame.
|
|
gl::Fence frame_fence_;
|
|
};
|
|
|
|
} // namespace detail
|
|
|
|
/// Instance buffer of the line pipeline: one `LineInstance` per segment.
|
|
class LineBuffer {
|
|
public:
|
|
bool create(Status* st = nullptr, UploadMode mode = UploadMode::Orphan) noexcept {
|
|
return store_.create(mode, st);
|
|
}
|
|
bool begin_frame() noexcept { return store_.begin_frame(); }
|
|
void upload(const f32* interleaved, u32 count) noexcept {
|
|
store_.upload(interleaved, count, sizeof(LineInstance));
|
|
}
|
|
bool mark_drawn() noexcept { return store_.mark_drawn(); }
|
|
usize slot_offset() const noexcept { return store_.slot_offset(); }
|
|
u64 epoch() const noexcept { return store_.epoch(); }
|
|
bool persistent() const noexcept { return store_.persistent(); }
|
|
void bind() const noexcept { store_.bind(); }
|
|
|
|
private:
|
|
detail::InstanceStore store_;
|
|
};
|
|
|
|
/// Instance buffer of the text pipeline: one `TextInstance` per glyph.
|
|
class TextBuffer {
|
|
public:
|
|
bool create(Status* st = nullptr, UploadMode mode = UploadMode::Orphan) noexcept {
|
|
return store_.create(mode, st);
|
|
}
|
|
bool begin_frame() noexcept { return store_.begin_frame(); }
|
|
void upload(const f32* interleaved, u32 count) noexcept {
|
|
store_.upload(interleaved, count, sizeof(TextInstance));
|
|
}
|
|
bool mark_drawn() noexcept { return store_.mark_drawn(); }
|
|
usize slot_offset() const noexcept { return store_.slot_offset(); }
|
|
u64 epoch() const noexcept { return store_.epoch(); }
|
|
bool persistent() const noexcept { return store_.persistent(); }
|
|
void bind() const noexcept { store_.bind(); }
|
|
|
|
private:
|
|
detail::InstanceStore store_;
|
|
};
|
|
|
|
} // namespace plot::render
|