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
use crate::resources::{camera::*, renderables::*};
use oxygengine_core::prelude::*;
use oxygengine_ha_renderer::prelude::*;

pub trait GuiWidget<T>: Sized {
    fn execute(self, gui: Gui<T>) -> Rect;
}

pub struct Gui<'a, T> {
    layout: Rect,
    pointer: Vec2,
    input_consumed: &'a mut bool,
    camera: &'a Camera,
    renderables: &'a mut Renderables,
    pub context: &'a mut T,
}

macro_rules! impl_make {
    ( $owner:expr, $layout:expr ) => {
        Gui {
            layout: $layout,
            pointer: $owner.pointer,
            input_consumed: $owner.input_consumed,
            camera: $owner.camera,
            renderables: $owner.renderables,
            context: $owner.context,
        }
    };
}

impl<'a, T> Gui<'a, T> {
    pub fn layout(&self) -> Rect {
        self.layout
    }

    pub fn pointer(&self) -> Vec2 {
        self.pointer
    }

    pub fn input_consumed(&self) -> bool {
        *self.input_consumed
    }

    pub fn hovers(&self) -> bool {
        !*self.input_consumed && self.layout.contains_point(self.pointer)
    }

    pub fn widget<W>(&mut self, widget: W) -> Rect
    where
        W: GuiWidget<T>,
    {
        widget.execute(self.gui())
    }

    pub fn scope<F>(&mut self, mut f: F)
    where
        F: FnMut(Gui<T>),
    {
        f(self.gui());
    }

    pub fn clip<F>(&mut self, mut f: F)
    where
        F: FnMut(Gui<T>),
    {
        let dim = self.camera.world_size();
        let half_dim = dim * 0.5;
        let pos = self
            .camera
            .camera_to_screen_point(vec2(self.layout.x + half_dim.x, self.layout.y + half_dim.y));
        let size = self
            .camera
            .camera_to_screen_point(vec2(self.layout.w, self.layout.h));
        let dim = self.camera.viewport_size();
        let rect = Rect {
            x: pos.x / dim.x,
            y: pos.y / dim.y,
            w: size.x / dim.x,
            h: size.y / dim.y,
        };
        self.renderables.draw(Renderable::PushScissor(rect));
        f(self.gui());
        self.renderables.draw(Renderable::PopScissor);
    }

    pub fn freeform_aligned<F>(
        &mut self,
        size: impl Into<Vec2>,
        alignment: impl Into<Vec2>,
        pivot: impl Into<Vec2>,
        mut f: F,
    ) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        let size = size.into();
        let alignment = alignment.into();
        let pivot = pivot.into();
        let layout = Rect {
            x: self.layout.x + self.layout.w * alignment.x - size.x * pivot.x,
            y: self.layout.y + self.layout.h * alignment.y - size.y * pivot.y,
            w: size.x,
            h: size.y,
        };
        f(impl_make!(self, layout));
        layout
    }

    pub fn freeform_at<F>(
        &mut self,
        size: impl Into<Vec2>,
        position: impl Into<Vec2>,
        pivot: impl Into<Vec2>,
        relative: bool,
        mut f: F,
    ) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        let size = size.into();
        let position = position.into();
        let pivot = pivot.into();
        let mut layout = Rect {
            x: position.x - size.x * pivot.x,
            y: position.y - size.y * pivot.y,
            w: size.x,
            h: size.y,
        };
        if relative {
            layout.x += self.layout.x;
            layout.y += self.layout.y;
        }
        f(impl_make!(self, layout));
        layout
    }

    pub fn growable<F>(&mut self, alignment: impl Into<Vec2>, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>) -> Rect,
    {
        let alignment = alignment.into();
        self.renderables.begin();
        let layout = f(self.gui());
        let offset = vec2(self.layout.w - layout.w, self.layout.h - layout.h) * alignment
            - layout.position();
        for mut renderable in self.renderables.consume().unwrap() {
            match &mut renderable {
                Renderable::PushTransform(transform) => transform.position += offset,
                Renderable::PushScissor(rect) => {
                    let dim = self.camera.world_size();
                    let offset = self.camera.camera_to_screen_point(offset);
                    rect.x += offset.x / dim.x;
                    rect.y += offset.y / dim.y;
                }
                Renderable::Mesh(renderable) => renderable.transform.position += offset,
                Renderable::Sprite(renderable) => renderable.transform.position += offset,
                Renderable::Text(renderable) => renderable.transform.position += offset,
                _ => {}
            }
            self.renderables.draw(renderable);
        }
        layout
    }

    pub fn horizontal_overflow<F>(&mut self, alignment: Scalar, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>) -> Rect,
    {
        let layout = Rect {
            x: self.layout.x,
            y: self.layout.y + self.layout.h * alignment,
            w: self.layout.w,
            h: 0.0,
        };
        f(impl_make!(self, layout))
    }

    pub fn vertical_overflow<F>(&mut self, alignment: Scalar, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>) -> Rect,
    {
        let layout = Rect {
            x: self.layout.x + self.layout.w * alignment,
            y: self.layout.y,
            w: 0.0,
            h: self.layout.h,
        };
        f(impl_make!(self, layout))
    }

    pub fn scale<F>(&mut self, value: Scalar, alignment: impl Into<Vec2>, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        let alignment = alignment.into();
        let width = self.layout.w * value;
        let height = self.layout.h * value;
        let horizontal_space = self.layout.w - width;
        let vertical_space = self.layout.h - height;
        let layout = Rect {
            x: self.layout.x + horizontal_space * alignment.x,
            y: self.layout.y + vertical_space * alignment.y,
            w: width,
            h: height,
        };
        f(impl_make!(self, layout));
        layout
    }

    pub fn margin<F>(
        &mut self,
        mut left: Scalar,
        right: Scalar,
        mut top: Scalar,
        bottom: Scalar,
        mut f: F,
    ) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        let mut horizontal = left + right;
        if horizontal > self.layout.w {
            left = self.layout.w * 0.5;
            horizontal = self.layout.w;
        }
        let mut vertical = top + bottom;
        if vertical > self.layout.h {
            top = self.layout.h * 0.5;
            vertical = self.layout.h;
        }
        let layout = Rect {
            x: self.layout.x + left,
            y: self.layout.y + top,
            w: self.layout.w - horizontal,
            h: self.layout.h - vertical,
        };
        f(impl_make!(self, layout));
        layout
    }

    pub fn absolute<F>(&mut self, layout: Rect, mut f: F)
    where
        F: FnMut(Gui<T>),
    {
        f(impl_make!(self, layout));
    }

    pub fn section<F>(&mut self, relative: Rect, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        let layout = Rect {
            x: self.layout.x + relative.x,
            y: self.layout.y + relative.y,
            w: relative.w,
            h: relative.h,
        };
        f(impl_make!(self, layout));
        layout
    }

    pub fn section_left<F>(&mut self, mut value: Scalar, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        value = value.clamp(0.0, self.layout.w);
        let [low, _] = self.layout.split_at_x(self.layout.x + value);
        f(impl_make!(self, low));
        low
    }

    pub fn section_right<F>(&mut self, mut value: Scalar, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        value = value.clamp(0.0, self.layout.w);
        let [_, high] = self
            .layout
            .split_at_x(self.layout.x + self.layout.w - value);
        f(impl_make!(self, high));
        high
    }

    pub fn section_top<F>(&mut self, mut value: Scalar, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        value = value.clamp(0.0, self.layout.h);
        let [low, _] = self.layout.split_at_y(self.layout.y + value);
        f(impl_make!(self, low));
        low
    }

    pub fn section_bottom<F>(&mut self, mut value: Scalar, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        value = value.clamp(0.0, self.layout.h);
        let [_, high] = self
            .layout
            .split_at_y(self.layout.y + self.layout.h - value);
        f(impl_make!(self, high));
        high
    }

    pub fn cut_left<F>(&mut self, mut value: Scalar, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        value = value.clamp(0.0, self.layout.w);
        let [low, high] = self.layout.split_at_x(self.layout.x + value);
        f(impl_make!(self, low));
        self.layout = high;
        low
    }

    pub fn cut_right<F>(&mut self, mut value: Scalar, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        value = value.clamp(0.0, self.layout.w);
        let [low, high] = self
            .layout
            .split_at_x(self.layout.x + self.layout.w - value);
        f(impl_make!(self, high));
        self.layout = low;
        high
    }

    pub fn cut_top<F>(&mut self, mut value: Scalar, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        value = value.clamp(0.0, self.layout.h);
        let [low, high] = self.layout.split_at_y(self.layout.y + value);
        f(impl_make!(self, low));
        self.layout = high;
        low
    }

    pub fn cut_bottom<F>(&mut self, mut value: Scalar, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        value = value.clamp(0.0, self.layout.h);
        let [low, high] = self
            .layout
            .split_at_y(self.layout.y + self.layout.h - value);
        f(impl_make!(self, high));
        self.layout = low;
        high
    }

    pub fn grow_left<F>(&mut self, mut value: Scalar, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        value = value.max(0.0);
        let layout = Rect {
            x: self.layout.x - value,
            y: self.layout.y,
            w: value,
            h: self.layout.h,
        };
        f(impl_make!(self, layout));
        self.layout.x -= value;
        self.layout.w += value;
        layout
    }

    pub fn grow_right<F>(&mut self, mut value: Scalar, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        value = value.max(0.0);
        let layout = Rect {
            x: self.layout.x + self.layout.w,
            y: self.layout.y,
            w: value,
            h: self.layout.h,
        };
        f(impl_make!(self, layout));
        self.layout.w += value;
        layout
    }

    pub fn grow_top<F>(&mut self, mut value: Scalar, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        value = value.max(0.0);
        let layout = Rect {
            x: self.layout.x,
            y: self.layout.y - value,
            w: self.layout.w,
            h: value,
        };
        f(impl_make!(self, layout));
        self.layout.y -= value;
        self.layout.h += value;
        layout
    }

    pub fn grow_bottom<F>(&mut self, mut value: Scalar, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        value = value.max(0.0);
        let layout = Rect {
            x: self.layout.x,
            y: self.layout.y + self.layout.h,
            w: self.layout.w,
            h: value,
        };
        f(impl_make!(self, layout));
        self.layout.h += value;
        layout
    }

    pub fn offset<F>(&mut self, value: impl Into<Vec2>, mut f: F) -> Rect
    where
        F: FnMut(Gui<T>),
    {
        let value = value.into();
        let layout = Rect {
            x: self.layout.x + value.x,
            y: self.layout.y + value.y,
            w: self.layout.w,
            h: self.layout.h,
        };
        f(impl_make!(self, layout));
        layout
    }

    pub fn horizontal_number<F>(&mut self, mut count: usize, mut f: F)
    where
        F: FnMut(Gui<T>, usize),
    {
        count = count.max(1);
        let size = self.layout.w / count as Scalar;
        for index in 0..count {
            let layout = Rect {
                x: self.layout.x + size * index as Scalar,
                y: self.layout.y,
                w: size,
                h: self.layout.h,
            };
            f(impl_make!(self, layout), index);
        }
    }

    pub fn horizontal_separation<F>(&mut self, mut value: Scalar, f: F)
    where
        F: FnMut(Gui<T>, usize),
    {
        value = value.clamp(0.0, self.layout.w);
        let count = (self.layout.w / value) as usize;
        self.horizontal_number(count, f);
    }

    pub fn vertical_number<F>(&mut self, mut count: usize, mut f: F)
    where
        F: FnMut(Gui<T>, usize),
    {
        count = count.max(1);
        let size = self.layout.h / count as Scalar;
        for index in 0..count {
            let layout = Rect {
                x: self.layout.x,
                y: self.layout.y + size * index as Scalar,
                w: self.layout.w,
                h: size,
            };
            f(impl_make!(self, layout), index);
        }
    }

    pub fn vertical_separation<F>(&mut self, mut value: Scalar, f: F)
    where
        F: FnMut(Gui<T>, usize),
    {
        value = value.clamp(0.0, self.layout.h);
        let count = (self.layout.h / value) as usize;
        self.vertical_number(count, f);
    }

    pub fn grid_number<F>(&mut self, mut cols: usize, mut rows: usize, mut f: F)
    where
        F: FnMut(Gui<T>, usize, usize),
    {
        cols = cols.max(1);
        rows = rows.max(1);
        let width = self.layout.w / cols as Scalar;
        let height = self.layout.h / rows as Scalar;
        for row in 0..rows {
            for col in 0..cols {
                let layout = Rect {
                    x: self.layout.x + width * col as Scalar,
                    y: self.layout.y + height * row as Scalar,
                    w: width,
                    h: height,
                };
                f(impl_make!(self, layout), col, row);
            }
        }
    }

    pub fn grid_separation<F>(&mut self, mut cell_width: Scalar, mut cell_height: Scalar, f: F)
    where
        F: FnMut(Gui<T>, usize, usize),
    {
        cell_width = cell_width.clamp(0.0, self.layout.w);
        cell_height = cell_height.clamp(0.0, self.layout.h);
        let cols = (self.layout.w / cell_width) as usize;
        let rows = (self.layout.h / cell_height) as usize;
        self.grid_number(cols, rows, f);
    }

    pub fn sprite(&mut self, name: impl ToString, tint: Rgba) {
        self.renderables.draw(
            SpriteRenderable::new(name)
                .position(self.layout.center())
                .size([self.layout.w, self.layout.h])
                .tint(tint),
        );
    }

    pub fn sprite_region(&mut self, name: impl ToString, tint: Rgba, region: Rect) {
        self.renderables.draw(
            SpriteRenderable::new(name)
                .position(self.layout.center())
                .size([self.layout.w, self.layout.h])
                .tint(tint)
                .region(region),
        );
    }

    pub fn sprite_sliced(
        &mut self,
        name: impl ToString,
        tint: Rgba,
        image_region: Rect,
        (mut left, mut right, mut top, mut bottom): (Scalar, Scalar, Scalar, Scalar),
        frame: bool,
    ) {
        // TODO: handle zero hor and ver.
        let horizontal = left + right;
        if horizontal > self.layout.w {
            left /= horizontal;
            right /= horizontal;
        }
        let vertical = top + bottom;
        if vertical > self.layout.h {
            top /= vertical;
            bottom /= vertical;
        }
        let name = name.to_string();
        self.cut_left(left, |mut gui| {
            gui.cut_top(top, |mut gui| {
                gui.sprite_region(
                    &name,
                    tint,
                    Rect {
                        x: 0.0,
                        y: 0.0,
                        w: image_region.x,
                        h: image_region.y,
                    },
                )
            });
            gui.cut_bottom(bottom, |mut gui| {
                gui.sprite_region(
                    &name,
                    tint,
                    Rect {
                        x: 0.0,
                        y: image_region.y + image_region.h,
                        w: image_region.x,
                        h: 1.0 - (image_region.y + image_region.h),
                    },
                )
            });
            gui.sprite_region(
                &name,
                tint,
                Rect {
                    x: 0.0,
                    y: image_region.y,
                    w: image_region.x,
                    h: image_region.h,
                },
            );
        });
        self.cut_right(right, |mut gui| {
            gui.cut_top(top, |mut gui| {
                gui.sprite_region(
                    &name,
                    tint,
                    Rect {
                        x: image_region.x + image_region.w,
                        y: 0.0,
                        w: 1.0 - (image_region.x + image_region.w),
                        h: image_region.y,
                    },
                )
            });
            gui.cut_bottom(bottom, |mut gui| {
                gui.sprite_region(
                    &name,
                    tint,
                    Rect {
                        x: image_region.x + image_region.w,
                        y: image_region.y + image_region.h,
                        w: 1.0 - (image_region.x + image_region.w),
                        h: 1.0 - (image_region.y + image_region.h),
                    },
                )
            });
            gui.sprite_region(
                &name,
                tint,
                Rect {
                    x: image_region.x + image_region.w,
                    y: image_region.y,
                    w: 1.0 - (image_region.x + image_region.w),
                    h: image_region.h,
                },
            );
        });
        self.cut_top(top, |mut gui| {
            gui.sprite_region(
                &name,
                tint,
                Rect {
                    x: image_region.x,
                    y: 0.0,
                    w: image_region.w,
                    h: image_region.y,
                },
            )
        });
        self.cut_bottom(bottom, |mut gui| {
            gui.sprite_region(
                &name,
                tint,
                Rect {
                    x: image_region.x,
                    y: image_region.y + image_region.h,
                    w: image_region.w,
                    h: 1.0 - (image_region.y + image_region.h),
                },
            )
        });
        if !frame {
            self.sprite_region(
                &name,
                tint,
                Rect {
                    x: image_region.x,
                    y: image_region.y,
                    w: image_region.w,
                    h: image_region.h,
                },
            );
        }
    }

    pub fn text(
        &mut self,
        font: impl ToString,
        content: impl Into<HaTextContent>,
        size: Scalar,
        color: Rgba,
        alignment: impl Into<Vec2>,
    ) {
        let alignment = alignment.into();
        self.renderables.draw(
            TextRenderable::new(font, content)
                .position(Vec2::lerp(
                    vec2(self.layout.x, self.layout.y),
                    vec2(self.layout.x + self.layout.w, self.layout.y + self.layout.h),
                    alignment,
                ))
                .size(size)
                .color(color)
                .alignment(alignment)
                .bounds_width(Some(self.layout.w))
                .bounds_height(Some(self.layout.h)),
        );
    }

    pub fn button<F>(&mut self, mut f: F) -> bool
    where
        F: FnMut(Gui<T>, bool) -> bool,
    {
        let hovers = self.hovers();
        let gui = self.gui();
        if f(gui, hovers) && hovers {
            *self.input_consumed = true;
            true
        } else {
            false
        }
    }

    pub fn gui(&mut self) -> Gui<T> {
        Gui {
            layout: self.layout,
            pointer: self.pointer,
            input_consumed: self.input_consumed,
            camera: self.camera,
            renderables: self.renderables,
            context: self.context,
        }
    }
}

pub fn gui<T, F>(
    screen_pointer: impl Into<Vec2>,
    camera: &Camera,
    renderables: &mut Renderables,
    context: &mut T,
    mut f: F,
) -> bool
where
    F: FnMut(Gui<T>),
{
    let point = camera.screen_to_camera_point(screen_pointer.into());
    let dim = camera.world_size();
    if !point.x.is_finite()
        || !point.y.is_finite()
        || !dim.x.is_finite()
        || !dim.y.is_finite()
        || dim.x.abs() < 1.0e-6
        || dim.y.abs() < 1.0e-6
    {
        return false;
    }
    let half_dim = dim * 0.5;
    let layout = Rect {
        x: -half_dim.x,
        y: -half_dim.y,
        w: dim.x,
        h: dim.y,
    };
    let mut input_consumed = false;
    renderables.draw(Renderable::PushTransform(camera.transform()));
    let gui = Gui::<T> {
        layout,
        pointer: point - half_dim,
        input_consumed: &mut input_consumed,
        camera,
        renderables,
        context,
    };
    f(gui);
    renderables.draw(Renderable::PopTransform);
    input_consumed
}