gooey-rs 0.12.1

Tile-based UI library with audio support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! Tile and pixel positions and dimensions.
//!
//! # Coordinate systems
//!
//! The interface works with two types of coordinates: tile and pixel.
//!
//! Tile coordinates are given in (row,column) pairs, while pixel coordinates
//! are defined as (x,y) pairs, where $x$ is understood to be the horizontal
//! component and $y$ the vertical component.
//!
//! Both coordinate systems are left-handed, however they are oriented
//! differently:
//!
//! - The tile coordinate origin is taken to be the upper-left, with
//!   rows increasing towards the bottom and columns increasing towards the
//!   right.
//! - The pixel coordinate origin is taken to be the bottom-left, with $x$
//!   increasing towards the right and $y$ increasing towards the top.
//!
//! The main layout component is the view *`Canvas`* component which contains a
//! coordinates field.
//!
//! ## Presentation backends
//!
//! Different presentation backends may have their own coordinate systems.
//!
//! **Curses**
//!
//! TODO
//!
//! **OpenGL**
//!
//! The OpenGL rendering backend supports both pixel-based and tile-based
//! rendering.
//!
//! By default the 2D camera is centered with (0,0) in the center of the screen.
//! In the presentation implementation, the camera is moved so that (0,0) is at
//! the bottom-left of the screen.
//!
//! TODO: more

use std;
use std::sync::LazyLock;
use derive_more::{From, TryInto};

// TODO: use tagged coordinates?

use crate::math::Vector2;
use crate::geometry::integer::Aabb2;

pub use self::position::Position;
pub use self::dimensions::Dimensions;

pub (crate) static TILE_WH : LazyLock <[u32; 2]> = LazyLock::new (||{
  let width  = std::env::var ("GOOEY_TILE_WIDTH").unwrap().parse().unwrap();
  let height = std::env::var ("GOOEY_TILE_HEIGHT").unwrap().parse().unwrap();
  [width, height]
});
pub (crate) static SCREEN_WH : LazyLock <std::sync::RwLock <[u32; 2]>> = LazyLock::new (
  || std::sync::RwLock::new ([0, 0]));

#[derive(Clone, Copy, Debug, Eq, PartialEq, From, TryInto)]
pub enum Coordinates {
  Tile  (position::Tile,  dimensions::Tile),
  Pixel (position::Pixel, dimensions::Pixel)
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Kind {
  Tile, Pixel
}

/// Convert a screen pixel (x, y) coordinate to a tile (row, column) coordinate
pub fn pixel_to_tile (x : i32, y : i32) -> [i32; 2] {
  let [tile_w,   tile_h]    = *TILE_WH;
  let [_screen_w, screen_h] = *SCREEN_WH.read().unwrap();
  let column = x / tile_w as i32;
  let row    = (screen_h as i32 - y) / tile_h as i32;
  [row, column]
}

/// Convert a screen pixel (x, y) AABB to tile (row, column) coordinate AABB
pub fn pixel_to_tile_aabb (aabb : Aabb2 <i32>) -> Aabb2 <i32> {
  let [min_x, min_y] = aabb.min().0.into_array();
  let [max_x, max_y] = aabb.max().0.into_array();
  let min = pixel_to_tile (min_x, max_y).into();
  let max = pixel_to_tile (max_x, min_y).into();
  Aabb2::with_minmax (min, max)
}

/// Convert a (row, column) coordinate to a screen pixel (x, y) coordinate
pub fn tile_to_pixel (row : i32, column : i32) -> [i32; 2] {
  let [tile_w,   tile_h]    = *TILE_WH;
  let [_screen_w, screen_h] = *SCREEN_WH.read().unwrap();
  let x = column * tile_w as i32;
  let y = screen_h as i32 - row * tile_h as i32;
  [x, y]
}

/// Convert a (row, column) AABB to a screen pixel (x, y) coordinate AABB
pub fn tile_to_pixel_aabb (aabb : Aabb2 <i32>) -> Aabb2 <i32> {
  let aabb = Aabb2::with_minmax (
    aabb.min(),
    aabb.max() + Vector2::new (1, 1)
  );
  let [min_row, min_col] = aabb.min().0.into_array();
  let [max_row, max_col] = aabb.max().0.into_array();
  let min = tile_to_pixel (max_row, min_col).into();
  let max = tile_to_pixel (min_row, max_col).into();
  Aabb2::with_minmax (min, max)
}

impl Coordinates {
  #[inline]
  pub fn default_tile() -> Self {
    (position::Tile::default(), dimensions::Tile::default()).into()
  }
  #[inline]
  pub fn default_pixel() -> Self {
    (position::Pixel::default(), dimensions::Pixel::default()).into()
  }
  pub fn tile_from_aabb (aabb : Aabb2 <i32>) -> Self {
    let position   = (aabb.min()).into();
    let dimensions = aabb.dimensions().numcast().unwrap().into();
    Coordinates::Tile (position, dimensions)
  }
  pub fn pixel_from_aabb (aabb : Aabb2 <i32>) -> Self {
    let position   = aabb.min().into();
    let dimensions = aabb.dimensions().numcast().unwrap().into();
    Coordinates::Pixel (position, dimensions)
  }
  #[inline]
  pub const fn kind (&self) -> Kind {
    match self {
      Coordinates::Tile  (_, _) => Kind::Tile,
      Coordinates::Pixel (_, _) => Kind::Pixel
    }
  }
  #[inline]
  pub fn dimensions (&self) -> Dimensions {
    match self {
      Coordinates::Tile  (_, dimensions) => (*dimensions).into(),
      Coordinates::Pixel (_, dimensions) => (*dimensions).into()
    }
  }
  #[inline]
  pub fn position (&self) -> Position {
    match self {
      Coordinates::Tile  (position, _) => (*position).into(),
      Coordinates::Pixel (position, _) => (*position).into()
    }
  }
  #[inline]
  pub const fn dimensions_horizontal (&self) -> u32 {
    match self {
      Coordinates::Tile  (_, dimensions) => dimensions.columns(),
      Coordinates::Pixel (_, dimensions) => dimensions.width()
    }
  }
  #[inline]
  pub const fn dimensions_vertical (&self) -> u32 {
    match self {
      Coordinates::Tile  (_, dimensions) => dimensions.rows(),
      Coordinates::Pixel (_, dimensions) => dimensions.height()
    }
  }
  #[inline]
  pub fn position_horizontal (&self) -> i32 {
    match self {
      Coordinates::Tile  (position, _) => position.column(),
      Coordinates::Pixel (position, _) => position.0.x
    }
  }
  #[inline]
  pub fn position_vertical (&self) -> i32 {
    match self {
      Coordinates::Tile  (position, _) => position.row(),
      Coordinates::Pixel (position, _) => position.0.y
    }
  }
  #[inline]
  pub fn modify_dimensions_horizontal (&mut self, d : i32) {
    match self {
      Coordinates::Tile  (_, dimensions) =>
        *dimensions.columns_mut() =
          std::cmp::max (0, dimensions.columns() as i32 + d) as u32,
      Coordinates::Pixel (_, dimensions) =>
        dimensions.x = std::cmp::max (0, dimensions.x as i32 + d) as u32
    }
  }
  #[inline]
  pub fn modify_dimensions_vertical (&mut self, d : i32) {
    match self {
      Coordinates::Tile  (_, dimensions) =>
        *dimensions.rows_mut() =
          std::cmp::max (0, dimensions.rows() as i32 + d) as u32,
      Coordinates::Pixel (_, dimensions) =>
        dimensions.y = std::cmp::max (0, dimensions.y as i32 + d) as u32
    }
  }
  #[inline]
  pub fn modify_position_horizontal (&mut self, d : i32) {
    match self {
      Coordinates::Tile  (position, _) => *position.column_mut() = position.column() + d,
      Coordinates::Pixel (position, _) => position.0.x += d
    }
  }
  #[inline]
  pub fn modify_position_vertical (&mut self, d : i32) {
    match self {
      Coordinates::Tile  (position, _) => *position.row_mut() = position.row() + d,
      Coordinates::Pixel (position, _) => position.0.y += d
    }
  }
  #[inline]
  /// &#9888; Position types must match
  pub fn set_position (&mut self, position : Position) {
    match (self, position) {
      (Coordinates::Tile  (position, _), Position::Tile  (p)) => *position = p,
      (Coordinates::Pixel (position, _), Position::Pixel (p)) => *position = p,
      _ => unreachable!()
    }
  }
  #[inline]
  /// &#9888; Dimensions types must match
  pub fn set_dimensions (&mut self, dimensions : Dimensions) {
    match (self, dimensions) {
      (Coordinates::Tile  (_, dimensions), Dimensions::Tile  (d)) =>
        *dimensions = d,
      (Coordinates::Pixel (_, dimensions), Dimensions::Pixel (d)) =>
        *dimensions = d,
      _ => unreachable!()
    }
  }
}

impl From <Coordinates> for Aabb2 <i32> {
  fn from (coordinates : Coordinates) -> Aabb2 <i32> {
    log::trace!("aabb2 from coordinates: {coordinates:?}");
    // NOTE: we subtract (1, 1) below because integer aabbs are inclusive of
    // their max endpoints; however if the dimensions are zero then we can't
    // subtract so it will result in the same Aabb as when the dimensions are 1
    let (min, max) = match coordinates {
      Coordinates::Tile  (position, dimensions) => {
        let mut max = *position + dimensions.numcast().unwrap();
        if dimensions.x > 0 {
          max.0.x -= 1;
        }
        if dimensions.y > 0 {
          max.0.y -= 1;
        }
        (*position, max)
      }
      Coordinates::Pixel (position, dimensions) => {
        let mut max = *position + dimensions.numcast().unwrap();
        if dimensions.x > 0 {
          max.0.x -= 1;
        }
        if dimensions.y > 0 {
          max.0.y -= 1;
        }
        (*position, max)
      }
    };
    log::trace!("aabb2 with min, max: {:?}", (min, max));
    Aabb2::with_minmax (min, max)
  }
}

impl TryFrom <(Position, Dimensions)> for Coordinates {
  type Error = (Position, Dimensions);
  fn try_from ((position, dimensions) : (Position, Dimensions))
    -> Result <Coordinates, (Position, Dimensions)>
  {
    let coordinates = match (position, dimensions) {
      (Position::Tile  (position), Dimensions::Tile  (dimensions)) =>
        Coordinates::Tile  (position, dimensions),
      (Position::Pixel (position), Dimensions::Pixel (dimensions)) =>
        Coordinates::Pixel (position, dimensions),
      _ => return Err ((position, dimensions))
    };
    Ok (coordinates)
  }
}

pub mod position {
  use derive_more::{From, TryInto};
  use crate::math::Point2;

  #[derive(Clone, Copy, Debug, Eq, PartialEq, From, TryInto)]
  pub enum Position {
    Tile  (Tile),
    Pixel (Pixel)
  }

  #[derive(Clone, Copy, Debug, Eq, PartialEq)]
  pub struct Tile {
    pub position_rc : Point2 <i32>
  }

  #[derive(Clone, Copy, Debug, Eq, PartialEq)]
  pub struct Pixel {
    pub position_xy : Point2 <i32>
  }

  // TODO: 3d coordinates?

  impl Tile {
    #[inline]
    pub const fn origin() -> Self {
      Tile {
        position_rc: Point2::new (0, 0)
      }
    }
    #[inline]
    pub fn new_rc (row : i32, column : i32) -> Self {
      Point2::new (row, column).into()
    }
    #[inline]
    pub const fn row (&self) -> i32 {
      self.position_rc.0.x
    }
    #[inline]
    pub const fn column (&self) -> i32 {
      self.position_rc.0.y
    }
    #[inline]
    pub const fn row_mut (&mut self) -> &mut i32 {
      &mut self.position_rc.0.x
    }
    #[inline]
    pub const fn column_mut (&mut self) -> &mut i32 {
      &mut self.position_rc.0.y
    }
  }

  impl Default for Tile {
    fn default() -> Self {
      Tile { position_rc: [0,0].into() }
    }
  }

  impl From <Point2 <i32>> for Tile {
    fn from (position_rc : Point2 <i32>) -> Self {
      Tile { position_rc }
    }
  }

  impl std::ops::Deref for Tile {
    type Target = Point2 <i32>;
    fn deref (&self) -> &Point2 <i32> {
      &self.position_rc
    }
  }

  impl std::ops::DerefMut for Tile {
    fn deref_mut (&mut self) -> &mut Point2 <i32> {
      &mut self.position_rc
    }
  }

  impl Pixel {
    #[inline]
    pub const fn origin() -> Self {
      Pixel {
        position_xy: Point2::new (0, 0)
      }
    }
    #[inline]
    pub fn new_xy (x : i32, y : i32) -> Self {
      Point2::new (x, y).into()
    }
  }

  impl Default for Pixel {
    fn default() -> Self {
      Pixel { position_xy: [0,0].into() }
    }
  }

  impl From <Point2 <i32>> for Pixel {
    fn from (position_xy : Point2 <i32>) -> Self {
      Pixel { position_xy }
    }
  }

  impl std::ops::Deref for Pixel {
    type Target = Point2 <i32>;
    fn deref (&self) -> &Point2 <i32> {
      &self.position_xy
    }
  }

  impl std::ops::DerefMut for Pixel {
    fn deref_mut (&mut self) -> &mut Point2 <i32> {
      &mut self.position_xy
    }
  }
}

pub mod dimensions {
  use derive_more::{From, TryInto};
  use crate::math::Vector2;

  #[derive(Clone, Copy, Debug, Eq, PartialEq, From, TryInto)]
  pub enum Dimensions {
    Tile  (Tile),
    Pixel (Pixel)
  }

  #[derive(Clone, Copy, Debug, Eq, PartialEq)]
  pub struct Tile {
    pub dimensions_rc : Vector2 <u32>
  }

  #[derive(Clone, Copy, Debug, Eq, PartialEq)]
  pub struct Pixel {
    pub dimensions_xy : Vector2 <u32>
  }

  // TODO: 3d dimensions?

  impl Dimensions {
    pub const fn horizontal (&self) -> u32 {
      match self {
        Dimensions::Tile  (tile)  => tile.columns(),
        Dimensions::Pixel (pixel) => pixel.width()
      }
    }

    pub const fn vertical (&self) -> u32 {
      match self {
        Dimensions::Tile  (tile)  => tile.rows(),
        Dimensions::Pixel (pixel) => pixel.height()
      }
    }

    pub fn vec (&self) -> Vector2 <u32> {
      match self {
        Dimensions::Tile  (tile)  => **tile,
        Dimensions::Pixel (pixel) => **pixel
      }
    }
  }

  impl Tile {
    #[inline]
    pub fn new_rc (rows : u32, columns : u32) -> Self {
      Vector2::new (rows, columns).into()
    }
    #[inline]
    pub const fn columns (&self) -> u32 {
      self.dimensions_rc.y
    }
    #[inline]
    pub const fn rows (&self) -> u32 {
      self.dimensions_rc.x
    }
    #[inline]
    pub const fn rows_mut (&mut self) -> &mut u32 {
      &mut self.dimensions_rc.x
    }
    #[inline]
    pub const fn columns_mut (&mut self) -> &mut u32 {
      &mut self.dimensions_rc.y
    }
    #[inline]
    pub fn to_pixel (self) -> Pixel {
      Vector2::new (self.columns(), self.rows()).into()
    }
  }

  impl Pixel {
    #[inline]
    pub fn new_wh (width : u32, height : u32) -> Self {
      Vector2::new (width, height).into()
    }
    #[inline]
    pub const fn width (&self) -> u32 {
      self.dimensions_xy.x
    }
    #[inline]
    pub const fn height (&self) -> u32 {
      self.dimensions_xy.y
    }
    #[inline]
    pub fn to_tile (self) -> Tile {
      Vector2::new (self.height(), self.width()).into()
    }
  }

  impl Default for Tile {
    fn default() -> Self {
      Tile { dimensions_rc: [0,0].into() }
    }
  }

  impl From <Vector2 <u32>> for Tile {
    fn from (dimensions_rc : Vector2 <u32>) -> Self {
      Tile { dimensions_rc }
    }
  }

  impl std::ops::Deref for Tile {
    type Target = Vector2 <u32>;
    fn deref (&self) -> &Self::Target {
      &self.dimensions_rc
    }
  }

  impl std::ops::DerefMut for Tile {
    fn deref_mut (&mut self) -> &mut Self::Target {
      &mut self.dimensions_rc
    }
  }

  impl Default for Pixel {
    fn default() -> Self {
      Pixel { dimensions_xy: [0,0].into() }
    }
  }

  impl From <Vector2 <u32>> for Pixel {
    fn from (dimensions_xy : Vector2 <u32>) -> Self {
      Pixel { dimensions_xy }
    }
  }

  impl std::ops::Deref for Pixel {
    type Target = Vector2 <u32>;
    fn deref (&self) -> &Self::Target {
      &self.dimensions_xy
    }
  }

  impl std::ops::DerefMut for Pixel {
    fn deref_mut (&mut self) -> &mut Self::Target {
      &mut self.dimensions_xy
    }
  }
}

impl std::ops::Add <dimensions::Tile> for position::Tile {
  type Output = Self;
  fn add (self, rhs : dimensions::Tile) -> Self {
    (self.position_rc + rhs.dimensions_rc.numcast().unwrap()).into()
  }
}

impl std::ops::Add <dimensions::Pixel> for position::Pixel {
  type Output = Self;
  fn add (self, rhs : dimensions::Pixel) -> Self {
    (self.position_xy + rhs.dimensions_xy.numcast().unwrap()).into()
  }
}

impl std::ops::Sub <dimensions::Tile> for position::Tile {
  type Output = Self;
  fn sub (self, rhs : dimensions::Tile) -> Self {
    (self.position_rc - rhs.dimensions_rc.numcast().unwrap()).into()
  }
}

impl std::ops::Sub <dimensions::Pixel> for position::Pixel {
  type Output = Self;
  fn sub (self, rhs : dimensions::Pixel) -> Self {
    (self.position_xy - rhs.dimensions_xy.numcast().unwrap()).into()
  }
}

#[cfg(test)]
mod tests {
  use crate::geometry::integer::Aabb2;
  use super::*;
  /// ```text
  /// [0,0]
  /// (tile)    [8,100]
  ///       +---+---------------+
  ///       |   |               |
  /// [0,92]+---+               |
  ///       |    [1,1](tile)    |
  ///       |                   | 100
  ///       |                   |
  ///       |                   |
  ///       |                   |
  ///       |                   |
  ///       +-------------------+
  ///   [0,0]       100
  /// (pixel)
  /// ```
  ///
  /// Sets the screen to dimensions [100,100] and tile dimensions [8,8].
  ///
  /// Given tile coordinates with position [0,0] and dimensions [1,1], computes an AABB
  /// in pixel coordinates which is min = [0,92] and max = [8,100].
  #[test]
  fn tile_to_pixel_aabb() {
    use super::tile_to_pixel_aabb;
    unsafe {
      std::env::set_var ("GOOEY_TILE_WIDTH",  "8");
      std::env::set_var ("GOOEY_TILE_HEIGHT", "8");
    }
    *SCREEN_WH.write().unwrap() = [100, 100];
    let coordinates = Coordinates::Tile (
      position::Tile::new_rc (0, 0),
      dimensions::Tile::new_rc (1, 1));
    let aabb = Aabb2::from (coordinates);
    assert!(aabb.contains ([0, 0].into()));
    assert!(!aabb.contains ([1, 1].into()));
    let aabb_pixel = tile_to_pixel_aabb (aabb);
    assert_eq!(aabb_pixel.min(), [0, 92].into());
    assert_eq!(aabb_pixel.max(), [8, 100].into());
  }
}