sgl-2d 0.2.0

Caller-driven 2D rendering, assets, text, lighting, and immediate UI for SGL games
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
//! Layout widgets: splitters that resize caller-owned extents, and clipped
//! scroll areas.

use super::{UiFrame, widget_id};
use crate::canvas::draw::Rect;

/// Scroll-wheel lines → content pixels (one "line" of a list).
const SCROLL_LINE_PX: f32 = 40.0;
/// Scrollbar track width in logical pixels.
const SCROLLBAR_W: f32 = 8.0;

/// Axis along which a splitter changes its caller-owned extent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SplitterAxis {
    /// Left/right movement changes width.
    Horizontal,
    /// Up/down movement changes height.
    Vertical,
}

/// Cursor intent; the game maps this to its platform cursor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UiCursor {
    /// Left/right resize.
    ResizeHorizontal,
    /// Up/down resize.
    ResizeVertical,
}

/// Caller-owned splitter configuration. Bounds must be finite and `min <= max`.
#[derive(Debug, Clone, Copy)]
pub struct Splitter {
    pub axis: SplitterAxis,
    pub min: f32,
    pub max: f32,
}

/// Splitter result for this frame. Cursor intent persists outside the handle
/// during capture; apply it before dispatching pointer input to the world.
#[derive(Debug, Clone, Copy)]
pub struct SplitterResponse {
    pub changed: bool,
    pub dragging: bool,
    pub cursor: Option<UiCursor>,
}

#[derive(Debug, Clone, Copy)]
pub(super) struct SplitterDrag {
    id: u64,
    start: f32,
    extent: f32,
}

impl UiFrame<'_> {
    /// Capture a press on `handle` and resize `extent` by pointer travel.
    /// Composition and drawing remain caller-owned. Submit once each frame;
    /// removal ends capture at frame end. Dragging continues across panes and
    /// outside the handle/clip until release or `Ui::cancel_interactions`.
    pub fn splitter(
        &mut self,
        name: &str,
        handle: Rect,
        extent: &mut f32,
        options: Splitter,
    ) -> SplitterResponse {
        let id = widget_id(name);
        let hover = self.hit(&handle);
        let position = match options.axis {
            SplitterAxis::Horizontal => self.input.mouse_pos.x,
            SplitterAxis::Vertical => self.input.mouse_pos.y,
        };
        if hover && self.input.mouse_pressed {
            self.ui.pointer_consumed = true;
            self.ui.splitter_drag = Some(SplitterDrag {
                id,
                start: position,
                extent: *extent,
            });
            self.ui.active = Some(id);
        }
        let mut changed = false;
        let captured = self.ui.splitter_drag.filter(|drag| drag.id == id);
        if let Some(drag) = captured {
            self.splitter_seen = true;
            if self.input.mouse_down || self.input.mouse_released {
                let next = (drag.extent + position - drag.start).clamp(options.min, options.max);
                changed = *extent != next;
                *extent = next;
            }
        }
        let dragging = captured.is_some() && !self.input.mouse_released;
        SplitterResponse {
            changed,
            dragging,
            cursor: (hover || dragging).then_some(match options.axis {
                SplitterAxis::Horizontal => UiCursor::ResizeHorizontal,
                SplitterAxis::Vertical => UiCursor::ResizeVertical,
            }),
        }
    }

    /// Begin a vertically scrollable, clipped region: `content_h` is the
    /// total content height laid out from `rect.min.y - *offset`. The wheel
    /// scrolls while hovered; a draggable scrollbar appears when content
    /// overflows; `*offset` is clamped to the valid range. Draws after this
    /// clip to `rect` (including text) until
    /// [`scroll_area_end`](Self::scroll_area_end).
    pub fn scroll_area_begin(&mut self, name: &str, rect: Rect, content_h: f32, offset: &mut f32) {
        let id = widget_id(name);
        let view_h = rect.size().y;
        let max_off = (content_h - view_h).max(0.0);

        if self.hit(&rect) {
            *offset -= self.input.scroll.y * SCROLL_LINE_PX;
        }
        *offset = offset.clamp(0.0, max_off);

        if max_off > 0.0 {
            let track = Rect::new(rect.max.x - SCROLLBAR_W, rect.min.y, SCROLLBAR_W, view_h);
            let thumb_h = (view_h * view_h / content_h).clamp(20.0_f32.min(view_h), view_h);
            let travel = view_h - thumb_h;
            let thumb_at = |off: f32| {
                Rect::new(
                    track.min.x,
                    rect.min.y + (off / max_off) * travel,
                    SCROLLBAR_W,
                    thumb_h,
                )
            };

            // Thumb drag: grab on press, track the pointer while held.
            if self.input.mouse_pressed && self.hit(&thumb_at(*offset)) {
                self.ui.active = Some(id);
                self.ui.thumb_drag = Some((id, self.input.mouse_pos.y - thumb_at(*offset).min.y));
            }
            if let Some((drag_id, grab)) = self.ui.thumb_drag
                && drag_id == id
            {
                if self.input.mouse_down && travel > 0.0 {
                    let t = ((self.input.mouse_pos.y - grab) - rect.min.y) / travel;
                    *offset = t.clamp(0.0, 1.0) * max_off;
                } else {
                    self.ui.thumb_drag = None;
                }
            }

            let thumb = thumb_at(*offset);
            let dragging = matches!(self.ui.thumb_drag, Some((d, _)) if d == id);
            let color = if dragging || self.hit(&thumb) {
                self.ui.theme.scroll_thumb_hovered
            } else {
                self.ui.theme.scroll_thumb
            };
            self.rect(track, self.ui.theme.scroll_track);
            self.rect(thumb, color);
        }

        self.set_clip(Some(rect));
    }

    /// End the current scroll area (drops the clip).
    pub fn scroll_area_end(&mut self) {
        self.set_clip(None);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::canvas::draw::DrawList;
    use crate::ui::UiInput;
    use crate::ui::test_ui::{fixture, hover_at, press_at};
    use sgl_core::math::Vec2;
    use wasm_bindgen_test::wasm_bindgen_test;

    #[wasm_bindgen_test(unsupported = test)]
    fn splitter_capture_crosses_panes_and_cancels() {
        let (mut ui, mut text, _assets) = fixture();
        let mut extent = 100.0;
        let options = Splitter {
            axis: SplitterAxis::Horizontal,
            min: 60.0,
            max: 180.0,
        };
        for (x, press, release, expected) in [
            (102.0, true, false, 100.0),
            (142.0, false, false, 140.0),
            (300.0, false, false, 180.0),
            (-50.0, false, true, 60.0),
        ] {
            let mut list = DrawList::new();
            let mut f = ui.begin(
                &mut text,
                &mut list,
                UiInput {
                    mouse_pos: Vec2::new(x, 15.0),
                    mouse_pressed: press,
                    mouse_released: release,
                    mouse_down: !release,
                    ..UiInput::default()
                },
            );
            let result = f.splitter(
                "split",
                Rect::new(extent, 0.0, 5.0, 100.0),
                &mut extent,
                options,
            );
            assert!(!f.button("pane", Rect::new(-100.0, 0.0, 500.0, 100.0), "Pane", 12.0));
            assert_eq!(extent, expected);
            assert_eq!(result.dragging, !release);
            f.end();
            assert!(
                ui.pointer_captured(),
                "release remains consumed for world dispatch"
            );
        }
        for remove in [false, true] {
            let mut list = DrawList::new();
            let mut f = ui.begin(
                &mut text,
                &mut list,
                UiInput {
                    mouse_pos: Vec2::new(62.0, 15.0),
                    mouse_pressed: true,
                    mouse_down: true,
                    ..UiInput::default()
                },
            );
            f.splitter(
                "split",
                Rect::new(60.0, 0.0, 5.0, 100.0),
                &mut extent,
                options,
            );
            f.end();
            assert!(ui.pointer_captured());
            if remove {
                ui.begin(&mut text, &mut list, UiInput::default()).end();
            } else {
                ui.cancel_interactions();
            }
            assert_eq!(ui.pointer_captured(), remove);
            let mut f = ui.begin(
                &mut text,
                &mut list,
                UiInput {
                    mouse_pos: Vec2::new(170.0, 15.0),
                    mouse_down: true,
                    ..UiInput::default()
                },
            );
            assert!(
                !f.splitter(
                    "split",
                    Rect::new(60.0, 0.0, 5.0, 100.0),
                    &mut extent,
                    options
                )
                .changed
            );
            f.end();
            assert_eq!(extent, 60.0);
        }
    }

    /// #255: the drawn geometry the games rely on, against hand-computed
    /// rects — the scrollbar track and thumb for a known offset, the thumb
    /// drag mapping, and the tooltip's placement and clamping.
    #[wasm_bindgen_test(unsupported = test)]
    fn scrollbar_thumb_and_tooltip_geometry_are_exact() {
        let (mut ui, mut text, _assets) = fixture();
        let area = Rect::new(100.0, 100.0, 200.0, 100.0);
        let content_h = 400.0; // max offset 300, thumb 25 px, travel 75 px
        let mut offset = 150.0;
        let mut list = DrawList::new();
        let mut f = ui.begin(&mut text, &mut list, hover_at(0.0, 0.0, false));
        f.scroll_area_begin("s", area, content_h, &mut offset);
        f.scroll_area_end();
        f.end();
        let rects: Vec<(Vec2, Vec2)> = list.screen.iter().map(|q| (q.pos, q.scale)).collect();
        let track = (Vec2::new(296.0, 150.0), Vec2::new(8.0, 100.0));
        let thumb = (Vec2::new(296.0, 100.0 + 37.5 + 12.5), Vec2::new(8.0, 25.0));
        assert!(rects.contains(&track), "track missing in {rects:?}");
        assert!(rects.contains(&thumb), "thumb missing in {rects:?}");

        // Grab the thumb at its center and drag to the bottom of the track:
        // the offset follows the thumb's top through the travel.
        let mut list = DrawList::new();
        let mut f = ui.begin(&mut text, &mut list, press_at(296.0, 150.0));
        f.scroll_area_begin("s", area, content_h, &mut offset);
        f.scroll_area_end();
        f.end();
        let mut list = DrawList::new();
        let mut f = ui.begin(&mut text, &mut list, hover_at(296.0, 300.0, true));
        f.scroll_area_begin("s", area, content_h, &mut offset);
        f.scroll_area_end();
        f.end();
        assert_eq!(
            offset, 300.0,
            "dragged past the end clamps to the max offset"
        );

        // Tooltip: below the anchor with 6 px padding, clamped inside bounds.
        let bounds = Rect::new(0.0, 0.0, 400.0, 300.0);
        let anchor = Rect::new(350.0, 250.0, 40.0, 20.0);
        let mut list = DrawList::new();
        let mut f = ui.begin(&mut text, &mut list, hover_at(360.0, 260.0, false));
        f.tooltip(anchor, bounds, "tip", 16.0);
        let size = f.measure_text("tip", 16.0);
        f.end();
        let tip_w = size.x + 12.0;
        let tip_h = size.y + 6.0;
        let tip_x = (350.0f32).min(400.0 - tip_w - 2.0);
        let tip_y = 250.0 - tip_h - 4.0; // no room below: flipped above
        let backdrop = (
            Vec2::new(tip_x + tip_w * 0.5, tip_y + tip_h * 0.5),
            Vec2::new(tip_w, tip_h),
        );
        let close = |a: Vec2, b: Vec2| (a - b).abs().max_element() < 1e-3;
        let found = list
            .screen
            .iter()
            .any(|q| close(q.pos, backdrop.0) && close(q.scale, backdrop.1));
        let rects: Vec<(Vec2, Vec2)> = list.screen.iter().map(|q| (q.pos, q.scale)).collect();
        assert!(found, "tooltip backdrop {backdrop:?} missing in {rects:?}");
    }

    /// Scroll area: wheel scrolls only while hovered, the offset clamps to
    /// the content range, and content drawn inside carries the clip rect.
    #[wasm_bindgen_test(unsupported = test)]
    fn scroll_area_scrolls_clamps_and_clips() {
        let (mut ui, mut text, _assets) = fixture();
        let mut list = DrawList::new();
        let area = Rect::new(700.0, 60.0, 200.0, 300.0);
        let mut offset = 0.0_f32;

        // Wheel down (negative y) while hovered scrolls the content down.
        let input = UiInput {
            mouse_pos: Vec2::new(750.0, 200.0),
            scroll: Vec2::new(0.0, -2.0),
            ..UiInput::default()
        };
        let mut f = ui.begin(&mut text, &mut list, input);
        f.scroll_area_begin("palette", area, 900.0, &mut offset);
        f.rect(Rect::new(710.0, 70.0, 100.0, 40.0), [1.0; 4]);
        f.scroll_area_end();
        f.rect(Rect::new(0.0, 0.0, 10.0, 10.0), [1.0; 4]);
        f.end();
        assert!(offset > 0.0, "wheel-down scrolled: {offset}");
        let n = list.screen.len();
        assert_eq!(
            list.screen[n - 2].clip,
            Some(area),
            "content carries the clip"
        );
        assert_eq!(list.screen[n - 1].clip, None, "clip resets after end");

        // Wheel while NOT hovered does nothing.
        let before = offset;
        let input = UiInput {
            mouse_pos: Vec2::new(100.0, 100.0),
            scroll: Vec2::new(0.0, -2.0),
            ..UiInput::default()
        };
        let mut f = ui.begin(&mut text, &mut list, input);
        f.scroll_area_begin("palette", area, 900.0, &mut offset);
        f.scroll_area_end();
        f.end();
        assert_eq!(offset, before, "unhovered wheel must not scroll");

        // The offset clamps to [0, content_h - view_h].
        offset = 1e6;
        let mut f = ui.begin(&mut text, &mut list, UiInput::default());
        f.scroll_area_begin("palette", area, 900.0, &mut offset);
        f.scroll_area_end();
        f.end();
        assert_eq!(offset, 600.0, "clamped to content_h - view_h");
        offset = -50.0;
        let mut f = ui.begin(&mut text, &mut list, UiInput::default());
        f.scroll_area_begin("palette", area, 900.0, &mut offset);
        f.scroll_area_end();
        f.end();
        assert_eq!(offset, 0.0);

        // Content shorter than the view: no scrolling, no scrollbar thumb.
        offset = 10.0;
        let mut f = ui.begin(&mut text, &mut list, UiInput::default());
        f.scroll_area_begin("palette", area, 100.0, &mut offset);
        f.scroll_area_end();
        f.end();
        assert_eq!(offset, 0.0, "short content pins to the top");
    }

    /// Widgets clipped by a scroll area only respond where visible: a press
    /// inside the widget rect but outside the clip is ignored.
    #[wasm_bindgen_test(unsupported = test)]
    fn clipped_widgets_ignore_presses_outside_the_clip() {
        let (mut ui, mut text, _assets) = fixture();
        let mut list = DrawList::new();
        let area = Rect::new(0.0, 0.0, 200.0, 100.0);
        let mut offset = 0.0_f32;

        // The button extends below the clip (y 80..160); press at y=120.
        let mut f = ui.begin(&mut text, &mut list, press_at(50.0, 120.0));
        f.scroll_area_begin("list", area, 400.0, &mut offset);
        let fired = f.button("item", Rect::new(10.0, 80.0, 150.0, 80.0), "I", 16.0);
        f.scroll_area_end();
        f.end();
        assert!(!fired, "press outside the clip must not fire");

        // The same press inside the visible part fires.
        let mut f = ui.begin(&mut text, &mut list, press_at(50.0, 90.0));
        f.scroll_area_begin("list", area, 400.0, &mut offset);
        let fired = f.button("item", Rect::new(10.0, 80.0, 150.0, 80.0), "I", 16.0);
        f.scroll_area_end();
        f.end();
        assert!(fired, "visible part still fires");
    }
}