# UI

> Immediate-mode UI with flexbox-style layout, for game HUDs and full applications alike.

Kaigen's UI is immediate mode: you describe the whole UI every frame, in code, and there's no widget tree to keep in sync with your game. Layout is [Clay](https://github.com/nicbarker/clay) (rows, columns, grow, fit, padding, gaps: think flexbox), and the engine adds what games and tools need on top: SDF text in any size, rounded corners, shadows, gradients, blur, animation, scrolling, text input.

The same UI runs the game HUD, the editor, and Kaigen Studio itself.

A health panel in the top right:

```
ui_element({.id = ui_id("Health"),
            .floating = {.attach_to = UI_ATTACH_TO_ROOT,
                         .attach_points = {.element = UI_ATTACH_POINT_RIGHT_TOP,
                                           .parent = UI_ATTACH_POINT_RIGHT_TOP},
                         .offset = {-16, 16}},
            .layout = {.padding = ui_padding_all(12), .child_gap = 6,
                       .layout_direction = UI_TOP_TO_BOTTOM},
            .background_color = {0, 0, 0, 180},
            .corner_radius = ui_corner_radius(8)}) {
  ui_text(ui_str_c("HEALTH"),
          ui_text_config({.fontSize = 14, .textColor = {200, 200, 200, 255}}));
  // hp is 0..1
  ui_element({.layout = {.sizing = {ui_sizing_fixed(200 * hp), ui_sizing_fixed(10)}},
              .background_color = {230, 60, 50, 255}}) {}
}
```

## The frame

UI lives on the main lane. Build it after your ECS scope, between `ui_begin_frame` and `ui_finish_layout`, and the renderer draws it on top of the frame:

Where the UI goes:

```
if (is_main_thread()) {
  ui_begin_frame(ui, input, memory->dt);
  draw_hud(state);
  ui_finish_layout(ui);
}
lane_sync();
renderer_update(...);
```

Read your game's state for the UI from resources (`ecs_resource_get`). Don't change the world from inside UI code; write a request into a resource and let a system act on it.

## Interaction

Inside an element, `ui_interact(input)` tells you if it's hovered, pressed or clicked. `ui_interact_anim` gives the same with springy 0-to-1 values for hover and press animations. There are ready-made pieces for sliders, dropdowns, modals, scroll areas, tooltips, text fields and drag and drop, in `hz/src/engine/ui/`.

For in-world UI (name tags, prompts, damage numbers), see the `world_ui` [gameplay block](https://kaigen3d.com/docs/gameplay-blocks).

## Worth knowing

- Element ids must be unique in a frame. In a loop, use `ui_idi("Row", i)`.
- Text you pass to `ui_text` has to live until the frame is drawn. `ui_str_c` copies it for you; don't point at scratch memory you give back before the frame ends.
- Phones have notches. `os_get_safe_area()` gives you the insets.
- `--commands` can click UI by element id (`touch_move_to:Health`) or by the text it shows (`move_to_text:Play`), so you can script your menus.

The API is `hz/src/engine/ui/ui.h`.
