Skip to main content
← PSoXide SDK guides and examples · SDK 80d1c329e977 · All Cargo features enabled; check feature gates before use.

psx_gpu/
gpu.rs

1//! The GPU driver.
2
3use crate::chain::StaticChain;
4use crate::display::DisplayConfig;
5use crate::material::{TextureMaterial, TextureWindow};
6use crate::prim::GpuPacket;
7use psx_hw::gpu::{gp0, gp1, DmaDirection};
8use psx_io::gpu::{wait_command_ready, write_command, write_display_control};
9use psx_io::periph::GpuDma;
10
11bitflags::bitflags! {
12    /// GP0(E6h) mask-bit state.
13    ///
14    /// With both flags set the GPU gives front-to-back occlusion without a
15    /// Z-buffer: draw nearest first, and farther pixels that would overdraw
16    /// are rejected. The state applies until changed, so return to
17    /// [`MaskMode::empty`] before translucent passes that must not mask.
18    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
19    pub struct MaskMode: u32 {
20        /// Force bit 15 on every pixel written.
21        const SET_ON_DRAW = 1 << 0;
22        /// Skip pixels whose bit 15 is already set.
23        const CHECK_BEFORE_DRAW = 1 << 1;
24    }
25}
26
27/// The PS1 GPU: its command port (GP0), its control port (GP1) and DMA
28/// channel 2, which feeds GP0.
29///
30/// `Gpu` owns the [`GpuDma`] token, so every operation that writes a GPU
31/// port is a method that needs `&mut Gpu`. That puts the borrow checker
32/// between two users of one command stream: drawing immediately while a
33/// linked-list walk feeds GP0 is a compile error, not a corrupted frame.
34///
35/// ```compile_fail,E0500
36/// # use psx_gpu::{ot::OrderingTable, prim::TriFlat, Gpu};
37/// # fn f(gpu: &mut Gpu, ot: &mut OrderingTable<8>) {
38/// let frame = ot.frame();
39/// frame.submit_with(gpu.dma_mut(), || {
40///     gpu.draw(&TriFlat::new([(0, 0), (8, 0), (0, 8)], 255, 0, 0)); // GP0 mid-walk
41/// });
42/// # }
43/// ```
44///
45/// It is zero-sized, so holding and passing it costs nothing. Reading
46/// status (`psx_gpu::is_draw_done`, `psx_io::gpu::status`) needs no
47/// handle: a read can't disturb the command stream.
48///
49/// ```no_run
50/// use psx_gpu::display::{DisplayConfig, Resolution, VideoMode};
51/// use psx_gpu::prim::FillRect;
52/// use psx_gpu::Gpu;
53///
54/// fn start(dma: psx_io::periph::GpuDma) -> Gpu {
55///     let mut gpu = Gpu::new(dma, DisplayConfig::new(VideoMode::Ntsc, Resolution::R320X240));
56///     gpu.draw(&FillRect::new((0, 0), (320, 240), (0, 0, 32)));
57///     gpu
58/// }
59/// ```
60#[derive(Debug)]
61#[repr(transparent)]
62pub struct Gpu(GpuDma);
63
64impl Gpu {
65    /// Take over the GPU: reset it, program `display`, point DMA at GP0 and
66    /// turn the display on.
67    #[doc(alias = "ResetGraph")]
68    pub fn new(dma: GpuDma, display: DisplayConfig) -> Self {
69        reset(display);
70        Self(dma)
71    }
72
73    /// The driver as a view of a token held elsewhere, such as the one a
74    /// `FramePair` owns, for immediate drawing between its frames.
75    #[inline(always)]
76    pub fn from_dma_mut(dma: &mut GpuDma) -> &mut Self {
77        // SAFETY: `Gpu` is a `repr(transparent)` wrapper of `GpuDma`, so the
78        // two types have the same layout and the cast keeps the exclusive
79        // borrow.
80        unsafe { &mut *core::ptr::from_mut(dma).cast::<Self>() }
81    }
82
83    /// The token, for APIs that start channel 2 themselves (frame
84    /// submission, VRAM DMA). The driver stays borrowed meanwhile.
85    #[inline(always)]
86    pub fn dma_mut(&mut self) -> &mut GpuDma {
87        &mut self.0
88    }
89
90    /// Give the token back.
91    #[inline(always)]
92    pub fn release(self) -> GpuDma {
93        self.0
94    }
95
96    /// Reprogram the display mode and the picture position.
97    #[doc(alias = "PutDispEnv")]
98    pub fn set_display(&mut self, display: DisplayConfig) {
99        write_display_control(display.mode_command());
100        write_display_window(display);
101    }
102
103    /// Show VRAM from `origin` (GP1(05h)): a double-buffer flip.
104    ///
105    /// Under psx-rt this first waits for the presentation cap (`psx_tick::PresentCap`,
106    /// 30 fps unless the game opted out), so a loop that flips every VBlank runs at
107    /// the cap. Bounded, and skipped with interrupts masked.
108    #[inline]
109    pub fn set_display_start(&mut self, origin: (u16, u16)) {
110        psx_io::gpu::pace_flip();
111        write_display_control(gp1::display_start(origin.0 as u32, origin.1 as u32));
112    }
113
114    /// Turn the video output on or off (GP1(03h)).
115    #[doc(alias = "SetDispMask")]
116    #[inline]
117    pub fn set_display_enabled(&mut self, enabled: bool) {
118        write_display_control(gp1::display_enable(enabled));
119    }
120
121    /// Clip drawing to the rectangle from `top_left` to `bottom_right`
122    /// (inclusive VRAM coordinates).
123    #[inline]
124    pub fn set_draw_area(&mut self, top_left: (u16, u16), bottom_right: (u16, u16)) {
125        set_draw_area(top_left, bottom_right);
126    }
127
128    /// Add `offset` to every vertex drawn from now on (GP0(E5h)), so a
129    /// back buffer can be drawn in its own coordinates.
130    #[inline]
131    pub fn set_draw_offset(&mut self, offset: (i16, i16)) {
132        set_draw_offset(offset);
133    }
134
135    /// Set the mask-bit state (GP0(E6h)).
136    #[inline]
137    pub fn set_mask_mode(&mut self, mode: MaskMode) {
138        wait_command_ready();
139        write_command(gp0::mask_bit(
140            mode.contains(MaskMode::SET_ON_DRAW),
141            mode.contains(MaskMode::CHECK_BEFORE_DRAW),
142        ));
143    }
144
145    /// Apply `material`'s texture page, blend equation, dither and
146    /// texture window (GP0(E1h), GP0(E2h)).
147    #[inline]
148    pub fn set_draw_mode(&mut self, material: TextureMaterial) {
149        set_draw_mode(material);
150    }
151
152    /// Set the texture window (GP0(E2h)).
153    #[inline]
154    pub fn set_texture_window(&mut self, window: TextureWindow) {
155        wait_command_ready();
156        write_command(window.word());
157    }
158
159    /// Send `packet` to GP0 now, without an ordering table.
160    ///
161    /// The same packet types go into an `OtFrame`, so a primitive has one
162    /// encoder whether it is drawn now or linked into a frame.
163    #[inline(always)]
164    pub fn draw<P: GpuPacket>(&mut self, packet: &P) {
165        draw(packet);
166    }
167
168    /// Wait until the GPU has drawn everything sent to it.
169    ///
170    /// See [`crate::wait_idle`] for what that waits on.
171    #[doc(alias = "DrawSync")]
172    #[inline]
173    pub fn wait_idle(&mut self) {
174        crate::wait_idle_impl();
175    }
176
177    /// Clear GPUSTAT bit 24 (GP1(02h)) before kicking work that ends in
178    /// GP0(1Fh); see `psx_gpu::is_draw_done`.
179    #[inline]
180    pub fn arm_draw_done(&mut self) {
181        write_display_control(gp1::ACK_IRQ);
182    }
183
184    /// Send GP0(1Fh), closing immediate drawing so `is_draw_done` rises
185    /// once it is drawn.
186    #[inline]
187    pub fn signal_draw_done(&mut self) {
188        wait_command_ready();
189        write_command(gp0::REQUEST_IRQ);
190    }
191
192    /// Kick a `'static`, immutable chain, such as
193    /// [`DRAW_DONE_NODE`](crate::chain::DRAW_DONE_NODE), without waiting for it.
194    ///
195    /// The chain outlives any walk, so there is nothing to wait for before
196    /// reusing memory; a later kick waits for this walk on its own.
197    #[inline]
198    pub fn submit_static(&mut self, chain: &'static impl StaticChain) {
199        // SAFETY: `StaticChain` guarantees a well-formed list that stays live
200        // and unmodified for 'static.
201        unsafe { crate::chain::start_walk(chain.head()) }
202    }
203}
204
205/// [`Gpu::new`]'s port writes.
206pub(crate) fn reset(display: DisplayConfig) {
207    write_display_control(gp1::RESET);
208    write_display_control(display.mode_command());
209    write_display_window(display);
210    write_display_control(gp1::dma_direction(DmaDirection::CpuToGp0 as u32));
211    write_display_control(gp1::display_enable(true));
212}
213
214/// GP1(06h) and GP1(07h) for `display`.
215pub(crate) fn write_display_window(display: DisplayConfig) {
216    write_display_control(display.horizontal_range_command());
217    write_display_control(display.vertical_range_command());
218}
219
220pub(crate) fn set_draw_area(top_left: (u16, u16), bottom_right: (u16, u16)) {
221    wait_command_ready();
222    write_command(gp0::draw_area_top_left(
223        top_left.0 as u32,
224        top_left.1 as u32,
225    ));
226    write_command(gp0::draw_area_bottom_right(
227        bottom_right.0 as u32,
228        bottom_right.1 as u32,
229    ));
230}
231
232pub(crate) fn set_draw_offset(offset: (i16, i16)) {
233    wait_command_ready();
234    write_command(gp0::draw_offset(offset.0 as i32, offset.1 as i32));
235}
236
237pub(crate) fn set_draw_mode(material: TextureMaterial) {
238    wait_command_ready();
239    write_command(material.draw_mode_word());
240    write_command(material.texture_window_word());
241}
242
243/// One ready-wait, then the packet's payload words, in order.
244#[inline(always)]
245pub(crate) fn draw<P: GpuPacket>(packet: &P) {
246    let words = core::ptr::from_ref(packet).cast::<u32>();
247    wait_command_ready();
248    let mut index = 1;
249    while index <= P::WORDS as usize {
250        // SAFETY: `GpuPacket` guarantees a `repr(C)` layout of a tag word and
251        // then at least `WORDS` initialised `u32`s, so words 1..=WORDS are
252        // inside `packet`, which the borrow keeps alive and unchanged.
253        write_command(unsafe { words.add(index).read() });
254        index += 1;
255    }
256}
257
258/// Draw area and offset for a buffer at VRAM line `top`, written without a
259/// ready-wait, as `FrameBuffer` always has: state commands between frames.
260pub(crate) fn write_draw_target(top: u16, width: u16, height: u16) {
261    write_command(gp0::draw_area_top_left(0, top as u32));
262    write_command(gp0::draw_area_bottom_right(
263        (width - 1) as u32,
264        (top + height - 1) as u32,
265    ));
266    write_command(gp0::draw_offset(0, top as i32));
267}