bevy_quill 0.1.7

A reactive UI framework for Bevy
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
//! Example of a comprehensive UI layout
#![feature(impl_trait_in_assoc_type)]
// mod node_graph_demo;
mod reflect_demo;
// mod transform_overlay;

use bevy_mod_picking::{
    backends::raycast::{RaycastBackendSettings, RaycastPickable},
    debug::DebugPickingMode,
    prelude::*,
    DefaultPickingPlugins,
};
use bevy_mod_stylebuilder::*;
use bevy_quill_obsidian::{
    colors,
    controls::{
        Button, ButtonVariant, Checkbox, Dialog, DialogBody, DialogFooter, DialogHeader, ListView,
        Slider, Splitter, SplitterDirection, ToolButton, ToolPalette,
    },
    focus::TabGroup,
    prelude::ListRow,
    typography, viewport, ObsidianUiPlugin, RoundedCorners,
};
use bevy_quill_obsidian_inspect::InspectorPlugin;
use reflect_demo::{ResourcePropertyInspector, TestStruct, TestStruct2, TestStruct3};
// use transform_overlay::TransformOverlay;

use std::f32::consts::PI;

use bevy::{
    asset::io::{file::FileAssetReader, AssetSource},
    color::palettes,
    prelude::*,
    render::{
        render_asset::RenderAssetUsages,
        render_resource::{Extent3d, TextureDimension, TextureFormat},
    },
    ui,
};
use bevy_quill::*;

fn style_main(ss: &mut StyleBuilder) {
    ss.position(ui::PositionType::Absolute)
        .left(0)
        .top(0)
        .bottom(0)
        .right(0)
        .border(1)
        .border_color(colors::U2)
        .display(ui::Display::Flex)
        .pointer_events(false);
}

fn style_aside(ss: &mut StyleBuilder) {
    ss.display(ui::Display::Flex)
        .background_color(colors::U2)
        .padding(8)
        .gap(8)
        .flex_direction(ui::FlexDirection::Column)
        .width(200)
        .pointer_events(true);
}

fn style_button_row(ss: &mut StyleBuilder) {
    ss.gap(8);
}

fn style_button_flex(ss: &mut StyleBuilder) {
    ss.flex_grow(1.);
}

fn style_slider(ss: &mut StyleBuilder) {
    ss.align_self(ui::AlignSelf::Stretch);
}

fn style_column_group(ss: &mut StyleBuilder) {
    ss.display(ui::Display::Flex)
        .flex_direction(ui::FlexDirection::Column)
        .align_items(ui::AlignItems::FlexStart)
        .gap(8);
}

fn style_scroll_area(ss: &mut StyleBuilder) {
    ss.flex_grow(1.0);
}

// fn style_log_entry(ss: &mut StyleBuilder) {
//     ss.display(ui::Display::Flex)
//         .justify_content(ui::JustifyContent::SpaceBetween)
//         .align_self(ui::AlignSelf::Stretch);
// }

#[derive(Resource)]
pub struct PanelWidth(f32);

#[derive(Resource, Default)]
pub struct SelectedShape(Option<Entity>);

#[derive(States, Debug, Clone, PartialEq, Eq, Hash, Default)]
pub enum EditorState {
    #[default]
    Preview,
    Graph,
    Split,
}

#[derive(Resource)]
pub struct PreviewEntities {
    camera: Entity,
    _overlay: Entity,
}

#[derive(Resource, Default)]
pub struct ClickLog(pub Vec<String>);

fn main() {
    App::new()
        .register_asset_source(
            "demo",
            AssetSource::build()
                .with_reader(|| Box::new(FileAssetReader::new("examples/complex/assets"))),
        )
        .init_resource::<SelectedShape>()
        .init_resource::<TrackingScopeTracing>()
        .init_resource::<ClickLog>()
        // .init_resource::<DemoGraphRoot>()
        .insert_resource(TestStruct {
            unlit: Some(true),
            ..default()
        })
        .insert_resource(TestStruct2 {
            nested: TestStruct::default(),
            ..default()
        })
        .insert_resource(TestStruct3(true))
        .insert_resource(PanelWidth(200.))
        .init_resource::<viewport::ViewportInset>()
        .add_plugins(DefaultPlugins.set(ImagePlugin::default_nearest()))
        .add_plugins(DefaultPickingPlugins)
        .insert_state(EditorState::Preview)
        .insert_resource(DebugPickingMode::Disabled)
        .insert_resource(RaycastBackendSettings {
            require_markers: true,
            ..default()
        })
        .add_plugins(InspectorPlugin)
        .add_plugins((
            QuillPlugin,
            ObsidianUiPlugin,
            // overlays::OverlaysPlugin,
            // BackdropBackend,
        ))
        .add_systems(Startup, (setup, setup_ui.pipe(setup_view_root)))
        .add_systems(
            Update,
            (
                close_on_esc,
                rotate.run_if(in_state(EditorState::Preview)),
                rotate.run_if(in_state(EditorState::Split)),
                viewport::update_viewport_inset.run_if(in_state(EditorState::Preview)),
                viewport::update_viewport_inset.run_if(in_state(EditorState::Split)),
                viewport::update_camera_viewport.run_if(in_state(EditorState::Preview)),
                viewport::update_camera_viewport.run_if(in_state(EditorState::Split)),
            ),
        )
        .add_systems(OnEnter(EditorState::Preview), enter_preview_mode)
        .add_systems(OnExit(EditorState::Preview), exit_preview_mode)
        .add_systems(OnEnter(EditorState::Split), enter_preview_mode)
        .add_systems(OnExit(EditorState::Split), exit_preview_mode)
        .run();
}

/// A marker component for our shapes so we can query them separately from the ground plane
#[derive(Component)]
struct Shape;

const X_EXTENT: f32 = 14.5;

fn setup_view_root(camera: In<Entity>, mut commands: Commands) {
    commands.spawn(DemoUi(*camera).to_root());
}

#[derive(Clone, PartialEq)]
struct DemoUi(Entity);

impl ViewTemplate for DemoUi {
    type View = impl View;

    fn create(&self, cx: &mut Cx) -> Self::View {
        let dialog_open = cx.create_mutable(false);
        let checked_1 = cx.create_mutable(false);
        let checked_2 = cx.create_mutable(true);
        let red = cx.create_mutable::<f32>(128.);
        // let name = cx.create_mutable("filename.txt".to_string());

        let panel_width = cx.use_resource::<PanelWidth>().0;
        let camera = self.0;

        // Needed to ensure popup menus and dialogs render on the correct camera.
        cx.insert(TargetCamera(camera));

        Element::<NodeBundle>::new()
            .named("Main")
            .style((typography::text_default, style_main))
            .insert_dyn(move |_| (TabGroup::default(), TargetCamera(camera)), ())
            .children((
                Dialog::new()
                    .width(ui::Val::Px(400.))
                    .open(dialog_open.get(cx))
                    .on_close(cx.create_callback(move |world: &mut World| {
                        dialog_open.set(world, false);
                    }))
                    .children((
                        DialogHeader::new().children("Dialog Header"),
                        DialogBody::new().children("Example dialog body text."),
                        DialogFooter::new().children((
                            Button::new()
                                .children("Cancel")
                                .on_click(cx.create_callback(move |world: &mut World| {
                                    dialog_open.set(world, false);
                                })),
                            Button::new()
                                .children("Close")
                                .variant(ButtonVariant::Primary)
                                .autofocus(true)
                                .on_click(cx.create_callback(move |world: &mut World| {
                                    dialog_open.set(world, false);
                                })),
                        )),
                    )),
                Element::<NodeBundle>::new()
                    .named("ControlPalette")
                    .style(style_aside)
                    .style_dyn(
                        move |width, sb| {
                            sb.width(ui::Val::Px(width));
                        },
                        panel_width,
                    )
                    .children((
                        ToolPalette::new().columns(3).children((
                            ToolButton::new()
                                .children("Preview")
                                .corners(RoundedCorners::Left)
                                .variant({
                                    let st = cx.use_resource::<State<EditorState>>();
                                    if *st.get() == EditorState::Preview {
                                        ButtonVariant::Selected
                                    } else {
                                        ButtonVariant::Default
                                    }
                                })
                                .on_click(cx.create_callback(
                                    |mut mode: ResMut<NextState<EditorState>>| {
                                        mode.set(EditorState::Preview);
                                    },
                                )),
                            ToolButton::new()
                                .children("Materials")
                                .corners(RoundedCorners::None)
                                .variant({
                                    let st = cx.use_resource::<State<EditorState>>();
                                    if *st.get() == EditorState::Graph {
                                        ButtonVariant::Selected
                                    } else {
                                        ButtonVariant::Default
                                    }
                                })
                                .on_click(cx.create_callback(
                                    |mut mode: ResMut<NextState<EditorState>>| {
                                        mode.set(EditorState::Graph);
                                    },
                                )),
                            ToolButton::new()
                                .children("Split")
                                .corners(RoundedCorners::Right)
                                .variant({
                                    let st = cx.use_resource::<State<EditorState>>();
                                    if *st.get() == EditorState::Split {
                                        ButtonVariant::Selected
                                    } else {
                                        ButtonVariant::Default
                                    }
                                })
                                .on_click(cx.create_callback(
                                    |mut mode: ResMut<NextState<EditorState>>| {
                                        mode.set(EditorState::Split);
                                    },
                                )),
                        )),
                        Element::<NodeBundle>::new()
                            .style(style_button_row)
                            .children((
                                Button::new()
                                    .children("Open…")
                                    .on_click(cx.create_callback(move |world: &mut World| {
                                        let mut log = world.get_resource_mut::<ClickLog>().unwrap();
                                        log.0.push("Open clicked".to_string());
                                        dialog_open.set(world, true);
                                    }))
                                    .style(style_button_flex),
                                Button::new()
                                    .children("Save")
                                    .on_click(cx.create_callback(
                                        move |mut log: ResMut<ClickLog>| {
                                            log.0.push("Save clicked".to_string());
                                        },
                                    ))
                                    .style(style_button_flex),
                            )),
                        Element::<NodeBundle>::new()
                            .style(style_column_group)
                            .children((
                                Checkbox::new()
                                    // .style(|ss: &mut StyleBuilder| {
                                    //     ss.cursor_image("demo://unlock.png", Vec2::new(8., 8.));
                                    // })
                                    .label("Include Author Name")
                                    .checked(checked_1.get(cx))
                                    .on_change(cx.create_callback(
                                        move |checked: In<bool>, world: &mut World| {
                                            let mut log =
                                                world.get_resource_mut::<ClickLog>().unwrap();
                                            log.0
                                                .push(format!("Include Author Name: {}", *checked));
                                            checked_1.set(world, *checked);
                                        },
                                    )),
                                Checkbox::new()
                                    .label("Include Metadata")
                                    .checked(checked_2.get(cx))
                                    .on_change(cx.create_callback(
                                        move |checked: In<bool>, world: &mut World| {
                                            let mut log =
                                                world.get_resource_mut::<ClickLog>().unwrap();
                                            log.0.push(format!("Include Metadata: {}", *checked));
                                            checked_2.set(world, *checked);
                                        },
                                    )),
                            )),
                        Element::<NodeBundle>::new()
                            .style(style_column_group)
                            .children(
                                Slider::new()
                                    .min(0.)
                                    .max(255.)
                                    .value(red.get(cx))
                                    .style(style_slider)
                                    .precision(1)
                                    .on_change(cx.create_callback(
                                        move |value: In<f32>, world: &mut World| {
                                            let mut log =
                                                world.get_resource_mut::<ClickLog>().unwrap();
                                            log.0.push(format!("Slider value: {}", *value));
                                            red.set(world, *value);
                                        },
                                    )),
                                // )
                                // TextInput::new(TextInputProps {
                                //     value: name.signal(),
                                //     on_change: Some(cx.create_callback(
                                //         move |cx: &mut Cx, value: String| {
                                //             name.set_clone(cx, value.clone());
                                //         },
                                //     )),
                                //     ..default()
                                // }
                            ),
                        ResourcePropertyInspector::<TestStruct>::new(),
                        ResourcePropertyInspector::<TestStruct2>::new(),
                        ResourcePropertyInspector::<TestStruct3>::new(),
                        // ReactionsTable,
                        LogList,
                    )),
                Splitter::new()
                    .direction(SplitterDirection::Vertical)
                    .value(panel_width)
                    .on_change(cx.create_callback(|value: In<f32>, world: &mut World| {
                        let mut panel_width = world.get_resource_mut::<PanelWidth>().unwrap();
                        panel_width.0 = value.max(200.);
                    })),
                CenterPanel,
            ))
    }
}

fn wrapper_style(ss: &mut StyleBuilder) {
    ss.display(Display::Flex)
        .flex_grow(1.)
        .align_self(ui::AlignSelf::Stretch)
        .flex_direction(FlexDirection::Column);
}

#[derive(Clone, PartialEq)]
struct CenterPanel;

impl ViewTemplate for CenterPanel {
    type View = impl View;
    fn create(&self, _cx: &mut Cx) -> Self::View {
        Element::<NodeBundle>::new()
            .children((
                NodeGraphDemo {},
                //     Cond::new(
                //     *cx.use_resource::<State<EditorState>>().get() == EditorState::Graph,
                //     (
                //         Element::<NodeBundle>::new()
                //             .named("Preview")
                //             .style(style_viewport)
                //             .insert((viewport::ViewportInsetElement, Pickable::IGNORE))
                //             .children(
                //                 Element::<NodeBundle>::new()
                //                     .named("Log")
                //                     .style(style_log)
                //                     .children(Element::<NodeBundle>::new().style(style_log_inner)),
                //             ),
                //         Cond::new(
                //             *cx.use_resource::<State<EditorState>>().get() == EditorState::Split,
                //             (Element::<NodeBundle>::new()
                //                 .style(graph_view_style)
                //                 .style_dyn(
                //                     move |height, sb| {
                //                         sb.height(ui::Val::Px(height));
                //                     },
                //                     panel_height,
                //                 )
                //                 .children(NodeGraphDemo {}),),
                //             (),
                //         ),
                //     ),
                // ),
            ))
            .style(wrapper_style)
    }
}

#[derive(Clone, PartialEq)]
struct LogList;

impl ViewTemplate for LogList {
    type View = impl View;
    fn create(&self, cx: &mut Cx) -> Self::View {
        let log = cx.use_resource::<ClickLog>();
        ListView::new()
            .children(For::each(log.0.clone(), |msg| {
                ListRow::new(msg.clone()).children(msg.clone())
            }))
            .style(style_scroll_area)
    }
}

#[derive(Clone, PartialEq)]
struct NodeGraphDemo;

impl ViewTemplate for NodeGraphDemo {
    type View = impl View;
    fn create(&self, _cx: &mut Cx) -> Self::View {
        // ()
    }
}

// #[derive(Clone, PartialEq)]
// struct ReactionsTable;

// impl ViewTemplate for ReactionsTable {
//     type View = impl View;
//     fn create(&self, _cx: &mut Cx) -> Self::View {
//         ListView::new()
//             .children(For::each(
//                 |cx| {
//                     let tracing = cx.use_resource::<TrackingScopeTracing>();
//                     tracing.0.clone().into_iter()
//                 },
//                 |ent| {
//                     text_computed({
//                         let e = *ent;
//                         move |cx| {
//                             if let Some(name) = cx.world().get::<Name>(e) {
//                                 name.to_string()
//                             } else {
//                                 e.to_string()
//                             }
//                         }
//                     })
//                 },
//             ))
//             .style(style_scroll_area)
//     }
// }

// fn _overlay_views(cx: &mut Cx<Entity>) -> impl View {
//     let id = cx.create_entity();
//     let hovering = cx.create_hover_signal(id);
//     // let color = cx.create_derived(|cx| LinearRgba::from(cx.use_resource::<ColorEditState>().rgb));
//     let color: Signal<LinearRgba> = cx.create_derived(move |cx| {
//         if hovering.get(cx) {
//             colors::ACCENT.into()
//         } else {
//             colors::U1.into()
//         }
//     });

//     overlays::OverlayShape::for_entity(id, |_cx, sb| {
//         sb.with_stroke_width(0.3)
//             .stroke_circle(Vec2::new(0., 0.), 5., 64)
//             .stroke_polygon(
//                 &[Vec2::new(-4., -4.), Vec2::new(0., -4.), Vec2::new(-4., 0.)],
//                 overlays::PolygonOptions {
//                     start_marker: overlays::StrokeMarker::Arrowhead,
//                     end_marker: overlays::StrokeMarker::Arrowhead,
//                     // dash_length: 0.1,
//                     // gap_length: 0.1,
//                     closed: true,
//                     ..default()
//                 },
//             );
//     })
//     .with_color_signal(color)
//     .with_pickable(true)
//     // .with_transform(Transform::from_rotation(Quat::from_rotation_y(PI * 0.5)))
//     .insert(TargetCamera(cx.props))
// }

// struct TransformOverlayDemo;

// impl ViewTemplate for TransformOverlayDemo {
//     fn create(&self, cx: &mut Cx) -> impl IntoView {
//         let selected = cx.create_derived(|cx| cx.use_resource::<SelectedShape>().0);

//         let on_change = Some(cx.create_callback(move |cx, new_pos| {
//             let selected = selected.get(cx).unwrap();
//             let mut entity = cx.world_mut().entity_mut(selected);
//             let mut transform = entity.get_mut::<Transform>().unwrap();
//             transform.translation = new_pos;
//         }));

//         TransformOverlay {
//             target: selected,
//             on_change,
//         }
//     }
// }

// Setup 3d shapes
fn setup(
    mut commands: Commands,
    mut meshes: ResMut<Assets<Mesh>>,
    mut images: ResMut<Assets<Image>>,
    mut materials: ResMut<Assets<StandardMaterial>>,
) {
    let debug_material = materials.add(StandardMaterial {
        base_color_texture: Some(images.add(uv_debug_texture())),
        ..default()
    });

    let shapes = [
        meshes.add(Cuboid::default()),
        meshes.add(Capsule3d::default()),
        meshes.add(Torus::default()),
        meshes.add(Cylinder::default()),
        meshes.add(Sphere::default().mesh().ico(5).unwrap()),
        meshes.add(Sphere::default().mesh().uv(32, 18)),
    ];

    let num_shapes = shapes.len();

    let shapes_parent = commands
        .spawn((
            SpatialBundle { ..default() },
            // BackdropPickable,
            On::<Pointer<Down>>::run(
                |mut event: ListenerMut<Pointer<Down>>,
                 shapes: Query<&Shape>,
                 mut selection: ResMut<SelectedShape>| {
                    if shapes.get(event.target).is_ok() {
                        selection.0 = Some(event.target);
                        // println!("Pointer down on shape {:?}", event.target);
                    } else {
                        selection.0 = None;
                        // println!("Pointer down on backdrop {:?}", event.target);
                    }
                    event.stop_propagation();
                },
            ),
        ))
        .id();

    for (i, shape) in shapes.into_iter().enumerate() {
        commands
            .spawn((
                PbrBundle {
                    mesh: shape,
                    material: debug_material.clone(),
                    transform: Transform::from_xyz(
                        -X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
                        2.0,
                        0.0,
                    )
                    .with_rotation(Quat::from_rotation_x(-PI / 4.)),
                    ..default()
                },
                Shape,
                // PickableBundle::default(),
                RaycastPickable,
            ))
            .set_parent(shapes_parent);
    }

    commands.spawn(PointLightBundle {
        point_light: PointLight {
            // intensity: 9000.0,
            intensity: 10000000.0,
            range: 100.,
            shadows_enabled: true,
            ..default()
        },
        transform: Transform::from_xyz(8.0, 16.0, 8.0),
        ..default()
    });

    // ground plane
    commands.spawn(PbrBundle {
        mesh: meshes.add(Plane3d::default().mesh().size(50.0, 50.0)),
        material: materials.add(Color::from(palettes::css::SILVER)),
        ..default()
    });
}

fn setup_ui(mut commands: Commands) -> Entity {
    commands
        .spawn((Camera2dBundle {
            camera: Camera {
                // HUD goes on top of 3D
                order: 1,
                clear_color: ClearColorConfig::None,
                ..default()
            },
            camera_2d: Camera2d {},
            ..default()
        },))
        .id()
}

fn enter_preview_mode(mut commands: Commands) {
    let camera = commands
        .spawn((
            Camera3dBundle {
                transform: Transform::from_xyz(0.0, 6., 12.0)
                    .looking_at(Vec3::new(0., 1., 0.), Vec3::Y),
                ..default()
            },
            viewport::ViewportCamera,
            RaycastPickable,
            // BackdropPickable,
        ))
        .id();

    // let overlay = commands.spawn(TransformOverlayDemo.to_root()).id();
    let overlay = commands.spawn_empty().id();
    commands.insert_resource(PreviewEntities {
        camera,
        _overlay: overlay,
    });
}

fn exit_preview_mode(mut commands: Commands, preview: Res<PreviewEntities>) {
    commands.entity(preview.camera).despawn();
    // commands.add(DespawnViewRoot::new(preview.overlay));
    commands.remove_resource::<PreviewEntities>()
}

fn rotate(mut query: Query<&mut Transform, With<Shape>>, time: Res<Time>) {
    for mut transform in &mut query {
        transform.rotate_y(time.delta_seconds() / 2.);
    }
}

/// Creates a colorful test pattern
fn uv_debug_texture() -> Image {
    const TEXTURE_SIZE: usize = 8;

    let mut palette: [u8; 32] = [
        255, 102, 159, 255, 255, 159, 102, 255, 236, 255, 102, 255, 121, 255, 102, 255, 102, 255,
        198, 255, 102, 198, 255, 255, 121, 102, 255, 255, 236, 102, 255, 255,
    ];

    let mut texture_data = [0; TEXTURE_SIZE * TEXTURE_SIZE * 4];
    for y in 0..TEXTURE_SIZE {
        let offset = TEXTURE_SIZE * y * 4;
        texture_data[offset..(offset + TEXTURE_SIZE * 4)].copy_from_slice(&palette);
        palette.rotate_right(4);
    }

    Image::new_fill(
        Extent3d {
            width: TEXTURE_SIZE as u32,
            height: TEXTURE_SIZE as u32,
            depth_or_array_layers: 1,
        },
        TextureDimension::D2,
        &texture_data,
        TextureFormat::Rgba8UnormSrgb,
        RenderAssetUsages::default(),
    )
}

pub fn close_on_esc(input: Res<ButtonInput<KeyCode>>, mut exit: EventWriter<AppExit>) {
    if input.just_pressed(KeyCode::Escape) {
        exit.send(AppExit::Success);
    }
}