Skip to content

cvcGL: streaming overlay geometry with partial uploads (StreamingGeometryNode, RibbonNode, terrain-hugging links) - #512

Merged
transfix merged 6 commits into
masterfrom
feat/cvcgl-streaming-geometry
Oct 1, 2026
Merged

transfix merged 6 commits into
masterfrom
feat/cvcgl-streaming-geometry

Conversation

@transfix

@transfix transfix commented Oct 1, 2026 •

Copy link
Copy Markdown
Owner

Stops dynamic overlays from re-uploading whole arrays every time they change, which is the per-frame churn that can dominate the main thread of an overlay-heavy wasm app. On WebGL2, VTK 9.5 fakes texture buffers with 2-D textures, and any Modified() deletes and re-creates every array texture.

New cvcGL API

  • SceneGraph::postEventCoalesced(key, fn): at most one apply per key per frame, latest wins.
  • StreamingGeometryNode has reserved capacity.
    • writePoints(first, xyz, n) is callable from any thread: it stages the data and merges the dirty range, with one coalesced apply.
    • setDrawRange(firstTri, n), uniforms, reserved bounds, and streamStats().
    • Mapper subclasses for both the classic and low-memory VTK mappers upload only the dirty range: bufferSubData on desktop, texSubImage2D row spans on GLES-emulated texture buffers. They also draw a sub-range and keep raw connectivity.
  • RibbonNode: append for tracks writes only the new quad; assign handles a spine replan; setVisibleCenters uses a draw range plus an arc-length clip uniform.
  • HeightFieldTexture and a terrain-hugging link ribbon: the vertex shader offsets a fixed segment between two endpoint uniforms onto the heightmap, so a link costs 0 uploads per frame.
  • Wrapped in pycvc_gl.

Evidence from the spike (spike/cvcgl-streaming-mapper, 72/72 checks native + 72/72 Chromium WebGL2): one track append drops from 221 KB / 20 GL calls / 10 buffers + 5 textures created to one 48-byte texSubImage2D. A spine replan is one sub-range upload, then 0 uploads per frame; a link endpoint move is 0 uploads.

Review status: implemented and unit-tested natively. The adversarial review has not run yet. Do not merge until it does. CI is running now for cross-platform build and test coverage.

Streaming overlays (next commit) are fed by producers off the render
thread that may stage several vertex ranges between two frames. Applying
each one on the owner thread would be wasted main-thread work, so
SceneGraph::postEventCoalesced(key, fn) runs at most one callback per key
per processEvents() -- the latest posted -- at the queue position of the
key's first post, so it still orders after the work queued before it.
A replaced callback is destroyed outside the queue lock, since its
captures may take other locks on the way out (a Python callable's
deleter takes the GIL).

A streaming node needs its own mapper subclass, but GeometryNode
hard-coded the factory mapper and kept its VTK objects private. Add a
protected constructor taking a mapper, protected accessors for the
actor/mapper/polydata, and factor the texture-unit reservation out of
onUpdateShader into a reusable bindShaderTextures(); the public behaviour
is unchanged apart from skipping a texture that has no context instead of
dereferencing it.

GraphicsNode::addGraphicsChild<T> now forwards extra constructor
arguments, so nodes whose existence depends on more than a name (a
streaming node's layout, a ribbon's capacity) can be created as children
the same way as every other node.

pycvc_gl hides the new protected GeometryNode hooks from the director
(dirprot would expose them with opaque VTK types) and wraps
postEventCoalesced as post_event_coalesced(key_object, callable), keyed
by the Python object's identity.
A demo frame spent most of its main-thread budget rewriting every overlay
wholesale through GeometryNode::updateVertices: VTK re-sends the whole
point array on Modified(), and on WebGL2 the low-memory mapper deletes and
re-creates every array texture. Overlays change a few vertices at a time,
so they should upload a few vertices at a time, staged off the render
thread.

StreamingGeometryNode is a GeometryNode of fixed capacity whose points
are written piecewise from any thread: writePoints copies into a staging
buffer under the node's lock, merges the dirty range and posts one
coalesced apply, which moves the range into VTK on the owner thread.
Draw ranges are applied with the points (so a range never shows unwritten
points) and uniforms are stored under a mutex and pushed at draw time --
neither uploads anything. Writes past the capacity throw; a generic node
cannot extend a topology it does not own.

It draws through one of two thin mapper subclasses, ported from the L3
spike's verified hooks, chosen as the factory mapper would be (classic on
desktop GL, low-memory on GLES/WebGL2) unless forced:
- classic: sub-range glBufferSubData on vertexMC, a raw-connectivity IBO
  (the stock builder drops coincident placeholder triangles) and a true
  [first, first+count) triangle draw;
- low-memory: sub-range upload of the positions texture buffer, or at
  most three glTexSubImage2D row spans where GLES emulates it with a 2-D
  texture, cell-group offsets for the draw range, and the VTK 9.5.0
  uninitialised shift/scale workaround.
Both report reserved bounds, since writes never re-walk the points and a
template-space link would otherwise be culled. The row-span upload is
compiled on every platform and tested natively against a real texture.

On top: RibbonNode (track append = one 48-byte upload re-mitring the
previous point; route assign = one sub-range upload; setVisibleCenters =
draw range plus a fragment clip, no upload; grows when full so a track
keeps its history), HeightFieldTexture (R32F, texelFetch + manual
bilinear, with a CPU twin) and DrapedLinkNode (a fixed template draped in
the vertex shader between two endpoint uniforms; the #define vertexMC
splice survives the shadow baker; colour and opacity are uniforms).

cvcgl_streaming_geometry and cvcgl_streaming_overlays check, on both
mapper families, upload bytes/calls via the node's stats and a GL-level
counter, pixel parity with the same triangles drawn by a GeometryNode,
one upload per frame under vtkShadowMapPass, coalesced off-thread writes,
and the capacity contract.
Python drives demos and labs through pycvc_gl, so the streaming overlays
need the same surface there as GeometryNode has. Their C++ constructors
take a StreamingLayout and a bounding_box, neither of which marshals, so
they are created through SceneGraph factories (add_ribbon,
add_draped_link, add_streaming_geometry, optionally under a parent) with
typed downcasts, and getGraphics() hands back the most-derived proxy.
Point and height data cross as any float32/float64 buffer (numpy) or a
flat sequence, and stats come back as dicts. No directors: the protected
draw hooks take raw VTK types.

test_pycvc_gl_streaming covers the surface headless and, with offscreen
GL, the upload accounting.
- Apply key: a streaming node coalesces its applies under a private member
  address, not `this`, and the one-slot-in-flight flag is gone (the scene
  already de-duplicates). A caller coalescing "per node", or a slot its scene
  never ran, can no longer freeze the node. SceneGraph.h now says keys must be
  private to one producer.
- Unattached writes are staged only: nothing touches VTK on the producer
  thread. SceneNode gains an onSceneGraphChanged() hook, from which a
  streaming node applies what it staged on attach (or re-attach), and its
  scene pointer pair is now read and written under a mutex.
- Picking: streaming actors default to PickableOff() (VTK's CPU picker hits
  the polydata: unwritten capacity, hidden tails, a link's template), with
  setPickable() to opt in.
- RibbonNode grows its reserved box over every centre it writes (append,
  assign, setHalfWidth), so a track that leaves its box is never culled.
- DrapedLinkNode drapes at //VTK::Clip::Impl, ahead of VTK's clip-plane
  distances, so clipping uses the draped point. setStyle no longer replaces a
  box pinned with setReservedBounds, and derived bounds follow
  HeightFieldTexture changes (a new generation() counter, checked when VTK
  asks the mapper for its bounds, so a culled link recovers).
- GeometryNode keeps subclass ("internal") shader replacements apart from the
  public ones: a caller's replacement on the same anchor composes after it and
  clearShaderReplacements() leaves it in place. RibbonNode and DrapedLinkNode
  use it.
- pycvc_gl: post_event_coalesced keeps its key alive until the slot drains and
  treats every proxy of one node as one key; add_streaming_geometry accepts
  numpy integer arrays and scalars.
- Header notes for the deferred costs: relayout's O(capacity) rebuild on the
  owner thread, and the one-frame clip-uniform vs draw-range skew.
- Tests: regressions for each of the above; the track parity floor is derived
  from the ribbon's area (a fixed 500 px sat above its exact 498 px, which
  Apple's software rasteriser hits); the streaming tests switch off NVIDIA's
  swap throttling of unmapped windows (minutes of wall time for ~1 s of CPU).
- Scene teardown vs producers: a SceneGraph's event queue, coalesced map,
  render flag and owner thread move into a SceneEventSink held by
  shared_ptr. Producers post through SceneNode::sceneEvents() (a locked
  sink), never a raw SceneGraph*; ~SceneGraph closes the sink, so a post that
  races the destruction is refused instead of touching freed memory, and the
  staged write stays pending for the next attach. runOnMainThread and the
  streaming node's apply/render requests go through it; postEvent and
  runOnMainThread behave as before. The sink is allocated with new, not
  make_shared, so a raw-pointer regression shows up in ASan/valgrind.
- processEvents: a throwing callback puts the callbacks it did not reach back
  at the front of the queue before rethrowing, so their coalesced keys keep
  their slots (a streaming node's apply key was stranded for good).
- A posted apply runs only if the node still belongs to the scene draining
  it; a slot left in a scene the node moved out of leaves its staging alone.
- DrapedLinkNode: setStyle, refreshReservedBounds and beforeComputeBounds
  derive-and-commit the bounds under one mutex, and record the height
  generation read BEFORE the extent, so an older box can no longer overwrite
  a newer one or be marked current.
- The low-memory streaming mapper rebuilds its shader program when the
  actor's shader replacements change (VTK 9.5's low-memory mapper never
  checks GetShaderMTime), so add/clearShaderReplacements after the first draw
  take effect on WebGL2 too.
- The streaming tests are desktop-GL only (glad pointer swapping,
  glGetTexImage) and are no longer added to the Emscripten build.
- Tests: cvcgl_streaming_races (Linux; an interposed pthread_mutex_lock pauses
  a thread at a chosen lock) forces the teardown and both bounds
  interleavings; the throwing-callback and moved-node cases join
  cvcgl_streaming_geometry; the replacement checks now show a visible change
  on both mappers; the picking check uses a height field whose extent covers
  the template and also asserts a pickable link would be hit.
@transfix
transfix force-pushed the feat/cvcgl-streaming-geometry branch from 84f2bad to 5bbe97d Compare October 1, 2026 19:42
~SceneGraph closed the event sink before resetting its alive token. In
between, a producer's refused runOnMainThread post ran its work inline on the
producer while getSceneGraph() still returned the scene being destroyed, so
owner-thread-only lambdas (LightNode -> applyLights, the requestRender
calls) could touch it off the owner thread. The token now goes first: a post
that lands before close() is queued and dropped by it, as events queued to a
dying scene always were, and a refused post already sees no scene and takes
the no-scene path. A streaming node's refused apply still leaves its staging
pending for the next attach.

runOnMainThread no longer copies the callback to keep a fallback:
SceneEventSink::tryPost takes it only when it accepts, and the refused job
runs inline.

cvcgl_streaming_races gains the runOnMainThread variant: the producer holds
the sink and is let go from inside ~SceneGraph's close(); its inline work
must see getSceneGraph() == nullptr (it fails with the old order).
@transfix
transfix merged commit 91893be into master Oct 1, 2026
13 checks passed
transfix added a commit that referenced this pull request Oct 19, 2026
… test (#583)

NVIDIA's GLX driver throttles buffer swaps of an unmapped (offscreen) window
to about one per second while sync-to-vblank is on, so an offscreen GL test
spends minutes of wall time on seconds of CPU (#512: cvcgl_streaming_overlays
took 4m15s wall for 1.7 s CPU, 4.7 s with __GL_SYNC_TO_VBLANK=0). #512 and
later tests worked around it one test at a time, with setenv before the first
GL context. Every other offscreen GL test was still throttled.

- src/cvcGL/CMakeLists.txt: append __GL_SYNC_TO_VBLANK=0 and vblank_mode=0 to
  the ENVIRONMENT of every test in the directory. It uses the same
  DIRECTORY TESTS sweep as the cvcgl_gl_context resource lock, so a new test
  gets it without asking. APPEND keeps any per-test ENVIRONMENT.
- bindings/pycvc/CMakeLists.txt: the twelve GL-block tests (pycvc_gl_*,
  pycvc_ari, pycvc_vtk, pycvc_texture) each repeated the same
  PYTHONPATH/LD_LIBRARY_PATH string. They now share _PYCVC_GL_TEST_ENV, which
  also carries the two variables.
- Drop the per-test workarounds: streaming_test_util.h's
  disableSwapThrottle() and its four callers (cvcgl_streaming_geometry,
  cvcgl_streaming_overlays, cvcgl_clip_children, cvcgl_clip_planes), the
  vblank lines in cvcgl_lowmem_fastdraw, and os.environ.setdefault in
  test_pycvc_gl_streaming.py and test_pycvc_gl_clip.py. cvcgl_lowmem_bench
  keeps its own: it is not a ctest, so the ENVIRONMENT never reaches it.

No setenv is needed, so Windows and wasm build as before. ctest's
ENVIRONMENT overrides the caller's environment; to time a test with vsync on,
run its binary directly.

Why not disable buffer swaps on cvcGL's offscreen windows instead
(vtkRenderWindow::SetSwapBuffers(false))? In VTK 9.5, SwapBuffers off also
skips the render-to-display framebuffer resolve in
vtkOpenGLRenderWindow::Frame(). writePNG/frameRGB read the back buffer and
would be fine. A front-buffer read through renderWindow(), for example a
default vtkWindowToImageFilter, would return a stale frame. vtkHardwareSelector
also calls SwapBuffersOn() unconditionally after every selection
(cvcgl_lowmem_fastdraw picks on a SceneRenderer window). The DoubleBuffer
variant collides with FrameYield, which owns DoubleBuffer, and with
cvcgl_frame_yield's check that DoubleBuffer stays 1 natively.
@transfix
transfix deleted the feat/cvcgl-streaming-geometry branch October 29, 2026 20:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant