DataViewer Rendering Optimization Refactoring Guide
DataViewer Rendering Optimization Refactoring Guide
Overview
This guide provides a step-by-step implementation plan to resolve the performance bottlenecks identified in the Rendering Performance Audit.
The refactoring is structured around the Integer Vertex Attribute Architecture: time is represented as a 32-bit integer primitive (TimeFrameIndex / sample index) in GPU vertex buffers and shaders, matching the strongly typed integer design of the core library.
Phase 1: Integer Vertex Attribute & Shader Pipeline (Static VBOs)
│
▼
Phase 2: True Incremental GPU Streaming (glBufferSubData & Offset Drawing)
│
▼
Phase 3: Fast-Path 1.0px Line Rendering (Bypass Geometry Shader)
│
▼
Phase 4: Adaptive Source-Level Min-Max Decimation
│
▼
Phase 5: Scratch Buffer Reuse & Heap Allocation Reduction
Status and Progress
| Phase | Description | Status | Target / Notes |
|---|---|---|---|
| Phase 1 | Integer Vertex Attribute & Shader Pipeline | Completed | glVertexAttribIPointer, u_view_start_sample, static integer packing via std::bit_cast |
| Phase 2 | True Incremental GPU Streaming & Persistent VBOs | Completed | Multi-batch single-pass staging, persistent VBO allocation (glBufferSubData), sliding window streaming |
| Phase 3 | Fast-Path 1.0px Line Rendering | Pending | Bypass geometry shader for thickness <= 1.0f |
| Phase 4 | Adaptive Source-Level Min-Max Decimation | Pending | Direct contiguous storage decimation for high-density zoomed-out views |
| Phase 5 | Scratch Buffer Reuse & Heap Reduction | Pending | Reusable scratch buffers in SceneCacheState |
Phase 1: Integer Vertex Attribute & Shader Pipeline (Completed)
Objective
Replace the float-based X coordinate pipeline with a 32-bit integer attribute (int32_t) representing TimeFrameIndex / sample tick. Subtraction of the view window offset occurs directly on the GPU with bit-exact integer arithmetic, rendering stored VBO data completely static and invariant to scrolling.
1.1 Renderable Batch & Data Layout
struct RenderablePolyLineBatch {
std::vector<float> vertices; ///< Interleaved: (time_index bit-cast to float, value)
std::vector<int> line_start_indices;
std::vector<int> line_vertex_counts;
glm::vec4 global_color{1.0f, 1.0f, 1.0f, 1.0f};
float thickness{1.0f};
glm::mat4 model_matrix{1.0f};
bool is_integer_time{false}; ///< True when X attribute represents int32_t sample tick
int32_t view_start_time{0}; ///< Viewport start sample passed to shader as u_view_start_sample
};Vertices are tightly packed with 8 bytes per vertex: * Attribute 0 (Location 0): 32-bit signed integer time index (int32_t). Packed into std::vector<float> via std::bit_cast<float>(time_index). * Attribute 1 (Location 1): 32-bit single-precision float analog value (float).
1.2 VAO / Vertex Attribute Setup (glVertexAttribIPointer)
In PolyLineRenderer.cpp and StreamingPolyLineRenderer.cpp:
- Attribute 0 (
a_time_index): Bound viagl_extra->glVertexAttribIPointer(theIprefix preserves integer bit patterns in GLSL without implicit float conversion). - Attribute 1 (
a_value): Bound via standardgl_extra->glVertexAttribPointer.
void PolyLineRenderer::setupVertexAttributes() {
auto * gl_extra = GLFunctions::getExtra();
if (!gl_extra) {
return;
}
(void) m_vao.bind();
(void) m_vbo.bind();
// Location 0: 32-bit signed integer time index (stride = 8 bytes, offset = 0)
gl_extra->glVertexAttribIPointer(0, 1, GL_INT, 2 * sizeof(float), nullptr);
gl_extra->glEnableVertexAttribArray(0);
// Location 1: 32-bit float analog value (stride = 8 bytes, offset = 4 bytes)
gl_extra->glVertexAttribPointer(
1, 1, GL_FLOAT, GL_FALSE, 2 * sizeof(float), reinterpret_cast<void *>(sizeof(float)));
gl_extra->glEnableVertexAttribArray(1);
m_vbo.release();
m_vao.release();
}1.3 Vertex Shader Implementation
In wide_line.vert and embedded fallback strings:
#version 330 core
layout(location = 0) in int a_time_index;
layout(location = 1) in float a_value;
uniform mat4 u_mvp_matrix;
uniform int u_view_start_sample;
void main() {
int rel_sample = a_time_index - u_view_start_sample;
gl_Position = u_mvp_matrix * vec4(float(rel_sample), a_value, 0.0, 1.0);
}1.4 Cache & Pipeline Integration
AnalogVertexCache.cpp:getVerticesForRangepopulates sample indices directly without CPU origin baking:for (size_t i = start_idx; i < end_idx; ++i) { auto const & v = data.points[i]; vertices.push_back(std::bit_cast<float>(static_cast<int32_t>(v.x.getValue()))); vertices.push_back(v.y); }SceneBuildingHelpers.cpp: BothbuildAnalogSeriesBatchCachedandbuildAnalogSeriesBatchSimplifiedsetbatch.is_integer_time = trueandbatch.view_start_time = static_cast<int32_t>(params.x_origin_master_absolute_time.getValue()).SVGPolyLineRenderer.cpp: Decodesstd::bit_cast<int32_t>whenbatch.is_integer_timeis enabled to produce correct SVG polylines during static vector exports.
Phase 2: True Incremental GPU Streaming & Persistent VBOs (Completed)
Objective
Eliminate repeated GPU memory allocation and redundant byte re-transfers when panning, scrolling, or playing back multi-channel data.
2.1 Multi-Batch Single-Pass Staging in PolyLineRenderer & SceneRenderer
Previously, SceneRenderer::uploadScene iterated through all polyline batches and called uploadData per channel. Because each uploadData call reallocated and reuploaded the entire cumulative buffer, an \(N\)-channel scene caused \(O(N^2)\) byte transfers and \(N\) GPU reallocations per frame.
Implemented PolyLineRenderer::uploadBatches(std::span<RenderablePolyLineBatch const> batches): 1. Computes total vertex count across all channels upfront and reserves CPU buffer memory in one pass. 2. Stages all channel descriptors (line_start_indices, line_vertex_counts, model_matrix, view_start_time, global_color, thickness). 3. Uses a persistent GPU buffer: if required_bytes <= m_gpu_buffer_capacity, updates GPU memory using m_vbo.write(0, data, size) (glBufferSubData) with zero buffer reallocations. If growth is required, grows capacity by \(2\times\) with dynamic draw allocation.
// Upload all polyline batches in a single combined pass
m_poly_line_renderer.uploadBatches(scene.poly_line_batches);2.2 Integer-Time Sliding Window Streaming in StreamingPolyLineRenderer
In StreamingPolyLineRenderer.cpp:
For integer time series batches, StreamingPolyLineRenderer allocates persistent GPU capacity (\(2\times\) to \(3\times\) visible points) and dynamically computes time index delta \(\Delta = T_{\text{new\_start}} - T_{\text{cached\_start}}\):
- Forward Scroll (\(0 < \Delta < N\)):
- The trailing \(\Delta\) samples are written to the VBO at byte offset
(m_vbo_vertex_offset + N) * 8viaglBufferSubData. m_vbo_vertex_offsetadvances by \(\Delta\), andline_start_indices[0] = m_vbo_vertex_offset.- Only \(\Delta \times 8\) bytes are transferred to the GPU (e.g. 80 bytes for a 10-sample shift instead of 8,000 bytes, achieving >99% bandwidth reduction).
- The trailing \(\Delta\) samples are written to the VBO at byte offset
- Backward Scroll (\(-\text{N} < \Delta < 0\)):
- The leading \(|\Delta|\) samples are written at
(m_vbo_vertex_offset - |\Delta|) * 8viaglBufferSubData. m_vbo_vertex_offsetdecrements by \(|\Delta|\).
- The leading \(|\Delta|\) samples are written at
- Discontinuous Scrub / Large Jump (\(|\Delta| \ge N\)):
- Full re-upload resets
m_vbo_vertex_offset = 0into the persistent VBO.
- Full re-upload resets
- Buffer Ring Wrap:
- When scrolling reaches the boundary of the allocated capacity, it seamlessly resets
m_vbo_vertex_offset = 0.
- When scrolling reaches the boundary of the allocated capacity, it seamlessly resets
Phase 3: Fast-Path 1.0px Line Rendering
Objective
Bypass geometry shader quad expansion (wide_line.geom) when thickness == 1.0f.
Implementation
Dual Shader Program Setup: In
PolyLineRenderer/StreamingPolyLineRenderer:m_fast_program: Compiled fromline_fast.vert+line_fast.frag(no geometry shader).m_wide_program: Compiled fromwide_line.vert+wide_line.geom+wide_line.frag.
Conditional Draw Dispatch:
void PolyLineRenderer::render(glm::mat4 const & view_matrix, glm::mat4 const & projection_matrix) { for (auto const & batch : m_batches) { if (batch.thickness <= 1.0f) { m_fast_program->use(); m_fast_program->setUniform("u_view_start_sample", m_view_start_sample); m_fast_program->setUniform("u_projection_matrix", projection_matrix); m_fast_program->setUniform("u_model_matrix", batch.model_matrix); m_fast_program->setUniform("u_color", batch.global_color); gl->glDrawArrays(GL_LINE_STRIP, batch.vertex_offset, batch.total_vertices); } else { m_wide_program->use(); // Set wide line uniforms and draw through geometry shader ... } } }
Phase 4: Adaptive Source-Level Min-Max Decimation
Objective
Downsample dense time series directly during storage reads when the sample count exceeds screen resolution, reducing data transfer before VBO upload.
Implementation
Adaptive Decimation Threshold: In
OpenGLWidget::addAnalogBatchesToBuilder:int64_t const visible_points = end_time.getValue() - start_time.getValue(); int const canvas_width = std::max(1, width()); if (opts->enable_min_max_line_decimation || visible_points > canvas_width * 4) { batch_params.min_max_decimation_bucket_count = std::clamp(canvas_width * 2, 512, 4096); }Direct-From-Storage Decimation: Add a fast-path in
AnalogTimeSeriesthat computes the min and max for each pixel bin directly from raw contiguous memory:std::vector<AnalogTimeVertex> decimateContiguousSpan( std::span<float const> values, TimeFrameIndex start, TimeFrameIndex end, int bucket_count);
Phase 5: Memory Reuse and Transient Allocation Reduction
Objective
Eliminate per-frame heap churn during interactive mouse drags and playback scrolling.
Implementation
Persistent Batch Buffers: Add reusable scratch vectors to
SceneCacheStateinOpenGLWidget.hpp:struct SceneCacheState { ... std::vector<AnalogTimeVertex> scratch_vertex_buffer; };Reuse Across Frames: Call
.clear()(retaining allocated capacity) instead of reallocating new vectors every frame.
Verification & Testing Plan
- Unit Testing:
- Verify
AnalogTimeVertexalignment and packing inAnalogVertexCache.test.cpp. - Test integer subtraction edge cases across large indices (\(> 10^8\)) in Catch2.
- Verify
- Visual & Benchmark Validation:
- Test with a \(50\text{M}\)-sample recording: verify zero visual jitter or sub-sample snapping.
- Measure draw call latency during continuous scrolling: target \(< 1.5\text{ ms}\) at 60 FPS.