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
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
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._implot_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 imgui-bundle is not installed.

        Example::

            app.start()
        """
        if not _HAS_IMGUI:
            _err = getattr(sys.modules[__name__], "_IMGUI_IMPORT_ERROR", "unknown")
            print(
                f"[BulletLab] UI disabled — required packages missing.\n"
                f"  Run:   pip install imgui-bundle glfw PyOpenGL\n"
                f"  Error: {_err}"
            )
            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

        # Create ImGui context and initialize the backend renderer.
        # imgui_bundle requires the context to be current before GlfwRenderer
        # builds its device objects (font atlas upload, shader compile).
        self._imgui_context = _imgui_bundle.create_context()
        _imgui_bundle.set_current_context(self._imgui_context)

        if _HAS_IMPLOT:
            self._implot_context = implot.create_context()
            implot.set_current_context(self._implot_context)

        try:
            self._apply_style()
        except Exception as _style_err:  # pragma: no cover
            import warnings
            warnings.warn(f"[BulletLab] Could not apply custom theme: {_style_err}")


        self._impl = _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()
        if self._implot_context is not None and _HAS_IMPLOT:
            implot.destroy_context(self._implot_context)
            self._implot_context = None
        self._window = None
        self._impl = None
        self._imgui_context = None

    def _set_window_icon(self, target_window: Any = None) -> 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.
        """
        target = target_window or self._window
        if target is None:
            return
        try:
            from PIL import Image
            from pathlib import Path

            # Search: next to this file, then from CWD, then from repo root
            candidates = [
                Path(__file__).parent.parent.parent / "docs" / "assets" / "logo.png",
                Path.cwd() / "docs" / "assets" / "logo.png",
            ]
            icon_path = next((p for p in candidates if p.exists()), None)
            if icon_path is None:
                print(f"[BulletLab] Window icon not found in {candidates[0]} or {candidates[1]}")
                return

            img = Image.open(icon_path).convert("RGBA").resize((64, 64), Image.LANCZOS)
            glfw.set_window_icon(target, 1, [img])
        except Exception as e:
            print(f"[BulletLab] Failed to set window icon: {e}")

    # ------------------------------------------------------------------
    # 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()

        # Tick the sequential console script runner (one statement per frame)
        if self._console is not None:
            self._console.tick()

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

        _imgui_bundle.new_frame()
        self._render_frame()
        _imgui_bundle.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_bundle.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_pos(imgui.ImVec2(0, menu_h))
        imgui.set_next_window_size(imgui.ImVec2(w, h - menu_h))
        imgui.begin(
            "##main",
            flags=(
                imgui.WindowFlags_.no_title_bar
                | imgui.WindowFlags_.no_resize
                | imgui.WindowFlags_.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.TreeNodeFlags_.default_open):
                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.TreeNodeFlags_.default_open):
                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.TreeNodeFlags_.default_open):
                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.TreeNodeFlags_.default_open):
                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.TreeNodeFlags_.default_open):
                imgui.indent(8)
                if _HAS_IMPLOT and self._implot_context is not None:
                    implot.set_current_context(self._implot_context)
                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.TreeNodeFlags_.default_open):
                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_bundle.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

        self._set_window_icon(self._console_window)

        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)

        # Create a *new* independent ImGui context for the console window.
        # imgui-bundle requires explicit context selection before GlfwRenderer
        # initialises its device objects.
        self._console_imgui_context = _imgui_bundle.create_context()
        _imgui_bundle.set_current_context(self._console_imgui_context)
        self._apply_style()
        self._console_impl = _GlfwRenderer(self._console_window)
        # imgui-bundle's GlfwRenderer.char_callback() calls imgui.get_io()
        # which resolves to the *current* context.  Event polling happens
        # while the main context is current, so we override the char callback
        # to switch context before forwarding — identical to the old behaviour.
        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.

        imgui-bundle's GlfwRenderer.char_callback() calls imgui.get_io() which
        resolves to whichever ImGui context is *current* at call time.  We must
        therefore switch to the console context before forwarding and restore
        the main context in the finally block.
        """
        if self._console_impl is None or self._console_imgui_context is None:
            return
        _imgui_bundle.set_current_context(self._console_imgui_context)
        try:
            self._console_impl.char_callback(window, codepoint)
        finally:
            if self._imgui_context is not None:
                _imgui_bundle.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_bundle.set_current_context(self._console_imgui_context)
        self._console_impl.process_inputs()
        _imgui_bundle.new_frame()

        width, height = glfw.get_window_size(self._console_window)
        imgui.set_next_window_pos(imgui.ImVec2(0, 0))
        imgui.set_next_window_size(imgui.ImVec2(width, height))
        imgui.begin(
            "##native_console_host",
            flags=(
                imgui.WindowFlags_.no_title_bar
                | imgui.WindowFlags_.no_resize
                | imgui.WindowFlags_.no_move
                | imgui.WindowFlags_.no_collapse
            ),
        )
        self._console.render_expanded()
        imgui.end()
        _imgui_bundle.render()

        gl.glClearColor(0.1, 0.1, 0.12, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        self._console_impl.render(_imgui_bundle.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_bundle.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_bundle.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.TreeNodeFlags_.default_open):
            imgui.indent(8)

            # ── Enable / disable toggle (capsule switch) ────────────────────
            from bulletlab.ui import widgets as _ui_widgets
            _ui_widgets.toggle_switch(
                "Dynamic Follow",
                getter=lambda: cam.enabled,
                setter=lambda v: setattr(cam, "enabled", v),
                color_on=(0.2, 0.85, 0.45, 1.0),
                color_off=(0.35, 0.35, 0.35, 1.0),
            )

            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(0, 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, sim=self._sim)

    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.

        Uses imgui.style_colors_dark() as a base, then overlays custom colours.
        Resilient to imgui-bundle version differences in the Style API.
        """
        from imgui_bundle import imgui as _bi
        from imgui_bundle import ImVec4, ImVec2

        # ── base dark theme ──────────────────────────────────────────────────
        _bi.style_colors_dark()

        style = _bi.get_style()

        # ── colour setter: tries every known API pattern ─────────────────────
        def _sc(col_idx: int, color: ImVec4) -> None:
            """Set one style colour, handling API differences across versions."""
            # imgui-bundle <= 1.4: style.colors is a mutable list
            try:
                style.colors[col_idx] = color
                return
            except (AttributeError, TypeError):
                pass
            # imgui-bundle with capital-C binding
            try:
                style.Colors[col_idx] = color  # type: ignore[index]
                return
            except (AttributeError, TypeError):
                pass
            # imgui-bundle 1.5+ method-based setter
            try:
                style.set_color_(col_idx, color)  # type: ignore[attr-defined]
                return
            except AttributeError:
                pass
            # Final fallback: push_style_color in the frame (handled by caller)

        # ── custom BulletLab colours ─────────────────────────────────────────
        _sc(_bi.Col_.window_bg.value,          ImVec4(0.10, 0.10, 0.13, 0.98))
        _sc(_bi.Col_.title_bg.value,           ImVec4(0.15, 0.15, 0.20, 1.0))
        _sc(_bi.Col_.title_bg_active.value,    ImVec4(0.20, 0.25, 0.35, 1.0))
        _sc(_bi.Col_.button.value,             ImVec4(0.20, 0.40, 0.65, 0.8))
        _sc(_bi.Col_.button_hovered.value,     ImVec4(0.30, 0.55, 0.80, 1.0))
        _sc(_bi.Col_.button_active.value,      ImVec4(0.15, 0.30, 0.55, 1.0))
        _sc(_bi.Col_.frame_bg.value,           ImVec4(0.18, 0.18, 0.22, 1.0))
        _sc(_bi.Col_.frame_bg_hovered.value,   ImVec4(0.22, 0.22, 0.28, 1.0))
        _sc(_bi.Col_.header.value,             ImVec4(0.20, 0.30, 0.45, 0.8))
        _sc(_bi.Col_.header_hovered.value,     ImVec4(0.25, 0.38, 0.55, 1.0))
        _sc(_bi.Col_.header_active.value,      ImVec4(0.15, 0.25, 0.40, 1.0))
        _sc(_bi.Col_.slider_grab.value,        ImVec4(0.40, 0.65, 0.90, 1.0))
        _sc(_bi.Col_.slider_grab_active.value, ImVec4(0.55, 0.80, 1.0,  1.0))
        _sc(_bi.Col_.check_mark.value,         ImVec4(0.40, 0.90, 0.40, 1.0))
        _sc(_bi.Col_.separator.value,          ImVec4(0.30, 0.30, 0.40, 1.0))
        _sc(_bi.Col_.menu_bar_bg.value,        ImVec4(0.12, 0.12, 0.16, 1.0))
        _sc(_bi.Col_.popup_bg.value,           ImVec4(0.12, 0.12, 0.16, 0.98))
        _sc(_bi.Col_.text.value,               ImVec4(0.90, 0.90, 0.95, 1.0))

        # ── sizing (these use named attributes, stable across versions) ───────
        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     = ImVec2(10.0, 8.0)
        style.frame_padding      = ImVec2(6.0,  4.0)
        style.item_spacing       = ImVec2(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 imgui-bundle 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 imgui-bundle is not installed.

    Example::

        app.start()
    """
    if not _HAS_IMGUI:
        _err = getattr(sys.modules[__name__], "_IMGUI_IMPORT_ERROR", "unknown")
        print(
            f"[BulletLab] UI disabled — required packages missing.\n"
            f"  Run:   pip install imgui-bundle glfw PyOpenGL\n"
            f"  Error: {_err}"
        )
        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

    # Create ImGui context and initialize the backend renderer.
    # imgui_bundle requires the context to be current before GlfwRenderer
    # builds its device objects (font atlas upload, shader compile).
    self._imgui_context = _imgui_bundle.create_context()
    _imgui_bundle.set_current_context(self._imgui_context)

    if _HAS_IMPLOT:
        self._implot_context = implot.create_context()
        implot.set_current_context(self._implot_context)

    try:
        self._apply_style()
    except Exception as _style_err:  # pragma: no cover
        import warnings
        warnings.warn(f"[BulletLab] Could not apply custom theme: {_style_err}")


    self._impl = _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()

    # Tick the sequential console script runner (one statement per frame)
    if self._console is not None:
        self._console.tick()

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

    _imgui_bundle.new_frame()
    self._render_frame()
    _imgui_bundle.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_bundle.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()
    if self._implot_context is not None and _HAS_IMPLOT:
        implot.destroy_context(self._implot_context)
        self._implot_context = None
    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.TreeNodeFlags_.default_open if default_open else 0
    result = imgui.collapsing_header(label, flags=flags)
    # compat wrapper returns (expanded, visible); plain imgui-bundle also returns bool
    return bool(result[0]) if isinstance(result, tuple) else bool(result)

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

joystick(label: str, on_x: 'Callable[[float], None] | None' = None, on_y: 'Callable[[float], None] | None' = None, snap: bool = True, size: int = 60, handle_color: 'tuple[float, float, float, float]' = (0.2, 0.6, 1.0, 1.0)) -> 'tuple[float, float]'

Render an interactive 2D virtual joystick inside any custom panel.

The joystick consists of a fixed outer ring and a smaller draggable handle. Both axes are reported as floats in [-1.0, 1.0] and the callbacks on_x / on_y are called every frame so that continuous commands (e.g. wheel velocities) keep firing even when the handle is held still.

Parameters:

Name Type Description Default
label str

Unique name for this joystick. Displayed as a label above the widget. Must be unique per panel if you have more than one joystick.

required
on_x 'Callable[[float], None] | None'

Callback receiving the X axis value in [-1, 1]. Positive X → right. Pass None to ignore X.

None
on_y 'Callable[[float], None] | None'

Callback receiving the Y axis value in [-1, 1]. Positive Y → up (handle dragged toward top of screen), which is the natural "forward" direction for a drive joystick. Pass None to ignore Y.

None
snap bool

If True (default) the handle jumps back to center when the mouse is released — the robot stops when you let go. If False the handle stays where it was dropped and keeps sending that command until you move it again (latching / cruise mode).

True
size int

Radius of the outer ring in pixels. The handle radius is size // 3.

60
handle_color 'tuple[float, float, float, float]'

RGBA color of the draggable handle as four floats in [0, 1]. Defaults to a vivid blue.

(0.2, 0.6, 1.0, 1.0)

Returns:

Type Description
'tuple[float, float]'

(x, y) — the current normalized axis values [-1, 1].

Examples::

# Differential drive rover — Y drives forward, X turns
@app.custom_panel("Drive")
def drive_panel():
    ui.joystick(
        "Rover Drive",
        on_x=lambda v: [setattr(robot.joints["wheel_left"],  "velocity", (-v) * 10),
                         setattr(robot.joints["wheel_right"], "velocity",   v  * 10)],
        on_y=lambda v: [setattr(robot.joints["wheel_left"],  "velocity", v * 10),
                        setattr(robot.joints["wheel_right"], "velocity", v * 10)],
    )

# Two independent joysticks in the same panel
@app.custom_panel("Arm Control")
def arm_panel():
    ui.joystick("Shoulder", on_y=lambda v: setattr(robot.joints["shoulder"], "velocity", v * 5))
    ui.same_line()
    ui.joystick("Elbow",    on_y=lambda v: setattr(robot.joints["elbow"],    "velocity", v * 5),
                handle_color=(1.0, 0.5, 0.1, 1.0))

# Latching joystick — keeps driving after you release
@app.custom_panel("Cruise")
def cruise_panel():
    ui.joystick("Cruise Drive", on_y=lambda v: setattr(robot.joints["drive"], "velocity", v * 8),
                snap=False, handle_color=(0.2, 0.9, 0.4, 1.0))
Source code in bulletlab/ui/widgets.py
def joystick(
    label: str,
    on_x: "Callable[[float], None] | None" = None,
    on_y: "Callable[[float], None] | None" = None,
    snap: bool = True,
    size: int = 60,
    handle_color: "tuple[float, float, float, float]" = (0.2, 0.6, 1.0, 1.0),
) -> "tuple[float, float]":
    """Render an interactive 2D virtual joystick inside any custom panel.

    The joystick consists of a fixed outer ring and a smaller draggable
    handle.  Both axes are reported as floats in ``[-1.0, 1.0]`` and the
    callbacks ``on_x`` / ``on_y`` are called **every frame** so that
    continuous commands (e.g. wheel velocities) keep firing even when the
    handle is held still.

    Args:
        label:        Unique name for this joystick. Displayed as a label
                      above the widget.  Must be unique per panel if you
                      have more than one joystick.
        on_x:         Callback receiving the X axis value in ``[-1, 1]``.
                      Positive X → right.  Pass ``None`` to ignore X.
        on_y:         Callback receiving the Y axis value in ``[-1, 1]``.
                      Positive Y → **up** (handle dragged toward top of
                      screen), which is the natural "forward" direction
                      for a drive joystick.  Pass ``None`` to ignore Y.
        snap:         If ``True`` (default) the handle jumps back to center
                      when the mouse is released — the robot stops when you
                      let go.  If ``False`` the handle stays where it was
                      dropped and keeps sending that command until you move
                      it again (latching / cruise mode).
        size:         Radius of the outer ring in pixels.  The handle radius
                      is ``size // 3``.
        handle_color: RGBA color of the draggable handle as four floats in
                      ``[0, 1]``.  Defaults to a vivid blue.

    Returns:
        ``(x, y)`` — the current normalized axis values ``[-1, 1]``.

    Examples::

        # Differential drive rover — Y drives forward, X turns
        @app.custom_panel("Drive")
        def drive_panel():
            ui.joystick(
                "Rover Drive",
                on_x=lambda v: [setattr(robot.joints["wheel_left"],  "velocity", (-v) * 10),
                                 setattr(robot.joints["wheel_right"], "velocity",   v  * 10)],
                on_y=lambda v: [setattr(robot.joints["wheel_left"],  "velocity", v * 10),
                                setattr(robot.joints["wheel_right"], "velocity", v * 10)],
            )

        # Two independent joysticks in the same panel
        @app.custom_panel("Arm Control")
        def arm_panel():
            ui.joystick("Shoulder", on_y=lambda v: setattr(robot.joints["shoulder"], "velocity", v * 5))
            ui.same_line()
            ui.joystick("Elbow",    on_y=lambda v: setattr(robot.joints["elbow"],    "velocity", v * 5),
                        handle_color=(1.0, 0.5, 0.1, 1.0))

        # Latching joystick — keeps driving after you release
        @app.custom_panel("Cruise")
        def cruise_panel():
            ui.joystick("Cruise Drive", on_y=lambda v: setattr(robot.joints["drive"], "velocity", v * 8),
                        snap=False, handle_color=(0.2, 0.9, 0.4, 1.0))
    """
    if not _check_imgui():
        return (0.0, 0.0)

    # ── Initialise per-joystick state ────────────────────────────────────────
    if label not in _joystick_state:
        _joystick_state[label] = [0.0, 0.0]   # [handle_x_px, handle_y_px]
    state = _joystick_state[label]

    handle_r = max(8, size // 3)

    # ── Draw label ───────────────────────────────────────────────────────────
    imgui.text(label)

    # ── Invisible interaction button (full bounding box) ─────────────────────
    btn_size = (size * 2 + 4, size * 2 + 4)
    _pos = imgui.get_cursor_screen_pos()
    cursor_x, cursor_y = _pos.x, _pos.y
    imgui.invisible_button(f"##jstk_{label}", imgui.ImVec2(float(btn_size[0]), float(btn_size[1])))

    is_active  = imgui.is_item_active()
    is_hovered = imgui.is_item_hovered()

    center_x = cursor_x + size + 2
    center_y = cursor_y + size + 2

    # ── Handle drag ──────────────────────────────────────────────────────────
    if is_active:
        io = imgui.get_io()
        dx = io.mouse_delta[0]
        dy = io.mouse_delta[1]
        state[0] += dx
        state[1] += dy
        # Constrain handle to stay within the outer ring
        dist = (state[0] ** 2 + state[1] ** 2) ** 0.5
        max_r = float(size - handle_r)
        if dist > max_r and dist > 0:
            scale = max_r / dist
            state[0] *= scale
            state[1] *= scale
    elif snap:
        # Smooth snap-back: lerp toward center (instant for now, looks fine)
        state[0] = 0.0
        state[1] = 0.0

    # ── Normalise to [-1, 1] ─────────────────────────────────────────────────
    max_r = float(size - handle_r)
    norm_x =  state[0] / max_r if max_r > 0 else 0.0
    norm_y = -state[1] / max_r if max_r > 0 else 0.0  # flip Y: up = positive

    norm_x = max(-1.0, min(1.0, norm_x))
    norm_y = max(-1.0, min(1.0, norm_y))

    # ── Fire callbacks every frame ───────────────────────────────────────────
    if on_x is not None:
        on_x(norm_x)
    if on_y is not None:
        on_y(norm_y)

    # ── Draw ─────────────────────────────────────────────────────────────────
    draw = imgui.get_window_draw_list()

    # Outer ring background
    ring_bg_col = imgui.get_color_u32(imgui.ImVec4(0.15, 0.15, 0.15, 0.85)) if not is_hovered \
                  else imgui.get_color_u32(imgui.ImVec4(0.2,  0.2,  0.2,  0.9))
    draw.add_circle_filled(imgui.ImVec2(center_x, center_y), float(size), ring_bg_col, 64)

    # Outer ring border
    border_col = imgui.get_color_u32(imgui.ImVec4(0.5, 0.5, 0.5, 0.7)) if not is_active \
                 else imgui.get_color_u32(imgui.ImVec4(0.8, 0.8, 0.8, 1.0))
    draw.add_circle(imgui.ImVec2(center_x, center_y), float(size), border_col, 64, 2.0)

    # Cross-hair lines (subtle guide)
    guide_col = imgui.get_color_u32(imgui.ImVec4(0.4, 0.4, 0.4, 0.4))
    draw.add_line(imgui.ImVec2(center_x - size + 4, center_y), imgui.ImVec2(center_x + size - 4, center_y), guide_col, 1.0)
    draw.add_line(imgui.ImVec2(center_x, center_y - size + 4), imgui.ImVec2(center_x, center_y + size - 4), guide_col, 1.0)

    # Handle
    hx = center_x + state[0]
    hy = center_y + state[1]
    r, g, b, a = handle_color
    h_col      = imgui.get_color_u32(imgui.ImVec4(r, g, b, a))
    h_col_dark = imgui.get_color_u32(imgui.ImVec4(r * 0.6, g * 0.6, b * 0.6, a))
    draw.add_circle_filled(imgui.ImVec2(hx, hy), float(handle_r), h_col, 32)
    draw.add_circle(imgui.ImVec2(hx, hy), float(handle_r), h_col_dark, 32, 1.5)

    return (norm_x, norm_y)

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', highlight: bool = False) -> 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",
    highlight: bool = False,
) -> 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)

    if highlight:
        imgui.push_style_color(imgui.Col_.slider_grab, imgui.ImVec4(0.9, 0.2, 0.2, 1.0))
        imgui.push_style_color(imgui.Col_.slider_grab_active, imgui.ImVec4(1.0, 0.3, 0.3, 1.0))

    changed, new_val = imgui.slider_float(label, current, min_val, max_val, fmt)

    if highlight:
        imgui.pop_style_color(2)

    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))

toggle_switch(label: str, getter: 'Callable[[], bool] | bool', setter: 'Callable[[bool], None] | None' = None, color_on: 'tuple[float, float, float, float]' = (0.2, 0.75, 1.0, 1.0), color_off: 'tuple[float, float, float, float]' = (0.3, 0.3, 0.3, 1.0), width: int = 44, height: int = 22) -> bool

Render a capsule-shaped toggle switch with a sliding handle.

The capsule is grayed out when False and lit up in color_on when True. The inner circle glides between the left and right sides. A text label is rendered to the right of the switch.

Follows the same getter / setter pattern as all other BulletLab widgets, so state can live in any Python variable.

Parameters:

Name Type Description Default
label str

Text label shown to the right of the switch.

required
getter 'Callable[[], bool] | bool'

Current state (bool) or a callable that returns it.

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

Called with the new state when clicked.

None
color_on 'tuple[float, float, float, float]'

RGBA color of the capsule when the switch is True.

(0.2, 0.75, 1.0, 1.0)
color_off 'tuple[float, float, float, float]'

RGBA color of the capsule when the switch is False.

(0.3, 0.3, 0.3, 1.0)
width int

Total width of the capsule in pixels.

44
height int

Height of the capsule in pixels (also the diameter of the handle).

22

Returns:

Type Description
bool

Current state (True / False) after this frame.

Example::

# Simple one-liner — state lives in a list cell
ui.toggle_switch("Autopilot", lambda: autopilot_on[0],
                 setter=lambda v: autopilot_on.__setitem__(0, v))

# Or compose it yourself
toggled = ui.toggle_switch("Motors", lambda: motors_on)
if toggled != motors_on:
    motors_on = toggled
    apply_motors(motors_on)
Source code in bulletlab/ui/widgets.py
def toggle_switch(
    label: str,
    getter: "Callable[[], bool] | bool",
    setter: "Callable[[bool], None] | None" = None,
    color_on:  "tuple[float, float, float, float]" = (0.2, 0.75, 1.0, 1.0),
    color_off: "tuple[float, float, float, float]" = (0.3, 0.3, 0.3, 1.0),
    width: int = 44,
    height: int = 22,
) -> bool:
    """Render a capsule-shaped toggle switch with a sliding handle.

    The capsule is **grayed out** when ``False`` and **lit up** in ``color_on``
    when ``True``.  The inner circle glides between the left and right sides.
    A text label is rendered to the right of the switch.

    Follows the same getter / setter pattern as all other BulletLab widgets,
    so state can live in any Python variable.

    Args:
        label:     Text label shown to the right of the switch.
        getter:    Current state (``bool``) or a callable that returns it.
        setter:    Called with the new state when clicked.
        color_on:  RGBA color of the capsule when the switch is ``True``.
        color_off: RGBA color of the capsule when the switch is ``False``.
        width:     Total width of the capsule in pixels.
        height:    Height of the capsule in pixels (also the diameter of the handle).

    Returns:
        Current state (``True`` / ``False``) after this frame.

    Example::

        # Simple one-liner — state lives in a list cell
        ui.toggle_switch("Autopilot", lambda: autopilot_on[0],
                         setter=lambda v: autopilot_on.__setitem__(0, v))

        # Or compose it yourself
        toggled = ui.toggle_switch("Motors", lambda: motors_on)
        if toggled != motors_on:
            motors_on = toggled
            apply_motors(motors_on)
    """
    if not _check_imgui():
        return bool(getter() if callable(getter) else getter)

    current = bool(getter() if callable(getter) else getter)

    # ── Geometry ─────────────────────────────────────────────────────────────
    radius   = height / 2.0
    handle_r = radius - 2.0
    padding  = 2.0

    # ── Invisible hit-box (covers just the capsule) ───────────────────────────
    _pos = imgui.get_cursor_screen_pos()
    cursor_x, cursor_y = _pos.x, _pos.y
    imgui.invisible_button(f"##tgsw_{label}", imgui.ImVec2(float(width), float(height)))
    clicked = imgui.is_item_clicked(0)

    new_val = current
    if clicked:
        new_val = not current
        if setter is not None:
            setter(new_val)

    # ── Draw capsule background ───────────────────────────────────────────────
    draw = imgui.get_window_draw_list()

    bg_r, bg_g, bg_b, bg_a = color_on if new_val else color_off
    # Darken slightly when off to look naturally inactive
    if not new_val:
        bg_r, bg_g, bg_b = bg_r * 0.8, bg_g * 0.8, bg_b * 0.8

    bg_col = imgui.get_color_u32(imgui.ImVec4(bg_r, bg_g, bg_b, bg_a))
    x0 = cursor_x
    y0 = cursor_y
    x1 = cursor_x + width
    y1 = cursor_y + height
    draw.add_rect_filled(imgui.ImVec2(x0, y0), imgui.ImVec2(x1, y1), bg_col, radius)

    # Subtle border
    border_alpha = 0.6 if new_val else 0.3
    border_col = imgui.get_color_u32(imgui.ImVec4(1.0, 1.0, 1.0, border_alpha))
    draw.add_rect(imgui.ImVec2(x0, y0), imgui.ImVec2(x1, y1), border_col, rounding=radius)

    # ── Draw sliding circle ───────────────────────────────────────────────────
    handle_x = (cursor_x + width - radius - padding) if new_val \
               else (cursor_x + radius + padding)
    handle_y = cursor_y + radius
    handle_col = imgui.get_color_u32(imgui.ImVec4(1.0, 1.0, 1.0, 1.0))
    shadow_col = imgui.get_color_u32(imgui.ImVec4(0.0, 0.0, 0.0, 0.25))
    # Tiny shadow
    draw.add_circle_filled(imgui.ImVec2(handle_x + 1, handle_y + 1), handle_r, shadow_col, 20)
    draw.add_circle_filled(imgui.ImVec2(handle_x, handle_y), handle_r, handle_col, 20)

    # ── Label to the right ────────────────────────────────────────────────────
    imgui.same_line()
    imgui.set_cursor_pos_y(imgui.get_cursor_pos_y() + (height - imgui.get_font_size()) * 0.5)
    imgui.text(label)

    return new_val

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()