ferravex_play/ui/minimap.rs
1//! Checked, allocation-free projection of caller-authorized planar points.
2//!
3//! World coordinates are `(x, y)` in caller units (adapt an XZ plane explicitly
4//! with `vec2(position.x, position.z)`). [`WorldYAxis`] declares whether positive
5//! world Y points up or down. Map coordinates are logical UI units, X right and
6//! Y down. Positive rotation is **clockwise on screen**, in radians, applied
7//! after the Y convention. The world center stays at the map center. One uniform
8//! scale contains the entire rotated world rectangle, with centered letterboxing;
9//! there is no crop/stretch mode. [`Minimap::footprint`] is the actual rotated
10//! world boundary, which can occupy less than its axis-aligned bounding box.
11//!
12//! Both rectangles reuse [`Rect`]. Negative extents are rejected, never
13//! normalized. Edges are `min` and the f32 sum `min + size`, matching UI geometry;
14//! world edges are closed for projection. Pointer picking first uses the map's
15//! **half-open** bounds and the caller's half-open safe/clip rectangle, then
16//! rejects letterbox/rotated-corner space outside the world footprint. No DPR
17//! conversion occurs here. Feed already-logical coordinates, or call
18//! [`super::Viewport::unproject`] exactly once before picking in viewport space.
19//!
20//! Arithmetic widens before subtraction, scaling and rotation. Returned [`Vec2`]
21//! coordinates round to f32; round trips are approximate, especially near large
22//! origins or thin rectangles. Picking allows half the larger adjacent f32
23//! spacing per map coordinate around the world footprint (plus an f64 arithmetic
24//! allowance), then clamps that numerical fringe to its closed world edge.
25//! This never widens the half-open map/safe rectangles. Rectangles with
26//! subnormal/zero extents or collapsed/overflowing f32 edges are rejected, as is
27//! a fitted world boundary with collapsed/collinear corners. There is no
28//! exact-predicate or cross-platform bitwise-determinism promise.
29//!
30//! No journal, discovery, renderer, input, simulation or global state is owned.
31//! Unknown/unauthorized points must be **omitted by the caller**; absence never
32//! creates a marker. Reconfiguration replaces all geometry transactionally; no
33//! separate reset is needed. Queries and batches retain no history and allocate
34//! no heap storage. All batches have a fixed [`MAX_MINIMAP_POINTS`] work bound.
35//!
36//! # Runnable Crystal-style revealed-room and waypoint recipe
37//!
38//! This uses supplied sample data, not Crystal's real journal. Parent adoption
39//! must select only rooms already revealed by accepted game events, retain IDs,
40//! and authorize any picked waypoint. Geometry alone grants no gameplay access.
41//!
42//! ```rust
43//! use ferravex_math::{Vec2, vec2};
44//! use ferravex_play::ui::{Rect, Viewport};
45//! use ferravex_play::ui::minimap::{
46//! MapConfig, Minimap, MinimapError, OffMapPolicy, ProjectionStatus, WorldYAxis,
47//! };
48//!
49//! fn main() -> Result<(), MinimapError> {
50//! let viewport = Viewport::responsive([400., 300.], [12., 20., 8., 10.]).unwrap();
51//! let config = MapConfig {
52//! world: Rect { min: [-20., -10.], size: [80., 40.] },
53//! map: Rect { min: [16., 24.], size: [240., 160.] },
54//! y_axis: WorldYAxis::Up,
55//! rotation_radians: 0.,
56//! };
57//! let mut map = Minimap::new(config)?;
58//! // None represents unknown/omitted location, never an inferred objective.
59//! let supplied_rooms = [(7, Some(vec2(0., 0.))), (9, None),
60//! (12, Some(vec2(40., 20.)))];
61//! let mut ids = [0; 3];
62//! let mut known = [Vec2::ZERO; 3];
63//! let mut count = 0;
64//! for (id, point) in supplied_rooms {
65//! if let Some(point) = point {
66//! ids[count] = id;
67//! known[count] = point;
68//! count += 1;
69//! }
70//! }
71//! let seed = map.project(known[0], OffMapPolicy::ClampToEdge)?;
72//! let mut markers = [seed; 3];
73//! assert_eq!(map.project_into(&known[..count], OffMapPolicy::ClampToEdge,
74//! &mut markers)?, 2);
75//! assert_eq!(&ids[..count], &[7, 12]); // No room 9 marker.
76//! assert_eq!(markers[0].status, ProjectionStatus::Inside);
77//! let waypoint = map.project(vec2(100., 10.), OffMapPolicy::ClampToEdge)?;
78//! assert_eq!(waypoint.status, ProjectionStatus::Clamped);
79//! assert!(waypoint.off_map.unwrap().direction.x > 0.);
80//! let outside = map.project(vec2(100., 10.), OffMapPolicy::Preserve)?;
81//! assert_eq!(outside.status, ProjectionStatus::Outside);
82//! assert_eq!(outside.off_map, waypoint.off_map);
83//! let boundary = map.footprint(); // Use the same vertices for painting.
84//! assert!(boundary.into_iter().all(Vec2::is_finite));
85//! // Host pointer is already in logical screen units, with no DPR rescaling.
86//! let host_pointer = [markers[0].position.x + 12., markers[0].position.y + 20.];
87//! let logical = viewport.unproject(host_pointer).unwrap();
88//! let picked = map.pick(Vec2::from_array(logical), viewport.bounds())?.unwrap();
89//! assert!((picked - known[0]).length() < 0.0001);
90//! let old = map;
91//! let mut invalid = map.config();
92//! invalid.world.size[0] = 0.;
93//! assert!(map.reconfigure(invalid).is_err());
94//! assert_eq!(map, old); // Last-good transform survives failure.
95//! map.reconfigure(config)?; // Also the scene/resize reset operation.
96//! Ok(())
97//! }
98//! ```
99
100use super::Rect;
101use ferravex_math::Vec2;
102
103/// Maximum input count for one atomic [`Minimap::project_into`] call.
104pub const MAX_MINIMAP_POINTS: usize = 4096;
105
106/// Positive planar world Y convention before clockwise screen rotation.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub enum WorldYAxis {
109 /// Positive world Y initially points toward the screen top.
110 Up,
111 /// Positive world Y initially points toward the screen bottom.
112 Down,
113}
114
115/// Explicit world and map geometry. See the module recipe for construction.
116#[derive(Clone, Copy, Debug, PartialEq)]
117pub struct MapConfig {
118 /// Closed planar world bounds; not inferred from supplied points.
119 pub world: Rect,
120 /// Logical UI panel bounds, half-open for picking.
121 pub map: Rect,
122 pub y_axis: WorldYAxis,
123 /// Clockwise screen rotation in radians, after applying `y_axis`.
124 /// Any finite f32 angle is accepted; very large angles lose phase precision.
125 pub rotation_radians: f32,
126}
127
128/// Treatment of finite points outside the closed world rectangle.
129#[derive(Clone, Copy, Debug, PartialEq, Eq)]
130pub enum OffMapPolicy {
131 /// Preserve the projected location, which can be outside the panel.
132 /// Return `Unrepresentable` rather than an infinite f32 position.
133 Preserve,
134 /// Put the marker on the world-boundary ray intersection. This stays inside
135 /// the map's closed bounds, including under rotation and letterboxing.
136 ClampToEdge,
137}
138
139/// Separates inside, outside/unclamped, and outside/clamped markers.
140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141pub enum ProjectionStatus {
142 Inside,
143 Outside,
144 Clamped,
145}
146
147/// Boundary marker for an outside point, regardless of projection policy.
148#[derive(Clone, Copy, Debug, PartialEq)]
149pub struct OffMapIndicator {
150 /// Intersection of the center-to-point ray with the rotated world boundary;
151 /// this is not necessarily an edge of the axis-aligned panel.
152 pub position: Vec2,
153 /// Unit screen direction from map center toward the outside point.
154 pub direction: Vec2,
155}
156
157/// One projection, with no inferred ID, discovery or gameplay permission.
158#[derive(Clone, Copy, Debug, PartialEq)]
159pub struct MapProjection {
160 pub position: Vec2,
161 pub status: ProjectionStatus,
162 /// `None` exactly when `status == Inside`; otherwise the edge indicator.
163 pub off_map: Option<OffMapIndicator>,
164}
165
166/// Checked failure. Rejected updates/batches leave their destinations unchanged.
167#[derive(Clone, Copy, Debug, PartialEq, Eq)]
168#[non_exhaustive]
169pub enum MinimapError {
170 /// Nonfinite/degenerate rectangle, angle, pointer, or clip rectangle.
171 InvalidGeometry,
172 /// A supplied world point contains NaN or infinity.
173 InvalidPoint,
174 /// Required f32 output overflows or the fitted world collapses in f32.
175 Unrepresentable,
176 /// Too many input points or too little caller output storage.
177 Capacity,
178}
179
180impl std::fmt::Display for MinimapError {
181 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182 f.write_str(match self {
183 Self::InvalidGeometry => "invalid minimap geometry",
184 Self::InvalidPoint => "minimap world point must be finite",
185 Self::Unrepresentable => "minimap output is not representable in f32",
186 Self::Capacity => "minimap batch capacity exceeded",
187 })
188 }
189}
190impl std::error::Error for MinimapError {}
191
192/// Immutable checked geometry with transactional replacement, no heap storage.
193/// See the module recipe for all queries, batch projection and reconfiguration.
194#[derive(Clone, Copy, Debug, PartialEq)]
195pub struct Minimap {
196 config: MapConfig,
197 world_min: [f64; 2],
198 world_max: [f64; 2],
199 world_center: [f64; 2],
200 half: [f64; 2],
201 map_min: [f64; 2],
202 map_max: [f64; 2],
203 map_center: [f64; 2],
204 scale: f64,
205 sin: f64,
206 cos: f64,
207 y_sign: f64,
208}
209
210impl Minimap {
211 /// Validate explicit bounds and aspect-fit the full rotated world. Reject
212 /// collapsed/subnormal geometry rather than silently repairing it.
213 /// See the module recipe for an executed example.
214 pub fn new(config: MapConfig) -> Result<Self, MinimapError> {
215 let (world_min, world_max) = checked_rect(config.world)?;
216 let (map_min, map_max) = checked_rect(config.map)?;
217 if !config.rotation_radians.is_finite() {
218 return Err(MinimapError::InvalidGeometry);
219 }
220 let half = std::array::from_fn(|i| (world_max[i] - world_min[i]) * 0.5);
221 let map_half: [f64; 2] = std::array::from_fn(|i| (map_max[i] - map_min[i]) * 0.5);
222 let (sin, cos) = f64::from(config.rotation_radians).sin_cos();
223 let rotated_half = [
224 cos.abs() * half[0] + sin.abs() * half[1],
225 sin.abs() * half[0] + cos.abs() * half[1],
226 ];
227 let scale = (map_half[0] / rotated_half[0]).min(map_half[1] / rotated_half[1]);
228 let map = Self {
229 config,
230 world_min,
231 world_max,
232 world_center: std::array::from_fn(|i| world_min[i] + half[i]),
233 half,
234 map_min,
235 map_max,
236 map_center: std::array::from_fn(|i| map_min[i] + map_half[i]),
237 scale,
238 sin,
239 cos,
240 y_sign: if config.y_axis == WorldYAxis::Up {
241 -1.
242 } else {
243 1.
244 },
245 };
246 let corners = map.footprint();
247 // Display rounding must preserve a strictly convex quadrilateral. Even
248 // distinct adjacent vertices can all lie on one line at a large origin.
249 let turns: [f64; 4] = std::array::from_fn(|i| {
250 let a = corners[i].to_array().map(f64::from);
251 let b = corners[(i + 1) % 4].to_array().map(f64::from);
252 let c = corners[(i + 2) % 4].to_array().map(f64::from);
253 (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
254 });
255 if turns
256 .iter()
257 .any(|turn| *turn == 0. || turn.is_sign_positive() != turns[0].is_sign_positive())
258 {
259 return Err(MinimapError::Unrepresentable);
260 }
261 Ok(map)
262 }
263
264 /// Replace all geometry only after full validation. On error `self` stays
265 /// bit-for-bit unchanged. This is also the explicit resize/scene reset path.
266 /// See the module recipe for failure followed by successful replacement.
267 pub fn reconfigure(&mut self, config: MapConfig) -> Result<(), MinimapError> {
268 *self = Self::new(config)?;
269 Ok(())
270 }
271
272 /// Original configuration, without normalization. See the module recipe.
273 pub fn config(&self) -> MapConfig {
274 self.config
275 }
276
277 /// Display boundary in world corner order: min/min, max/min, max/max,
278 /// min/max. Y-up reverses its screen winding. Vertices round to f32 and stay
279 /// in the panel's closed bounds. See the module recipe for paint geometry.
280 pub fn footprint(&self) -> [Vec2; 4] {
281 [[-1., -1.], [1., -1.], [1., 1.], [-1., 1.]]
282 .map(|sign| self.bounded_screen([sign[0] * self.half[0], sign[1] * self.half[1]]))
283 }
284
285 /// Project a supplied finite point; world edges count as inside. Outside
286 /// points always carry an indicator, even when `Preserve` puts the position
287 /// inside a rotated footprint's bounding box. An overflowing preserved
288 /// position returns `Unrepresentable`; `ClampToEdge` remains bounded.
289 /// See the module recipe for both policies.
290 pub fn project(
291 &self,
292 point: Vec2,
293 policy: OffMapPolicy,
294 ) -> Result<MapProjection, MinimapError> {
295 if !point.is_finite() {
296 return Err(MinimapError::InvalidPoint);
297 }
298 let point = point.to_array().map(f64::from);
299 let delta = std::array::from_fn(|i| point[i] - self.world_center[i]);
300 let inside = (0..2).all(|i| point[i] >= self.world_min[i] && point[i] <= self.world_max[i]);
301 if inside {
302 return Ok(MapProjection {
303 position: self.bounded_screen(delta),
304 status: ProjectionStatus::Inside,
305 off_map: None,
306 });
307 }
308 let fraction = (0..2)
309 .map(|i| self.half[i] / delta[i].abs())
310 .fold(1., f64::min);
311 let position = self.bounded_screen(delta.map(|v| v * fraction));
312 let rotated = self.rotate(delta);
313 let length = rotated[0].hypot(rotated[1]);
314 let indicator = OffMapIndicator {
315 position,
316 direction: Vec2::from_array(rotated.map(|v| (v / length) as f32)),
317 };
318 let (position, status) = match policy {
319 OffMapPolicy::ClampToEdge => (position, ProjectionStatus::Clamped),
320 OffMapPolicy::Preserve => (checked_vec(self.screen(delta))?, ProjectionStatus::Outside),
321 };
322 Ok(MapProjection {
323 position,
324 status,
325 off_map: Some(indicator),
326 })
327 }
328
329 /// Atomic bounded batch, preserving input order and writing only the output
330 /// prefix of length `points.len()`. Empty input succeeds. Capacity is checked
331 /// first, then **every projection**, before any write. Any invalid point or
332 /// unrepresentable preserved output leaves the entire output unchanged.
333 /// Two passes take at most `2 * MAX_MINIMAP_POINTS` scalar projections and
334 /// constant scratch space. Unknown points must be omitted before this call.
335 /// See the module recipe for caller-owned ID and output buffers.
336 pub fn project_into(
337 &self,
338 points: &[Vec2],
339 policy: OffMapPolicy,
340 output: &mut [MapProjection],
341 ) -> Result<usize, MinimapError> {
342 if points.len() > MAX_MINIMAP_POINTS || output.len() < points.len() {
343 return Err(MinimapError::Capacity);
344 }
345 for point in points {
346 self.project(*point, policy)?;
347 }
348 for (point, slot) in points.iter().zip(output.iter_mut()) {
349 // Inputs and transform are immutable; the validation pass has already
350 // checked every conversion. No callback can change them between passes.
351 *slot = self.project(*point, policy)?;
352 }
353 Ok(points.len())
354 }
355
356 /// Inverse pick in the same logical units as `config.map`. `clip` is the
357 /// caller's current safe/visible rectangle, not another scale or DPR input.
358 /// Both map and clip use half-open containment. A valid empty clip is inert.
359 /// Returns `None` for letterbox space or outside the rotated footprint;
360 /// nonfinite pointers or invalid clips return `InvalidGeometry`.
361 /// Rounded boundary picks clamp only the documented half-cell fringe.
362 /// See the module recipe for safe-area and viewport composition.
363 pub fn pick(&self, pointer: Vec2, clip: Rect) -> Result<Option<Vec2>, MinimapError> {
364 if !pointer.is_finite() || !clip.valid() {
365 return Err(MinimapError::InvalidGeometry);
366 }
367 if !self.config.map.contains(pointer.to_array()) || !clip.contains(pointer.to_array()) {
368 return Ok(None);
369 }
370 let p = pointer.to_array();
371 let offset: [f64; 2] = std::array::from_fn(|i| f64::from(p[i]) - self.map_center[i]);
372 let delta = [
373 (self.cos * offset[0] + self.sin * offset[1]) / self.scale,
374 (-self.sin * offset[0] + self.cos * offset[1]) * self.y_sign / self.scale,
375 ];
376 // Invert the screen rounding cell as well as its center. The tiny f64
377 // arithmetic allowance covers cancellation in the inverse rotation.
378 let cell = p.map(rounding_radius);
379 let tolerance = [
380 (self.cos.abs() * cell[0] + self.sin.abs() * cell[1]) / self.scale,
381 (self.sin.abs() * cell[0] + self.cos.abs() * cell[1]) / self.scale,
382 ];
383 if (0..2).any(|i| {
384 delta[i].abs() > self.half[i] + tolerance[i] + 16. * f64::EPSILON * self.half[i]
385 }) {
386 return Ok(None);
387 }
388 let world = std::array::from_fn(|i| {
389 (self.world_center[i] + delta[i].clamp(-self.half[i], self.half[i]))
390 .clamp(self.world_min[i], self.world_max[i])
391 });
392 Ok(Some(checked_vec(world)?))
393 }
394
395 fn rotate(&self, delta: [f64; 2]) -> [f64; 2] {
396 let y = delta[1] * self.y_sign;
397 [
398 self.cos * delta[0] - self.sin * y,
399 self.sin * delta[0] + self.cos * y,
400 ]
401 }
402
403 fn screen(&self, delta: [f64; 2]) -> [f64; 2] {
404 let rotated = self.rotate(delta);
405 std::array::from_fn(|i| self.map_center[i] + rotated[i] * self.scale)
406 }
407
408 fn bounded_screen(&self, delta: [f64; 2]) -> Vec2 {
409 // The analytical fitted footprint is inside the panel. Clip only f64
410 // arithmetic drift before rounding to the panel's representable edges.
411 let screen = self.screen(delta);
412 Vec2::from_array(std::array::from_fn(|i| {
413 screen[i].clamp(self.map_min[i], self.map_max[i]) as f32
414 }))
415 }
416}
417
418fn checked_rect(rect: Rect) -> Result<([f64; 2], [f64; 2]), MinimapError> {
419 if !rect.valid()
420 || (0..2)
421 .any(|i| rect.size[i] < f32::MIN_POSITIVE || rect.min[i] + rect.size[i] <= rect.min[i])
422 {
423 return Err(MinimapError::InvalidGeometry);
424 }
425 Ok((
426 rect.min.map(f64::from),
427 std::array::from_fn(|i| f64::from(rect.min[i] + rect.size[i])),
428 ))
429}
430
431fn checked_vec(point: [f64; 2]) -> Result<Vec2, MinimapError> {
432 let result = Vec2::from_array(point.map(|v| v as f32));
433 result
434 .is_finite()
435 .then_some(result)
436 .ok_or(MinimapError::Unrepresentable)
437}
438
439fn rounding_radius(value: f32) -> f64 {
440 let magnitude = value.abs();
441 // At MAX use the preceding spacing rather than constructing infinity.
442 let spacing = if magnitude == f32::MAX {
443 f64::from(magnitude) - f64::from(f32::from_bits(magnitude.to_bits() - 1))
444 } else {
445 f64::from(f32::from_bits(magnitude.to_bits() + 1)) - f64::from(magnitude)
446 };
447 spacing * 0.5
448}