Skip to content

feat(cvcGL): built-in CameraController (orbit/fly/track) + pure-C++ lsystem_forest example - #199

Merged
transfix merged 24 commits into
masterfrom
feat/cvcgl-camera
Aug 20, 2026
Merged

transfix merged 24 commits into
masterfrom
feat/cvcgl-camera

Conversation

@transfix

Copy link
Copy Markdown
Owner

Bakes camera navigation into cvcGL as a first-class capability, wraps it for Python, and adds a pure-C++ lsystem_forest example that drives the whole stack.

cvc::gl::CameraController (new)

cvcGL was headless — SceneGraph::setRenderer never touches the vtkCamera, so navigation was 100% the host's problem. This makes orbit + fly + cinematic-track a built-in, so a lab demo (up to a real-time sim/game loop) gets usable navigation for free.

  • Three modes: Orbit (turntable), Fly (Quake — WASD along the look vector, mouse-look, Space/Ctrl up/down, Shift sprint, X11 pointer-capture), and Track (cinematic follow of a named scene actor — the grl-snam ChaseCamera math: two-stage EMA + critically-damped pose, up-axis-general, stop-safe). Tab toggles orbit/fly.
  • Fully cvc::state, two-way: mode, up axis, orbit center, fly pose, movement/mouse/sprint settings, pointer-capture, track.*, and key bindings all live in the state tree and are two-way bound (write state → camera follows; drive camera → state reflects). Seeded echo-free (state_init_scope), synchronous (setInstanceThreading(false)), pose mirrored on a throttle off the render path.
  • Configurable up axis (default +Z; Y-up works). Canonical, viewer-associated location: built from a SceneRenderer, the state roots at <scene prefix>.viewers.<name>.camera, so it's obvious which viewer a camera belongs to (SceneRenderer gained a name).
  • No singletons — the cvc::app is injected throughout (ctor or viewer.scene().appContext()), never context()/instancePtr().

Build + bindings

  • New top-level CVC_BUILD_CVCGL builds cvcGL standalone against the in-tree cvc core with no SWIG/Python (the pycvc path reuses the target when present).
  • pycvc_gl.CameraController wraps it: CameraController(view) (no raw vtk handles) or (app, path); all config methods + Mode_Track. Being a state_object, config also works via pycvc.state_set(app, "<...>.camera.mode", ...).

lsystem_forest C++ example (behind CVC_BUILD_EXAMPLES, OFF)

A pure-C++ port of the volrover demo, owning an injected cvc::app: island heightfield (matte + procedural bump), an L-system forest (each tree merged route-C to one wood + one needle actor, wind re-posed every frame via updateVertices, procedural bark shader on the wood), a sea volume (depth under a travelling wave), the afternoon sun (disc + directional light) + striped shadows — navigable in orbit/fly/track. The bump/bark reproduce the latest master demo (PR #39). (The cloud/sky volume is the one part not yet ported.)

Tests

cvcgl_camera (27 checks — navigation math, state↔camera round-trips, Y-up, key rebinding, canonical path, Track follow) and test_pycvc_gl_camera (16 checks). Both green. Example verified offscreen (--offscreen --frames N --png).

cvcGL was headless-only: SceneGraph::setRenderer touches props, never the
vtkCamera, so navigation was 100% the host's problem. Add a first-class
cvc::gl::CameraController so a lab demo (up to a real-time sim/game loop) gets
usable navigation for free:

  * ORBIT — turntable azimuth/elevation about a center, wheel dolly, drag to look.
  * FLY   — Quake-style: WASD strafe/forward along the look vector, mouse-look
            (yaw + clamped pitch), Space/Ctrl world up/down, Shift sprint, wheel
            = speed. Tab toggles orbit<->fly, carrying the pose across seamlessly.

Z-UP throughout (cvc scenes — terrain, forests, volumes — are built Z-up), unlike
volrover3's Qt CameraController whose fly/orbit math is hardcoded Y-up. Two drive
paths that compose: attach(interactor) installs an internal vtkInteractorStyle so
an onscreen SceneRenderer window steers the camera with zero wiring; or feed
events yourself (keyDown/mouseLook/...) from any host loop. update(dt) integrates
held-key motion once per frame so movement is frame-rate independent under a
manual render loop. Not a SceneNode and not on the state tree — plain camera pose.

Build wiring: cvcGL was only buildable via the pycvc bindings. Add a top-level
CVC_BUILD_CVCGL option so cvcGL builds standalone against the in-tree cvc core
with no SWIG/Python, and guard the pycvc path to reuse that target when present.

Test cvcgl_camera drives a bare vtkCamera and asserts Z-up framing, the seamless
orbit<->fly toggle, WASD/strafe/vertical motion, mouse-look, and orbit-drag
(17 checks, no window needed).
… up-configurable

Make the whole camera configurable from cvc::state and pin it to a canonical,
viewer-associated location in the state graph.

  * state_object: mode, up axis, orbit center/distance/az/el, fly position/yaw/
    pitch, movement/mouse/sprint settings, pointer-capture, AND key bindings all
    live in the state tree and are TWO-WAY bound — write state and the camera
    follows (synchronous, setInstanceThreading(false)); drive the camera and state
    reflects it. Seeded with state_init_scope (no echo); self-write guard + a
    throttled pose mirror keep per-frame state churn off the render path.
  * Canonical location: constructed from a SceneRenderer, state roots at
    "<scene prefix>.viewers.<viewer name>.camera" so it is obvious which viewer a
    camera belongs to. SceneRenderer gains a `name` + scene()/name() accessors;
    SceneGraph exposes appContext(). Low-level (app, path) ctor stays for headless.
  * Configurable up axis (state "up.{x,y,z}", default +Z): the fly/orbit basis is
    derived from it, so a Y-up scene works by setting up=+Y. Z-up math unchanged.
  * Quake pointer capture: hide the cursor and X11-warp it to centre each frame so
    mouse-look is continuous; Escape releases; auto-enabled in fly. Degrades to
    cursor-delta off X11. cvcGL links X11 (guarded, Linux only).
  * Key bindings are VTK key syms, rebindable via state "keys.<action>" or the API.

cvcgl_camera now covers 22 checks: navigation math, state->camera and camera->
state round-trips (mode, orbit center, settings), configurable up axis (Y-up), key
rebinding via state + API, and the canonical viewer path.
…config

Expose the built-in cvcGL camera to Python so demos can drive it. The primary
Python path is CameraController(view) — constructed from a wrapped SceneRenderer,
so no raw vtk handles cross the boundary; a (app, path) ctor covers headless use,
taking the injected shared_ptr<cvc::app> (make_app()) — no singleton. The raw
vtk-pointer wiring (setCamera/attach/...) and the C-array pose getters are hidden
(pose/up are read from state); everything else — setMode, setUpAxis, frameBounds,
setOrbitCenter, setKeyBinding, update, toggleMode, pointer-capture, tunables — is
wrapped. Being a state_object, the SAME settings are ALSO reachable via
pycvc.state_set/get on "<scene prefix>.viewers.<name>.camera.*". The %pythonappend
keep-alive holds the injected viewer/app so ~state_object doesn't dangle.

test_pycvc_gl_camera.py (registered as pycvc_gl_camera): construct from an
injected app and from a SceneRenderer; methods write state; pycvc.state_set drives
the camera (mode, key rebind, move speed); the canonical viewer path resolves. Hard
-exits with the real status to sidestep cvcGL's known static-teardown lock_error.
…scene actor)

A third camera mode, harvested from grl-snam's ChaseCamera: cinematically follow a
named actor in the scene. Which actor is state "track.target" (a scene-graph node
name); the controller reads that node's world position each frame from the scene
(taken from the viewer, or setScene()). The follow is the ChaseCamera math,
generalised to the configurable up axis: two-stage EMA (light on position ->
heavier on velocity for a stable heading) + a critically-damped pose, all
frame-rate-independent (1-exp(-dt/tau)) and stop-safe (heading held below
min_speed). Trailing distance/height/look-ahead/look-up and the pos/vel/cam time
constants are state "track.*". Tab still toggles the two interactive modes;
setMode(Track) enters the follow and eases in from the current view.

setMode is now explicit per target (three modes) rather than a 2-way toggle.
Wrapped in pycvc_gl (Mode_Track + setTrackTarget/trackTarget; setScene ignored —
the viewer ctor sets it). Tests: cvcgl_camera drives an actor along +X and asserts
the camera trails behind + above and the focal follows (now 27 checks);
test_pycvc_gl_camera exercises the Track surface via API + state (16 checks).
…camera (WIP)

The pure-C++ port of the volrover lsystem_forest demo, behind CVC_BUILD_EXAMPLES
(OFF). This first increment stands up the whole pipeline and the navigation:

  * owns an explicit cvc::app and injects it (SceneGraph(app,"forest")) — no
    global/singleton context;
  * an island heightfield (dome + relief) as a cvc::geometry with per-vertex
    matte grass/sand/rock colour;
  * the procedural fragment BUMP MAP on the ground (value-noise height, normal
    perturbed by its surface gradient — Mikkelsen's tangent-free method), verbatim
    from the latest master demo, via GeometryNode::disableCoordinateShiftScale +
    add{Vertex,Fragment}ShaderReplacement — the SAME shader-replacement path the
    tree bark uses;
  * afternoon sun + cool sky fill, shadows on with a 3-frame re-bake stride;
  * SceneRenderer as the window (onscreen; --offscreen/--frames/--png to verify
    headless), driven by CameraController (orbit / Quake-fly / cinematic track).

Verified offscreen: the island renders with a rough, sun-catching micro-surface
(the bump map working) and cast shadows, framed by the camera. NEXT: the L-system
trees (route-C merge + updateVertices wind + procedural bark), the sea/sky volumes
and the sun disc. (Known: the lab grid/axis box still shows — chase when adding trees.)
…rocedural bark

Port the tree grammar to C++: each tree is grown from the 5-rule L-system into a
module hierarchy (expandTree), each module's cylinders + needle stars baked in its
local frame, then MERGED into one wood mesh + one needle mesh per tree (route C).
Row-major Mat4 math mirrors the Python demo exactly (the numpy reproduction this
was checked against matched to 7e-15). Every frame the wind cascade is re-run over
the merged vertices and pushed with one GeometryNode::updateVertices per actor —
wind intact, ~2 actors per tree instead of one per module.

Procedural BARK (verbatim GLSL from master #39) rides on each wood node via the
GeometryNode shader-replacement path: vertical furrows from the bind-pose normal
angle + axial variation, normal perturbed by the height's surface gradient; the
per-vertex light/dark wood colour is kept. Needles are single-colour LINES.

55 trees planted on the dry land (deterministic std::mt19937), each at its own
maturity/size/phase/sway. Verified offscreen: a forest of conifers on the bump-
mapped island, casting shadows, framed by the camera. NEXT: sea/sky volumes, the
sun disc, and the stray grid box.
Complete the island. The SEA is a cvc::volume (Float, over the island footprint)
whose field is depth below a travelling wave surface bounded by the seabed, so
water sits only in the hollows; its transfer function is translucent in the
shallows and opaque offshore (sand shows through knee-deep water). The field is
rebuilt and re-uploaded every 3rd frame (VOL_STRIDE) — setVolume RESETS the TF, so
it is re-applied after each upload, as the cvcGL VolumeNode requires. Water is a
lit surface (shading on, tight specular) so the swell throws a sun glint.

The SUN is a flat-lit disc + a wider faint halo far out along the light direction,
added AFTER the camera frames the island so its ~430-unit distance doesn't shrink
the view. And the lab grid/axis box is hidden (setGridVisible/setAxisVisible now
land — do it after the render target exists + pump).

The demo is now the full island — terrain, forest (route-C trees + bark + wind),
sea, sun, shadows — navigable in orbit/fly/track. Verified offscreen. Only the
cloud/sky volume (needs the cloud L-system grammar) remains from the Python demo.
… axis

GridNode draws with three plane actors + per-plane tick-label actors, and AxisNode
with a vtkAxesActor and its X/Y/Z caption labels — but getProp() returns only the
first actor, and the base GraphicsNode::setVisible touched only that one prop + the
label. So setGridVisible(false)/setAxisVisible(false) left the planes, tick labels
and axis captions rendering (and casting shadows). A demo that hid the grid still
showed a grid.

Make GraphicsNode::setVisible virtual and override it in both nodes to set
visibility on ALL their actors — and gate every place the grid (re)applies plane/
tick visibility (createGridPlanes rebuilds, handleStateChanged) on isVisible() too,
so a rebuild triggered by a bounds change can't silently re-show a hidden grid.
GridNode::setVisible also add/removes its actors from the renderer, so a hidden
grid neither renders nor bakes into the shadow pass.

cvcgl_camera: hard-exit (std::_Exit) with the real status after the checks, so
cvcGL's known state_object/handler-thread teardown race at process exit can't flip
a green run red (matches the pycvc_gl test). 27 checks, 5/5 clean.
…hadows

The island is a scene, not a lab bench, so hide cvcGL's default helpers:
setGridVisible(false) + setAxisVisible(false) (now that they actually work), and
getGraphicsRoot()->setShowBBox(false) — the scene root (a NullGraphic) shows its
yellow bounding box by default, which was the box floating around the island (it
tracked the scene bounds, blown up by the far-off sun). Also add a --no-shadows
flag (handy for isolating shading from shadow artifacts while developing).

The demo now renders as intended: just the bump-mapped island, the forest and its
cast shadows, framed by the camera — no stray grid, axis, tick labels or bbox.
setShadowsEnabled installed a render-pass sequence of just the shadow-map baker
plus the shadow pass, which draws only the OPAQUE layer. Everything else —
translucent geometry, volumes, 2-D overlays — was silently dropped, so any scene
with a VolumeNode (the sea, a cloud slab, any transfer-function volume) rendered
as if the volume weren't there the instant shadows were switched on: field right,
transfer function right, prop in the renderer and marked visible, drawing nothing.

Follow the shadow pass with the rest of VTK's standard layer order — translucent,
then volumetric (ray-cast over the shadowed opaque depth, so volumes are occluded
by terrain yet composite over open sky), then overlay. cvcgl_shadow_volume guards
it two ways: structurally (the installed pass tree must carry a volumetric pass —
needs no GPU) and end-to-end (a solid volume paints as many bright pixels with
shadows on as off).
The last piece of the Python demo's scene: an L-system 3-D turtle grows two cloud
density fields (a Gaussian ball per F, so puffs are round not columnar), faded at
the slab faces and normalised on a high percentile. Per frame the two skies are
crossfaded (the cloud changes shape as it travels) and sub-cell scrolled along
+x (smooth drift at any speed), uploaded on the VOL_STRIDE beat the sea skips so
the two volume re-imports never share a frame. Seed 20 grows both maps centred so
cloud is visible from the first frame rather than fading in only as the morph
reaches the second map.

The cloud ceiling is folded into the framing bounds (unlike the sun, which is
pure far scenery added after framing): the island fills the lower frame with the
clouds drifting overhead. Renders correctly now that shadows no longer drop the
volumetric pass.
vtkSmartVolumeMapper's GPU ray-caster can cast secondary rays so a volume shades
itself — sculpted, lit tops and dim undersides instead of flat fog — but the
knobs were unreachable. Expose them as state-backed VolumeNode properties that
forward to the mapper / volume property:

  setVolumetricScattering(blend)   [0,2]  -- surfacic <-> volumetric multi-scatter
  setGlobalIlluminationReach(reach)[0,1]  -- shadow locality vs cost
  setScatteringAnisotropy(g)      [-1,1]  -- Henyey-Greenstein phase (>0 forward)

Defaults are 0, so existing volumes are unchanged until a caller opts in. Only
active when shading is on. cvcgl_volume_range asserts the setters forward and
round-trip through cvc::state (SceneNode dispatches inline, so it is synchronous
and needs no GPU); test_pycvc_gl adds the Python-wrapper round-trip (auto-wrapped
via %include — a SWIG regen is needed after the header change).
Two cloud-lighting effects, both driven by the actual drifting density field:

GROUND SHADOW (true volumetric, for the directional sun): parallel sun rays make
the ground shadow a rigid shear of the cloud's along-sun optical depth, so per
cloud update we ray-march the same field the volume shows — from each ground
point up the sun ray through the slab — and bake albedo x transmittance into a
texture the terrain samples (world xy -> UV). Identical to a per-fragment GPU
light pass for a directional light, computed once per update. Terrain colour now
lives in that texture (flat-white mesh) so it reads whether VTK modulates or
replaces, at texel rather than vertex resolution.

SELF-SHADOW: the cloud VolumeNode now uses the new volumetric-scattering controls
(blend 0.5, GI reach 0.3, strong forward anisotropy 0.85) for a sunlit top and a
shadowed underside. On so thin a field a higher blend just dims the whole body to
storm-grey, so it is dialed for a directional silver-lining gradient, not more.

The shadow moves with the cloud each VOL_STRIDE beat, in sync with the volume.
git clang-format against the PR base over CameraController, the lsystem_forest
example, and the camera / shadow-volume tests. Whitespace only — no behaviour
change; cvcGL suite still green.
…ds, capture CLI

Visual overhaul of the island demo:
- SKY: a gradient background (hazy horizon -> deep-blue zenith) replaces the flat
  void, and the sun is a camera-relative billboard fixed in the light's direction —
  always in the sky where the light comes from, never eclipsing the island as the
  old fixed-world disc did when the camera came around. Its depth along the sun ray
  is CAPPED at treetop height so it never stretches the shadow-map's depth range
  (a far occluder there leaves the island at the far end with no depth precision
  and self-shadows it to black).
- CLOUDS: fractal fBm noise frays the smooth L-system density into fluffy cumulus
  (finer 84x84x38 grid so the detail resolves); rendered bright white with the
  fractal density carrying the form (VTK volume gradient-shading grays a noisy
  field, so shading is off, no dark scattering rim); the ground dapple is now soft.

CLI: arg parsing moved to boost::program_options, with cinematic capture folded in
as real options — --capture fly|orbit --width --height --fps --out writes a numbered
PNG sequence on a fixed synthetic clock (real-time playback) to encode. --help lists
everything.
…p size

vtkShadowMapBakerPass defaults to a 256px shadow map, which aliases thin casters
(a forest of trunks and line-needles tears into displaced, speckled, inverted
shadows) and speckles broad surfaces with self-shadow acne. Expose the resolution
as a live SceneGraph knob (applied to the baker on enable and on the fly), clamped
off silly-small values, default 1024. cvcgl_lighting asserts the interval +
resolution round-trip and the clamp. (A bigger map helps, but line/thin geometry
is inherently a poor shadow-map caster — see the lsystem_forest note.)
…calmer motion

Iterating the look on feedback:
- CLOUD depth: a cheap BAKED top-light — each voxel is thinned by the cloud density
  between it and the sun, so sunlit crowns stay solid-white and self-shadowed parts
  go soft with a cool blue-grey wash (in the transfer's low end). Depth without
  VTK's volume gradient-shade, which grays the fractal field. Floor kept high (0.72)
  so it shades WITHOUT fraying the puffs apart.
- CALMER: cloud drift 5->3 u/s and crossfade 26->60 s so it barely pulses; a capture
  now refreshes both volumes EVERY frame (was every 3rd) so the motion is smooth, not
  a stepped stutter.
- BRIGHTER island: terrain material ambient/diffuse lifted and the sun/fill nudged up.
- SHADOWS now opt-in (--shadows), OFF by default: a shadow map can't represent the
  thin trunks / line needles without displaced, speckled artifacts, and the scene
  reads cleaner and brighter without it. The cloud's soft GROUND dapple stays — it's
  a terrain texture, independent of the shadow pass.
…w speckle

The shadow map itself was fine (correct dark shadows on the ground); the artifact
the eye read as 'inverted, bright tree shapes' was the shadow map SELF-shadowing
the thin trunks and line-needles into harsh dark/bright mottling on the trees.
Fix without dropping shadows: lift the trees' material ambient (wood 0.5, needles
0.55) so a fully self-shadowed sample still keeps most of its light — the residual
line-needle shadowing reads as a gentle dapple, not speckle. Shadows are back ON by
default (--no-shadows to drop them). Ground tree shadows + the cloud dapple stay.
…readout

Sea was a lone travelling sine (an obvious diagonal stripe). Replace with four
travelling waves at different headings, wavelengths and INCOMMENSURATE speeds so the
combined period reads erratic, each CRESTED via a sharpened sine (s^2.4) that pinches
peaks and broadens troughs for a rolling look. Overall amplitude reduced. Also print
an averaged FPS readout in the interactive loop (not during capture) for a quick
realtime-speed check.
…or merge (~8→36 fps)

The demo capped at ~8 fps interactive. Two fixed per-frame costs dominated,
neither pixel-bound (dropping the render resolution barely moved the needle):

  1. Every animated volume (sea, cloud) refreshed via setVolume() — a full
     re-import each call: AllocateScalars realloc + GetScalarRange rescan +
     setDefaultTransferFunction reset + ~20 log lines. New VolumeNode::updateScalars()
     overwrites the voxels in place (memcpy + Modified only), leaving the range and
     transfer function as set. Captures the data BY VALUE because runOnMainThread
     marshals off the owner thread. This is the reusable primitive per-frame volume
     animation always wanted.

  2. The forest was 32 trees × 2 actors = 64 actors, each re-posed by the wind with
     its own updateVertices every frame — 64 VBO uploads and 64 draw calls in BOTH
     the main pass and the shadow bake. Merged the whole forest into ONE wood + ONE
     needle actor (route C across trees): the wind now writes every tree into two
     shared buffers uploaded once. 64 draws → 2. This was the single biggest win
     (17 → 29 fps on its own at full res).

Also: decouple the interactive update cadences (wind/sea every 2nd/4th frame, cloud
8th, ground shadow 16th; captures still refresh every frame so nothing steps), and
size the cloud grid + ground-shadow map for realtime. Net ~36 fps at 1280×800 with
shadows on, full quality — comfortably past the 30 fps target. (Two GPU ray-cast
volumes put a hard ~30 fps ceiling on the scene even with zero animation, so 60 is
not reachable without dropping a volume.)

Test: cvcgl_volume_range gains a VolumeNode::updateScalars guard — it preserves the
transfer function where setVolume resets it (the work it skips), and a voxel-count
mismatch is an honest no-op.
The cloud→ground shadow marched the TRUE sun (elevation 34°). At that angle the
shadow is thrown ~145 units horizontally — clear off the 120-unit island, onto the
untextured sea — so the ground directly under the cloud read as unshadowed, which is
exactly where the eye looks for a cloud's shadow.

March a steeper pseudo-sun instead (same azimuth, 66° elevation): the shadow now
lands on the island just off nadir beneath the cloud, tracking it as it drifts. A
small, honest lie about the sun angle for a legible shadow — the usual stylisation.
Also firm it up a little (floor 0.78→0.55, k 0.06→0.13) so it reads as a soft,
clear cloud-shaped patch rather than a barely-there dapple.
Documents the demo end to end: the two L-systems (the tree grammar/turtle and the
3-D cloud turtle + fBm), the cvcGL render path (scene graph, mesh vs volume nodes,
bark shader, shadow-map pass order, the cloud→ground shadow bake, sky/sun), the
realtime performance work (in-place volume refresh, forest actor merge, decoupled
strides, the ~30 fps two-volume ceiling), CLI usage, and a code map. Plus a hero
image.
…gleton

VolumeNode/GeometryNode logged (and registered thread_info) through the
process-wide cvc::gl::context() singleton — so the demo, which deliberately runs
under its own injected cvc::app, still had no way to control its console output
short of poking that global. Route all 44 node log calls and the thread_info
registrations through SceneNode::app() (the injected context each node already
holds). No singleton in the node path anymore; cvc/gl/context.h is dropped from
both files.

With logging on the injected app, verbosity is the caller's to set. Also re-level
the output: it was almost entirely at level 0 (ERROR), so nothing but silencing
the app could hide it. It's now DEBUG (3), keeping the two genuine cases visible —
the null-pointer copy failure at ERROR (0) and "volume not in renderer" plus
GeometryNode's updateVertices count-mismatch at WARNING (1).

The demo sets `system.log_verbosity` on ITS app (errors+warnings only), with
`--verbose`/`-v` to restore the full per-frame trace. Interactive and offscreen
runs are now quiet apart from the banner and FPS readout.

Remaining cvcGL singletons (follow-up, not this change): the SceneGraph default
ctor's cvc::gl::context() fallback (kept for VolRover back-compat, used by ~22
tests) and state_publisher::instance().
…lisher

Completes the no-singleton work: cvc::gl::context() (a process-wide `static cvc::app`)
is deleted entirely (context.cpp/context.h gone). What used it:

- state_publisher: dropped its static instance(). The SceneGraph now OWNS a
  state_publisher, built with its injected app and reached via SceneGraph::publisher();
  GraphicsNode poses publish through getSceneGraph()->publisher() (direct state write
  if somehow detached). No global.
- SceneGraph: the default (no-app) ctor is removed — every scene names its app. The
  injected-app ctor gained a default prefix so call sites stay terse. (VolRover must
  switch SceneGraph() -> SceneGraph(app,...); accepted.)
- ~10 tests inject a local cvc::app; cvcgl_teardown's thread check and
  cvcgl_volume_range's volume ctors run under that app; cvcgl_state_publisher uses the
  scene's publisher.

Making the publisher per-scene surfaced threading bugs the process-wide singleton hid
(it lived forever and was never stopped). Two adversarial review passes found, and this
fixes, three:
- The pooled worker was signalled but never JOINED, so it could run flush() after the
  publisher and its nodes were freed (use-after-free on every teardown).
- A fixed pool key made two scenes-per-app collide: the second's start() interrupt+
  joined the first's worker, which parks in a std condition variable (not a boost
  interruption point) — deadlock.
- A pool worker loops for the scene's whole life, pinning a bounded-pool slot; past
  maxPoolSize live scenes the excess worker never schedules and a join-on-stop hangs.

Fix: the drain worker runs on the publisher's OWN std::thread, joined in stop() — join
is the whole synchronization (no hand-shake to race), it needs no pool slot (no
starvation/deadlock), and it is one mostly-idle thread per live scene. worker() catches
exceptions so a failed write can't std::terminate the process (the pool used to).

Tests: cvcgl_state_publisher gains three guards — two scenes/one app (no collision),
rapid teardown-churn (join, no UAF), and pool-size-1/two-scenes (worker independent of
the pool). All 12 cvcGL tests pass; the demo renders and its console is quiet.
@transfix
transfix merged commit d038063 into master Aug 20, 2026
12 checks passed
@transfix
transfix deleted the feat/cvcgl-camera branch August 20, 2026 14:44
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