Skip to content

cvcGL: first-class Dear ImGui overlay — menus, panels, widgets (native + WebAssembly) - #214

Merged
transfix merged 6 commits into
masterfrom
feat/cvcgl-imgui
Aug 21, 2026
Merged

transfix merged 6 commits into
masterfrom
feat/cvcgl-imgui

Conversation

@transfix

Copy link
Copy Markdown
Owner

Adds cvc::gl::ImGuiOverlay: real UI in cvcGL — menu bars, panels, sliders, plots — from plain immediate-mode ImGui, in the same code path natively and in the browser.

cvc::gl::ImGuiOverlay ui(view);          // one object on a SceneRenderer, like FpsHud
ui.setDrawCallback([&]{
  if (ImGui::BeginMainMenuBar()) { /* ... */ ImGui::EndMainMenuBar(); }
  ImGui::Begin("Swarm");
  ImGui::SliderFloat("speed", &speed, 0.1f, 4.0f);
  ImGui::End();
});

The host loop is unchanged — no NewFrame/Render calls, no swap handling. The overlay draws inside VTK's own render, so it also lands in offscreen captures.

Verified

  • Native: lsystem_forest renders a menu bar + panel (slider, checkbox) over the island in an offscreen PNG.
  • WebAssembly: rebuilt against a wasm imgui and loaded in a browser — the ImGui menu bar and panel render over the scene (canvas pixel sampling: top strip 92% dark chrome + text glyphs). Zero #ifdef in the drawing path.

Two bugs found and fixed (both fail SILENTLY — worth knowing)

  1. Compositing: RenderDrawData must target vtkOpenGLRenderWindow::GetRenderFramebuffer(), bracketed by PushFramebufferBindings()/Pop. Drawing to whatever was bound put the UI nowhere — the callback ran every frame and produced no pixels, no error. Hook RenderEvent (scene drawn, not yet resolved); StartEvent is too early and EndEvent is after the result frame is copied out. On wasm the same chain ends at the WebGL default framebuffer (BlitToCurrent).
  2. Input: observe the interactor at priority 1.0, never the interactor style. vtkInteractorStyle::ProcessEvents is if (HandleObservers && HasObserver(evt)) InvokeEvent(evt) else OnMouseMove() — merely registering a style observer diverts every event into the observer branch permanently, so OnMouseMove/OnLeftButtonDown never run again and orbit/pan/zoom/fly would die the instant an overlay was constructed. Observing the interactor leaves the style untouched; the camera is suppressed only via the abort flag, and only while io.WantCaptureMouse/Keyboard — which is what makes clicking a widget not also orbit the scene.

Also: GL backend init is deferred to the first render (no current context at construction — that fails with "Failed to initialize OpenGL loader"), and io.DeltaTime is fed from vtkTimerLog (ImGui requires > 0).

Build

CVC_ENABLE_IMGUI (ON when found) locates the config-less cvcpkg imgui bundle by header/lib and compiles the stock imgui_impl_opengl3 backend — shipped as SOURCE in the bundle — into cvcGL, with IMGUI_IMPL_OPENGL_ES3 under Emscripten. Without imgui the class compiles to inert no-ops, so consumers need no #ifdef and existing builds are unaffected.

Requires libcvc-deps feat/imgui-wasm for the browser build (adds imgui's platform: wasm matrix entry; the published bundle is linux/BSD/macOS-only today).

The hook pattern follows Jaswant Panchumarti's vtkDearImGUIInjector (BSD-3) — this is a cvcGL-native reimplementation against SceneRenderer, not a vendored copy. Known upstream wasm limitation: mouse works, keyboard does not reach the browser build, so design UI to be mouse-drivable.

Follow-ups (not in this PR): state-bound widget wrappers (ui::SliderDouble("path", ...)) so UIs are scriptable/persistent like the rest of cvcGL, and attachCamera() to gate ImGui during Quake pointer-capture.

Phase 1 of first-class Dear ImGui in cvcGL — menus/panels/widgets from plain
immediate-mode code, one object on a SceneRenderer, same path native and wasm.

WORKING:
- cvc::gl::ImGuiOverlay (inc/cvc/gl/ImGuiOverlay.h + src/cvcGL/ImGuiOverlay.cpp):
  construct on a SceneRenderer, setDrawCallback([]{ ImGui::* }). Compiles to
  inert no-ops without CVC_ENABLE_IMGUI so consumers need no #ifdef.
- CMake: CVC_ENABLE_IMGUI gate that locates the config-less cvcpkg imgui bundle
  by header/lib and compiles the stock imgui_impl_opengl3 backend (shipped as
  SOURCE) into cvcGL; IMGUI_IMPL_OPENGL_ES3 under Emscripten. Verified:
  ImGui_ImplOpenGL3_Init + cvc::gl::ImGuiOverlay exported, libimgui.so NEEDED.
- Input: interceptor observers at priority 1.0 on the CURRENT interactor style
  (the vtkDearImGuiInjector pattern) so ImGui sits in FRONT of the style —
  CameraController keeps the single style slot and only stops seeing events when
  io.WantCaptureMouse/Keyboard is set.
- GL backend init deferred to the first render (VTK has no current context at
  construction — that failed with 'Failed to initialize OpenGL loader').
- io.DeltaTime is fed from vtkTimerLog (ImGui requires > 0).
- lsystem_forest grows a menu bar + panel as the end-to-end gate.

NOT WORKING YET: the draw callback runs every frame (verified via
CVC_IMGUI_DEBUG) but the UI does not appear in offscreen PNG captures — neither
on RenderEvent nor EndEvent. Prime suspect: in offscreen mode VTK renders into
its own FBO and the ImGui draw lands on a different/unbound framebuffer, so the
next step is binding vtkOpenGLRenderWindow's render framebuffer before
RenderDrawData (and testing the onscreen path, which may already work).
Phase 1 lands: Dear ImGui as a first-class cvcGL overlay. Construct one object
on a SceneRenderer, write plain immediate-mode ImGui in a callback:

    cvc::gl::ImGuiOverlay ui(view);
    ui.setDrawCallback([&]{ ImGui::Begin("Swarm"); ImGui::SliderFloat(...); ImGui::End(); });

Two bugs found and fixed against the first spike (both would have been silent):

1. COMPOSITING: RenderDrawData must target vtkOpenGLRenderWindow's OWN render
   framebuffer (bracketed by PushFramebufferBindings/Pop). Drawing to whatever
   was bound put the UI nowhere — the callback ran every frame and produced no
   pixels. At RenderEvent the scene is drawn but not yet resolved, so the UI
   composites on top in the window AND in offscreen captures. On wasm the same
   chain ends at the WebGL default framebuffer (BlitToCurrent) — no #ifdef in
   the draw path.
2. INPUT: observe the INTERACTOR at priority 1.0, never the interactor style.
   vtkInteractorStyle::ProcessEvents is
     if (HandleObservers && HasObserver(evt)) InvokeEvent(evt) else OnMouseMove()
   so merely REGISTERING an observer on the style diverts every event into the
   observer branch permanently — OnMouseMove/OnLeftButtonDown never run again and
   orbit/pan/zoom/fly would die the moment an overlay was constructed. Observing
   the interactor leaves the style untouched; the camera is suppressed only via
   the abort flag, and only while io.WantCaptureMouse/Keyboard.

Also: GL backend init deferred to the first render (no current context at
construction), io.DeltaTime fed from vtkTimerLog (ImGui requires > 0), and the
class compiles to inert no-ops without CVC_ENABLE_IMGUI so consumers need no
#ifdef. CMake locates the config-less cvcpkg imgui bundle by header/lib and
compiles the stock imgui_impl_opengl3 backend (shipped as source) into cvcGL,
with IMGUI_IMPL_OPENGL_ES3 under Emscripten.

Verified: lsystem_forest renders a menu bar + panel (slider, checkbox) over the
island in an offscreen capture.
cvc::gl::ui — ImGui widgets that read/write cvc::state instead of a local
variable, which is what makes a cvcGL UI SCRIPTABLE: a slider shows what a
script/config/peer set, and dragging it writes back for every observer to see.

    u::SliderDouble(app, "Move speed", prefix + ".camera.settings.move_speed", 1, 200);
    u::Combo(app, "Belief", "demo.swarm.belief", {"shared","grouped","private"});

Write policy matters: continuous widgets (slider/drag) edit a per-path cache and
commit ONLY on IsItemDeactivatedAfterEdit, so a drag is one state write instead
of sixty a second — state writes fan out to observers and replicated peers.
Discrete widgets (checkbox/menu item/combo) commit immediately. When not being
dragged the cache follows state, so external writes move the widget.

ImGuiOverlay::attachCamera(CameraController&) fixes two real input bugs:
 * while the camera holds POINTER CAPTURE (Quake fly warps the cursor to centre
   each frame) absolute mouse position is meaningless — the overlay stops
   consuming the mouse entirely instead of hit-testing garbage;
 * on the rising edge of WantCaptureKeyboard the camera's held keys are released
   (new CameraController::releaseHeldKeys()), so a key pressed before the UI took
   focus and released after it can't leave the camera drifting forever.

Both compile to inert no-ops without CVC_ENABLE_IMGUI.
…rotate

Mode::Map is a true 2-D map camera: parallel projection straight down, drag PANS
(pixel motion converted through the parallel scale so the grabbed point stays
under the cursor at any zoom), wheel ZOOMS the parallel scale, and rotation is
unreachable — toggleMode() refuses to leave Map, so Tab can't tumble the view
out of a map. frameMap(cx, cy, halfHeight) sets it up.

navdemo::set_ortho_topdown() takes an optional CameraController: pass it and the
ortho view becomes interactive the 2-D way; omit it (scripted captures) and the
camera is simply parked as before. All three nav demos pass it when not
capturing, so --ortho / --view map is now a real map you can pan and zoom but
never accidentally rotate.

Merges master (nav demos v2) into the ImGui branch so the overlay work builds on
the v2 demos.
…-D toggle

Menus (Sim / View / Camera) plus a control panel that drives everything:
- Sim: pause, step-one-frame, Restart, Restart with a new seed.
- View: 2-D map <-> 3-D perspective LIVE (the map is CameraController::Map, so
  it pans and zooms but cannot rotate), trails / goals / shadows toggles.
- Camera: look sensitivity + move speed as STATE-BOUND sliders (cvc::gl::ui), so
  a script or a peer moving those values moves the slider too.
- Panel: agent count, belief mode, fog, sim Hz, live agents/arrived/fps.

RESTART is a genuine rebuild, not a reset: agent count and belief mode are
constructor-time properties of sim_world, so the world is reconstructed and every
N-sized mesh (agent glyphs, goal pyramids, trail ring-buffer) is rebuilt with it.
The sim_thread is joined first — it borrows the world, so swapping the world
underneath a running worker would be a data race.

The demo's sim_world/sim_thread now live behind unique_ptrs for exactly that
reason. Verified: capture shows the panel over the running swarm; restart
rebuilds cleanly at new agent counts.
@transfix
transfix merged commit 62eba78 into master Aug 21, 2026
12 checks passed
@transfix
transfix deleted the feat/cvcgl-imgui branch August 21, 2026 21:07
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