ferravex_play/input/touch/
layout.rs

1//! Saved logical touch-layout edits. Slots refer to stable authored controls.
2use super::*;
3use crate::persistence::{Document, SaveData, SaveError, Value};
4
5/// Bounded diagnostics for an already resolved layout, indexed by authored slot.
6///
7/// Unused slots and the overlap diagonal are false. Overlaps are symmetric and
8/// include look regions: an intentional background look region can overlap a
9/// button, but layout order still determines which control captures a finger.
10/// Touching edges count as overlaps because touch hit tests include boundaries.
11/// No controls are moved, removed or reordered by diagnostics.
12///
13/// ```
14/// use ferravex_math::{Rect, Vec2};
15/// use ferravex_play::input::touch::{Control, Output, Region, TouchLayoutSettings};
16/// let controls = [Control {
17///     region: Region::Rect(Rect::new(0., 0., 60., 60.)),
18///     output: Output::Button(0),
19/// }; 2];
20/// let report = TouchLayoutSettings::diagnose_layout(
21///     &controls, Vec2::splat(200.), Rect::new(10., 10., 180., 180.),
22/// )?;
23/// assert!(report.out_of_bounds[0]);
24/// assert!(report.overlaps[0][1] && report.overlaps[1][0]);
25/// assert!(!report.is_clear());
26/// # Ok::<(), ferravex_play::input::InputError>(())
27/// ```
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29pub struct TouchLayoutDiagnostics {
30    /// True when any part of a control's hit region lies outside the safe area.
31    pub out_of_bounds: [bool; MAX_TOUCH_CONTROLS],
32    /// True when two distinct controls share any point in their hit regions.
33    pub overlaps: [[bool; MAX_TOUCH_CONTROLS]; MAX_TOUCH_CONTROLS],
34}
35impl TouchLayoutDiagnostics {
36    /// Whether every region fits and no distinct regions share a hit point.
37    /// See the type's example for inspecting individual slots.
38    pub fn is_clear(&self) -> bool {
39        !self.out_of_bounds.iter().any(|&outside| outside)
40            && !self.overlaps.iter().flatten().any(|&overlap| overlap)
41    }
42}
43
44#[derive(Clone, Copy, Debug, PartialEq)]
45pub struct TouchEdit {
46    pub offset: Vec2,
47    pub scale: f32,
48}
49impl Default for TouchEdit {
50    fn default() -> Self {
51        Self {
52            offset: Vec2::ZERO,
53            scale: 1.,
54        }
55    }
56}
57#[derive(Clone, Copy, Debug, PartialEq)]
58pub struct TouchLayoutSettings {
59    pub mirrored: bool,
60    pub scale: f32,
61    pub opacity: f32,
62    pub edits: [TouchEdit; MAX_TOUCH_CONTROLS],
63}
64impl Default for TouchLayoutSettings {
65    fn default() -> Self {
66        Self {
67            mirrored: false,
68            scale: 1.,
69            opacity: 0.65,
70            edits: [TouchEdit::default(); MAX_TOUCH_CONTROLS],
71        }
72    }
73}
74impl TouchLayoutSettings {
75    pub fn valid(self) -> bool {
76        self.scale.is_finite()
77            && (0.6..=1.8).contains(&self.scale)
78            && self.opacity.is_finite()
79            && (0.2..=1.).contains(&self.opacity)
80            && self.edits.iter().all(|e| {
81                e.offset.is_finite()
82                    && e.offset.abs().max_element() <= 0.4
83                    && e.scale.is_finite()
84                    && (0.5..=2.).contains(&e.scale)
85            })
86    }
87    pub fn apply(self, mut c: Control, slot: usize, viewport: Vec2) -> Result<Control, InputError> {
88        if !self.valid()
89            || slot >= MAX_TOUCH_CONTROLS
90            || !c.valid()
91            || !viewport.is_finite()
92            || viewport.min_element() < 64.
93        {
94            return Err(InputError::InvalidTouch);
95        }
96        if self == Self::default() {
97            return Ok(c);
98        }
99        if let Output::Look { .. } = c.output {
100            if self.mirrored {
101                c.region = match c.region {
102                    Region::Rect(r) => {
103                        Region::Rect(Rect::new(viewport.x - r.x - r.w, r.y, r.w, r.h))
104                    }
105                    Region::Circle { center, radius } => Region::Circle {
106                        center: Vec2::new(viewport.x - center.x, center.y),
107                        radius,
108                    },
109                };
110            }
111            return Ok(c);
112        }
113        let edit = self.edits[slot];
114        let scale = self.scale * edit.scale;
115        let mut center = c.region.center();
116        if self.mirrored {
117            center.x = viewport.x - center.x;
118        }
119        center += edit.offset * viewport;
120        c.region = match c.region {
121            Region::Circle { radius, .. } => {
122                let radius = (radius * scale)
123                    .max(22.)
124                    .min(viewport.min_element() * 0.5 - 8.);
125                let center = center.clamp(
126                    Vec2::splat(radius + 8.),
127                    viewport - Vec2::splat(radius + 8.),
128                );
129                Region::Circle { center, radius }
130            }
131            Region::Rect(r) => {
132                let size = (Vec2::new(r.w, r.h) * scale)
133                    .max(Vec2::splat(44.))
134                    .min(viewport - Vec2::splat(16.));
135                let half = size * 0.5;
136                let center =
137                    center.clamp(half + Vec2::splat(8.), viewport - half - Vec2::splat(8.));
138                Region::Rect(Rect::new(
139                    center.x - half.x,
140                    center.y - half.y,
141                    size.x,
142                    size.y,
143                ))
144            }
145        };
146        if let Output::Stick { radius, .. } = &mut c.output {
147            *radius = (*radius * scale).clamp(8., viewport.min_element() * 0.5 - 8.);
148        }
149        Ok(c)
150    }
151
152    /// Apply saved edits inside a checked safe rectangle in logical pixels.
153    ///
154    /// `c` must be the authored control for `viewport`, before any saved edits
155    /// or safe-area adaptation. Its center is mapped by `center / viewport`
156    /// into `safe_area`; mirroring and normalized edit offsets are relative to
157    /// that area. Buttons and sticks keep their logical-pixel size, scaled by
158    /// the saved settings, with the same 44-pixel minimum and 8-pixel margin as
159    /// customized [`Self::apply`] layouts. Oversized controls shrink to fit.
160    /// Look regions scale with the safe area and fit without that margin;
161    /// like `apply`, they ignore per-slot edits and size settings.
162    ///
163    /// Always recompute from authored controls when resizing. Neither saved
164    /// offsets nor authored controls are mutated, so clamping in a small area
165    /// cannot accumulate drift after resizing back. Geometry never depends on
166    /// opacity or edits to other slots. Unlike legacy `apply`, default settings
167    /// also fit controls. Installing a changed layout in [`TouchSurface`] still
168    /// releases existing captures; this method does not remap active fingers.
169    ///
170    /// Returns [`InputError::InvalidTouch`] for invalid settings/slot/control,
171    /// non-finite or out-of-range geometry, or a safe area outside the viewport.
172    /// Each viewport dimension must be in `64..=1_000_000`; each safe-area
173    /// dimension must be at least 64. Resolved controls must also satisfy the
174    /// existing touch geometry limits. Errors leave caller-owned state intact.
175    ///
176    /// ```
177    /// use ferravex_math::{Rect, Vec2};
178    /// use ferravex_play::input::touch::{Control, Output, Region, TouchLayoutSettings};
179    /// let mut settings = TouchLayoutSettings::default();
180    /// settings.edits[0].offset = Vec2::new(0.1, 0.);
181    /// let authored = Control {
182    ///     region: Region::Circle { center: Vec2::new(100., 100.), radius: 24. },
183    ///     output: Output::Button(0),
184    /// };
185    /// let viewport = Vec2::new(400., 200.);
186    /// let safe = Rect::new(20., 10., 360., 180.);
187    /// let resolved = settings.apply_in_safe_area(authored, 0, viewport, safe)?;
188    /// assert_eq!(resolved.region, Region::Circle {
189    ///     center: Vec2::new(146., 100.), radius: 24.,
190    /// });
191    /// assert!(TouchLayoutSettings::diagnose_layout(&[resolved], viewport, safe)?.is_clear());
192    /// assert_eq!(settings.edits[0].offset, Vec2::new(0.1, 0.));
193    /// # Ok::<(), ferravex_play::input::InputError>(())
194    /// ```
195    pub fn apply_in_safe_area(
196        self,
197        mut c: Control,
198        slot: usize,
199        viewport: Vec2,
200        safe_area: Rect,
201    ) -> Result<Control, InputError> {
202        check_safe_area(viewport, safe_area)?;
203        if !self.valid() || slot >= MAX_TOUCH_CONTROLS || !c.valid() {
204            return Err(InputError::InvalidTouch);
205        }
206        let available = Vec2::new(safe_area.w, safe_area.h);
207        let origin = Vec2::new(safe_area.x, safe_area.y);
208        let look = matches!(c.output, Output::Look { .. });
209        let edit = self.edits[slot];
210        let mut normalized = c.region.center() / viewport;
211        if self.mirrored {
212            normalized.x = 1. - normalized.x;
213        }
214        if !look {
215            normalized += edit.offset;
216        }
217        let center = origin + normalized * available;
218        let margin = if look { 0. } else { 8. };
219        let scale = self.scale * edit.scale;
220        let ratio = available / viewport;
221        c.region = match c.region {
222            Region::Circle { radius, .. } => {
223                let radius = if look {
224                    radius * ratio.min_element()
225                } else {
226                    (radius * scale).max(22.)
227                };
228                fit_circle(center, radius, safe_area, margin)
229            }
230            Region::Rect(r) => {
231                let size = Vec2::new(r.w, r.h);
232                let size = if look {
233                    size * ratio
234                } else {
235                    (size * scale).max(Vec2::splat(44.))
236                };
237                let (x, w) = fit_axis(center.x, size.x, safe_area.x, safe_area.w, margin);
238                let (y, h) = fit_axis(center.y, size.y, safe_area.y, safe_area.h, margin);
239                Region::Rect(Rect::new(x, y, w, h))
240            }
241        };
242        if let Output::Stick { radius, .. } = &mut c.output {
243            *radius = (*radius * scale).clamp(8., available.min_element() * 0.5 - 8.);
244        }
245        if !c.valid() || !region_inside(c.region, safe_area) {
246            return Err(InputError::InvalidTouch);
247        }
248        Ok(c)
249    }
250
251    /// Check resolved controls against a safe area without applying settings.
252    ///
253    /// Reports all out-of-bounds regions and every intersecting pair, including
254    /// pairs outside the safe area. Shape tests distinguish circles from their
255    /// bounding boxes and include tangencies, matching inclusive touch regions.
256    /// Work is bounded by 16 controls / 120 pairs and allocates no heap storage.
257    /// Invalid controls or safe geometry return [`InputError::InvalidTouch`];
258    /// more than [`MAX_TOUCH_CONTROLS`] returns [`InputError::TouchCapacity`].
259    /// Safe-area limits are those of [`Self::apply_in_safe_area`].
260    ///
261    /// ```
262    /// use ferravex_math::{Rect, Vec2};
263    /// use ferravex_play::input::touch::{Control, Output, Region, TouchLayoutSettings};
264    /// let controls = [Control {
265    ///     region: Region::Circle { center: Vec2::splat(50.), radius: 24. },
266    ///     output: Output::Button(0),
267    /// }];
268    /// let report = TouchLayoutSettings::diagnose_layout(
269    ///     &controls, Vec2::splat(100.), Rect::new(0., 0., 100., 100.),
270    /// )?;
271    /// assert!(report.is_clear());
272    /// # Ok::<(), ferravex_play::input::InputError>(())
273    /// ```
274    pub fn diagnose_layout(
275        controls: &[Control],
276        viewport: Vec2,
277        safe_area: Rect,
278    ) -> Result<TouchLayoutDiagnostics, InputError> {
279        if controls.len() > MAX_TOUCH_CONTROLS {
280            return Err(InputError::TouchCapacity);
281        }
282        check_safe_area(viewport, safe_area)?;
283        if controls.iter().any(|c| !c.valid()) {
284            return Err(InputError::InvalidTouch);
285        }
286        let mut report = TouchLayoutDiagnostics::default();
287        for (slot, control) in controls.iter().enumerate() {
288            report.out_of_bounds[slot] = !region_inside(control.region, safe_area);
289            for (other, previous) in controls[..slot].iter().enumerate() {
290                let overlap = regions_overlap(control.region, previous.region);
291                report.overlaps[slot][other] = overlap;
292                report.overlaps[other][slot] = overlap;
293            }
294        }
295        Ok(report)
296    }
297}
298
299fn check_safe_area(viewport: Vec2, safe: Rect) -> Result<(), InputError> {
300    if !viewport.is_finite()
301        || viewport.min_element() < 64.
302        || viewport.max_element() > 1e6
303        || ![safe.x, safe.y, safe.w, safe.h]
304            .into_iter()
305            .all(f32::is_finite)
306        || safe.x < 0.
307        || safe.y < 0.
308        || safe.w < 64.
309        || safe.h < 64.
310        || f64::from(safe.x) + f64::from(safe.w) > f64::from(viewport.x)
311        || f64::from(safe.y) + f64::from(safe.h) > f64::from(viewport.y)
312    {
313        return Err(InputError::InvalidTouch);
314    }
315    Ok(())
316}
317
318fn region_inside(region: Region, safe: Rect) -> bool {
319    let (min, max) = match region {
320        Region::Circle { center, radius } => (
321            [
322                f64::from(center.x) - f64::from(radius),
323                f64::from(center.y) - f64::from(radius),
324            ],
325            [
326                f64::from(center.x) + f64::from(radius),
327                f64::from(center.y) + f64::from(radius),
328            ],
329        ),
330        Region::Rect(r) => (
331            [f64::from(r.x), f64::from(r.y)],
332            [
333                f64::from(r.x) + f64::from(r.w),
334                f64::from(r.y) + f64::from(r.h),
335            ],
336        ),
337    };
338    min[0] >= f64::from(safe.x)
339        && min[1] >= f64::from(safe.y)
340        && max[0] <= f64::from(safe.x) + f64::from(safe.w)
341        && max[1] <= f64::from(safe.y) + f64::from(safe.h)
342}
343
344// Fit in f64 so fractional origins cannot invert equal f32 clamp endpoints.
345// Round sizes inward after returning to f32, including any center rounding.
346fn round_size_down(value: f64) -> f32 {
347    let rounded = value as f32;
348    if f64::from(rounded) > value {
349        rounded.next_down()
350    } else {
351        rounded
352    }
353}
354
355fn fit_axis(center: f32, size: f32, origin: f32, extent: f32, margin: f32) -> (f32, f32) {
356    let low = f64::from(origin) + f64::from(margin);
357    let high = f64::from(origin) + f64::from(extent) - f64::from(margin);
358    let size = f64::from(size).min(high - low);
359    let mut start = (f64::from(center) - size * 0.5).clamp(low, high - size) as f32;
360    if f64::from(start) < low {
361        start = start.next_up();
362    }
363    (start, round_size_down(size.min(high - f64::from(start))))
364}
365
366fn fit_circle(center: Vec2, radius: f32, safe: Rect, margin: f32) -> Region {
367    let low = [
368        f64::from(safe.x) + f64::from(margin),
369        f64::from(safe.y) + f64::from(margin),
370    ];
371    let high = [
372        f64::from(safe.x) + f64::from(safe.w) - f64::from(margin),
373        f64::from(safe.y) + f64::from(safe.h) - f64::from(margin),
374    ];
375    let radius = f64::from(radius).min((high[0] - low[0]).min(high[1] - low[1]) * 0.5);
376    let center = Vec2::new(
377        f64::from(center.x).clamp(low[0] + radius, high[0] - radius) as f32,
378        f64::from(center.y).clamp(low[1] + radius, high[1] - radius) as f32,
379    );
380    let radius = radius
381        .min(f64::from(center.x) - low[0])
382        .min(high[0] - f64::from(center.x))
383        .min(f64::from(center.y) - low[1])
384        .min(high[1] - f64::from(center.y));
385    Region::Circle {
386        center,
387        radius: round_size_down(radius),
388    }
389}
390
391fn regions_overlap(a: Region, b: Region) -> bool {
392    match (a, b) {
393        (Region::Rect(a), Region::Rect(b)) => {
394            f64::from(a.x) <= f64::from(b.x) + f64::from(b.w)
395                && f64::from(b.x) <= f64::from(a.x) + f64::from(a.w)
396                && f64::from(a.y) <= f64::from(b.y) + f64::from(b.h)
397                && f64::from(b.y) <= f64::from(a.y) + f64::from(a.h)
398        }
399        (
400            Region::Circle {
401                center: a,
402                radius: ar,
403            },
404            Region::Circle {
405                center: b,
406                radius: br,
407            },
408        ) => distance_within(a, b, f64::from(ar) + f64::from(br)),
409        (Region::Circle { center, radius }, Region::Rect(r))
410        | (Region::Rect(r), Region::Circle { center, radius }) => {
411            let x = f64::from(center.x);
412            let y = f64::from(center.y);
413            let dx = x - x.clamp(f64::from(r.x), f64::from(r.x) + f64::from(r.w));
414            let dy = y - y.clamp(f64::from(r.y), f64::from(r.y) + f64::from(r.h));
415            dx * dx + dy * dy <= f64::from(radius) * f64::from(radius)
416        }
417    }
418}
419
420fn distance_within(a: Vec2, b: Vec2, radius: f64) -> bool {
421    let x = f64::from(a.x) - f64::from(b.x);
422    let y = f64::from(a.y) - f64::from(b.y);
423    x * x + y * y <= radius * radius
424}
425
426impl SaveData for TouchLayoutSettings {
427    const SCHEMA: u64 = 0x4658544f55434831;
428    const VERSION: u32 = 1;
429    const MAX_BYTES: usize = 512;
430    fn write(&self, d: &mut Document) -> Result<(), SaveError> {
431        if !self.valid() {
432            return Err(SaveError::InvalidData);
433        }
434        let mut b = vec![u8::from(self.mirrored)];
435        for v in [self.scale, self.opacity] {
436            b.extend_from_slice(&v.to_le_bytes());
437        }
438        for e in self.edits {
439            for v in [e.offset.x, e.offset.y, e.scale] {
440                b.extend_from_slice(&v.to_le_bytes());
441            }
442        }
443        d.set("layout", Value::Bytes(b))
444    }
445    fn read(d: &Document) -> Result<Self, SaveError> {
446        let b = d.bytes("layout")?;
447        if b.len() != 201 || b[0] > 1 {
448            return Err(SaveError::InvalidData);
449        }
450        let mut values = b[1..]
451            .as_chunks::<4>()
452            .0
453            .iter()
454            .map(|w| f32::from_le_bytes(*w));
455        let mut result = Self {
456            mirrored: b[0] != 0,
457            scale: values.next().unwrap(),
458            opacity: values.next().unwrap(),
459            ..Default::default()
460        };
461        for e in &mut result.edits {
462            *e = TouchEdit {
463                offset: Vec2::new(values.next().unwrap(), values.next().unwrap()),
464                scale: values.next().unwrap(),
465            };
466        }
467        if !result.valid() {
468            return Err(SaveError::InvalidData);
469        }
470        Ok(result)
471    }
472}
473#[cfg(test)]
474mod tests {
475    use super::*;
476
477    fn button(region: Region) -> Control {
478        Control {
479            region,
480            output: Output::Button(0),
481        }
482    }
483
484    fn circle(x: f32, y: f32, radius: f32) -> Region {
485        Region::Circle {
486            center: Vec2::new(x, y),
487            radius,
488        }
489    }
490
491    fn close(a: Vec2, b: Vec2) {
492        assert!((a - b).abs().max_element() < 0.0001, "{a:?} != {b:?}");
493    }
494
495    #[test]
496    fn safe_area_preserves_normalized_edits_across_resize_and_clamping() {
497        let mut settings = TouchLayoutSettings::default();
498        settings.edits[0].offset = Vec2::new(0.1, -0.1);
499        let saved = settings.encode(9).unwrap();
500        let resolve = |viewport: Vec2, safe: Rect| {
501            let authored = button(Region::Circle {
502                center: viewport * Vec2::new(0.25, 0.75),
503                radius: 30.,
504            });
505            settings
506                .apply_in_safe_area(authored, 0, viewport, safe)
507                .unwrap()
508        };
509        let viewport = Vec2::new(400., 300.);
510        let safe = Rect::new(20., 30., 360., 240.);
511        let original = resolve(viewport, safe);
512        close(original.region.center(), Vec2::new(146., 186.));
513        let larger = resolve(viewport * 2., Rect::new(20., 30., 760., 540.));
514        close(larger.region.center(), Vec2::new(286., 381.));
515        assert_eq!(larger.region, circle(286., 381., 30.));
516        let tiny = resolve(Vec2::splat(80.), Rect::new(8., 8., 64., 64.));
517        assert_eq!(tiny.region, circle(40., 40., 24.));
518        assert_eq!(resolve(viewport, safe), original);
519        assert_eq!(settings.encode(9).unwrap(), saved);
520        assert_eq!(TouchLayoutSettings::VERSION, 1);
521    }
522
523    #[test]
524    fn mirroring_and_stick_radius_use_the_asymmetric_safe_area() {
525        let settings = TouchLayoutSettings {
526            mirrored: true,
527            scale: 1.5,
528            ..Default::default()
529        };
530        let c = Control {
531            region: circle(100., 100., 24.),
532            output: Output::Stick {
533                x: 2,
534                y: 3,
535                radius: 20.,
536                floating: true,
537            },
538        };
539        let adapted = settings
540            .apply_in_safe_area(c, 0, Vec2::new(400., 200.), Rect::new(40., 0., 320., 200.))
541            .unwrap();
542        assert_eq!(adapted.region, circle(280., 100., 36.));
543        assert_eq!(
544            adapted.output,
545            Output::Stick {
546                x: 2,
547                y: 3,
548                radius: 30.,
549                floating: true,
550            }
551        );
552    }
553
554    #[test]
555    fn look_regions_map_into_safe_area_without_button_minimums_or_edits() {
556        let viewport = Vec2::new(400., 200.);
557        let safe = Rect::new(40., 10., 320., 160.);
558        let c = Control {
559            region: Region::Rect(Rect::new(200., 0., 200., 200.)),
560            output: Output::Look { x: 0, y: 1 },
561        };
562        let mut settings = TouchLayoutSettings {
563            mirrored: true,
564            scale: 1.8,
565            ..Default::default()
566        };
567        settings.edits[0] = TouchEdit {
568            offset: Vec2::splat(0.4),
569            scale: 2.,
570        };
571        let adapted = settings.apply_in_safe_area(c, 0, viewport, safe).unwrap();
572        assert_eq!(
573            adapted.region,
574            Region::Rect(Rect::new(40., 10., 160., 160.))
575        );
576        assert_eq!(adapted.output, c.output);
577        let small = Control {
578            region: circle(100., 100., 10.),
579            ..c
580        };
581        assert_eq!(
582            settings
583                .apply_in_safe_area(small, 0, viewport, safe)
584                .unwrap()
585                .region,
586            circle(280., 90., 8.)
587        );
588    }
589
590    #[test]
591    fn opacity_and_other_slots_never_move_controls_or_drop_captures() {
592        let viewport = Vec2::new(400., 200.);
593        let safe = Rect::new(20., 10., 360., 180.);
594        let c = button(circle(100., 100., 10.));
595        let mut settings = TouchLayoutSettings::default();
596        let original = settings.apply_in_safe_area(c, 0, viewport, safe).unwrap();
597        let mut surface = TouchSurface::default();
598        let mut map = ActionMap::default();
599        surface.set_layout(&[original], &mut map).unwrap();
600        surface
601            .handle(
602                Event {
603                    id: 1,
604                    position: original.region.center(),
605                    phase: Phase::Start,
606                },
607                &mut map,
608            )
609            .unwrap();
610        settings.opacity = 0.2;
611        settings.edits[1].scale = 2.;
612        let restyled = settings.apply_in_safe_area(c, 0, viewport, safe).unwrap();
613        assert_eq!(restyled, original);
614        surface.set_layout(&[restyled], &mut map).unwrap();
615        assert_eq!(surface.active(), 1);
616        assert_eq!(map.physical_value(InputCode::Touch(0)), 1.);
617
618        let resized = settings
619            .apply_in_safe_area(
620                button(circle(100.25, 100., 10.)),
621                0,
622                Vec2::new(401., 200.),
623                Rect::new(20., 10., 361., 180.),
624            )
625            .unwrap();
626        close(
627            resized.region.center() - original.region.center(),
628            Vec2::new(0.25, 0.),
629        );
630        surface.set_layout(&[resized], &mut map).unwrap();
631        assert_eq!(surface.active(), 0);
632        assert_eq!(map.physical_value(InputCode::Touch(0)), 0.);
633    }
634
635    #[test]
636    fn checked_safe_area_rejects_invalid_geometry_settings_and_output() {
637        let settings = TouchLayoutSettings::default();
638        let c = button(circle(50., 50., 24.));
639        let viewport = Vec2::splat(200.);
640        let safe = Rect::new(10., 10., 180., 180.);
641        for viewport in [
642            Vec2::new(f32::NAN, 200.),
643            Vec2::new(200., f32::INFINITY),
644            Vec2::new(63., 200.),
645            Vec2::new(-200., 200.),
646            Vec2::splat(f32::MAX),
647            Vec2::splat(1_000_001.),
648        ] {
649            assert_eq!(
650                settings.apply_in_safe_area(c, 0, viewport, safe),
651                Err(InputError::InvalidTouch)
652            );
653            assert_eq!(
654                TouchLayoutSettings::diagnose_layout(&[c], viewport, safe),
655                Err(InputError::InvalidTouch)
656            );
657        }
658        for safe in [
659            Rect::new(f32::NAN, 0., 100., 100.),
660            Rect::new(0., f32::INFINITY, 100., 100.),
661            Rect::new(0., 0., f32::INFINITY, 100.),
662            Rect::new(0., 0., 100., f32::NAN),
663            Rect::new(-1., 0., 100., 100.),
664            Rect::new(0., -1., 100., 100.),
665            Rect::new(0., 0., 0., 100.),
666            Rect::new(0., 0., 100., 63.),
667            Rect::new(101., 0., 100., 100.),
668            Rect::new(0., 101., 100., 100.),
669        ] {
670            assert_eq!(
671                settings.apply_in_safe_area(c, 0, viewport, safe),
672                Err(InputError::InvalidTouch)
673            );
674            assert_eq!(
675                TouchLayoutSettings::diagnose_layout(&[c], viewport, safe),
676                Err(InputError::InvalidTouch)
677            );
678        }
679        assert_eq!(
680            settings.apply_in_safe_area(c, MAX_TOUCH_CONTROLS, viewport, safe),
681            Err(InputError::InvalidTouch)
682        );
683        assert_eq!(
684            TouchLayoutSettings {
685                scale: f32::NAN,
686                ..settings
687            }
688            .apply_in_safe_area(c, 0, viewport, safe),
689            Err(InputError::InvalidTouch)
690        );
691        let invalid = Control {
692            output: Output::Button(64),
693            ..c
694        };
695        assert_eq!(
696            settings.apply_in_safe_area(invalid, 0, viewport, safe),
697            Err(InputError::InvalidTouch)
698        );
699        assert_eq!(
700            TouchLayoutSettings::diagnose_layout(&[invalid], viewport, safe),
701            Err(InputError::InvalidTouch)
702        );
703        // Finite inputs can still produce a radius beyond TouchSurface's limit.
704        assert_eq!(
705            TouchLayoutSettings {
706                scale: 1.8,
707                ..settings
708            }
709            .apply_in_safe_area(
710                button(circle(500_000., 500_000., 100_000.)),
711                0,
712                Vec2::splat(1_000_000.),
713                Rect::new(0., 0., 1_000_000., 1_000_000.),
714            ),
715            Err(InputError::InvalidTouch)
716        );
717    }
718
719    #[test]
720    fn fits_buttons_rectangles_and_sticks_at_the_minimum_safe_size() {
721        let settings = TouchLayoutSettings::default();
722        let viewport = Vec2::splat(200.);
723        let safe = Rect::new(20., 30., 64., 64.);
724        for region in [
725            circle(-50., 250., 100.),
726            Region::Rect(Rect::new(-50., -50., 400., 400.)),
727        ] {
728            let c = Control {
729                region,
730                output: Output::Stick {
731                    x: 0,
732                    y: 1,
733                    radius: 200.,
734                    floating: false,
735                },
736            };
737            let adapted = settings.apply_in_safe_area(c, 0, viewport, safe).unwrap();
738            assert!(region_inside(adapted.region, safe));
739            close(adapted.region.center(), Vec2::new(52., 62.));
740            assert!(matches!(adapted.output, Output::Stick { radius: 24., .. }));
741            assert!(
742                TouchLayoutSettings::diagnose_layout(&[adapted], viewport, safe)
743                    .unwrap()
744                    .is_clear()
745            );
746        }
747    }
748
749    #[test]
750    fn fractional_safe_edges_fit_without_panics_or_spurious_bounds_errors() {
751        let settings = TouchLayoutSettings::default();
752        let viewport = Vec2::splat(1_000_000.);
753        for origin in [0.1, 0.3, 1.1, 17.3, 100_000.1] {
754            for size in [64.1, 100.3, 240.7] {
755                let safe = Rect::new(origin, origin, size, size);
756                for region in [
757                    Region::Rect(Rect::new(0., 0., 1_000_000., 1_000_000.)),
758                    circle(500_000., 500_000., 100_000.),
759                ] {
760                    for output in [Output::Look { x: 0, y: 1 }, Output::Button(0)] {
761                        let authored = Control { region, output };
762                        let adapted = settings
763                            .apply_in_safe_area(authored, 0, viewport, safe)
764                            .unwrap();
765                        assert!(
766                            TouchLayoutSettings::diagnose_layout(&[adapted], viewport, safe)
767                                .unwrap()
768                                .is_clear()
769                        );
770                    }
771                }
772            }
773        }
774        // A look circle filling the safe area has equal clamp endpoints.
775        let adapted = settings
776            .apply_in_safe_area(
777                Control {
778                    region: circle(100., 100., 100.),
779                    output: Output::Look { x: 0, y: 1 },
780                },
781                0,
782                Vec2::splat(200.),
783                Rect::new(17.3, 17.3, 64.1, 64.1),
784            )
785            .unwrap();
786        assert!(region_inside(
787            adapted.region,
788            Rect::new(17.3, 17.3, 64.1, 64.1)
789        ));
790    }
791
792    #[test]
793    fn diagnostics_keep_small_extents_at_large_coordinates() {
794        let viewport = Vec2::splat(1_000_000.);
795        let safe = Rect::new(500_000., 500_000., 64., 64.);
796        let report = TouchLayoutSettings::diagnose_layout(
797            &[button(circle(500_000., 500_000., 0.001))],
798            viewport,
799            safe,
800        )
801        .unwrap();
802        assert!(report.out_of_bounds[0]);
803        let report = TouchLayoutSettings::diagnose_layout(
804            &[
805                button(Region::Rect(Rect::new(500_000., 500_001., 0.005, 1.))),
806                button(circle(500_000.03, 500_001., 0.03)),
807            ],
808            viewport,
809            safe,
810        )
811        .unwrap();
812        assert!(report.overlaps[0][1]);
813    }
814
815    #[test]
816    fn diagnostics_use_real_shapes_and_inclusive_edges() {
817        let viewport = Vec2::splat(400.);
818        let safe = Rect::new(0., 0., 400., 400.);
819        let overlap = |a, b| {
820            let report =
821                TouchLayoutSettings::diagnose_layout(&[button(a), button(b)], viewport, safe)
822                    .unwrap();
823            assert_eq!(report.overlaps[0][1], report.overlaps[1][0]);
824            assert!(!report.overlaps[0][0] && !report.overlaps[1][1]);
825            report.overlaps[0][1]
826        };
827        assert!(!overlap(circle(50., 50., 10.), circle(65., 65., 10.)));
828        assert!(overlap(circle(50., 50., 10.), circle(70., 50., 10.)));
829        assert!(overlap(circle(50., 50., 20.), circle(50., 50., 1.)));
830        let rect = Region::Rect(Rect::new(100., 100., 40., 40.));
831        assert!(!overlap(rect, circle(92., 92., 10.)));
832        assert!(overlap(rect, circle(94., 92., 10.))); // 6-8-10 corner tangency.
833        assert!(overlap(circle(90., 120., 10.), rect));
834        assert!(overlap(rect, circle(120., 120., 1.)));
835        assert!(overlap(rect, Region::Rect(Rect::new(140., 140., 20., 20.))));
836        assert!(!overlap(
837            rect,
838            Region::Rect(Rect::new(140.5, 100., 20., 20.))
839        ));
840    }
841
842    #[test]
843    fn diagnostics_report_full_extents_without_changing_priority_or_controls() {
844        let viewport = Vec2::splat(200.);
845        let safe = Rect::new(10., 10., 180., 180.);
846        let controls = [
847            button(circle(20., 30., 11.)),
848            button(Region::Rect(Rect::new(10., 10., 180., 180.))),
849            Control {
850                region: circle(100., 100., 10.),
851                output: Output::Look { x: 0, y: 1 },
852            },
853            button(Region::Rect(Rect::new(189., 30., 2., 2.))),
854        ];
855        let before = controls;
856        let report = TouchLayoutSettings::diagnose_layout(&controls, viewport, safe).unwrap();
857        assert_eq!(&report.out_of_bounds[..4], &[true, false, false, true]);
858        assert!(report.overlaps[0][1] && report.overlaps[1][2] && report.overlaps[1][3]);
859        assert!(!report.overlaps[0][2]);
860        assert!(report.out_of_bounds[4..].iter().all(|&outside| !outside));
861        assert!(
862            report.overlaps[4..]
863                .iter()
864                .flatten()
865                .all(|&overlap| !overlap)
866        );
867        assert_eq!(controls, before);
868    }
869
870    #[test]
871    fn diagnostic_capacity_is_bounded_and_empty_layout_is_clear() {
872        let viewport = Vec2::splat(200.);
873        let safe = Rect::new(0., 0., 200., 200.);
874        assert!(
875            TouchLayoutSettings::diagnose_layout(&[], viewport, safe)
876                .unwrap()
877                .is_clear()
878        );
879        let controls = [button(circle(50., 50., 24.)); MAX_TOUCH_CONTROLS];
880        let report = TouchLayoutSettings::diagnose_layout(&controls, viewport, safe).unwrap();
881        assert_eq!(
882            report
883                .overlaps
884                .iter()
885                .flatten()
886                .filter(|&&value| value)
887                .count(),
888            240
889        );
890        assert_eq!(
891            TouchLayoutSettings::diagnose_layout(
892                &[controls[0]; MAX_TOUCH_CONTROLS + 1],
893                viewport,
894                safe
895            ),
896            Err(InputError::TouchCapacity)
897        );
898    }
899
900    #[test]
901    fn edits_roundtrip_mirror_resize_and_stay_visible() {
902        let mut p = TouchLayoutSettings {
903            mirrored: true,
904            scale: 1.5,
905            ..Default::default()
906        };
907        p.edits[0].offset = Vec2::new(0.4, 0.4);
908        assert_eq!(
909            TouchLayoutSettings::decode(&p.encode(4).unwrap()).unwrap(),
910            (p, 4)
911        );
912        let c = Control {
913            region: Region::Circle {
914                center: Vec2::new(40., 140.),
915                radius: 20.,
916            },
917            output: Output::Button(2),
918        };
919        let output = p.apply(c, 0, Vec2::new(320., 200.)).unwrap();
920        if let Region::Circle { center, radius } = output.region {
921            assert!(center.x + radius <= 312. && center.y + radius <= 192.);
922            assert!(radius >= 22.);
923        }
924        assert_eq!(output.output, c.output);
925        assert!(p.apply(c, 16, Vec2::new(320., 200.)).is_err());
926    }
927    #[test]
928    fn defaults_preserve_authored_controls() {
929        let c = Control {
930            region: Region::Rect(Rect::new(0., 0., 100., 100.)),
931            output: Output::Look { x: 0, y: 1 },
932        };
933        assert_eq!(
934            TouchLayoutSettings::default()
935                .apply(c, 0, Vec2::new(320., 200.))
936                .unwrap(),
937            c
938        );
939    }
940}