nightshade-api 0.48.0

Procedural high level API for the nightshade game engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
//! Retained UI: panels anchored to the window that stack their children,
//! themed buttons, and labels, with click and hover queries. These build on the
//! same retained UI tree as [`spawn_text`](crate::prelude::spawn_text).

use crate::text::ScreenAnchor;
use crate::text::ui_root;
use nightshade::ecs::ui::layout_types::FlowDirection;
use nightshade::ecs::ui::units::UiValue;
use nightshade::prelude::*;

/// Turns on immediate-mode egui (requires the `egui` feature). Call it from
/// setup, then draw each frame by pulling the frame's context with
/// [`egui_context`](crate::prelude::egui_context) from your update closure or
/// any system. `egui` and `egui_context` are re-exported from the prelude.
///
/// ```ignore
/// run(
///     |world| { enable_egui(world); spawn_cube(world, vec3(0.0, 0.5, 0.0)) },
///     |world, cube| {
///         if let Some(ctx) = egui_context(world) {
///             egui::Window::new("Inspector").show(&ctx, |ui| ui.label(format!("{cube:?}")));
///         }
///     },
/// )
/// .unwrap();
/// ```
#[cfg(feature = "egui")]
pub fn enable_egui(world: &mut World) {
    world.resources.egui.enabled = true;
}

/// Spawns an empty panel anchored to a window corner or the center, sized in
/// pixels. It has a themed translucent background and stacks whatever you add to
/// it from top to bottom. Fill it with [`panel_button`] and [`panel_label`].
pub fn spawn_panel(world: &mut World, anchor: ScreenAnchor, width: f32, height: f32) -> Entity {
    let root = ui_root(world);
    let (position, anchor_kind) = panel_anchor(anchor);
    let panel = {
        let mut tree = UiTreeBuilder::from_parent(world, root);
        tree.add_node()
            .window(position, Ab(vec2(width, height)), anchor_kind)
            .with_rect(8.0, 1.0, Vec4::new(1.0, 1.0, 1.0, 0.1))
            .color_raw::<UiBase>(Vec4::new(0.05, 0.05, 0.08, 0.85))
            .flow(FlowDirection::Vertical, 12.0, 8.0)
            .entity()
    };
    ui_mark_render_dirty(world);
    panel
}

/// Adds a themed button to a panel and returns it. Poll it every frame with
/// [`button_clicked`].
pub fn panel_button(world: &mut World, panel: Entity, text: &str) -> Entity {
    let button = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_button(text)
    };
    ui_mark_render_dirty(world);
    button
}

/// Adds a line of text to a panel and returns it. Update it with
/// [`set_text`](crate::prelude::set_text) and restyle it with
/// [`set_text_color`](crate::prelude::set_text_color) and
/// [`set_text_size`](crate::prelude::set_text_size).
pub fn panel_label(world: &mut World, panel: Entity, text: &str) -> Entity {
    let label = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_node()
            .flow_child(Rl(vec2(100.0, 0.0)) + Ab(vec2(0.0, 24.0)))
            .with_text(text, 18.0)
            .color_raw::<UiBase>(Vec4::new(1.0, 1.0, 1.0, 1.0))
            .entity()
    };
    ui_mark_render_dirty(world);
    label
}

/// Adds a labeled checkbox to a panel and returns it. Read it with
/// [`checkbox_value`].
pub fn panel_checkbox(world: &mut World, panel: Entity, label: &str, initial: bool) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_checkbox(label, initial)
    };
    ui_mark_render_dirty(world);
    entity
}

/// The checkbox's current on or off value.
#[inline]
pub fn checkbox_value(world: &World, checkbox: Entity) -> bool {
    ui_checkbox_value(world, checkbox).unwrap_or(false)
}

/// Adds a slider from `min` to `max` starting at `initial` to a panel. Read it
/// with [`slider_value`], set it with [`set_slider_value`].
pub fn panel_slider(world: &mut World, panel: Entity, min: f32, max: f32, initial: f32) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_slider(min, max, initial)
    };
    ui_mark_render_dirty(world);
    entity
}

/// The slider's current value.
#[inline]
pub fn slider_value(world: &World, slider: Entity) -> f32 {
    ui_slider_value(world, slider).unwrap_or(0.0)
}

/// Sets the slider's value.
pub fn set_slider_value(world: &mut World, slider: Entity, value: f32) {
    ui_slider_set_value(world, slider, value);
    ui_mark_render_dirty(world);
}

/// Adds a single line text input with grey `placeholder` text to a panel. Read
/// edits with [`text_input_changed`].
pub fn panel_text_input(world: &mut World, panel: Entity, placeholder: &str) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_text_input(placeholder)
    };
    ui_mark_render_dirty(world);
    entity
}

/// The input's new contents if it changed this frame, else `None`.
#[inline]
pub fn text_input_changed(world: &World, input: Entity) -> Option<String> {
    ui_text_input_changed(world, input).map(str::to_string)
}

/// Adds a dropdown of `options` with `initial` selected to a panel. Read it with
/// [`dropdown_selected`].
pub fn panel_dropdown(
    world: &mut World,
    panel: Entity,
    options: &[&str],
    initial: usize,
) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_dropdown(options, initial)
    };
    ui_mark_render_dirty(world);
    entity
}

/// The newly chosen index if the dropdown selection changed this frame.
#[inline]
pub fn dropdown_selected(world: &World, dropdown: Entity) -> Option<usize> {
    ui_dropdown_selected_changed(world, dropdown)
}

/// Adds a progress bar filled to `initial` (0.0 to 1.0) to a panel. Update it
/// with [`set_progress`].
pub fn panel_progress_bar(world: &mut World, panel: Entity, initial: f32) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_progress_bar(initial)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Sets a progress bar's fill, 0.0 to 1.0.
pub fn set_progress(world: &mut World, bar: Entity, value: f32) {
    ui_progress_bar_set_value(world, bar, value);
    ui_mark_render_dirty(world);
}

/// Adds an on or off toggle starting at `initial` to a panel. Read it with
/// [`toggle_value`].
pub fn panel_toggle(world: &mut World, panel: Entity, initial: bool) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_toggle(initial)
    };
    ui_mark_render_dirty(world);
    entity
}

/// The toggle's current on or off value.
#[inline]
pub fn toggle_value(world: &World, toggle: Entity) -> bool {
    ui_toggle_value(world, toggle).unwrap_or(false)
}

/// Adds a radio button to a panel, one option of a group identified by
/// `group_id`. Radios sharing a group are mutually exclusive. Read the group's
/// choice with [`radio_selected`].
pub fn panel_radio(
    world: &mut World,
    panel: Entity,
    label: &str,
    group_id: u32,
    option_index: usize,
) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_radio(label, group_id, option_index)
    };
    ui_mark_render_dirty(world);
    entity
}

/// The selected option index of a radio group, if any option is selected.
#[inline]
pub fn radio_selected(world: &World, group_id: u32) -> Option<usize> {
    ui_radio_group_value(world, group_id)
}

/// Adds a dual-handle range slider to a panel, selecting a span from `low` to
/// `high` within `min` and `max`. Set both handles with [`set_range`].
pub fn panel_range_slider(
    world: &mut World,
    panel: Entity,
    min: f32,
    max: f32,
    low: f32,
    high: f32,
) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_range_slider(min, max, low, high)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Sets both handles of a range slider.
pub fn set_range(world: &mut World, slider: Entity, low: f32, high: f32) {
    ui_range_slider_set_values(world, slider, low, high);
    ui_mark_render_dirty(world);
}

/// Adds a tab bar of `labels` to a panel with `initial` selected. Switch the
/// active tab with [`set_tab`].
pub fn panel_tabs(world: &mut World, panel: Entity, labels: &[&str], initial: usize) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_tab_bar(labels, initial)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Selects a tab bar's active tab by index.
pub fn set_tab(world: &mut World, tabs: Entity, index: usize) {
    ui_tab_bar_set_value(world, tabs, index);
    ui_mark_render_dirty(world);
}

/// Adds a collapsing section titled `label` to a panel and returns its content
/// container. Add child widgets to the returned entity; they hide and show as
/// the header is toggled.
pub fn panel_collapsing(world: &mut World, panel: Entity, label: &str, open: bool) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_collapsing_header(label, open)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Adds a color picker to a panel starting at `initial` linear RGBA. Read the
/// chosen color with [`color_value`].
pub fn panel_color_picker(world: &mut World, panel: Entity, initial: [f32; 4]) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_color_picker(Vec4::new(initial[0], initial[1], initial[2], initial[3]))
    };
    ui_mark_render_dirty(world);
    entity
}

/// The color picker's current color as linear RGBA.
pub fn color_value(world: &World, picker: Entity) -> [f32; 4] {
    ui_color_picker_color(world, picker)
        .map(|color| [color.x, color.y, color.z, color.w])
        .unwrap_or([1.0, 1.0, 1.0, 1.0])
}

/// Whether the button was clicked this frame, a press and release on the same
/// button. Poll this every frame.
#[inline]
pub fn button_clicked(world: &World, button: Entity) -> bool {
    ui_clicked(world, button)
}

/// Whether the pointer is currently over the button.
#[inline]
pub fn button_hovered(world: &World, button: Entity) -> bool {
    world
        .ui
        .get_ui_node_interaction(button)
        .is_some_and(|interaction| interaction.hovered)
}

/// Removes a panel and everything in it.
#[inline]
pub fn despawn_panel(world: &mut World, panel: Entity) {
    despawn_recursive_immediate(world, panel);
    ui_mark_render_dirty(world);
}

/// Adds a horizontal row to a panel and returns it. Widgets added to the row
/// lay out left to right instead of the panel's top to bottom stacking, which is
/// how you put a label next to a value or a run of buttons on one line.
pub fn panel_row(world: &mut World, panel: Entity, height: f32) -> Entity {
    let row = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_node()
            .flow_child(Rl(vec2(100.0, 0.0)) + Ab(vec2(0.0, height)))
            .flow(FlowDirection::Horizontal, 0.0, 8.0)
            .entity()
    };
    ui_mark_render_dirty(world);
    row
}

/// Adds a fixed-column grid to a panel and returns it. Children flow into
/// `columns` cells of `row_height`, wrapping to a new row as they fill, for
/// inventory grids, palettes, and icon sheets.
pub fn panel_grid(
    world: &mut World,
    panel: Entity,
    columns: usize,
    row_height: f32,
    height: f32,
) -> Entity {
    let grid = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_node()
            .flow_child(Rl(vec2(100.0, 0.0)) + Ab(vec2(0.0, height)))
            .grid(columns, row_height, 0.0, 8.0, 8.0)
            .entity()
    };
    ui_mark_render_dirty(world);
    grid
}

/// Adds a scrollable region of the given pixel `height` to a panel and returns
/// its content container. Add widgets to the returned entity; when they exceed
/// the height the region scrolls with the mouse wheel and a draggable thumb.
/// This is what dense inventory and dialogue lists need.
pub fn panel_scroll(world: &mut World, panel: Entity, height: f32) -> Entity {
    let content = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        let area = tree.add_scroll_area(vec2(0.0, height));
        widget::<UiScrollAreaData>(tree.world_mut(), area)
            .map(|data| data.content_entity)
            .unwrap_or(area)
    };
    ui_mark_render_dirty(world);
    content
}

/// Scrolls a [`panel_scroll`] region (pass the panel-scroll entity, not the
/// content) to a pixel offset from the top.
pub fn set_scroll_offset(world: &mut World, scroll_area: Entity, offset: f32) {
    ui_scroll_area_set_offset(world, scroll_area, offset);
    ui_mark_render_dirty(world);
}

/// Sets a widget's keyboard focus order. Widgets with a focus order participate
/// in Tab navigation, lowest order first. Use it to make a form's fields step
/// in a sensible sequence.
pub fn set_focus_order(world: &mut World, entity: Entity, order: i32) {
    if let Some(interaction) = world.ui.get_ui_node_interaction_mut(entity) {
        interaction.tab_index = Some(order);
    }
}

/// Gives keyboard focus to a widget immediately, as if the user had tabbed to
/// it. Useful to focus the first field when a form opens.
pub fn focus_widget(world: &mut World, entity: Entity) {
    world.resources.retained_ui.interaction.focused_entity = Some(entity);
}

/// Adds a multi-line text area with grey `placeholder` text and `rows` visible
/// rows to a panel. Set its contents with [`set_text_area`].
pub fn panel_text_area(world: &mut World, panel: Entity, placeholder: &str, rows: usize) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_text_area(placeholder, rows)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Adds a multi-line text area pre-filled with `initial` to a panel.
pub fn panel_text_area_with_value(
    world: &mut World,
    panel: Entity,
    placeholder: &str,
    rows: usize,
    initial: &str,
) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_text_area_with_value(placeholder, rows, initial)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Replaces a text area's contents.
pub fn set_text_area(world: &mut World, area: Entity, text: &str) {
    ui_text_area_set_value(world, area, text);
    ui_mark_render_dirty(world);
}

/// Adds a multi-select chip list of `options` to a panel. Set which indices are
/// chosen with [`set_multi_select`].
pub fn panel_multi_select(world: &mut World, panel: Entity, options: &[&str]) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_multi_select(options)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Sets a multi-select's chosen option indices.
pub fn set_multi_select(world: &mut World, widget: Entity, indices: &[usize]) {
    ui_multi_select_set_selected(world, widget, indices);
    ui_mark_render_dirty(world);
}

/// Adds a date picker starting at the given date to a panel. Set it later with
/// [`set_date`].
pub fn panel_date_picker(
    world: &mut World,
    panel: Entity,
    year: i32,
    month: u32,
    day: u32,
) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_date_picker(year, month, day)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Sets a date picker's value.
pub fn set_date(world: &mut World, picker: Entity, year: i32, month: u32, day: u32) {
    ui_date_picker_set_value(world, picker, year, month, day);
    ui_mark_render_dirty(world);
}

/// Adds a dropdown menu labeled `label` listing `items` to a panel.
pub fn panel_menu(world: &mut World, panel: Entity, label: &str, items: &[&str]) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_menu(label, items)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Adds an HSV color picker starting at `initial` linear RGBA to a panel. Read it
/// with [`color_value`].
pub fn panel_color_picker_hsv(world: &mut World, panel: Entity, initial: [f32; 4]) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_color_picker_hsv(rgba(initial))
    };
    ui_mark_render_dirty(world);
    entity
}

/// Adds a draggable splitter dividing a panel into two resizable panes at
/// `initial_ratio` (0.0 to 1.0). Returns the splitter; its two panes are its
/// children. `direction` is [`SplitDirection::Horizontal`] or `Vertical`.
pub fn panel_splitter(
    world: &mut World,
    panel: Entity,
    direction: SplitDirection,
    initial_ratio: f32,
) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_splitter(direction, initial_ratio)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Adds a breadcrumb trail of `segments` to a panel, for showing a path or
/// navigation hierarchy.
pub fn panel_breadcrumb(world: &mut World, panel: Entity, segments: &[&str]) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_breadcrumb(segments)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Adds a virtual list to a panel that recycles a pool of `pool_size` rows of
/// `item_height` pixels each, so it scrolls thousands of items cheaply.
pub fn panel_virtual_list(
    world: &mut World,
    panel: Entity,
    item_height: f32,
    pool_size: usize,
) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_virtual_list(item_height, pool_size)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Adds a simple table with column `headers` of the given pixel `widths` to a
/// panel. For large or sortable data use [`panel_data_grid`].
pub fn panel_table(world: &mut World, panel: Entity, headers: &[&str], widths: &[f32]) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_table(headers, widths)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Adds a sortable, selectable data grid to a panel. `columns` are `(header,
/// width)` pairs and `pool_size` is how many rows to keep instantiated for
/// recycling. Fill cells with [`set_data_grid_rows`] and [`set_data_grid_cell`],
/// read clicks with [`data_grid_selection_changed`].
pub fn panel_data_grid(
    world: &mut World,
    panel: Entity,
    columns: &[(&str, f32)],
    pool_size: usize,
) -> Entity {
    let grid_columns: Vec<DataGridColumn> = columns
        .iter()
        .map(|(header, width)| DataGridColumn::new(header, *width))
        .collect();
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_data_grid(&grid_columns, pool_size)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Sets a data grid's total row count.
pub fn set_data_grid_rows(world: &mut World, grid: Entity, count: usize) {
    ui_data_grid_set_row_count(world, grid, count);
}

/// Sets the text of a single data grid cell.
pub fn set_data_grid_cell(world: &mut World, grid: Entity, row: usize, column: usize, text: &str) {
    ui_data_grid_set_cell(world, grid, row, column, text);
}

/// Whether the data grid's row selection changed this frame.
#[inline]
pub fn data_grid_selection_changed(world: &World, grid: Entity) -> bool {
    ui_data_grid_selection_changed(world, grid)
}

/// Adds a command palette to a panel: a searchable overlay of actions opened
/// from a hotkey, keeping `pool_size` result rows instantiated.
pub fn panel_command_palette(world: &mut World, panel: Entity, pool_size: usize) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_command_palette(pool_size)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Adds a property grid to a panel, a two-column label and value layout for
/// inspectors. `label_width` is the pixel width of the label column. Add rows
/// with [`panel_property_row`].
pub fn panel_property_grid(world: &mut World, panel: Entity, label_width: f32) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_property_grid(label_width)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Adds a labeled row to a [`panel_property_grid`] and returns its value cell.
/// Add the value widget (a slider, text input, and so on) to the returned cell.
pub fn panel_property_row(world: &mut World, grid: Entity, label: &str) -> Entity {
    let row = {
        let mut tree = UiTreeBuilder::from_parent(world, grid);
        tree.add_property_row(grid, grid, label)
    };
    ui_mark_render_dirty(world);
    row
}

/// Adds a tree view to a panel. Add root nodes to its [`tree_content`]
/// container with [`tree_node`], read the selection with [`tree_view_selected`].
pub fn panel_tree_view(world: &mut World, panel: Entity, multi_select: bool) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_tree_view(multi_select)
    };
    ui_mark_render_dirty(world);
    entity
}

/// The root container of a [`panel_tree_view`]; add top-level [`tree_node`]s to
/// it.
pub fn tree_content(world: &World, tree_view: Entity) -> Entity {
    widget::<UiTreeViewData>(world, tree_view)
        .map(|data| data.content_entity)
        .unwrap_or(tree_view)
}

/// Adds a node labeled `label` at `depth` under `parent_container` (a tree's
/// [`tree_content`] for a root node, or another node's [`tree_node_children`]
/// for a nested one). `user_data` is an id you choose to recognize the node.
pub fn tree_node(
    world: &mut World,
    tree_view: Entity,
    parent_container: Entity,
    label: &str,
    depth: usize,
    user_data: u64,
) -> Entity {
    let node = {
        let mut tree = UiTreeBuilder::from_parent(world, parent_container);
        tree.add_tree_node(tree_view, parent_container, label, depth, user_data)
    };
    ui_mark_render_dirty(world);
    node
}

/// The container a node's children go into; pass it as `parent_container` to
/// [`tree_node`] to nest under this node.
pub fn tree_node_children(world: &World, node: Entity) -> Entity {
    widget::<UiTreeNodeData>(world, node)
        .map(|data| data.children_container)
        .unwrap_or(node)
}

/// Expands or collapses a [`tree_node`].
pub fn set_tree_node_expanded(world: &mut World, node: Entity, expanded: bool) {
    ui_tree_node_set_expanded(world, node, expanded);
    ui_mark_render_dirty(world);
}

/// The entities of the currently selected [`tree_node`]s.
#[inline]
pub fn tree_view_selected(world: &World, tree_view: Entity) -> Vec<Entity> {
    ui_tree_view_selected(world, tree_view)
}

/// Adds a numeric drag value from `min` to `max` starting at `initial` to a
/// panel: a field whose value scrubs as you drag across it. Read it with
/// [`drag_value`].
pub fn panel_drag_value(
    world: &mut World,
    panel: Entity,
    min: f32,
    max: f32,
    initial: f32,
) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_drag_value(min, max, initial)
    };
    ui_mark_render_dirty(world);
    entity
}

/// The drag value's current value.
#[inline]
pub fn drag_value(world: &World, widget: Entity) -> f32 {
    ui_drag_value(world, widget).unwrap_or(0.0)
}

/// Adds a selectable label to a panel. Labels sharing a `group` are mutually
/// exclusive, like a list selection. Pass `None` for a standalone toggle.
pub fn panel_selectable(
    world: &mut World,
    panel: Entity,
    text: &str,
    group: Option<u32>,
) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_selectable_label(text, group)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Adds a centered modal dialog titled `title`, `width` by `height` pixels, to a
/// panel and returns its content container. Add the dialog's body to the
/// returned entity; toggle the whole modal with [`set_panel_visible`].
pub fn panel_modal(
    world: &mut World,
    panel: Entity,
    title: &str,
    width: f32,
    height: f32,
) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_modal_dialog(title, width, height)
    };
    ui_mark_render_dirty(world);
    entity
}

/// Adds an animated loading spinner to a panel.
pub fn panel_spinner(world: &mut World, panel: Entity) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_spinner()
    };
    ui_mark_render_dirty(world);
    entity
}

/// Adds a thin horizontal divider line to a panel.
pub fn panel_separator(world: &mut World, panel: Entity) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_separator()
    };
    ui_mark_render_dirty(world);
    entity
}

/// Adds a larger heading-styled line of text to a panel.
pub fn panel_heading(world: &mut World, panel: Entity, text: &str) -> Entity {
    let entity = {
        let mut tree = UiTreeBuilder::from_parent(world, panel);
        tree.add_heading(text)
    };
    ui_mark_render_dirty(world);
    entity
}

fn panel_anchor(anchor: ScreenAnchor) -> (UiValue<Vec2>, Anchor) {
    match anchor {
        ScreenAnchor::TopLeft => (Ab(vec2(20.0, 20.0)).into(), Anchor::TopLeft),
        ScreenAnchor::TopCenter => (Rl(vec2(50.0, 0.0)) + Ab(vec2(0.0, 20.0)), Anchor::TopCenter),
        ScreenAnchor::TopRight => (
            Rl(vec2(100.0, 0.0)) + Ab(vec2(-20.0, 20.0)),
            Anchor::TopRight,
        ),
        ScreenAnchor::BottomLeft => (
            Rl(vec2(0.0, 100.0)) + Ab(vec2(20.0, -20.0)),
            Anchor::BottomLeft,
        ),
        ScreenAnchor::BottomCenter => (
            Rl(vec2(50.0, 100.0)) + Ab(vec2(0.0, -20.0)),
            Anchor::BottomCenter,
        ),
        ScreenAnchor::BottomRight => (
            Rl(vec2(100.0, 100.0)) + Ab(vec2(-20.0, -20.0)),
            Anchor::BottomRight,
        ),
        ScreenAnchor::Center => (Rl(vec2(50.0, 50.0)).into(), Anchor::Center),
    }
}

/// The anchor's relative base position (as a percentage for [`Rl`]) and engine
/// anchor, with no margin, so a caller can add its own pixel offset.
fn anchor_base(anchor: ScreenAnchor) -> (Vec2, Anchor) {
    match anchor {
        ScreenAnchor::TopLeft => (vec2(0.0, 0.0), Anchor::TopLeft),
        ScreenAnchor::TopCenter => (vec2(50.0, 0.0), Anchor::TopCenter),
        ScreenAnchor::TopRight => (vec2(100.0, 0.0), Anchor::TopRight),
        ScreenAnchor::BottomLeft => (vec2(0.0, 100.0), Anchor::BottomLeft),
        ScreenAnchor::BottomCenter => (vec2(50.0, 100.0), Anchor::BottomCenter),
        ScreenAnchor::BottomRight => (vec2(100.0, 100.0), Anchor::BottomRight),
        ScreenAnchor::Center => (vec2(50.0, 50.0), Anchor::Center),
    }
}

fn rgba(color: [f32; 4]) -> Vec4 {
    Vec4::new(color[0], color[1], color[2], color[3])
}

const PANEL_BORDER: Vec4 = Vec4::new(0.12, 0.14, 0.2, 0.7);
const PANEL_SHADOW: Vec4 = Vec4::new(0.0, 0.0, 0.0, 0.55);

/// Spawns a panel anchored to any of the nine screen positions at a pixel
/// `offset` from that anchor, `size` pixels large, filled with `color`. Unlike
/// [`spawn_panel`] this gives full control over placement, size, and color for a
/// custom HUD; fill it with absolutely positioned [`panel_text`], [`panel_box`],
/// and [`panel_button_at`] children. Returns the panel entity.
pub fn spawn_panel_at(
    world: &mut World,
    anchor: ScreenAnchor,
    offset: Vec2,
    size: Vec2,
    color: [f32; 4],
) -> Entity {
    let root = ui_root(world);
    let (base, anchor_kind) = anchor_base(anchor);
    let panel = {
        let mut tree = UiTreeBuilder::from_parent(world, root);
        tree.add_node()
            .window(Rl(base) + Ab(offset), Ab(size), anchor_kind)
            .with_rect(10.0, 1.5, PANEL_BORDER)
            .color_raw::<UiBase>(rgba(color))
            .with_shadow(PANEL_SHADOW, vec2(0.0, 6.0), 18.0, 0.0)
            .entity()
    };
    ui_mark_render_dirty(world);
    panel
}

/// Adds a text label to `parent` in the pixel rectangle `rect` (`[x, y, width,
/// height]` from the parent's top left), at `font_size` in `color` with the
/// given horizontal alignment. Returns the label entity; update it with
/// [`set_panel_text`] and recolor it with [`set_panel_text_color`].
pub fn panel_text(
    world: &mut World,
    parent: Entity,
    text: &str,
    rect: [f32; 4],
    font_size: f32,
    color: [f32; 4],
    align: TextAlignment,
) -> Entity {
    let label = {
        let mut tree = UiTreeBuilder::from_parent(world, parent);
        tree.add_node()
            .window(
                Ab(vec2(rect[0], rect[1])),
                Ab(vec2(rect[2], rect[3])),
                Anchor::TopLeft,
            )
            .with_text(text, font_size)
            .with_text_alignment(align, VerticalAlignment::Middle)
            .color_raw::<UiBase>(rgba(color))
            .without_pointer_events()
            .entity()
    };
    ui_mark_render_dirty(world);
    label
}

/// Adds a solid colored rectangle to `parent` at a pixel `offset`, sized `size`.
/// Use it for bars, swatches, and dividers. Resize it with [`set_panel_rect`]
/// and recolor it with [`set_panel_color`].
pub fn panel_box(
    world: &mut World,
    parent: Entity,
    offset: Vec2,
    size: Vec2,
    color: [f32; 4],
) -> Entity {
    let box_entity = {
        let mut tree = UiTreeBuilder::from_parent(world, parent);
        tree.add_node()
            .window(Ab(offset), Ab(size), Anchor::TopLeft)
            .with_rect(6.0, 0.0, Vec4::new(0.0, 0.0, 0.0, 0.0))
            .color_raw::<UiBase>(rgba(color))
            .without_pointer_events()
            .entity()
    };
    ui_mark_render_dirty(world);
    box_entity
}

/// Adds an interactive button to `parent` at a pixel `offset`, sized `size`,
/// with a centered `label` (pass `""` for none and add your own children). It
/// has themed hover and press states and a selected state for
/// [`set_panel_selected`]. Poll it with [`button_clicked`]. Returns the button.
pub fn panel_button_at(
    world: &mut World,
    parent: Entity,
    label: &str,
    offset: Vec2,
    size: Vec2,
) -> Entity {
    let button = {
        let mut tree = UiTreeBuilder::from_parent(world, parent);
        tree.add_node()
            .window(Ab(offset), Ab(size), Anchor::TopLeft)
            .with_rect(8.0, 1.5, PANEL_BORDER)
            .color_raw::<UiBase>(Vec4::new(0.05, 0.06, 0.09, 0.92))
            .color_raw::<UiHover>(Vec4::new(0.09, 0.11, 0.17, 0.95))
            .color_raw::<UiPressed>(Vec4::new(0.04, 0.05, 0.08, 1.0))
            .with_transition::<UiHover>(12.0, 6.0)
            .with_transition::<UiPressed>(18.0, 10.0)
            .with_transition::<UiSelected>(10.0, 5.0)
            .with_interaction()
            .entity()
    };
    if !label.is_empty() {
        let mut tree = UiTreeBuilder::from_parent(world, button);
        tree.add_node()
            .window(Rl(vec2(50.0, 50.0)), Ab(size), Anchor::Center)
            .with_text(label, 14.0)
            .with_text_alignment(TextAlignment::Center, VerticalAlignment::Middle)
            .color_raw::<UiBase>(Vec4::new(0.92, 0.94, 1.0, 1.0))
            .without_pointer_events()
            .entity();
    }
    ui_mark_render_dirty(world);
    button
}

/// Repositions and resizes a UI node within its parent, in pixels. Drives a bar
/// fill or any element that changes size at runtime.
pub fn set_panel_rect(world: &mut World, node: Entity, offset: Vec2, size: Vec2) {
    if let Some(layout) = world.ui.get_ui_layout_node_mut(node) {
        layout.base_layout = Some(UiLayoutType::Window(WindowLayout {
            position: Ab(offset).into(),
            size: Ab(size).into(),
            anchor: Anchor::TopLeft,
        }));
    }
    ui_mark_render_dirty(world);
}

/// Sets a UI node's background color (linear RGBA), for panels, boxes, and bars.
pub fn set_panel_color(world: &mut World, node: Entity, color: [f32; 4]) {
    if let Some(node_color) = world.ui.get_ui_node_color_mut(node) {
        node_color.colors[UiBase::INDEX] = Some(rgba(color));
    }
    ui_mark_render_dirty(world);
}

/// Replaces a [`panel_text`] label's content. Skips work when unchanged, so it
/// is fine to call every frame with a formatted string.
pub fn set_panel_text(world: &mut World, label: Entity, text: &str) {
    ui_set_text(world, label, text);
}

/// Recolors a [`panel_text`] label.
pub fn set_panel_text_color(world: &mut World, label: Entity, color: [f32; 4]) {
    set_panel_color(world, label, color);
}

/// Toggles a button's selected highlight, tinting it with `accent` while
/// selected. Use it to show the active choice in a row of options.
pub fn set_panel_selected(world: &mut World, button: Entity, selected: bool, accent: [f32; 4]) {
    if let Some(node_color) = world.ui.get_ui_node_color_mut(button) {
        node_color.colors[UiSelected::INDEX] = Some(rgba(accent));
    }
    ui_set_selected(world, button, selected);
    ui_mark_render_dirty(world);
}

/// Shows or hides a UI node and its children, for toggling overlays like a wave
/// banner or a game over panel.
pub fn set_panel_visible(world: &mut World, node: Entity, visible: bool) {
    ui_set_visible(world, node, visible);
    ui_mark_render_dirty(world);
}