agb 0.23.1

Library for Game Boy Advance Development
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
//! Anything to do with tiled backgrounds
//!
//! Most games made for the Game Boy Advance use tiled backgrounds.
//! You can create and manage regular backgrounds using the [`RegularBackground`] struct,
//! and affine backgrounds using the [`AffineBackground`] struct.
//!
//! Palettes are managed using the [`VRAM_MANAGER`] global value.
//!
//! See the [background deep dive](https://agbrs.dev/book/articles/backgrounds.html) for further details about backgrounds.
#![warn(missing_docs)]
mod affine_background;
mod infinite_scrolled_map;
mod registers;
mod regular_background;
mod screenblock;
mod tiles;
mod vram_manager;

pub use affine_background::{
    AffineBackground, AffineBackgroundSize, AffineBackgroundWrapBehaviour, AffineMatrixBackground,
};
use alloc::rc::Rc;
pub use infinite_scrolled_map::{InfiniteScrolledMap, PartialUpdateStatus};
pub use regular_background::{RegularBackground, RegularBackgroundSize};
use tiles::Tiles;
pub use vram_manager::{
    DynamicTile16, DynamicTile256, TileFormat, TileSet, VRAM_MANAGER, VRamManager,
};

pub(crate) use vram_manager::TileIndex;

pub(crate) use registers::*;

use bilge::prelude::*;

use crate::{
    agb_alloc::{block_allocator::BlockAllocator, bump_allocator::StartEnd, impl_zst_allocator},
    display::tiled::screenblock::Screenblock,
    dma::DmaControllable,
    fixnum::{Num, Vector2D},
    memory_mapped::MemoryMapped,
};

use super::DISPLAY_CONTROL;

/// Represents a background which can be either [regular](RegularBackground) or [affine](AffineBackground).
///
/// You never need to create this directly, instead using the `From` implementation from [`AffineBackgroundId`] or
/// [`RegularBackgroundId`].
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct BackgroundId(pub(crate) u8);

impl From<RegularBackgroundId> for BackgroundId {
    fn from(value: RegularBackgroundId) -> Self {
        Self(value.0)
    }
}

impl From<AffineBackgroundId> for BackgroundId {
    fn from(value: AffineBackgroundId) -> Self {
        Self(value.0)
    }
}

/// Represents a [regular background](RegularBackground) that's about to be displayed.
///
/// This is returned by the [`show()`](RegularBackground::show) method. You'll need this if you want
/// to apply additional effects on the background while it is being displayed, such as adding it to a
/// [`Window`](super::Window::enable_background) or using one of the DMA registers.
///
/// See the `dma_effect_background_*` [examples](https://agbrs.dev/examples) for examples of how to use the DMA functions.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct RegularBackgroundId(pub(crate) u8);

impl RegularBackgroundId {
    /// Control the x scroll position every scan line
    #[must_use]
    pub fn x_scroll_dma(self) -> DmaControllable<u16> {
        unsafe { DmaControllable::new((0x0400_0010 + self.0 as usize * 4) as *mut _) }
    }

    /// Control the y scroll position every scan line.
    ///
    /// A thing to note here is that this is _not_ the y value drawn at each scan line.
    /// The current scan line is added to this value, and that is the line that is rendered (you are actually controlling the y-scroll position).
    #[must_use]
    pub fn y_scroll_dma(self) -> DmaControllable<u16> {
        unsafe { DmaControllable::new((0x0400_0012 + self.0 as usize * 4) as *mut _) }
    }

    /// Control the current scroll position every scan line
    #[must_use]
    pub fn scroll_dma(self) -> DmaControllable<Vector2D<u16>> {
        unsafe { DmaControllable::new((0x0400_0010 + self.0 as usize * 4) as *mut _) }
    }
}

/// Represents an [affine background](AffineBackground) that's about to be displayed.
///
/// This is returned by the [`show()`](AffineBackground::show) method. You'll need this if you
/// want to apply additional effects such as using it with DMA.
///
/// See the `dma_effect_affine_background_*` [examples](https://agbrs.dev/examples) for examples of how to use the DMA transform function.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct AffineBackgroundId(pub(crate) u8);

impl AffineBackgroundId {
    /// Change the transformation matrix every scan line
    ///
    /// Note that the current scroll position resets if you change the background transform as part of the DMA
    /// (unlike the regular background DMA), so you may need to add the current `y` offset to the position if you
    /// are looking for it to be displayed normally.
    #[must_use]
    pub fn transform_dma(self) -> DmaControllable<AffineMatrixBackground> {
        unsafe { DmaControllable::new((0x0400_0020 + (self.0 as usize - 2) * 16) as *mut _) }
    }
}

const TRANSPARENT_TILE_INDEX: u16 = 0xffff;

/// The `TileSetting` holds the index for the tile in the tile set, and which effects it should be rendered with.
///
/// You will mainly get a TileSetting from [`TileData.tile_settings`](super::tile_data::TileData::tile_settings) which
/// is produced by the [`include_background_gfx!`](crate::include_background_gfx) macro.
#[derive(Clone, Copy, Debug, Default)]
#[repr(align(4))]
pub struct TileSetting {
    tile_id: u16,
    tile_effect: TileEffect,
}

/// Represents the simple effects that can be applied to a tile.
///
/// A tile can be flipped horizontally, vertically or both. You can also configure which
/// palette to use for the tile.
///
/// The palette does nothing for 256 colour tiles, since there is only a single 256 colour palette.
#[derive(Clone, Copy, Debug, Default)]
#[repr(transparent)]
pub struct TileEffect(u16);

impl TileSetting {
    /// Displays a blank tile.
    ///
    /// Use this instead of a fully blank tile in your tile set if possible, since it is special cased to be more performant.
    ///
    /// ```rust
    /// # #![no_std]
    /// # #![no_main]
    /// use agb::{
    ///     display::Priority,
    ///     display::tiled::{
    ///         RegularBackground, RegularBackgroundSize, TileEffect, TileSetting,
    ///         VRAM_MANAGER,
    ///     },
    ///     include_background_gfx,
    /// };
    ///
    /// agb::include_background_gfx!(mod water_tiles, tiles => "examples/water_tiles.png");
    ///
    /// # #[agb::doctest]
    /// # fn test(gba: agb::Gba) {
    /// let mut bg = RegularBackground::new(Priority::P0, RegularBackgroundSize::Background32x32, water_tiles::tiles.tiles.format());
    ///
    /// // put something in the background
    /// bg.set_tile((0, 0), &water_tiles::tiles.tiles, water_tiles::tiles.tile_settings[1]);
    /// // set it back to blank
    /// bg.set_tile((0, 0), &water_tiles::tiles.tiles, TileSetting::BLANK);
    /// # }
    /// ```
    pub const BLANK: Self =
        TileSetting::new(TRANSPARENT_TILE_INDEX, TileEffect::new(false, false, 0));

    /// Create a new TileIndex with a given `tile_id` and `tile_effect`.
    ///
    /// You probably won't need to use this method, instead either using [`TileSetting::BLANK`] or one of the entries in
    /// [`TileData.tile_settings`](crate::display::tile_data::TileData::tile_settings).
    #[must_use]
    pub const fn new(tile_id: u16, tile_effect: TileEffect) -> Self {
        Self {
            tile_id,
            tile_effect,
        }
    }

    /// Gets the tile_effect and allows for manipulations of it.
    pub const fn tile_effect(&mut self) -> &mut TileEffect {
        &mut self.tile_effect
    }

    /// Horizontally flips the tile.
    ///
    /// If `should_flip` is false, returns the same as current. If it is true, will return a new
    /// `TileSetting` with ever setting the same, except it will be horizontally flipped.
    #[must_use]
    pub const fn hflip(mut self, should_flip: bool) -> Self {
        self.tile_effect = self.tile_effect.hflip(should_flip);
        self
    }

    /// Vertically flips the tile.
    ///
    /// If `should_flip` is false, returns the same as current. If it is true, will return a new
    /// `TileSetting` with ever setting the same, except it will be vertically flipped.
    #[must_use]
    pub const fn vflip(mut self, should_flip: bool) -> Self {
        self.tile_effect = self.tile_effect.vflip(should_flip);
        self
    }

    /// Sets which palette to use
    ///
    /// This has no effect if the background is set to use 256 colours.
    #[must_use]
    pub const fn palette(mut self, palette_id: u8) -> Self {
        self.tile_effect = self.tile_effect.palette(palette_id);
        self
    }

    /// Gets the internal tile ID for a given tile.
    ///
    /// The main use case for this is checking which tile_id was assigned when using the `deduplicate`
    /// option in [`include_background_gfx!()`](crate::include_background_gfx).
    ///
    /// Be careful when passing this ID to [`VRAM_MANAGER.replace_tile()`](crate::display::tiled::VRamManager::replace_tile)
    /// if you've generated this tile set with the `deduplicate` option, since tiles may be flipped or
    /// reused meaning replacing IDs could result in strange display behaviour.
    #[must_use]
    pub const fn tile_id(self) -> u16 {
        self.tile_id
    }

    const fn setting(self) -> u16 {
        self.tile_effect.0
    }
}

impl TileEffect {
    /// Creates a new [`TileEffect`] with the given state of being flipped and palette id.
    #[must_use]
    pub const fn new(hflip: bool, vflip: bool, palette_id: u8) -> Self {
        Self(((hflip as u16) << 10) | ((vflip as u16) << 11) | ((palette_id as u16) << 12))
    }

    /// Horizontally flips the tile.
    ///
    /// If `should_flip` is false, this does nothing.
    /// If `should_flip` is true, will mutate itself to show the tile flipped horizontally.
    ///
    /// Calling `.hflip` twice on the same TileEffect will flip the tile twice, resulting in no flipping.
    #[must_use]
    pub const fn hflip(mut self, should_flip: bool) -> Self {
        self.0 ^= (should_flip as u16) << 10;
        self
    }

    /// Vertically flips the tile.
    ///
    /// If `should_flip` is false, this does nothing.
    /// If `should_flip` is true, will mutate itself to show the tile flipped vertically.
    ///
    /// Calling `.hflip` twice on the same TileEffect will flip the tile twice, resulting in no flipping.
    #[must_use]
    pub const fn vflip(mut self, should_flip: bool) -> Self {
        self.0 ^= (should_flip as u16) << 11;
        self
    }

    /// Sets the palette index for the current TileEffect.
    #[must_use]
    pub const fn palette(mut self, palette_id: u8) -> Self {
        self.0 &= 0x0fff;
        self.0 |= (palette_id as u16) << 12;
        self
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[repr(transparent)]
pub(crate) struct Tile(u16);

impl Tile {
    fn new(idx: TileIndex, setting: TileSetting) -> Self {
        Self(idx.raw_index() | setting.setting())
    }

    fn tile_index(self, format: TileFormat) -> TileIndex {
        TileIndex::new(self.0 as usize & ((1 << 10) - 1), format)
    }
}

struct ScreenblockAllocator;

pub(crate) const VRAM_START: usize = 0x0600_0000;
pub(crate) const SCREENBLOCK_SIZE: usize = 0x800;
pub(crate) const CHARBLOCK_SIZE: usize = SCREENBLOCK_SIZE * 8;

const SCREENBLOCK_ALLOC_START: usize = VRAM_START + CHARBLOCK_SIZE * 2;

static SCREENBLOCK_ALLOCATOR: BlockAllocator = unsafe {
    BlockAllocator::new(StartEnd {
        start: || SCREENBLOCK_ALLOC_START,
        end: || SCREENBLOCK_ALLOC_START + 0x4000,
    })
};

impl_zst_allocator!(ScreenblockAllocator, SCREENBLOCK_ALLOCATOR);

struct RegularBackgroundCommitData {
    tiles: Tiles<Tile>,
    screenblock: Rc<Screenblock<RegularBackgroundSize>>,
}

#[derive(Default)]
struct RegularBackgroundData {
    bg_ctrl: BackgroundControlRegister,
    scroll_offset: Vector2D<u16>,
    commit_data: Option<RegularBackgroundCommitData>,
}

struct AffineBackgroundCommitData {
    tiles: Tiles<u8>,
    screenblock: Rc<Screenblock<AffineBackgroundSize>>,
}

#[derive(Default)]
struct AffineBackgroundData {
    bg_ctrl: BackgroundControlRegister,
    scroll_offset: Vector2D<Num<i32, 8>>,
    affine_transform: AffineMatrixBackground,
    commit_data: Option<AffineBackgroundCommitData>,
}

#[derive(Default)]
pub(crate) struct BackgroundFrame {
    num_regular: usize,
    regular_backgrounds: [RegularBackgroundData; 4],

    num_affine: usize,
    affine_backgrounds: [AffineBackgroundData; 2],
}

impl BackgroundFrame {
    fn set_next_regular(&mut self, data: RegularBackgroundData) -> RegularBackgroundId {
        let bg_index = self.next_regular_index();

        self.regular_backgrounds[bg_index] = data;
        RegularBackgroundId(bg_index as u8)
    }

    fn next_regular_index(&mut self) -> usize {
        if self.num_regular + self.num_affine * 2 >= 4 {
            panic!(
                "Can only have 4 backgrounds at once, affine counts as 2. regular: {}, affine: {}",
                self.num_regular, self.num_affine
            );
        }

        let index = self.num_regular;
        self.num_regular += 1;
        index
    }

    fn set_next_affine(&mut self, data: AffineBackgroundData) -> AffineBackgroundId {
        let bg_index = self.next_affine_index();

        self.affine_backgrounds[bg_index - 2] = data;
        AffineBackgroundId(bg_index as u8)
    }

    fn next_affine_index(&mut self) -> usize {
        if self.num_affine * 2 + self.num_regular >= 3 {
            panic!(
                "Can only have 4 backgrounds at once, affine counts as 2. regular: {}, affine: {}",
                self.num_regular, self.num_affine
            );
        }

        let index = self.num_affine;
        self.num_affine += 1;

        index + 2 // first affine BG is bg2
    }

    pub fn commit(&mut self) {
        let video_mode = self.num_affine as u16;
        let enabled_backgrounds =
            ((1u16 << self.num_regular) - 1) | (((1 << self.num_affine) - 1) << 2);

        let mut display_control_register = DISPLAY_CONTROL.get();
        display_control_register.set_video_mode(u3::new(video_mode as u8));
        display_control_register.set_enabled_backgrounds(u4::new(enabled_backgrounds as u8));
        display_control_register.set_forced_blank(false);

        DISPLAY_CONTROL.set(display_control_register);

        for (i, regular_background) in self
            .regular_backgrounds
            .iter_mut()
            .take(self.num_regular)
            .enumerate()
        {
            let bg_ctrl = unsafe { MemoryMapped::new(0x0400_0008 + i * 2) };
            bg_ctrl.set(regular_background.bg_ctrl);

            let bg_x_offset = unsafe { MemoryMapped::new(0x0400_0010 + i * 4) };
            bg_x_offset.set(regular_background.scroll_offset.x);
            let bg_y_offset = unsafe { MemoryMapped::new(0x0400_0012 + i * 4) };
            bg_y_offset.set(regular_background.scroll_offset.y);

            if let Some(commit_data) = regular_background.commit_data.as_ref() {
                unsafe {
                    commit_data.screenblock.copy_tiles(&commit_data.tiles);
                }

                commit_data.tiles.clean(commit_data.screenblock.ptr());
            }
        }

        for (i, affine_background) in self
            .affine_backgrounds
            .iter_mut()
            .take(self.num_affine)
            .enumerate()
        {
            let i = i + 2;

            let bg_ctrl = unsafe { MemoryMapped::new(0x0400_0008 + i * 2) };
            bg_ctrl.set(affine_background.bg_ctrl);

            let bg_x_offset = unsafe { MemoryMapped::new(0x0400_0028 + (i - 2) * 16) };
            bg_x_offset.set(affine_background.scroll_offset.x.to_raw());
            let bg_y_offset = unsafe { MemoryMapped::new(0x0400_002c + (i - 2) * 16) };
            bg_y_offset.set(affine_background.scroll_offset.y.to_raw());

            let affine_transform_offset = unsafe { MemoryMapped::new(0x0400_0020 + (i - 2) * 16) };
            affine_transform_offset.set(affine_background.affine_transform);

            if let Some(commit_data) = affine_background.commit_data.as_ref() {
                unsafe {
                    commit_data.screenblock.copy_tiles(&commit_data.tiles);
                }

                commit_data.tiles.clean(commit_data.screenblock.ptr());
            }
        }
    }
}