Skip to content

BulletLabUI API

Main ImGui control window for BulletLab.

Opens a GLFW + OpenGL window with Dear ImGui. Provides five built-in panels (Explorer, Properties, Telemetry, Console, Plots) and allows registering custom panels via :meth:custom_panel decorator or :meth:register_panel.

Parameters:

Name Type Description Default
sim 'Simulation'

The :class:~bulletlab.core.simulation.Simulation instance.

required
robots list['Robot'] | None

List of robots to display in the UI.

None
telemetry 'TelemetryManager | None'

Optional :class:~bulletlab.telemetry.manager.TelemetryManager.

None
width int

Initial window width in pixels.

600
height int

Initial window height in pixels.

800
title str

Window title.

'BulletLab'

Example::

app = BulletLabUI(sim=sim, robots=[robot], telemetry=telemetry)
app.run()
Source code in bulletlab/ui/app.py
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
class BulletLabUI:
    """Main ImGui control window for BulletLab.

    Opens a GLFW + OpenGL window with Dear ImGui. Provides five built-in
    panels (Explorer, Properties, Telemetry, Console, Plots) and allows
    registering custom panels via :meth:`custom_panel` decorator or
    :meth:`register_panel`.

    Args:
        sim: The :class:`~bulletlab.core.simulation.Simulation` instance.
        robots: List of robots to display in the UI.
        telemetry: Optional :class:`~bulletlab.telemetry.manager.TelemetryManager`.
        width: Initial window width in pixels.
        height: Initial window height in pixels.
        title: Window title.

    Example::

        app = BulletLabUI(sim=sim, robots=[robot], telemetry=telemetry)
        app.run()
    """

    def __init__(
        self,
        sim: "Simulation",
        robots: list["Robot"] | None = None,
        telemetry: "TelemetryManager | None" = None,
        camera: "Any | None" = None,
        highlighter: "Any | None" = None,
        width: int = 600,
        height: int = 800,
        title: str = "BulletLab",
    ) -> None:
        self._sim = sim
        self._robots: list["Robot"] = list(robots or [])
        self._telemetry = telemetry
        self._camera = camera          # CameraFollow instance (optional)
        self._highlighter = highlighter  # RobotHighlighter instance (optional)
        self._width = width
        self._height = height
        self._title = title

        self._window: Any = None
        self._impl: Any = None
        self._imgui_context: Any = None
        self._console_window: Any = None
        self._console_impl: Any = None
        self._console_imgui_context: Any = None
        self._running = False
        self._should_close = False

        # Built-in panels
        self._explorer: ExplorerPanel | None = None
        self._properties: PropertiesPanel | None = None
        self._telemetry_panel: TelemetryPanel | None = None
        self._console: ConsolePanel | None = None
        self._plots_panel: PlotsPanel | None = None

        # Custom panels
        self._custom_panels: list[_CustomPanel] = []

        # Panel visibility flags
        self._show_explorer = True
        self._show_properties = True
        self._show_telemetry = True
        self._show_console = True
        self._show_plots = True

    # ------------------------------------------------------------------
    # Lifecycle
    # ------------------------------------------------------------------

    def start(self) -> "BulletLabUI":
        """Initialize the GLFW window and ImGui context.

        Returns:
            self, for method chaining.

        Raises:
            ImportError: If pyimgui[glfw] or glfw is not installed.

        Example::

            app.start()
        """
        if not _HAS_IMGUI:
            print(
                f"[BulletLab] UI disabled: pyimgui[glfw] not available.\n"
                f"  Install with: pip install imgui[glfw]\n"
                f"  Error: {getattr(sys.modules[__name__], '_IMGUI_IMPORT_ERROR', 'unknown')}"
            )
            return self

        if self._running:
            return self

        # Init GLFW
        if not glfw.init():
            raise RuntimeError("GLFW initialization failed.")

        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)

        self._window = glfw.create_window(
            self._width, self._height, self._title, None, None
        )
        if not self._window:
            glfw.terminate()
            raise RuntimeError("Failed to create GLFW window.")

        # Set window icon from assets/logo.png
        self._set_window_icon()

        glfw.make_context_current(self._window)
        glfw.swap_interval(1)  # vsync

        # Style ImGui
        self._imgui_context = imgui.create_context()
        self._apply_style()

        self._impl = imgui_glfw.GlfwRenderer(self._window)

        # Build panels
        self._build_panels()
        self._running = True
        return self

    def stop(self) -> None:
        """Shut down the ImGui window and free GLFW resources.

        Example::

            app.stop()
        """
        if not self._running:
            return
        self._running = False
        self._close_console_window()
        if self._impl is not None:
            self._restore_main_context()
            self._impl.shutdown()
        if self._window is not None and glfw is not None:
            glfw.destroy_window(self._window)
            glfw.terminate()
        self._window = None
        self._impl = None
        self._imgui_context = None

    def _set_window_icon(self) -> None:
        """Load assets/logo.png and set it as the GLFW window icon.

        Silently skips if Pillow is not installed or the file is missing.
        The icon is displayed in the OS taskbar and the window title bar.
        """
        try:
            from PIL import Image
            import numpy as np
            from pathlib import Path

            # Search: next to this file, then from CWD, then from repo root
            candidates = [
                Path(__file__).parent.parent.parent / "assets" / "logo.png",
                Path.cwd() / "assets" / "logo.png",
            ]
            icon_path = next((p for p in candidates if p.exists()), None)
            if icon_path is None:
                return

            img = Image.open(icon_path).convert("RGBA").resize((64, 64), Image.LANCZOS)
            pixels = np.array(img, dtype=np.uint8)
            glfw.set_window_icon(self._window, 1, [pixels])
        except Exception:
            pass   # non-fatal — icon is cosmetic only

    # ------------------------------------------------------------------
    # Main loops
    # ------------------------------------------------------------------

    def run(self) -> None:
        """Start the BulletLabUI event loop (blocking).

        This loop runs until the window is closed. For non-blocking usage,
        call :meth:`start` and then :meth:`step` in your own simulation loop.

        Example::

            app.run()
        """
        self.start()
        if not _HAS_IMGUI or not self._running:
            return

        while not glfw.window_should_close(self._window):
            self.step()

        self.stop()

    def step(self) -> None:
        """Render one ImGui frame.

        Call this once per simulation step in your own loop.

        Example::

            while True:
                sim.step()
                telemetry.update(t=sim.elapsed_time)
                app.step()
                if app.should_close:
                    break
        """
        if not _HAS_IMGUI or not self._running:
            return

        if glfw.window_should_close(self._window):
            self._should_close = True
            return

        self._restore_main_context()
        glfw.poll_events()
        self._impl.process_inputs()

        # Highlighter: reset pending hover before the frame renders
        if self._highlighter is not None:
            self._highlighter.begin_frame()

        imgui.new_frame()
        self._render_frame()
        imgui.render()

        # Highlighter: commit pending hover → update 3D colours
        if self._highlighter is not None:
            self._highlighter.end_frame()

        gl.glClearColor(0.1, 0.1, 0.12, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        self._impl.render(imgui.get_draw_data())
        glfw.swap_buffers(self._window)
        self._render_console_window()

    @property
    def should_close(self) -> bool:
        """``True`` if the UI window has been closed by the user."""
        return self._should_close

    # ------------------------------------------------------------------
    # Frame rendering
    # ------------------------------------------------------------------

    def _render_frame(self) -> None:
        """Render all panels inside a single full-screen ImGui window."""
        self._render_main_menu()

        w, h = glfw.get_window_size(self._window)
        menu_h = 20  # approx height of the main menu bar

        # One full-screen, non-movable, non-resizable window that fills the
        # entire GLFW client area below the menu bar.
        imgui.set_next_window_position(0, menu_h)
        imgui.set_next_window_size(w, h - menu_h)
        imgui.begin(
            "##main",
            flags=(
                imgui.WINDOW_NO_TITLE_BAR
                | imgui.WINDOW_NO_RESIZE
                | imgui.WINDOW_NO_MOVE
            ),
        )

        # ── Camera panel (shown first when a CameraFollow is registered) ──────
        self._render_camera_panel()

        # ── Custom panels (shown next so they're immediately visible) ────────
        for cp in self._custom_panels:
            label = cp.title
            if imgui.collapsing_header(label, flags=imgui.TREE_NODE_DEFAULT_OPEN)[0]:
                imgui.indent(8)
                cp.render_fn()
                imgui.unindent(8)
            imgui.spacing()

        # ── Built-in panels ──────────────────────────────────────────────────
        if self._show_explorer and self._explorer is not None:
            if imgui.collapsing_header("Explorer", flags=imgui.TREE_NODE_DEFAULT_OPEN)[0]:
                imgui.indent(8)
                self._explorer.render()
                imgui.unindent(8)
            imgui.spacing()

        if self._show_properties and self._properties is not None:
            if self._explorer is not None:
                self._properties.set_target(self._explorer.selected_object)
            if imgui.collapsing_header("Properties", flags=imgui.TREE_NODE_DEFAULT_OPEN)[0]:
                imgui.indent(8)
                self._properties.render()
                imgui.unindent(8)
            imgui.spacing()

        if self._show_telemetry and self._telemetry_panel is not None:
            if imgui.collapsing_header("Telemetry", flags=imgui.TREE_NODE_DEFAULT_OPEN)[0]:
                imgui.indent(8)
                self._telemetry_panel.render()
                imgui.unindent(8)
            imgui.spacing()

        if self._show_plots and self._plots_panel is not None:
            if imgui.collapsing_header("Live Plots", flags=imgui.TREE_NODE_DEFAULT_OPEN)[0]:
                imgui.indent(8)
                self._plots_panel.render()
                imgui.unindent(8)
            imgui.spacing()

        if self._show_console and self._console is not None:
            if imgui.collapsing_header("Console", flags=imgui.TREE_NODE_DEFAULT_OPEN)[0]:
                imgui.indent(8)
                self._console.render()
                imgui.unindent(8)
            imgui.spacing()

        imgui.end()

    # ------------------------------------------------------------------
    # Native console window
    # ------------------------------------------------------------------

    def _restore_main_context(self) -> None:
        """Make the main GLFW and ImGui contexts current."""
        if self._window is not None:
            glfw.make_context_current(self._window)
        if self._imgui_context is not None:
            imgui.set_current_context(self._imgui_context)

    def _open_console_window(self) -> bool:
        """Create the separate native window used by the expanded console."""
        if self._console_window is not None:
            return True

        self._console_window = glfw.create_window(
            900, 650, "BulletLab Console", None, self._window
        )
        if not self._console_window:
            self._console_window = None
            if self._console is not None:
                self._console.log("Could not create the separate console window.")
                self._console.collapse()
            self._restore_main_context()
            return False

        main_x, main_y = glfw.get_window_pos(self._window)
        glfw.set_window_pos(self._console_window, main_x + 80, main_y + 80)
        glfw.make_context_current(self._console_window)
        glfw.swap_interval(1)

        self._console_imgui_context = imgui.create_context()
        # ImGui only makes a newly created context current when no context
        # already exists. Select it explicitly before the renderer builds its
        # device objects and font atlas.
        imgui.set_current_context(self._console_imgui_context)
        self._apply_style()
        self._console_impl = imgui_glfw.GlfwRenderer(self._console_window)
        # pyimgui's GLFW character callback looks up the current global ImGui
        # context. Event polling happens while the main context is current, so
        # route text input explicitly to the console context.
        glfw.set_char_callback(
            self._console_window,
            self._console_char_callback,
        )
        self._restore_main_context()
        return True

    def _console_char_callback(self, window: Any, codepoint: int) -> None:
        """Route native console text input to its own ImGui context."""
        if self._console_impl is None or self._console_imgui_context is None:
            return
        imgui.set_current_context(self._console_imgui_context)
        try:
            self._console_impl.char_callback(window, codepoint)
        finally:
            if self._imgui_context is not None:
                imgui.set_current_context(self._imgui_context)

    def _render_console_window(self) -> None:
        """Render one frame of the expanded console's native window."""
        if self._console is None or not self._console.is_expanded:
            self._close_console_window()
            return

        if not self._open_console_window():
            return

        if glfw.window_should_close(self._console_window):
            self._console.collapse()
            self._close_console_window()
            return

        glfw.make_context_current(self._console_window)
        imgui.set_current_context(self._console_imgui_context)
        self._console_impl.process_inputs()
        imgui.new_frame()

        width, height = glfw.get_window_size(self._console_window)
        imgui.set_next_window_position(0, 0)
        imgui.set_next_window_size(width, height)
        imgui.begin(
            "##native_console_host",
            flags=(
                imgui.WINDOW_NO_TITLE_BAR
                | imgui.WINDOW_NO_RESIZE
                | imgui.WINDOW_NO_MOVE
                | imgui.WINDOW_NO_COLLAPSE
            ),
        )
        self._console.render_expanded()
        imgui.end()
        imgui.render()

        gl.glClearColor(0.1, 0.1, 0.12, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        self._console_impl.render(imgui.get_draw_data())
        glfw.swap_buffers(self._console_window)

        if not self._console.is_expanded:
            self._close_console_window()
        else:
            self._restore_main_context()

    def _close_console_window(self) -> None:
        """Destroy the native console window and its ImGui resources."""
        if self._console_window is None:
            return

        glfw.make_context_current(self._console_window)
        if self._console_imgui_context is not None:
            imgui.set_current_context(self._console_imgui_context)
        if self._console_impl is not None:
            self._console_impl.shutdown()
        if self._console_imgui_context is not None:
            imgui.destroy_context(self._console_imgui_context)
        glfw.destroy_window(self._console_window)

        self._console_window = None
        self._console_impl = None
        self._console_imgui_context = None
        self._restore_main_context()

    def _render_camera_panel(self) -> None:
        """Render the built-in Camera Follow control panel.

        Only visible when a :class:`~bulletlab.core.camera.CameraFollow`
        was passed to the constructor via ``camera=``.
        """
        if self._camera is None:
            return

        cam = self._camera
        if imgui.collapsing_header("Camera", flags=imgui.TREE_NODE_DEFAULT_OPEN)[0]:
            imgui.indent(8)

            # ── Enable / disable toggle ─────────────────────────────────────
            changed, new_val = imgui.checkbox("Dynamic Follow", cam.enabled)
            if changed:
                cam.enabled = new_val
            imgui.same_line(spacing=12)
            status = "ON" if cam.enabled else "OFF"
            color  = (0.3, 0.9, 0.4, 1.0) if cam.enabled else (0.6, 0.6, 0.6, 1.0)
            imgui.text_colored(f"[{status}]", *color)

            if cam.enabled:
                imgui.spacing()

                # ── Mode label ──────────────────────────────────────────────
                imgui.text(f"Mode:  {cam.mode}")

                # ── Distance slider ──────────────────────────────────────────
                changed, val = imgui.slider_float(
                    "Distance", cam.distance, 1.0, 20.0, "%.1f m"
                )
                if changed:
                    cam.distance = val

                # ── Lerp / smoothness slider ─────────────────────────────────
                if cam.mode in ("smooth", "chase"):
                    changed, val = imgui.slider_float(
                        "Smoothness", 1.0 - cam.lerp, 0.0, 0.99, "%.2f"
                    )
                    if changed:
                        cam.lerp = 1.0 - val   # invert: high = smoother

                # ── Pitch slider ─────────────────────────────────────────────
                changed, val = imgui.slider_float(
                    "Pitch", cam.pitch, -89.0, 0.0, "%.0f°"
                )
                if changed:
                    cam.pitch = val

            imgui.unindent(8)
        imgui.spacing()

    def _render_main_menu(self) -> None:
        """Render the main menu bar."""
        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("View"):
                _, self._show_explorer = imgui.menu_item(
                    "Explorer", selected=self._show_explorer
                )
                _, self._show_properties = imgui.menu_item(
                    "Properties", selected=self._show_properties
                )
                _, self._show_telemetry = imgui.menu_item(
                    "Telemetry", selected=self._show_telemetry
                )
                _, self._show_plots = imgui.menu_item(
                    "Plots", selected=self._show_plots
                )
                _, self._show_console = imgui.menu_item(
                    "Console", selected=self._show_console
                )
                imgui.end_menu()

            if imgui.begin_menu("Simulation"):
                if imgui.menu_item("Pause")[0] and not self._sim.is_paused:
                    self._sim.pause()
                if imgui.menu_item("Resume")[0] and self._sim.is_paused:
                    self._sim.resume()
                if imgui.menu_item("Reset")[0]:
                    self._sim.reset()
                imgui.end_menu()

            # Status bar
            sim_status = "⏸ Paused" if self._sim.is_paused else "▶ Running"
            imgui.same_line(spacing=20)
            imgui.text(
                f"  {sim_status}  |  "
                f"Step: {self._sim.step_count}  |  "
                f"t={self._sim.elapsed_time:.2f}s  |  "
                f"Robots: {len(self._robots)}"
            )

            imgui.end_main_menu_bar()

    # ------------------------------------------------------------------
    # Panel management
    # ------------------------------------------------------------------

    def _build_panels(self) -> None:
        """Instantiate all built-in panels."""
        self._explorer = ExplorerPanel(
            sim=self._sim,
            robots=self._robots,
            highlighter=self._highlighter,
        )
        self._properties = PropertiesPanel(highlighter=self._highlighter)

        if self._telemetry is not None:
            self._telemetry_panel = TelemetryPanel(self._telemetry)
            self._plots_panel = PlotsPanel(self._telemetry)
        else:
            # Create empty telemetry so panels render gracefully
            from bulletlab.telemetry import TelemetryManager
            _empty = TelemetryManager()
            self._telemetry_panel = TelemetryPanel(_empty)
            self._plots_panel = PlotsPanel(_empty)

        ns = {"sim": self._sim}
        for i, r in enumerate(self._robots):
            ns[r.name] = r
            if i == 0:
                ns["robot"] = r
        if self._telemetry is not None:
            ns["telemetry"] = self._telemetry
        self._console = ConsolePanel(namespace=ns)

    def register_panel(self, title: str, render_fn: Callable[[], None]) -> None:
        """Register a custom panel.

        Args:
            title: Panel window title.
            render_fn: Function that renders the panel content using
                ``bulletlab.ui.widgets`` or raw imgui calls.

        Example::

            def my_controls():
                ui.button("Reset", robot.reset)
                ui.slider("Speed", lambda: target_speed, 0, 20,
                          setter=lambda v: set_target_speed(v))

            app.register_panel("My Controls", my_controls)
        """
        self._custom_panels.append(_CustomPanel(title=title, render_fn=render_fn))

    def custom_panel(self, title: str) -> Callable[[Callable[[], None]], Callable[[], None]]:
        """Decorator for registering a custom panel.

        Args:
            title: Panel window title.

        Returns:
            Decorator that registers the function as a panel.

        Example::

            @app.custom_panel("My Controls")
            def my_controls():
                ui.button("Reset", robot.reset)
        """
        def decorator(fn: Callable[[], None]) -> Callable[[], None]:
            self.register_panel(title, fn)
            return fn
        return decorator

    def add_robot(self, robot: "Robot") -> None:
        """Add a robot to the UI (explorer and console namespace).

        Args:
            robot: The robot to add.
        """
        if robot not in self._robots:
            self._robots.append(robot)
        if self._explorer is not None:
            self._explorer.add_robot(robot)
        if self._console is not None:
            self._console.update_namespace({robot.name: robot, "robot": robot})

    # ------------------------------------------------------------------
    # Styling
    # ------------------------------------------------------------------

    def _apply_style(self) -> None:
        """Apply a dark, modern ImGui theme."""
        style = imgui.get_style()

        # Colors
        style.colors[imgui.COLOR_WINDOW_BACKGROUND] = (0.10, 0.10, 0.13, 0.98)
        style.colors[imgui.COLOR_TITLE_BACKGROUND] = (0.15, 0.15, 0.20, 1.0)
        style.colors[imgui.COLOR_TITLE_BACKGROUND_ACTIVE] = (0.20, 0.25, 0.35, 1.0)
        style.colors[imgui.COLOR_BUTTON] = (0.20, 0.40, 0.65, 0.8)
        style.colors[imgui.COLOR_BUTTON_HOVERED] = (0.30, 0.55, 0.80, 1.0)
        style.colors[imgui.COLOR_BUTTON_ACTIVE] = (0.15, 0.30, 0.55, 1.0)
        style.colors[imgui.COLOR_FRAME_BACKGROUND] = (0.18, 0.18, 0.22, 1.0)
        style.colors[imgui.COLOR_FRAME_BACKGROUND_HOVERED] = (0.22, 0.22, 0.28, 1.0)
        style.colors[imgui.COLOR_HEADER] = (0.20, 0.30, 0.45, 0.8)
        style.colors[imgui.COLOR_HEADER_HOVERED] = (0.25, 0.38, 0.55, 1.0)
        style.colors[imgui.COLOR_HEADER_ACTIVE] = (0.15, 0.25, 0.40, 1.0)
        style.colors[imgui.COLOR_SLIDER_GRAB] = (0.40, 0.65, 0.90, 1.0)
        style.colors[imgui.COLOR_SLIDER_GRAB_ACTIVE] = (0.55, 0.80, 1.0, 1.0)
        style.colors[imgui.COLOR_CHECK_MARK] = (0.40, 0.90, 0.40, 1.0)
        style.colors[imgui.COLOR_SEPARATOR] = (0.30, 0.30, 0.40, 1.0)
        style.colors[imgui.COLOR_MENUBAR_BACKGROUND] = (0.12, 0.12, 0.16, 1.0)
        style.colors[imgui.COLOR_POPUP_BACKGROUND] = (0.12, 0.12, 0.16, 0.98)
        style.colors[imgui.COLOR_TEXT] = (0.90, 0.90, 0.95, 1.0)

        # Sizing
        style.window_rounding = 6.0
        style.frame_rounding = 4.0
        style.scrollbar_rounding = 4.0
        style.grab_rounding = 4.0
        style.tab_rounding = 4.0
        style.window_padding = (10.0, 8.0)
        style.frame_padding = (6.0, 4.0)
        style.item_spacing = (8.0, 6.0)

    # ------------------------------------------------------------------
    # Repr
    # ------------------------------------------------------------------

    def __repr__(self) -> str:
        status = "running" if self._running else "stopped"
        return f"BulletLabUI({self._title!r}, {status})"

should_close: bool property

True if the UI window has been closed by the user.

add_robot(robot: 'Robot') -> None

Add a robot to the UI (explorer and console namespace).

Parameters:

Name Type Description Default
robot 'Robot'

The robot to add.

required
Source code in bulletlab/ui/app.py
def add_robot(self, robot: "Robot") -> None:
    """Add a robot to the UI (explorer and console namespace).

    Args:
        robot: The robot to add.
    """
    if robot not in self._robots:
        self._robots.append(robot)
    if self._explorer is not None:
        self._explorer.add_robot(robot)
    if self._console is not None:
        self._console.update_namespace({robot.name: robot, "robot": robot})

custom_panel(title: str) -> Callable[[Callable[[], None]], Callable[[], None]]

Decorator for registering a custom panel.

Parameters:

Name Type Description Default
title str

Panel window title.

required

Returns:

Type Description
Callable[[Callable[[], None]], Callable[[], None]]

Decorator that registers the function as a panel.

Example::

@app.custom_panel("My Controls")
def my_controls():
    ui.button("Reset", robot.reset)
Source code in bulletlab/ui/app.py
def custom_panel(self, title: str) -> Callable[[Callable[[], None]], Callable[[], None]]:
    """Decorator for registering a custom panel.

    Args:
        title: Panel window title.

    Returns:
        Decorator that registers the function as a panel.

    Example::

        @app.custom_panel("My Controls")
        def my_controls():
            ui.button("Reset", robot.reset)
    """
    def decorator(fn: Callable[[], None]) -> Callable[[], None]:
        self.register_panel(title, fn)
        return fn
    return decorator

register_panel(title: str, render_fn: Callable[[], None]) -> None

Register a custom panel.

Parameters:

Name Type Description Default
title str

Panel window title.

required
render_fn Callable[[], None]

Function that renders the panel content using bulletlab.ui.widgets or raw imgui calls.

required

Example::

def my_controls():
    ui.button("Reset", robot.reset)
    ui.slider("Speed", lambda: target_speed, 0, 20,
              setter=lambda v: set_target_speed(v))

app.register_panel("My Controls", my_controls)
Source code in bulletlab/ui/app.py
def register_panel(self, title: str, render_fn: Callable[[], None]) -> None:
    """Register a custom panel.

    Args:
        title: Panel window title.
        render_fn: Function that renders the panel content using
            ``bulletlab.ui.widgets`` or raw imgui calls.

    Example::

        def my_controls():
            ui.button("Reset", robot.reset)
            ui.slider("Speed", lambda: target_speed, 0, 20,
                      setter=lambda v: set_target_speed(v))

        app.register_panel("My Controls", my_controls)
    """
    self._custom_panels.append(_CustomPanel(title=title, render_fn=render_fn))

run() -> None

Start the BulletLabUI event loop (blocking).

This loop runs until the window is closed. For non-blocking usage, call :meth:start and then :meth:step in your own simulation loop.

Example::

app.run()
Source code in bulletlab/ui/app.py
def run(self) -> None:
    """Start the BulletLabUI event loop (blocking).

    This loop runs until the window is closed. For non-blocking usage,
    call :meth:`start` and then :meth:`step` in your own simulation loop.

    Example::

        app.run()
    """
    self.start()
    if not _HAS_IMGUI or not self._running:
        return

    while not glfw.window_should_close(self._window):
        self.step()

    self.stop()

start() -> 'BulletLabUI'

Initialize the GLFW window and ImGui context.

Returns:

Type Description
'BulletLabUI'

self, for method chaining.

Raises:

Type Description
ImportError

If pyimgui[glfw] or glfw is not installed.

Example::

app.start()
Source code in bulletlab/ui/app.py
def start(self) -> "BulletLabUI":
    """Initialize the GLFW window and ImGui context.

    Returns:
        self, for method chaining.

    Raises:
        ImportError: If pyimgui[glfw] or glfw is not installed.

    Example::

        app.start()
    """
    if not _HAS_IMGUI:
        print(
            f"[BulletLab] UI disabled: pyimgui[glfw] not available.\n"
            f"  Install with: pip install imgui[glfw]\n"
            f"  Error: {getattr(sys.modules[__name__], '_IMGUI_IMPORT_ERROR', 'unknown')}"
        )
        return self

    if self._running:
        return self

    # Init GLFW
    if not glfw.init():
        raise RuntimeError("GLFW initialization failed.")

    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)

    self._window = glfw.create_window(
        self._width, self._height, self._title, None, None
    )
    if not self._window:
        glfw.terminate()
        raise RuntimeError("Failed to create GLFW window.")

    # Set window icon from assets/logo.png
    self._set_window_icon()

    glfw.make_context_current(self._window)
    glfw.swap_interval(1)  # vsync

    # Style ImGui
    self._imgui_context = imgui.create_context()
    self._apply_style()

    self._impl = imgui_glfw.GlfwRenderer(self._window)

    # Build panels
    self._build_panels()
    self._running = True
    return self

step() -> None

Render one ImGui frame.

Call this once per simulation step in your own loop.

Example::

while True:
    sim.step()
    telemetry.update(t=sim.elapsed_time)
    app.step()
    if app.should_close:
        break
Source code in bulletlab/ui/app.py
def step(self) -> None:
    """Render one ImGui frame.

    Call this once per simulation step in your own loop.

    Example::

        while True:
            sim.step()
            telemetry.update(t=sim.elapsed_time)
            app.step()
            if app.should_close:
                break
    """
    if not _HAS_IMGUI or not self._running:
        return

    if glfw.window_should_close(self._window):
        self._should_close = True
        return

    self._restore_main_context()
    glfw.poll_events()
    self._impl.process_inputs()

    # Highlighter: reset pending hover before the frame renders
    if self._highlighter is not None:
        self._highlighter.begin_frame()

    imgui.new_frame()
    self._render_frame()
    imgui.render()

    # Highlighter: commit pending hover → update 3D colours
    if self._highlighter is not None:
        self._highlighter.end_frame()

    gl.glClearColor(0.1, 0.1, 0.12, 1.0)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
    self._impl.render(imgui.get_draw_data())
    glfw.swap_buffers(self._window)
    self._render_console_window()

stop() -> None

Shut down the ImGui window and free GLFW resources.

Example::

app.stop()
Source code in bulletlab/ui/app.py
def stop(self) -> None:
    """Shut down the ImGui window and free GLFW resources.

    Example::

        app.stop()
    """
    if not self._running:
        return
    self._running = False
    self._close_console_window()
    if self._impl is not None:
        self._restore_main_context()
        self._impl.shutdown()
    if self._window is not None and glfw is not None:
        glfw.destroy_window(self._window)
        glfw.terminate()
    self._window = None
    self._impl = None
    self._imgui_context = None

Widget Helpers

Widget helper functions for building BulletLab custom panels.

Provides a minimal, boilerplate-free API for common ImGui widgets. All functions must be called from within an ImGui window context (i.e., between imgui.begin() and imgui.end()).

Example::

from bulletlab.ui import widgets as ui

@app.custom_panel("My Controls")
def my_panel():
    ui.button("Reset", robot.reset)
    ui.slider("Wheel Mass", robot.links["wheel"].mass, 0.1, 20,
              setter=lambda v: setattr(robot.links["wheel"], "mass", v))
    ui.checkbox("Motors On", lambda: motors_on,
                setter=lambda v: set_motors(v))
    ui.text("Speed", f"{robot.speed:.2f} m/s")

button(label: str, callback: Callable[[], Any] | None = None) -> bool

Render a clickable button.

Parameters:

Name Type Description Default
label str

Button text label.

required
callback Callable[[], Any] | None

Function to call when the button is clicked.

None

Returns:

Type Description
bool

True if the button was clicked this frame.

Example::

ui.button("Reset Robot", robot.reset)
Source code in bulletlab/ui/widgets.py
def button(label: str, callback: Callable[[], Any] | None = None) -> bool:
    """Render a clickable button.

    Args:
        label: Button text label.
        callback: Function to call when the button is clicked.

    Returns:
        ``True`` if the button was clicked this frame.

    Example::

        ui.button("Reset Robot", robot.reset)
    """
    if not _check_imgui():
        return False
    clicked = imgui.button(label)
    if clicked and callback is not None:
        callback()
    return clicked

checkbox(label: str, getter: Callable[[], bool] | bool, setter: Callable[[bool], None] | None = None) -> bool

Render a checkbox.

Parameters:

Name Type Description Default
label str

Widget label.

required
getter Callable[[], bool] | bool

Current state or callable returning current state.

required
setter Callable[[bool], None] | None

Called with the new state when toggled.

None

Returns:

Type Description
bool

Current checkbox state.

Example::

ui.checkbox("Motors Enabled", lambda: motors_on,
            setter=lambda v: set_motors(v))
Source code in bulletlab/ui/widgets.py
def checkbox(
    label: str,
    getter: Callable[[], bool] | bool,
    setter: Callable[[bool], None] | None = None,
) -> bool:
    """Render a checkbox.

    Args:
        label: Widget label.
        getter: Current state or callable returning current state.
        setter: Called with the new state when toggled.

    Returns:
        Current checkbox state.

    Example::

        ui.checkbox("Motors Enabled", lambda: motors_on,
                    setter=lambda v: set_motors(v))
    """
    if not _check_imgui():
        return False
    current = bool(getter()) if callable(getter) else bool(getter)
    changed, new_val = imgui.checkbox(label, current)
    if changed and setter is not None:
        setter(bool(new_val))
    return bool(new_val) if changed else current

collapsing_header(label: str, default_open: bool = True) -> bool

Render a collapsible section header.

Parameters:

Name Type Description Default
label str

Section title.

required
default_open bool

Whether the section starts expanded.

True

Returns:

Type Description
bool

True if the section is currently expanded.

Example::

if ui.collapsing_header("Physics Parameters"):
    ui.drag_float("Mass", ...)
Source code in bulletlab/ui/widgets.py
def collapsing_header(label: str, default_open: bool = True) -> bool:
    """Render a collapsible section header.

    Args:
        label: Section title.
        default_open: Whether the section starts expanded.

    Returns:
        ``True`` if the section is currently expanded.

    Example::

        if ui.collapsing_header("Physics Parameters"):
            ui.drag_float("Mass", ...)
    """
    if not _check_imgui():
        return True
    flags = imgui.TREE_NODE_DEFAULT_OPEN if default_open else 0
    return imgui.collapsing_header(label, flags=flags)

color_edit(label: str, getter: Callable[[], tuple[float, float, float]] | tuple[float, float, float], setter: Callable[[tuple[float, float, float]], None] | None = None) -> tuple[float, float, float]

Render an RGB color picker.

Parameters:

Name Type Description Default
label str

Widget label.

required
getter Callable[[], tuple[float, float, float]] | tuple[float, float, float]

Current color (r, g, b) normalized to [0, 1] or callable.

required
setter Callable[[tuple[float, float, float]], None] | None

Called with the new color when changed.

None

Returns:

Type Description
tuple[float, float, float]

Current color (r, g, b).

Example::

ui.color_edit("Light Color", lambda: color, setter=lambda c: set_color(c))
Source code in bulletlab/ui/widgets.py
def color_edit(
    label: str,
    getter: Callable[[], tuple[float, float, float]] | tuple[float, float, float],
    setter: Callable[[tuple[float, float, float]], None] | None = None,
) -> tuple[float, float, float]:
    """Render an RGB color picker.

    Args:
        label: Widget label.
        getter: Current color ``(r, g, b)`` normalized to [0, 1] or callable.
        setter: Called with the new color when changed.

    Returns:
        Current color ``(r, g, b)``.

    Example::

        ui.color_edit("Light Color", lambda: color, setter=lambda c: set_color(c))
    """
    if not _check_imgui():
        return (1.0, 1.0, 1.0)
    current = tuple(getter()) if callable(getter) else tuple(getter)
    r, g, b = float(current[0]), float(current[1]), float(current[2])
    changed, (nr, ng, nb) = imgui.color_edit3(label, r, g, b)
    result = (float(nr), float(ng), float(nb))
    if changed and setter is not None:
        setter(result)
    return result if changed else (r, g, b)

combo(label: str, items: list[str], getter: Callable[[], int] | int, setter: Callable[[int], None] | None = None) -> int

Render a dropdown combo box.

Parameters:

Name Type Description Default
label str

Widget label.

required
items list[str]

List of selectable items.

required
getter Callable[[], int] | int

Current selected index or callable.

required
setter Callable[[int], None] | None

Called with new index when changed.

None

Returns:

Type Description
int

Current selected index.

Example::

ui.combo("Mode", ["Velocity", "Position", "Torque"], lambda: mode_idx,
         setter=lambda i: set_mode(i))
Source code in bulletlab/ui/widgets.py
def combo(
    label: str,
    items: list[str],
    getter: Callable[[], int] | int,
    setter: Callable[[int], None] | None = None,
) -> int:
    """Render a dropdown combo box.

    Args:
        label: Widget label.
        items: List of selectable items.
        getter: Current selected index or callable.
        setter: Called with new index when changed.

    Returns:
        Current selected index.

    Example::

        ui.combo("Mode", ["Velocity", "Position", "Torque"], lambda: mode_idx,
                 setter=lambda i: set_mode(i))
    """
    if not _check_imgui():
        return 0
    current = int(getter()) if callable(getter) else int(getter)
    changed, new_idx = imgui.combo(label, current, items)
    if changed and setter is not None:
        setter(int(new_idx))
    return int(new_idx) if changed else current

drag_float(label: str, getter: Callable[[], float] | float, setter: Callable[[float], None] | None = None, speed: float = 0.1, min_val: float = 0.0, max_val: float = 0.0, fmt: str = '%.3f') -> float

Render a drag-to-edit float field.

Parameters:

Name Type Description Default
label str

Widget label.

required
getter Callable[[], float] | float

Current value or callable returning current value.

required
setter Callable[[float], None] | None

Called with the new value when changed.

None
speed float

Drag sensitivity.

0.1
min_val float

Minimum value (0 = no clamp).

0.0
max_val float

Maximum value (0 = no clamp).

0.0
fmt str

Printf format string for display.

'%.3f'

Returns:

Type Description
float

Current value.

Example::

ui.drag_float("Mass", lambda: link.mass, setter=lambda v: setattr(link, "mass", v))
Source code in bulletlab/ui/widgets.py
def drag_float(
    label: str,
    getter: Callable[[], float] | float,
    setter: Callable[[float], None] | None = None,
    speed: float = 0.1,
    min_val: float = 0.0,
    max_val: float = 0.0,
    fmt: str = "%.3f",
) -> float:
    """Render a drag-to-edit float field.

    Args:
        label: Widget label.
        getter: Current value or callable returning current value.
        setter: Called with the new value when changed.
        speed: Drag sensitivity.
        min_val: Minimum value (0 = no clamp).
        max_val: Maximum value (0 = no clamp).
        fmt: Printf format string for display.

    Returns:
        Current value.

    Example::

        ui.drag_float("Mass", lambda: link.mass, setter=lambda v: setattr(link, "mass", v))
    """
    if not _check_imgui():
        return 0.0
    current = float(getter()) if callable(getter) else float(getter)
    changed, new_val = imgui.drag_float(label, current, speed, min_val, max_val, fmt)
    if changed and setter is not None:
        setter(float(new_val))
    return float(new_val) if changed else current

input_float(label: str, getter: Callable[[], float] | float, setter: Callable[[float], None] | None = None, step: float = 0.1, fmt: str = '%.3f') -> float

Render a float input field.

Parameters:

Name Type Description Default
label str

Widget label.

required
getter Callable[[], float] | float

Current value or callable.

required
setter Callable[[float], None] | None

Called with the new value when committed.

None
step float

Increment step for +/- buttons.

0.1
fmt str

Display format string.

'%.3f'

Returns:

Type Description
float

Current value.

Example::

ui.input_float("Friction", lambda: link.friction,
               setter=lambda v: setattr(link, "friction", v))
Source code in bulletlab/ui/widgets.py
def input_float(
    label: str,
    getter: Callable[[], float] | float,
    setter: Callable[[float], None] | None = None,
    step: float = 0.1,
    fmt: str = "%.3f",
) -> float:
    """Render a float input field.

    Args:
        label: Widget label.
        getter: Current value or callable.
        setter: Called with the new value when committed.
        step: Increment step for +/- buttons.
        fmt: Display format string.

    Returns:
        Current value.

    Example::

        ui.input_float("Friction", lambda: link.friction,
                       setter=lambda v: setattr(link, "friction", v))
    """
    if not _check_imgui():
        return 0.0
    current = float(getter()) if callable(getter) else float(getter)
    changed, new_val = imgui.input_float(label, current, step, step * 10, fmt)
    if changed and setter is not None:
        setter(float(new_val))
    return float(new_val) if changed else current

same_line() -> None

Place the next widget on the same line.

Source code in bulletlab/ui/widgets.py
def same_line() -> None:
    """Place the next widget on the same line."""
    if _check_imgui():
        imgui.same_line()

separator(label: str = '') -> None

Render a horizontal separator, optionally with a label.

Parameters:

Name Type Description Default
label str

Optional section label.

''

Example::

ui.separator("Physics")
Source code in bulletlab/ui/widgets.py
def separator(label: str = "") -> None:
    """Render a horizontal separator, optionally with a label.

    Args:
        label: Optional section label.

    Example::

        ui.separator("Physics")
    """
    if not _check_imgui():
        return
    imgui.separator()
    if label:
        imgui.text(label)

slider(label: str, getter: Callable[[], float] | float, min_val: float, max_val: float, setter: Callable[[float], None] | None = None, fmt: str = '%.3f') -> float

Render a float slider.

Parameters:

Name Type Description Default
label str

Widget label.

required
getter Callable[[], float] | float

Current value or a callable returning the current value.

required
min_val float

Minimum value.

required
max_val float

Maximum value.

required
setter Callable[[float], None] | None

Called with the new value when the slider changes.

None
fmt str

Printf format string for display.

'%.3f'

Returns:

Type Description
float

Current slider value.

Example::

ui.slider("Wheel Mass", lambda: robot.links["wheel"].mass, 0.1, 20,
          setter=lambda v: setattr(robot.links["wheel"], "mass", v))
Source code in bulletlab/ui/widgets.py
def slider(
    label: str,
    getter: Callable[[], float] | float,
    min_val: float,
    max_val: float,
    setter: Callable[[float], None] | None = None,
    fmt: str = "%.3f",
) -> float:
    """Render a float slider.

    Args:
        label: Widget label.
        getter: Current value or a callable returning the current value.
        min_val: Minimum value.
        max_val: Maximum value.
        setter: Called with the new value when the slider changes.
        fmt: Printf format string for display.

    Returns:
        Current slider value.

    Example::

        ui.slider("Wheel Mass", lambda: robot.links["wheel"].mass, 0.1, 20,
                  setter=lambda v: setattr(robot.links["wheel"], "mass", v))
    """
    if not _check_imgui():
        return 0.0
    current = float(getter()) if callable(getter) else float(getter)
    changed, new_val = imgui.slider_float(label, current, min_val, max_val, fmt)
    if changed and setter is not None:
        setter(float(new_val))
    return float(new_val) if changed else current

text(label: str, value: Any = '') -> None

Render a read-only text label with an optional value.

Parameters:

Name Type Description Default
label str

Field label.

required
value Any

Value to display (converted to string).

''

Example::

ui.text("Speed", f"{robot.speed:.2f} m/s")
Source code in bulletlab/ui/widgets.py
def text(label: str, value: Any = "") -> None:
    """Render a read-only text label with an optional value.

    Args:
        label: Field label.
        value: Value to display (converted to string).

    Example::

        ui.text("Speed", f"{robot.speed:.2f} m/s")
    """
    if not _check_imgui():
        return
    if value != "":
        imgui.text(f"{label}: {value}")
    else:
        imgui.text(str(label))

tooltip(text_str: str) -> None

Show a tooltip when the previous widget is hovered.

Parameters:

Name Type Description Default
text_str str

Tooltip text.

required

Example::

ui.drag_float("Mass", ...)
ui.tooltip("Mass of the link in kilograms")
Source code in bulletlab/ui/widgets.py
def tooltip(text_str: str) -> None:
    """Show a tooltip when the previous widget is hovered.

    Args:
        text_str: Tooltip text.

    Example::

        ui.drag_float("Mass", ...)
        ui.tooltip("Mass of the link in kilograms")
    """
    if not _check_imgui():
        return
    if imgui.is_item_hovered():
        imgui.begin_tooltip()
        imgui.text(text_str)
        imgui.end_tooltip()