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
#![no_std]
#![deny(missing_docs)]
#![allow(unused_imports)]
#![cfg_attr(not(feature = "unsafe_addresses"), allow(dead_code))]

//! GBA Memory-mapped IO (MMIO) stuff.
//!
//! The GBA is controlled via MMIO. An MMIO location is called a "register",
//! similar to the CPU having registers. The different registers are all
//! globally accessible, so user code must have its own convention for who is
//! supposed to touch what values when.
//!
//! This crate defines newtypes that describe the data layout of each register,
//! and if you enable the `unsafe_addresses` feature it also defines the
//! addresses of each register. The type of address used for each register lets
//! you know about the safety (or not) of accessing a given register. The safety
//! assessment relies on the code being run only on a GBA, so if you use this
//! crate on your desktop or something that's your fault.
//!
//! This is only "work in progress" status, but please [file an
//! issue](https://github.com/Lokathor/rubidium/issues) if things are unclear.
//! While you're waiting you can also check
//! [GBATEK](https://problemkaputt.de/gbatek.htm), which is the standard
//! resource for GBA info (and it's most of where this crate's docs come from).
//!
//! ## Naming Conventions
//!
//! By default, the name used for an address is the same as the GBATEK name.
//!
//! In some cases I've combined what GBATEK considers multiple adjacent
//! registers into a single larger register. For example, `WININ` and `WINOUT`
//! have been combined to simply be exposed as `WIN_CONTROL`. The MMIO is
//! flexible like this, as long as the alignment of the combined address is
//! correct for the combined data type it's all fine. Let me know what you think
//! ([tracker](https://github.com/Lokathor/rubidium/issues/10)), because we
//! could make adjustments in this area.
//!
//! For each setting within a register data newtype there will be three methods
//! per setting contained within the newtype:
//! * A const "getter" named the same as the setting (eg: `foo`).
//! * A const "with-er" which takes `self` and returns a new value (eg:
//!   `with_foo`).
//! * A "setter" which takes `&mut self` and updates the value in place (eg:
//!   `set_foo`). This will hopefully also be const in a future version of Rust.

use core::mem::size_of;

macro_rules! pub_const_fn_new_zero {
  () => {
    pub const fn new() -> Self {
      Self(0)
    }
  };
}

//

#[rustfmt::skip]
macro_rules! bit {
   (0) => { 0b1 };
   (1) => { 0b10 };
   (2) => { 0b100 };
   (3) => { 0b1000 };
   (4) => { 0b1_0000 };
   (5) => { 0b10_0000 };
   (6) => { 0b100_0000 };
   (7) => { 0b1000_0000 };
   (8) => { 0b1_0000_0000 };
   (9) => { 0b10_0000_0000 };
  (10) => { 0b100_0000_0000 };
  (11) => { 0b1000_0000_0000 };
  (12) => { 0b1_0000_0000_0000 };
  (13) => { 0b10_0000_0000_0000 };
  (14) => { 0b100_0000_0000_0000 };
  (15) => { 0b1000_0000_0000_0000 };
}

macro_rules! bool_bit_u16 {
  ($bit:tt, $get:ident, $with:ident, $set:ident) => {
    #[must_use]
    #[inline(always)]
    #[allow(missing_docs)]
    pub const fn $get(self) -> bool {
      any_in_mask(self.0 as u32, bit!($bit))
    }
    #[must_use]
    #[inline(always)]
    #[allow(missing_docs)]
    pub const fn $with(self, b: bool) -> Self {
      Self(force_mask_bits(self.0 as u32, bit!($bit), b) as u16)
    }
    #[inline(always)]
    #[allow(missing_docs)]
    pub fn $set(&mut self, b: bool) {
      *self = self.$with(b);
    }
  };
}

macro_rules! const_enum_bits_u16 {
  ($the_type:tt, $mask:literal, $get:ident, $with:ident, $set:ident) => {
    #[must_use]
    #[inline(always)]
    #[allow(missing_docs)]
    pub const fn $get(self) -> $the_type {
      $the_type(self.0 & $mask)
    }
    #[must_use]
    #[inline(always)]
    #[allow(missing_docs)]
    pub const fn $with(self, t: $the_type) -> Self {
      Self(merge_mask_bits(self.0 as u32, t.0 as u32, $mask) as u16)
    }
    #[inline(always)]
    #[allow(missing_docs)]
    pub fn $set(&mut self, t: $the_type) {
      *self = self.$with(t);
    }
  };
}

macro_rules! unsigned_bits_u16 {
  ($low_bit:literal ..= $high_bit:literal, $get:ident, $with:ident, $set:ident) => {
    #[must_use]
    #[inline(always)]
    #[allow(missing_docs)]
    pub const fn $get(self) -> u16 {
      const MASK: u32 = (0b1 << ($high_bit - $low_bit + 1)) - 1;
      const SHIFT: u32 = u16::trailing_zeros(MASK as u16);
      const BASE_MASK: u32 = (MASK >> SHIFT) as u32;
      ((self.0 as u32 >> SHIFT) & BASE_MASK) as u16
    }
    #[must_use]
    #[inline(always)]
    #[allow(missing_docs)]
    pub const fn $with(self, u: u16) -> Self {
      const BASE_MASK: u32 = (0b1 << ($high_bit - $low_bit + 1)) - 1;
      const SHIFT: u32 = $low_bit;
      const MASK: u32 = BASE_MASK << SHIFT;
      let new_bits = (u as u32 & BASE_MASK) << SHIFT;
      Self(merge_mask_bits(self.0 as u32, new_bits, MASK) as u16)
    }
    #[inline(always)]
    #[allow(missing_docs)]
    pub fn $set(&mut self, u: u16) {
      *self = self.$with(u);
    }
  };
}

//

#[rustfmt::skip]
macro_rules! bit32 {
   (0) => { 0b1 };
   (1) => { 0b10 };
   (2) => { 0b100 };
   (3) => { 0b1000 };
   (4) => { 0b1_0000 };
   (5) => { 0b10_0000 };
   (6) => { 0b100_0000 };
   (7) => { 0b1000_0000 };
   (8) => { 0b1_0000_0000 };
   (9) => { 0b10_0000_0000 };
  (10) => { 0b100_0000_0000 };
  (11) => { 0b1000_0000_0000 };
  (12) => { 0b1_0000_0000_0000 };
  (13) => { 0b10_0000_0000_0000 };
  (14) => { 0b100_0000_0000_0000 };
  (15) => { 0b1000_0000_0000_0000 };
  (16) => { 0b1_0000_0000_0000_0000 };
  (17) => { 0b10_0000_0000_0000_0000 };
  (18) => { 0b100_0000_0000_0000_0000 };
  (19) => { 0b1000_0000_0000_0000_0000 };
  (20) => { 0b1_0000_0000_0000_0000_0000 };
  (21) => { 0b10_0000_0000_0000_0000_0000 };
  (22) => { 0b100_0000_0000_0000_0000_0000 };
  (23) => { 0b1000_0000_0000_0000_0000_0000 };
  (24) => { 0b1_0000_0000_0000_0000_0000_0000 };
  (25) => { 0b10_0000_0000_0000_0000_0000_0000 };
  (26) => { 0b100_0000_0000_0000_0000_0000_0000 };
  (27) => { 0b1000_0000_0000_0000_0000_0000_0000 };
  (28) => { 0b1_0000_0000_0000_0000_0000_0000_0000 };
  (29) => { 0b10_0000_0000_0000_0000_0000_0000_0000 };
  (30) => { 0b100_0000_0000_0000_0000_0000_0000_0000 };
  (31) => { 0b1000_0000_0000_0000_0000_0000_0000_0000 };
}

macro_rules! bool_bit_u32 {
  ($bit:tt, $get:ident, $with:ident, $set:ident) => {
    #[must_use]
    #[inline(always)]
    #[allow(missing_docs)]
    pub const fn $get(self) -> bool {
      any_in_mask(self.0, bit32!($bit))
    }
    #[must_use]
    #[inline(always)]
    #[allow(missing_docs)]
    pub const fn $with(self, b: bool) -> Self {
      Self(force_mask_bits(self.0, bit32!($bit), b))
    }
    #[inline(always)]
    #[allow(missing_docs)]
    pub fn $set(&mut self, b: bool) {
      *self = self.$with(b);
    }
  };
}

macro_rules! unsigned_bits_u32 {
  ($low_bit:literal ..= $high_bit:literal, $get:ident, $with:ident, $set:ident) => {
    #[must_use]
    #[inline(always)]
    #[allow(missing_docs)]
    pub const fn $get(self) -> u32 {
      const MASK: u32 = (0b1 << ($high_bit - $low_bit + 1)) - 1;
      const SHIFT: u32 = u32::trailing_zeros(MASK);
      const BASE_MASK: u32 = (MASK >> SHIFT);
      ((self.0 >> SHIFT) & BASE_MASK)
    }
    #[must_use]
    #[inline(always)]
    #[allow(missing_docs)]
    pub const fn $with(self, u: u32) -> Self {
      const BASE_MASK: u32 = (0b1 << ($high_bit - $low_bit + 1)) - 1;
      const SHIFT: u32 = $low_bit;
      const MASK: u32 = BASE_MASK << SHIFT;
      let new_bits = (u & BASE_MASK) << SHIFT;
      Self(merge_mask_bits(self.0, new_bits, MASK))
    }
    #[inline(always)]
    #[allow(missing_docs)]
    pub fn $set(&mut self, u: u32) {
      *self = self.$with(u);
    }
  };
}

//

macro_rules! submodule {
  ($v:vis $name:ident) => {
    mod $name;
    $v use $name::*;
  };
  ($v:vis $name:ident { $($content:tt)* }) => {
    mod $name { $($content)* }
    $v use $name::*;
  };
}

submodule!(pub video {
  use super::*;

  submodule!(pub bg_affine);
  submodule!(pub bg_cnt);
  submodule!(pub bg_ofs);
  submodule!(pub blending);
  submodule!(pub dispcnt);
  submodule!(pub dispstat);
  submodule!(pub mosaic);
  submodule!(pub vcount);
  submodule!(pub video_mode);
  submodule!(pub window);
});

submodule!(pub volatile {
  use super::*;

  use core::{
    marker::PhantomData,
    num::NonZeroUsize,
    ptr::{read_volatile, write_volatile},
  };

  macro_rules! impl_vol_eq {
    ($name:ty) => {
      impl<T> PartialEq for $name {
        fn eq(&self, other: &Self) -> bool {
          self.addr.eq(&other.addr)
        }
      }
      impl<T> Eq for $name {}
    }
  }

  submodule!(pub danger_write_vol_addr);
  submodule!(pub read_only_vol_addr);
  submodule!(pub simple_vol_addr);
  submodule!(pub write_only_vol_addr);
});

submodule!(pub vram {
  use super::*;

  /// Base address value of VRAM.
  pub const VRAM: usize = 0x0600_0000;

  #[cfg(feature = "unsafe_addresses")]
  submodule!(pub mode3);

  #[cfg(feature = "unsafe_addresses")]
  submodule!(pub mode4);

  #[cfg(feature = "unsafe_addresses")]
  submodule!(pub mode5);
});

/// Returns `true` if any bits within the mask bits are active.
#[must_use]
#[inline(always)]
pub(crate) const fn any_in_mask(val: u32, mask: u32) -> bool {
  val & mask > 0
}

/// Forces all bits within the mask to be the bool given.
#[must_use]
#[inline(always)]
pub(crate) const fn force_mask_bits(val: u32, mask: u32, b: bool) -> u32 {
  let f = b as u32;
  let neg_f = f.wrapping_neg();
  val ^ ((neg_f ^ val) & mask)
}

/// Merge the bits of two values according to the mask.
#[must_use]
#[inline(always)]
pub(crate) const fn merge_mask_bits(
  not_in_mask: u32,
  in_mask: u32,
  mask: u32,
) -> u32 {
  let a = not_in_mask;
  let b = in_mask;
  a ^ ((a ^ b) & mask)
}

/// On the GBA, colors have 5 bits per channel.
///
/// In order of increasing bit, the channel ordering is red, green, blue. The
/// high bit is ignored.
///
/// `0bIBBB_BBGG_GGGR_RRRR`
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Color(pub u16);

#[allow(missing_docs)]
impl Color {
  /// Assembles a color from channel values.
  ///
  /// Illegal channel values (>31) will just combine weirdly.
  pub const fn from_rgb(r: u16, g: u16, b: u16) -> Self {
    Self((b << 10) | (g << 5) | r)
  }
  unsigned_bits_u16!(0..=4, red, with_red, set_red);
  unsigned_bits_u16!(5..=9, green, with_green, set_green);
  unsigned_bits_u16!(10..=14, blue, with_blue, set_blue);
}

#[test]
fn color_value_check() {
  assert_eq!(Color::from_rgb(31, 0, 0).0, 0b11111);
  assert_eq!(Color::from_rgb(0, 31, 0).0, 0b1111100000);
  assert_eq!(Color::from_rgb(0, 0, 31).0, 0b111110000000000);

  assert_eq!(Color::from_rgb(31, 0, 0), Color(0).with_red(31));
  assert_eq!(Color::from_rgb(0, 31, 0), Color(0).with_green(31));
  assert_eq!(Color::from_rgb(0, 0, 31), Color(0).with_blue(31));
}

/// The GBA's key data, where a **low** value in a bit means the key is pressed.
///
/// This is the opposite convention from most usual input systems. You can
/// convert this into the [`HighActiveKeys`] keys type, and that will behave
/// more like how you probably expect.
#[derive(Debug, Clone, Copy, Default)]
pub struct LowActiveKeys(pub u16);

/// The register that lets you read the current state of all the keys.
///
/// The convention for this data is "low active", where (for each bit) 0 means
/// pressed and 1 means released. You probably want to convert data read from
/// here to a "high active" convention (where 1 = pressed) before using it. See
/// [`LowActiveKeys`] and [`HighActiveKeys`].
///
/// This responds instantly to key changes, so for a consistent user experience
/// you should generally read this register once per frame and then process the
/// entire frame using that one read. This helps prevent any minor tremors in
/// the button signal from creating inconsistent game input.
#[cfg(feature = "unsafe_addresses")]
pub const KEYINPUT: ReadOnlyVolAddr<LowActiveKeys> =
  unsafe { ReadOnlyVolAddr::new(0x0400_0130) };

/// The GBA's key data, where a **high** value in a bit means the key is
/// pressed.
///
/// Values of this type usually come from reading [`KEYINPUT`] and then
/// converting that value into this type.
#[derive(Debug, Clone, Copy, Default)]
pub struct HighActiveKeys(pub u16);

#[allow(missing_docs)]
impl HighActiveKeys {
  pub_const_fn_new_zero!();
  bool_bit_u16!(0, a, with_a, set_a);
  bool_bit_u16!(1, b, with_b, set_b);
  bool_bit_u16!(2, select, with_select, set_select);
  bool_bit_u16!(3, start, with_start, set_start);
  bool_bit_u16!(4, right, with_right, set_right);
  bool_bit_u16!(5, left, with_left, set_left);
  bool_bit_u16!(6, up, with_up, set_up);
  bool_bit_u16!(7, down, with_down, set_down);
  bool_bit_u16!(8, r, with_r, set_r);
  bool_bit_u16!(9, l, with_l, set_l);
}

impl From<LowActiveKeys> for HighActiveKeys {
  fn from(low: LowActiveKeys) -> Self {
    HighActiveKeys(low.0 ^ 0b11_1111_1111)
  }
}

/// A ZST for namespacing palette ram related functionality.
///
/// The palette ram consists of 2 blocks of 256 [`Color`] values, one for
/// backgrounds and one for objects.
///
/// When selecting a given address within either block of colors, both
/// backgrounds and objects can use either "8-bit per pixel" mode (8bpp) or
/// "4-bit per pixel" mode (4bpp).
///
/// * **8bpp:** Each color index within a background or object is 8 bits. The 8
///   bits index into the full block of colors as if it was a single set of 256
///   elements. Index 0 is counted as the "transparency" index.
///   * `base_addr + size_of::<Color>() * index`
/// * **4bpp:** Each color index within a background or object is 4 bits. The 4
///   bits within the image data is an entry into a "palette bank" of 16
///   entries. The palette bank used for the BG or OBJ overall is determined by
///   their control bits. Index 0 within a palbank is still considered the
///   "transparency" index.
///   * `base_addr + size_of::<Color>() * (pal_bank << 4 | entry)`
///
/// Index 0 of the BG palette is a special "backdrop" index. This is the color
/// drawn to a screen pixel when no BG or OBJ is drawing to that location.
///
/// Please note that there's **only one PALRAM**, the 8bpp and 4bpp modes are
/// just two ways to index into the same region of memory. A change to one will
/// affect the other.
#[derive(Debug, Clone, Copy)]
#[cfg(feature = "unsafe_addresses")]
pub struct PALRAM;

#[cfg(feature = "unsafe_addresses")]
impl PALRAM {
  const BG_ADDR: usize = 0x0500_0000;

  const OBJ_ADDR: usize = 0x0500_0200;

  /// Gets the address of an 8bpp BG color.
  ///
  /// Index 0 is used as transparent in an 8bpp BG. Instead of changing the
  /// color displayed in the BG itself, changing index 0 will change the
  /// "backdrop" color, which is the default color shown when no BG or OBJ draws
  /// to a given screen pixel.
  #[must_use]
  #[inline(always)]
  pub const fn bg_8bpp(self, index: u8) -> SimpleVolAddr<Color> {
    unsafe {
      SimpleVolAddr::new(PALRAM::BG_ADDR + size_of::<Color>() * index as usize)
    }
  }

  /// Get the address of an 8bpp OBJ color.
  ///
  /// Index 0 in an 8bpp OBJ is transparent, and setting it will have no effect.
  #[must_use]
  #[inline(always)]
  pub const fn obj_8bpp(self, index: u8) -> SimpleVolAddr<Color> {
    unsafe {
      SimpleVolAddr::new(PALRAM::OBJ_ADDR + size_of::<Color>() * index as usize)
    }
  }

  /// Gets the backdrop color address.
  ///
  /// This is identical to `PALRAM.bg_8bpp(0)`, See [`bg_8bpp`](PALRAM::bg_8bpp)
  #[must_use]
  #[inline(always)]
  pub const fn backdrop(self) -> SimpleVolAddr<Color> {
    unsafe { SimpleVolAddr::new(PALRAM::BG_ADDR) }
  }

  /// Get the address of a 4bpp BG color.
  /// ## Panics
  /// If either `pal_bank` or `entry` are 16 or more.
  #[must_use]
  #[inline(always)]
  pub fn bg_4bpp(self, pal_bank: usize, entry: usize) -> SimpleVolAddr<Color> {
    assert!(pal_bank < 16);
    assert!(entry < 16);
    let index = pal_bank << 4 | entry;
    unsafe { SimpleVolAddr::new(PALRAM::BG_ADDR + size_of::<Color>() * index) }
  }

  /// Get the address of a 4bpp OBJ color.
  /// ## Panics
  /// If either `pal_bank` or `entry` are 16 or more.
  #[must_use]
  #[inline(always)]
  pub fn obj_4bpp(self, pal_bank: usize, entry: usize) -> SimpleVolAddr<Color> {
    assert!(pal_bank < 16);
    assert!(entry < 16);
    let index = pal_bank << 4 | entry;
    unsafe { SimpleVolAddr::new(PALRAM::OBJ_ADDR + size_of::<Color>() * index) }
  }

  /// Get the address of a 4bpp BG color.
  ///
  /// Only uses the lowest 4 bits of each value given, effectively wrapping both
  /// values into the range `0..=15`.
  #[must_use]
  #[inline(always)]
  pub const fn bg_4bpp_wrapping(
    self,
    pal_bank: usize,
    entry: usize,
  ) -> SimpleVolAddr<Color> {
    let pal_bank = pal_bank & 0b1111;
    let entry = entry & 0b1111;
    let index = pal_bank << 4 | entry;
    unsafe { SimpleVolAddr::new(PALRAM::BG_ADDR + size_of::<Color>() * index) }
  }

  /// Get the address of a 4bpp OBJ color.
  ///
  /// Only uses the lowest 4 bits of each value given, effectively wrapping both
  /// values into the range `0..=15`.
  #[must_use]
  #[inline(always)]
  pub const fn obj_4bpp_wrapping(
    self,
    pal_bank: usize,
    entry: usize,
  ) -> SimpleVolAddr<Color> {
    let pal_bank = pal_bank & 0b1111;
    let entry = entry & 0b1111;
    let index = pal_bank << 4 | entry;
    unsafe { SimpleVolAddr::new(PALRAM::OBJ_ADDR + size_of::<Color>() * index) }
  }
}