1#![no_std]
59#![deny(unsafe_op_in_unsafe_fn)]
60#![warn(missing_docs)]
61
62use psx_hw::gpu::{gp0, gp1, pack_xy};
63use psx_io::dma::{self, Channel};
64use psx_io::gpu::{pause_recording, wait_command_ready, write_command, write_display_control};
65use psx_io::periph::GpuDma;
66
67pub const VRAM_WIDTH: u16 = 1024;
69pub const VRAM_HEIGHT: u16 = 512;
71
72#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
90#[repr(transparent)]
91pub struct Color555(u16);
92
93impl Color555 {
94 pub const TRANSPARENT: Self = Self(0);
97 pub const BLACK: Self = Self(0);
99 pub const WHITE: Self = Self(0x7fff);
101
102 pub const fn rgb8(r: u8, g: u8, b: u8) -> Self {
109 let r = (r as u16) >> 3;
110 let g = (g as u16) >> 3;
111 let b = (b as u16) >> 3;
112 Self(r | (g << 5) | (b << 10))
113 }
114
115 pub const fn rgb5(r: u8, g: u8, b: u8) -> Self {
118 assert!(r < 32, "rgb5: red must be < 32");
119 assert!(g < 32, "rgb5: green must be < 32");
120 assert!(b < 32, "rgb5: blue must be < 32");
121 Self((r as u16) | ((g as u16) << 5) | ((b as u16) << 10))
122 }
123
124 pub const fn raw(value: u16) -> Self {
127 Self(value)
128 }
129
130 pub const fn as_u16(self) -> u16 {
132 self.0
133 }
134
135 pub const fn with_mask_bit(self) -> Self {
142 Self(self.0 | 0x8000)
143 }
144
145 #[doc(alias = "STP")]
158 pub const fn with_semi_transparency(self) -> Self {
159 Self(self.0 | 0x8000)
160 }
161
162 #[doc(alias = "STP")]
164 pub const fn is_semi_transparent(self) -> bool {
165 self.0 & 0x8000 != 0
166 }
167}
168
169#[derive(Copy, Clone, Debug, PartialEq, Eq)]
179pub struct VramRect {
180 pub x: u16,
182 pub y: u16,
184 pub w: u16,
186 pub h: u16,
188}
189
190impl VramRect {
191 pub const fn new(x: u16, y: u16, w: u16, h: u16) -> Self {
193 assert!(w > 0, "VramRect: width must be > 0");
194 assert!(h > 0, "VramRect: height must be > 0");
195 assert!(x <= VRAM_WIDTH, "VramRect: x past VRAM right edge");
196 assert!(y <= VRAM_HEIGHT, "VramRect: y past VRAM bottom edge");
197 assert!(
198 (x as u32) + (w as u32) <= VRAM_WIDTH as u32,
199 "VramRect: (x + w) overflows VRAM width",
200 );
201 assert!(
202 (y as u32) + (h as u32) <= VRAM_HEIGHT as u32,
203 "VramRect: (y + h) overflows VRAM height",
204 );
205 Self { x, y, w, h }
206 }
207
208 pub const fn pixel_count(self) -> u32 {
210 (self.w as u32) * (self.h as u32)
211 }
212
213 pub const fn overlaps(self, other: Self) -> bool {
218 self.x < other.x + other.w
219 && other.x < self.x + self.w
220 && self.y < other.y + other.h
221 && other.y < self.y + self.h
222 }
223}
224
225pub const fn first_vram_overlap(rects: &[VramRect]) -> Option<(usize, usize)> {
254 let mut i = 0;
255 while i < rects.len() {
256 let mut j = i + 1;
257 while j < rects.len() {
258 if rects[i].overlaps(rects[j]) {
259 return Some((i, j));
260 }
261 j += 1;
262 }
263 i += 1;
264 }
265 None
266}
267
268pub const fn vram_layout_is_disjoint(rects: &[VramRect]) -> bool {
271 first_vram_overlap(rects).is_none()
272}
273
274pub const TEXTURE_WINDOW_UNIT_TEXELS: u16 = 8;
283
284pub const TEXTURE_PAGE_TEXELS: u16 = 256;
286
287const TEXTURE_PAGE_UNITS: usize = (TEXTURE_PAGE_TEXELS / TEXTURE_WINDOW_UNIT_TEXELS) as usize;
288
289#[derive(Copy, Clone, Debug, PartialEq, Eq)]
291pub struct TextureWindowPlacement {
292 page_index: u16,
293 origin_u: u8,
294 origin_v: u8,
295 width: u8,
296 height: u8,
297}
298
299impl TextureWindowPlacement {
300 pub const fn page_index(self) -> u16 {
302 self.page_index
303 }
304
305 pub const fn origin_u(self) -> u8 {
307 self.origin_u
308 }
309
310 pub const fn origin_v(self) -> u8 {
312 self.origin_v
313 }
314
315 pub const fn width(self) -> u8 {
317 self.width
318 }
319
320 pub const fn height(self) -> u8 {
322 self.height
323 }
324}
325
326#[derive(Copy, Clone, Debug, PartialEq, Eq)]
333pub struct TextureWindowAtlas<const PAGE_COUNT: usize> {
334 rows: [[u32; TEXTURE_PAGE_UNITS]; PAGE_COUNT],
335}
336
337impl<const PAGE_COUNT: usize> TextureWindowAtlas<PAGE_COUNT> {
338 pub const fn new() -> Self {
340 Self {
341 rows: [[0; TEXTURE_PAGE_UNITS]; PAGE_COUNT],
342 }
343 }
344
345 pub fn clear(&mut self) {
347 for page in &mut self.rows {
348 page.fill(0);
349 }
350 }
351
352 pub fn allocate(&mut self, width: u16, height: u16) -> Option<TextureWindowPlacement> {
358 self.allocate_with_usable_rows(width, height, 256)
359 }
360
361 pub fn allocate_with_usable_rows(
369 &mut self,
370 width: u16,
371 height: u16,
372 usable_rows: u16,
373 ) -> Option<TextureWindowPlacement> {
374 if usable_rows == 0
375 || usable_rows > 256
376 || !usable_rows.is_multiple_of(TEXTURE_WINDOW_UNIT_TEXELS)
377 {
378 return None;
379 }
380 let width_units = texture_window_units(width)?;
381 let height_units = texture_window_units(height)?;
382 let row_units = (usable_rows / TEXTURE_WINDOW_UNIT_TEXELS) as usize;
383 let max_y = row_units.checked_sub(height_units)?;
384 let max_x = TEXTURE_PAGE_UNITS.checked_sub(width_units)?;
385
386 for page_index in 0..PAGE_COUNT {
387 let mut y = 0usize;
388 while y <= max_y {
389 let mut x = 0usize;
390 while x <= max_x {
391 if texture_region_free(&self.rows[page_index], x, y, width_units, height_units)
392 {
393 texture_region_mark(
394 &mut self.rows[page_index],
395 x,
396 y,
397 width_units,
398 height_units,
399 );
400 return Some(TextureWindowPlacement {
401 page_index: u16::try_from(page_index).ok()?,
402 origin_u: u8::try_from(x * TEXTURE_WINDOW_UNIT_TEXELS as usize).ok()?,
403 origin_v: u8::try_from(y * TEXTURE_WINDOW_UNIT_TEXELS as usize).ok()?,
404 width: u8::try_from(width).ok()?,
405 height: u8::try_from(height).ok()?,
406 });
407 }
408 x += width_units;
409 }
410 y += height_units;
411 }
412 }
413 None
414 }
415
416 pub fn reserve_empty_page(&mut self) -> Option<usize> {
423 for page_index in 0..PAGE_COUNT {
424 if self.rows[page_index].iter().all(|row| *row == 0) {
425 self.rows[page_index].fill(u32::MAX);
426 return Some(page_index);
427 }
428 }
429 None
430 }
431
432 pub fn release(&mut self, placement: TextureWindowPlacement) {
437 let page = placement.page_index() as usize;
438 let (Some(width_units), Some(height_units)) = (
439 texture_window_units(placement.width() as u16),
440 texture_window_units(placement.height() as u16),
441 ) else {
442 return;
443 };
444 let x = (placement.origin_u() / TEXTURE_WINDOW_UNIT_TEXELS as u8) as usize;
445 let y = (placement.origin_v() / TEXTURE_WINDOW_UNIT_TEXELS as u8) as usize;
446 if page >= PAGE_COUNT {
447 return;
448 }
449 let mask = texture_region_mask(x, width_units);
450 for row in &mut self.rows[page][y..y + height_units] {
451 *row &= !mask;
452 }
453 }
454
455 pub fn release_page(&mut self, page_index: usize) {
458 if page_index < PAGE_COUNT {
459 self.rows[page_index].fill(0);
460 }
461 }
462
463 pub fn is_page_empty(&self, page_index: usize) -> bool {
467 self.rows
468 .get(page_index)
469 .is_some_and(|rows| rows.iter().all(|row| *row == 0))
470 }
471}
472
473impl<const PAGE_COUNT: usize> Default for TextureWindowAtlas<PAGE_COUNT> {
474 fn default() -> Self {
475 Self::new()
476 }
477}
478
479fn texture_window_units(size: u16) -> Option<usize> {
480 if !(TEXTURE_WINDOW_UNIT_TEXELS..=128).contains(&size)
481 || !size.is_power_of_two()
482 || !size.is_multiple_of(TEXTURE_WINDOW_UNIT_TEXELS)
483 {
484 return None;
485 }
486 Some((size / TEXTURE_WINDOW_UNIT_TEXELS) as usize)
487}
488
489fn texture_region_mask(x: usize, width: usize) -> u32 {
490 ((1u32 << width) - 1) << x
491}
492
493fn texture_region_free(
494 rows: &[u32; TEXTURE_PAGE_UNITS],
495 x: usize,
496 y: usize,
497 width: usize,
498 height: usize,
499) -> bool {
500 let mask = texture_region_mask(x, width);
501 for row in &rows[y..y + height] {
502 if row & mask != 0 {
503 return false;
504 }
505 }
506 true
507}
508
509fn texture_region_mark(
510 rows: &mut [u32; TEXTURE_PAGE_UNITS],
511 x: usize,
512 y: usize,
513 width: usize,
514 height: usize,
515) {
516 let mask = texture_region_mask(x, width);
517 for row in &mut rows[y..y + height] {
518 *row |= mask;
519 }
520}
521
522#[derive(Copy, Clone, Debug, PartialEq, Eq)]
529#[repr(u8)]
530pub enum TextureDepth {
531 Bit4 = 0,
533 Bit8 = 1,
535 Bit15 = 2,
537}
538
539impl TextureDepth {
540 const fn as_u16(self) -> u16 {
541 self as u16
542 }
543
544 pub const fn texels_per_halfword(self) -> u16 {
547 match self {
548 TextureDepth::Bit4 => 4,
549 TextureDepth::Bit8 => 2,
550 TextureDepth::Bit15 => 1,
551 }
552 }
553}
554
555#[derive(Copy, Clone, Debug, PartialEq, Eq)]
571pub struct TexturePage {
572 x: u16,
573 y: u16,
574 depth: TextureDepth,
575}
576
577impl TexturePage {
578 #[allow(clippy::manual_is_multiple_of)]
581 pub const fn new(x: u16, y: u16, depth: TextureDepth) -> Self {
582 assert!(x % 64 == 0, "TexturePage: x must be a multiple of 64");
583 assert!(x < VRAM_WIDTH, "TexturePage: x past VRAM");
584 assert!(y == 0 || y == 256, "TexturePage: y must be 0 or 256");
585 Self { x, y, depth }
586 }
587
588 pub const fn x(self) -> u16 {
590 self.x
591 }
592 pub const fn y(self) -> u16 {
594 self.y
595 }
596 pub const fn depth(self) -> TextureDepth {
598 self.depth
599 }
600
601 pub const fn covering_rect(self) -> VramRect {
604 let w = match self.depth {
605 TextureDepth::Bit4 => 64,
606 TextureDepth::Bit8 => 128,
607 TextureDepth::Bit15 => 256,
608 };
609 VramRect::new(self.x, self.y, w, 256)
613 }
614
615 #[doc(alias = "getTPage")]
630 pub const fn uv_word(self, semi_trans: u8) -> u16 {
631 assert!(semi_trans < 4, "semi_trans must be 0..4");
632 let tpx = (self.x / 64) & 0xf;
633 let tpy = if self.y == 256 { 1 } else { 0 };
634 let depth = self.depth.as_u16();
635 tpx | (tpy << 4) | ((semi_trans as u16) << 5) | (depth << 7)
636 }
637
638 pub fn apply_as_draw_mode(self) {
642 wait_command_ready();
643 write_command(gp0::draw_mode(
644 (self.x / 64) as u32,
645 if self.y == 256 { 1 } else { 0 },
646 0,
647 self.depth as u32,
648 false,
649 true,
650 ));
651 wait_command_ready();
655 write_command(gp0::tex_window(0, 0, 0, 0));
656 }
657}
658
659#[derive(Copy, Clone, Debug, PartialEq, Eq)]
663pub struct Clut {
664 x: u16,
665 y: u16,
666}
667
668impl Clut {
669 #[allow(clippy::manual_is_multiple_of)]
671 pub const fn new(x: u16, y: u16) -> Self {
672 assert!(x % 16 == 0, "Clut: x must be a multiple of 16");
673 assert!(x < VRAM_WIDTH, "Clut: x past VRAM");
674 assert!(y < VRAM_HEIGHT, "Clut: y past VRAM");
675 Self { x, y }
676 }
677
678 pub const fn x(self) -> u16 {
680 self.x
681 }
682 pub const fn y(self) -> u16 {
684 self.y
685 }
686
687 #[doc(alias = "getClut")]
695 pub const fn uv_word(self) -> u16 {
696 let cx = (self.x / 16) & 0x3f;
697 let cy = self.y & 0x1ff;
698 cx | (cy << 6)
699 }
700}
701
702const ALLOC_COL_W: u16 = 64;
708const ALLOC_ROW_H: u16 = 16;
710pub const VRAM_ALLOC_COLS: usize = (VRAM_WIDTH / ALLOC_COL_W) as usize;
712pub const VRAM_ALLOC_ROWS: usize = (VRAM_HEIGHT / ALLOC_ROW_H) as usize;
714const ALLOC_PAGE_ROWS: usize = (TEXTURE_PAGE_TEXELS / ALLOC_ROW_H) as usize;
716const CLUT_SLOTS_PER_ROW: u16 = VRAM_WIDTH / 16;
718
719#[derive(Copy, Clone, Debug, PartialEq, Eq)]
725pub enum VramHandle {
726 Empty,
728 Rect(VramRect),
730 Window(TextureWindowPlacement),
732 RoomPage(u16),
734 Clut {
736 x: u16,
738 y: u16,
740 entries: u16,
742 },
743}
744
745pub trait VramRegionSource {
748 fn alloc_page_run(
751 &mut self,
752 count: u16,
753 depth: TextureDepth,
754 page_y: u16,
755 ) -> Option<(TexturePage, VramHandle)>;
756
757 fn alloc_clut(&mut self, entries: u16) -> Option<(Clut, VramHandle)>;
759}
760
761#[derive(Copy, Clone, Debug)]
770pub struct ClutRowAllocator<const ROWS: usize> {
771 base_y: u16,
772 slots_per_row: u16,
773 rows: [u64; ROWS],
775}
776
777impl<const ROWS: usize> ClutRowAllocator<ROWS> {
778 pub const fn new(base_y: u16) -> Self {
780 Self {
781 base_y,
782 slots_per_row: CLUT_SLOTS_PER_ROW,
783 rows: [0; ROWS],
784 }
785 }
786
787 #[allow(clippy::manual_is_multiple_of)]
791 pub const fn with_width(base_y: u16, width: u16) -> Self {
792 assert!(
793 width >= 16 && width % 16 == 0 && width <= VRAM_WIDTH,
794 "ClutRowAllocator: width must be a multiple of 16 within VRAM"
795 );
796 assert!(
797 (base_y as usize) + ROWS <= VRAM_HEIGHT as usize,
798 "ClutRowAllocator: band runs past VRAM"
799 );
800 Self {
801 base_y,
802 slots_per_row: width / 16,
803 rows: [0; ROWS],
804 }
805 }
806
807 pub const fn bounds(&self) -> VramRect {
809 VramRect::new(0, self.base_y, self.slots_per_row * 16, ROWS as u16)
810 }
811
812 fn slot_count(entries: u16) -> usize {
813 (entries.max(1) as usize).div_ceil(16)
814 }
815
816 pub fn alloc(&mut self, entries: u16) -> Option<Clut> {
818 let slots = Self::slot_count(entries);
819 let cap = self.slots_per_row as usize;
820 if slots == 0 || slots > cap.min(64) {
821 return None;
822 }
823 let want: u64 = if slots == 64 {
825 u64::MAX
827 } else {
828 (1u64 << slots) - 1
829 };
830 for (r, row) in self.rows.iter_mut().enumerate() {
831 let mut s = 0usize;
832 while s + slots <= cap.min(64) {
833 let mask = want << s;
834 if *row & mask == 0 {
835 *row |= mask;
836 return Some(Clut::new((s as u16) * 16, self.base_y + r as u16));
837 }
838 s += 1;
839 }
840 }
841 None
842 }
843
844 pub fn free(&mut self, clut: Clut, entries: u16) {
846 let slots = Self::slot_count(entries);
847 let r = clut.y().saturating_sub(self.base_y) as usize;
848 let s = (clut.x() / 16) as usize;
849 if r >= ROWS || s + slots > self.slots_per_row as usize {
850 return;
851 }
852 let mask: u64 = if slots == 64 {
854 u64::MAX
856 } else {
857 (1u64 << slots) - 1
858 } << s;
859 self.rows[r] &= !mask;
860 }
861}
862
863#[derive(Copy, Clone, Debug)]
869pub struct VramAllocator<const ROOM_PAGES: usize, const CLUT_ROWS: usize> {
870 grid: [u16; VRAM_ALLOC_ROWS],
871 clut: ClutRowAllocator<CLUT_ROWS>,
872 room: TextureWindowAtlas<ROOM_PAGES>,
873 room_pages: [Option<TexturePage>; ROOM_PAGES],
877 room_page_handles: [VramHandle; ROOM_PAGES],
878 room_base_x: u16,
879 room_base_y: u16,
880 clut_band_reserved: bool,
881}
882
883impl<const ROOM_PAGES: usize, const CLUT_ROWS: usize> VramAllocator<ROOM_PAGES, CLUT_ROWS> {
884 pub const fn new(clut_base_y: u16) -> Self {
890 Self {
891 grid: [0; VRAM_ALLOC_ROWS],
892 clut: ClutRowAllocator::new(clut_base_y),
893 room: TextureWindowAtlas::new(),
894 room_pages: [None; ROOM_PAGES],
895 room_page_handles: [VramHandle::Empty; ROOM_PAGES],
896 room_base_x: 0,
897 room_base_y: 0,
898 clut_band_reserved: false,
899 }
900 }
901
902 #[allow(clippy::manual_is_multiple_of)]
916 pub const fn with_clut_band(band: VramRect) -> Self {
917 assert!(band.x == 0, "with_clut_band: CLUT slots start at x 0");
918 assert!(
919 band.h as usize == CLUT_ROWS,
920 "with_clut_band: band height must equal CLUT_ROWS"
921 );
922 assert!(
923 band.w % ALLOC_COL_W == 0 && band.y % ALLOC_ROW_H == 0 && band.h % ALLOC_ROW_H == 0,
924 "with_clut_band: band must align to the 64 x 16 occupancy cells"
925 );
926 let mut grid = [0u16; VRAM_ALLOC_ROWS];
927 let c1 = (band.w / ALLOC_COL_W) as usize;
928 let r0 = (band.y / ALLOC_ROW_H) as usize;
929 let r1 = ((band.y + band.h) / ALLOC_ROW_H) as usize;
930 let mut r = r0;
931 while r < r1 {
932 let mut c = 0;
933 while c < c1 {
934 grid[r] |= 1 << c;
935 c += 1;
936 }
937 r += 1;
938 }
939 Self {
940 grid,
941 clut: ClutRowAllocator::with_width(band.y, band.w),
942 room: TextureWindowAtlas::new(),
943 room_pages: [None; ROOM_PAGES],
944 room_page_handles: [VramHandle::Empty; ROOM_PAGES],
945 room_base_x: 0,
946 room_base_y: 0,
947 clut_band_reserved: true,
948 }
949 }
950
951 pub const fn clut_bounds(&self) -> VramRect {
953 self.clut.bounds()
954 }
955
956 pub const fn clut_band_is_reserved(&self) -> bool {
959 self.clut_band_reserved
960 }
961
962 fn span(x: u16, y: u16, w: u16, h: u16) -> (usize, usize, usize, usize) {
963 let c0 = (x / ALLOC_COL_W) as usize;
964 let c1 = ((x as usize + w as usize).div_ceil(ALLOC_COL_W as usize)).min(VRAM_ALLOC_COLS);
965 let r0 = (y / ALLOC_ROW_H) as usize;
966 let r1 = ((y as usize + h as usize).div_ceil(ALLOC_ROW_H as usize)).min(VRAM_ALLOC_ROWS);
967 (c0, c1, r0, r1)
968 }
969
970 #[allow(dead_code)] fn rect_free(&self, x: u16, y: u16, w: u16, h: u16) -> bool {
972 let (c0, c1, r0, r1) = Self::span(x, y, w, h);
973 for r in r0..r1 {
974 for c in c0..c1 {
975 if self.grid[r] & (1 << c) != 0 {
976 return false;
977 }
978 }
979 }
980 true
981 }
982
983 fn set_rect(&mut self, x: u16, y: u16, w: u16, h: u16, occupied: bool) {
984 let (c0, c1, r0, r1) = Self::span(x, y, w, h);
985 for r in r0..r1 {
986 for c in c0..c1 {
987 if occupied {
988 self.grid[r] |= 1 << c;
989 } else {
990 self.grid[r] &= !(1 << c);
991 }
992 }
993 }
994 }
995
996 pub fn reserve_rect(&mut self, rect: VramRect) -> VramHandle {
1000 assert!(
1001 !self.clut_band_reserved || !rect.overlaps(self.clut.bounds()),
1002 "reserve_rect: rectangle overlaps the reserved CLUT band"
1003 );
1004 self.set_rect(rect.x, rect.y, rect.w, rect.h, true);
1005 VramHandle::Rect(rect)
1006 }
1007
1008 pub fn reserve_room_band(&mut self, base_x: u16, base_y: u16) {
1012 self.room_base_x = base_x;
1013 self.room_base_y = base_y;
1014 }
1015
1016 fn ensure_room_page(&mut self, page_index: usize) -> Option<TexturePage> {
1017 if let Some(tpage) = self.room_pages.get(page_index).copied().flatten() {
1018 return Some(tpage);
1019 }
1020 if page_index >= ROOM_PAGES {
1021 return None;
1022 }
1023 let preferred_x = self
1024 .room_base_x
1025 .checked_add((page_index as u16).checked_mul(ALLOC_COL_W)?)?;
1026 let x = if preferred_x + ALLOC_COL_W <= VRAM_WIDTH
1027 && self.rect_free(
1028 preferred_x,
1029 self.room_base_y,
1030 ALLOC_COL_W,
1031 TEXTURE_PAGE_TEXELS,
1032 ) {
1033 preferred_x
1034 } else {
1035 self.find_page_run(1, self.room_base_y)?
1036 };
1037 self.set_rect(x, self.room_base_y, ALLOC_COL_W, TEXTURE_PAGE_TEXELS, true);
1038 let tpage = TexturePage::new(x, self.room_base_y, TextureDepth::Bit4);
1039 self.room_pages[page_index] = Some(tpage);
1040 self.room_page_handles[page_index] = VramHandle::Rect(VramRect::new(
1041 x,
1042 self.room_base_y,
1043 ALLOC_COL_W,
1044 TEXTURE_PAGE_TEXELS,
1045 ));
1046 Some(tpage)
1047 }
1048
1049 fn release_room_page_if_empty(&mut self, page_index: usize) {
1050 if page_index >= ROOM_PAGES || !self.room.is_page_empty(page_index) {
1051 return;
1052 }
1053 let handle = core::mem::replace(&mut self.room_page_handles[page_index], VramHandle::Empty);
1054 if let VramHandle::Rect(rect) = handle {
1055 self.set_rect(rect.x, rect.y, rect.w, rect.h, false);
1056 }
1057 self.room_pages[page_index] = None;
1058 }
1059
1060 fn find_page_run(&self, count: u16, page_y: u16) -> Option<u16> {
1061 let r0 = (page_y / ALLOC_ROW_H) as usize;
1062 let r1 = r0 + ALLOC_PAGE_ROWS;
1063 if r1 > VRAM_ALLOC_ROWS || count == 0 {
1064 return None;
1065 }
1066 let n = count as usize;
1067 let mut c = 0usize;
1068 while c + n <= VRAM_ALLOC_COLS {
1069 let cols_free = (c..c + n).all(|col| (r0..r1).all(|r| self.grid[r] & (1 << col) == 0));
1070 if cols_free {
1071 return Some((c as u16) * ALLOC_COL_W);
1072 }
1073 c += 1;
1074 }
1075 None
1076 }
1077
1078 pub fn alloc_window(
1081 &mut self,
1082 width_texels: u16,
1083 height_texels: u16,
1084 ) -> Option<(TexturePage, TextureWindowPlacement, VramHandle)> {
1085 let placement = self.room.allocate(width_texels, height_texels)?;
1086 let page_index = placement.page_index() as usize;
1087 let Some(tpage) = self.ensure_room_page(page_index) else {
1088 self.room.release(placement);
1089 return None;
1090 };
1091 Some((tpage, placement, VramHandle::Window(placement)))
1092 }
1093
1094 pub fn alloc_room_page(&mut self) -> Option<(TexturePage, VramHandle)> {
1098 let page_index = self.room.reserve_empty_page()?;
1099 let Some(tpage) = self.ensure_room_page(page_index) else {
1100 self.room.release_page(page_index);
1101 return None;
1102 };
1103 Some((tpage, VramHandle::RoomPage(page_index as u16)))
1104 }
1105
1106 pub fn alloc_model_slot(
1113 &mut self,
1114 halfwords_per_row: u16,
1115 depth: TextureDepth,
1116 ) -> Option<(TexturePage, VramHandle)> {
1117 if !matches!(depth, TextureDepth::Bit4 | TextureDepth::Bit8) {
1118 return None;
1119 }
1120 let pages = halfwords_per_row.div_ceil(ALLOC_COL_W).max(1);
1121 let x = self.find_page_run(pages, 256)?;
1122 self.set_rect(x, 256, pages * ALLOC_COL_W, TEXTURE_PAGE_TEXELS, true);
1123 Some((
1124 TexturePage::new(x, 256, depth),
1125 VramHandle::Rect(VramRect::new(
1126 x,
1127 256,
1128 pages * ALLOC_COL_W,
1129 TEXTURE_PAGE_TEXELS,
1130 )),
1131 ))
1132 }
1133
1134 pub fn free(&mut self, handle: VramHandle) {
1136 match handle {
1137 VramHandle::Empty => {}
1138 VramHandle::Rect(rect) => self.set_rect(rect.x, rect.y, rect.w, rect.h, false),
1139 VramHandle::Window(placement) => {
1140 let page = placement.page_index() as usize;
1141 self.room.release(placement);
1142 self.release_room_page_if_empty(page);
1143 }
1144 VramHandle::RoomPage(page) => {
1145 let page = page as usize;
1146 self.room.release_page(page);
1147 self.release_room_page_if_empty(page);
1148 }
1149 VramHandle::Clut { x, y, entries } => self.clut.free(Clut::new(x, y), entries),
1150 }
1151 }
1152}
1153
1154impl<const ROOM_PAGES: usize, const CLUT_ROWS: usize> VramRegionSource
1155 for VramAllocator<ROOM_PAGES, CLUT_ROWS>
1156{
1157 fn alloc_page_run(
1158 &mut self,
1159 count: u16,
1160 depth: TextureDepth,
1161 page_y: u16,
1162 ) -> Option<(TexturePage, VramHandle)> {
1163 let x = self.find_page_run(count, page_y)?;
1164 self.set_rect(x, page_y, count * ALLOC_COL_W, TEXTURE_PAGE_TEXELS, true);
1165 Some((
1166 TexturePage::new(x, page_y, depth),
1167 VramHandle::Rect(VramRect::new(
1168 x,
1169 page_y,
1170 count * ALLOC_COL_W,
1171 TEXTURE_PAGE_TEXELS,
1172 )),
1173 ))
1174 }
1175
1176 fn alloc_clut(&mut self, entries: u16) -> Option<(Clut, VramHandle)> {
1177 let clut = self.clut.alloc(entries)?;
1178 Some((
1179 clut,
1180 VramHandle::Clut {
1181 x: clut.x(),
1182 y: clut.y(),
1183 entries,
1184 },
1185 ))
1186 }
1187}
1188
1189pub fn upload_16bpp(rect: VramRect, pixels: &[u16]) {
1203 let expected = rect.pixel_count();
1204 assert!(
1207 pixels.len() as u32 == expected,
1208 "upload_16bpp: pixels.len() != rect.w * rect.h"
1209 );
1210 assert!(
1211 expected.is_multiple_of(2),
1212 "upload_16bpp: odd pixel count not supported; round the rect up"
1213 );
1214
1215 let _pause = pause_recording();
1227 copy_to_vram_header(rect);
1228 let mut i = 0;
1229 while i + 1 < pixels.len() {
1230 let lo = pixels[i] as u32;
1231 let hi = pixels[i + 1] as u32;
1232 psx_io::gpu::write_command_unguarded(lo | (hi << 16));
1233 i += 2;
1234 }
1235}
1236
1237pub fn upload_bytes(rect: VramRect, bytes: &[u8]) {
1247 let expected = (rect.pixel_count() as usize) * 2;
1248 assert_eq!(
1249 bytes.len(),
1250 expected,
1251 "upload_bytes: bytes.len() ({}) != 2 × rect.w × rect.h ({})",
1252 bytes.len(),
1253 expected,
1254 );
1255 assert!(
1256 bytes.len() >= 2 && bytes.len().is_multiple_of(2),
1257 "upload_bytes: byte count must be a positive multiple of 2"
1258 );
1259
1260 let _pause = pause_recording();
1267 copy_to_vram_header(rect);
1268 let mut i = 0;
1269 while i < bytes.len() {
1270 psx_io::gpu::write_command_unguarded(packed_upload_word(bytes, i));
1271 i += 4;
1272 }
1273}
1274
1275#[inline]
1276fn packed_upload_word(bytes: &[u8], offset: usize) -> u32 {
1277 u32::from_le_bytes([
1278 bytes[offset],
1279 bytes[offset + 1],
1280 bytes.get(offset + 2).copied().unwrap_or(0),
1281 bytes.get(offset + 3).copied().unwrap_or(0),
1282 ])
1283}
1284
1285pub fn upload_bytes_aligned(rect: VramRect, bytes: &[u8]) {
1288 if cfg!(target_endian = "little")
1289 && bytes.as_ptr().align_offset(4) == 0
1290 && bytes.len().is_multiple_of(4)
1291 {
1292 let words =
1293 unsafe { core::slice::from_raw_parts(bytes.as_ptr().cast::<u32>(), bytes.len() / 4) };
1296 upload_words(rect, words);
1297 } else {
1298 upload_bytes(rect, bytes);
1299 }
1300}
1301
1302#[doc(alias = "LoadImage")]
1310pub fn upload_words(rect: VramRect, words: &[u32]) {
1311 let expected_words = rect.pixel_count() as usize / 2;
1312 assert!(
1313 rect.pixel_count().is_multiple_of(2),
1314 "upload_words: odd pixel count is not supported"
1315 );
1316 assert_eq!(
1317 words.len(),
1318 expected_words,
1319 "upload_words: words.len() ({}) != rect.w*rect.h/2 ({})",
1320 words.len(),
1321 expected_words,
1322 );
1323 assert!(!words.is_empty(), "upload_words: empty upload");
1324
1325 let _pause = pause_recording();
1326 copy_to_vram_header(rect);
1327 for &word in words {
1328 psx_io::gpu::write_command_unguarded(word);
1329 }
1330}
1331
1332#[inline]
1336fn copy_to_vram_header(rect: VramRect) {
1337 if !dma::wait_done(Channel::Gpu, dma::DEFAULT_SPINS) {
1344 dma::abort(Channel::Gpu);
1345 }
1346 wait_command_ready();
1347 write_command(gp0::COPY_CPU_TO_VRAM);
1348 write_command(pack_xy(rect.x, rect.y));
1349 write_command(pack_xy(rect.w, rect.h));
1350}
1351
1352#[doc(alias = "LoadImage")]
1367pub fn dma_copy_to_vram(_dma: &mut GpuDma, rect: VramRect, words: &[u32]) -> bool {
1368 if words.len() < copy_words(rect) {
1369 return false;
1370 }
1371 if !unsafe { kick_copy_to_vram(rect, words.as_ptr()) } {
1375 return false;
1376 }
1377 dma::wait_or_abort(Channel::Gpu, dma::DEFAULT_SPINS)
1380}
1381
1382#[doc(alias = "LoadImage")]
1399pub unsafe fn dma_copy_to_vram_start(_dma: &mut GpuDma, rect: VramRect, words: *const u32) -> bool {
1400 unsafe { kick_copy_to_vram(rect, words) }
1402}
1403
1404#[inline]
1406pub fn dma_copy_to_vram_done() -> bool {
1407 !dma::is_busy(Channel::Gpu)
1408}
1409
1410fn copy_words(rect: VramRect) -> usize {
1412 (rect.w / 2) as usize * rect.h as usize
1413}
1414
1415unsafe fn kick_copy_to_vram(rect: VramRect, src: *const u32) -> bool {
1424 if !rect.w.is_multiple_of(2) || rect.w == 0 || rect.h == 0 {
1425 return false;
1426 }
1427 let words_per_row = rect.w / 2;
1428 if words_per_row > 16 {
1433 return false;
1434 }
1435 let _pause = pause_recording();
1436 copy_to_vram_header(rect);
1437 write_display_control(gp1::dma_direction(2));
1440 dma::enable_channel(Channel::Gpu);
1441 unsafe {
1445 dma::start(
1446 Channel::Gpu,
1447 dma::Transfer {
1448 address: src as u32,
1449 size: dma::size_blocks(words_per_row, rect.h),
1450 control: psx_hw::dma::CHCR_TO_DEVICE
1451 | psx_hw::dma::CHCR_SYNC_BLOCK
1452 | psx_hw::dma::CHCR_START,
1453 },
1454 )
1455 };
1456 true
1457}
1458
1459pub fn upload_15bpp(rect: VramRect, pixels: &[Color555]) {
1462 let as_u16: &[u16] = unsafe {
1463 core::slice::from_raw_parts(pixels.as_ptr() as *const u16, pixels.len())
1466 };
1467 upload_16bpp(rect, as_u16);
1468}
1469
1470pub fn upload_clut(clut: Clut, entries: &[Color555]) {
1474 let rect = VramRect::new(clut.x(), clut.y(), entries.len() as u16, 1);
1475 upload_15bpp(rect, entries);
1476}
1477
1478#[deprecated(note = "renamed to `TexturePage`")]
1484pub type Tpage = TexturePage;
1485
1486#[deprecated(note = "renamed to `TextureDepth`")]
1488pub type TexDepth = TextureDepth;
1489
1490impl TexturePage {
1491 #[deprecated(note = "renamed to `uv_word`")]
1493 #[inline(always)]
1494 pub const fn uv_tpage_word(self, semi_trans: u8) -> u16 {
1495 self.uv_word(semi_trans)
1496 }
1497}
1498
1499impl Clut {
1500 #[deprecated(note = "renamed to `uv_word`")]
1502 #[inline(always)]
1503 pub const fn uv_clut_word(self) -> u16 {
1504 self.uv_word()
1505 }
1506}
1507
1508#[cfg(test)]
1509mod tests {
1510 use super::*;
1511
1512 #[test]
1513 fn dma_copy_to_vram_refuses_what_it_cannot_send_whole() {
1514 let mut dma = unsafe { GpuDma::steal() };
1517 let words = [0u32; 8];
1518 assert!(!dma_copy_to_vram(
1520 &mut dma,
1521 VramRect::new(0, 0, 8, 2),
1522 &words[..7]
1523 ));
1524 assert!(!dma_copy_to_vram(
1526 &mut dma,
1527 VramRect::new(0, 0, 3, 1),
1528 &words
1529 ));
1530 assert!(!dma_copy_to_vram(
1531 &mut dma,
1532 VramRect {
1533 x: 0,
1534 y: 0,
1535 w: 0,
1536 h: 1
1537 },
1538 &words
1539 ));
1540 assert!(!dma_copy_to_vram(
1541 &mut dma,
1542 VramRect::new(0, 0, 34, 1),
1543 &[0; 17]
1544 ));
1545 assert!(!dma_copy_to_vram(
1546 &mut dma,
1547 VramRect {
1548 x: 0,
1549 y: 0,
1550 w: 2,
1551 h: 0
1552 },
1553 &words
1554 ));
1555 }
1556
1557 #[test]
1558 fn byte_upload_word_zero_pads_an_odd_final_halfword() {
1559 assert_eq!(
1560 packed_upload_word(&[0x11, 0x22, 0x33, 0x44], 0),
1561 0x4433_2211
1562 );
1563 assert_eq!(packed_upload_word(&[0x55, 0x66], 0), 0x0000_6655);
1564 }
1565
1566 #[test]
1567 fn stp_is_the_mask_bit_named_for_its_palette_meaning() {
1568 let opaque = Color555::rgb8(255, 255, 255);
1569 assert!(!opaque.is_semi_transparent());
1570 assert_eq!(
1571 opaque.with_semi_transparency().as_u16(),
1572 opaque.with_mask_bit().as_u16()
1573 );
1574 assert!(opaque.with_semi_transparency().is_semi_transparent());
1575 assert_eq!(Color555::TRANSPARENT.as_u16(), 0);
1578 assert!(!Color555::TRANSPARENT.is_semi_transparent());
1579 }
1580
1581 #[test]
1582 fn color_rgb8_truncates_low_bits() {
1583 assert_eq!(Color555::rgb8(0, 0, 0).as_u16(), 0);
1584 assert_eq!(Color555::rgb8(255, 255, 255).as_u16(), 0x7fff);
1585 assert_eq!(Color555::rgb8(24, 0, 0).as_u16(), 3);
1587 }
1588
1589 #[test]
1590 fn color_rgb5_rejects_out_of_range_via_panic() {
1591 assert_eq!(Color555::rgb5(31, 0, 0).as_u16(), 31);
1594 assert_eq!(Color555::rgb5(0, 31, 0).as_u16(), 31 << 5);
1595 assert_eq!(Color555::rgb5(0, 0, 31).as_u16(), 31 << 10);
1596 }
1597
1598 #[test]
1599 #[should_panic = "red must be < 32"]
1600 fn color_rgb5_panics_on_32() {
1601 let _ = Color555::rgb5(32, 0, 0);
1602 }
1603
1604 #[test]
1605 fn vram_rect_new_accepts_valid_positions() {
1606 let _ = VramRect::new(0, 0, 64, 64);
1607 let _ = VramRect::new(VRAM_WIDTH - 1, 0, 1, 1);
1608 let _ = VramRect::new(0, VRAM_HEIGHT - 1, 1, 1);
1609 }
1610
1611 #[test]
1612 #[should_panic = "overflows VRAM width"]
1613 fn vram_rect_new_rejects_horizontal_overflow() {
1614 let _ = VramRect::new(1000, 0, 100, 10);
1615 }
1616
1617 #[test]
1618 fn texture_window_row_bound_preserves_scan_order_and_palette_rows() {
1619 let mut atlas = TextureWindowAtlas::<2>::new();
1620 for index in 0..24 {
1621 let placement = atlas.allocate_with_usable_rows(64, 64, 224).unwrap();
1622 assert_eq!(placement.page_index(), index / 12);
1623 assert_eq!(u16::from(placement.origin_u()), (index % 4) * 64);
1624 assert_eq!(u16::from(placement.origin_v()), ((index % 12) / 4) * 64);
1625 assert!(u16::from(placement.origin_v()) + u16::from(placement.height()) <= 224);
1626 }
1627 assert!(atlas.allocate_with_usable_rows(64, 64, 224).is_none());
1628 let strip = atlas.allocate_with_usable_rows(32, 32, 224).unwrap();
1630 assert_eq!(
1631 (strip.page_index(), strip.origin_u(), strip.origin_v()),
1632 (0, 0, 192)
1633 );
1634 assert_eq!(core::mem::size_of_val(&atlas), 2 * 32 * 4);
1635 }
1636
1637 #[test]
1638 fn texture_window_row_bound_rejects_invalid_input_without_mutation() {
1639 let mut atlas = TextureWindowAtlas::<1>::new();
1640 atlas.allocate(32, 32).unwrap();
1641 let before = atlas;
1642 for rows in [0, 1, 7, 9, 223, 255, 257, 264, u16::MAX] {
1643 assert!(atlas.allocate_with_usable_rows(8, 8, rows).is_none());
1644 assert_eq!(atlas, before);
1645 }
1646 assert!(atlas.allocate_with_usable_rows(64, 64, 56).is_none());
1647 assert_eq!(atlas, before);
1648 assert!(atlas.allocate_with_usable_rows(48, 32, 224).is_none());
1649 assert_eq!(atlas, before);
1650 let edge = atlas.allocate_with_usable_rows(8, 8, 8).unwrap();
1651 assert_eq!((edge.origin_u(), edge.origin_v()), (32, 0));
1652 }
1653
1654 #[test]
1655 fn texture_window_full_row_bound_matches_default_allocator() {
1656 let mut default = TextureWindowAtlas::<2>::new();
1657 let mut bounded = default;
1658 for index in 0..160 {
1659 let (width, height) = [(32, 32), (64, 16), (8, 128), (128, 8)][index % 4];
1660 assert_eq!(
1661 default.allocate(width, height),
1662 bounded.allocate_with_usable_rows(width, height, 256)
1663 );
1664 assert_eq!(default, bounded);
1665 }
1666 }
1667
1668 #[test]
1669 fn texture_window_atlas_packs_32x32_textures_inside_one_page() {
1670 let mut atlas = TextureWindowAtlas::<1>::new();
1671
1672 let first = atlas.allocate(32, 32).expect("first texture fits");
1673 let second = atlas.allocate(32, 32).expect("second texture fits");
1674 let eighth = {
1675 let mut placement = second;
1676 for _ in 2..8 {
1677 placement = atlas.allocate(32, 32).expect("top row texture fits");
1678 }
1679 placement
1680 };
1681 let ninth = atlas.allocate(32, 32).expect("second row texture fits");
1682
1683 assert_eq!(first.page_index(), 0);
1684 assert_eq!((first.origin_u(), first.origin_v()), (0, 0));
1685 assert_eq!((second.origin_u(), second.origin_v()), (32, 0));
1686 assert_eq!((eighth.origin_u(), eighth.origin_v()), (224, 0));
1687 assert_eq!((ninth.origin_u(), ninth.origin_v()), (0, 32));
1688 }
1689
1690 #[test]
1691 fn texture_window_atlas_moves_to_next_page_when_current_page_is_full() {
1692 let mut atlas = TextureWindowAtlas::<2>::new();
1693
1694 for _ in 0..16 {
1695 atlas
1696 .allocate(64, 64)
1697 .expect("64x64 slot fits in first page");
1698 }
1699 let next = atlas.allocate(64, 64).expect("second page has space");
1700
1701 assert_eq!(next.page_index(), 1);
1702 assert_eq!((next.origin_u(), next.origin_v()), (0, 0));
1703 }
1704
1705 #[test]
1706 fn texture_window_atlas_reserves_empty_page_for_unwindowed_texture() {
1707 let mut atlas = TextureWindowAtlas::<2>::new();
1708
1709 let page = atlas.reserve_empty_page().expect("page reserved");
1710 assert_eq!(page, 0);
1711 let next = atlas.allocate(64, 64).expect("second page still free");
1712
1713 assert_eq!(next.page_index(), 1);
1714 assert_eq!((next.origin_u(), next.origin_v()), (0, 0));
1715 }
1716
1717 #[test]
1718 fn texture_window_atlas_aligns_each_allocation_to_its_own_size() {
1719 let mut atlas = TextureWindowAtlas::<1>::new();
1720
1721 atlas.allocate(32, 32).expect("small texture fits");
1722 let large = atlas.allocate(64, 64).expect("large texture fits");
1723
1724 assert_eq!((large.origin_u(), large.origin_v()), (64, 0));
1725 }
1726
1727 #[test]
1728 fn texture_window_atlas_rejects_non_texture_window_dimensions() {
1729 let mut atlas = TextureWindowAtlas::<1>::new();
1730
1731 assert!(atlas.allocate(48, 32).is_none());
1732 assert!(atlas.allocate(4, 32).is_none());
1733 assert!(atlas.allocate(256, 32).is_none());
1734 }
1735
1736 #[test]
1737 fn tpage_encodes_uv_word_correctly() {
1738 let tp = TexturePage::new(640, 0, TextureDepth::Bit15);
1739 let word = tp.uv_word(0);
1741 assert_eq!(word & 0xf, 10, "tpx");
1742 assert_eq!((word >> 4) & 1, 0, "tpy");
1743 assert_eq!((word >> 5) & 3, 0, "semi_trans");
1744 assert_eq!((word >> 7) & 3, 2, "depth");
1745 }
1746
1747 #[test]
1748 #[should_panic = "x must be a multiple of 64"]
1749 fn tpage_rejects_misaligned_x() {
1750 let _ = TexturePage::new(32, 0, TextureDepth::Bit8);
1751 }
1752
1753 #[test]
1754 #[should_panic = "y must be 0 or 256"]
1755 fn tpage_rejects_bad_y() {
1756 let _ = TexturePage::new(0, 128, TextureDepth::Bit4);
1757 }
1758
1759 #[test]
1760 fn clut_encodes_uv_word_correctly() {
1761 let cl = Clut::new(640, 240);
1762 let word = cl.uv_word();
1764 assert_eq!(word & 0x3f, 40, "cx");
1765 assert_eq!((word >> 6) & 0x1ff, 240, "cy");
1766 }
1767
1768 #[test]
1769 #[should_panic = "x must be a multiple of 16"]
1770 fn clut_rejects_misaligned_x() {
1771 let _ = Clut::new(8, 0);
1772 }
1773
1774 #[test]
1775 fn tex_depth_texels_per_halfword() {
1776 assert_eq!(TextureDepth::Bit4.texels_per_halfword(), 4);
1777 assert_eq!(TextureDepth::Bit8.texels_per_halfword(), 2);
1778 assert_eq!(TextureDepth::Bit15.texels_per_halfword(), 1);
1779 }
1780
1781 #[test]
1782 fn vram_alloc_reserves_framebuffer_then_packs_pages_past_it() {
1783 let mut a = VramAllocator::<6, 16>::new(480);
1784 a.reserve_rect(VramRect::new(0, 0, 320, 480));
1785 let (tp, _h) = a
1786 .alloc_page_run(3, TextureDepth::Bit4, 0)
1787 .expect("3 contiguous pages");
1788 assert_eq!(tp.x() % 64, 0, "page X is 64-aligned");
1789 assert!(tp.x() >= 320, "page must not overlap the framebuffer");
1790 assert_eq!(tp.y(), 0);
1791 }
1792
1793 #[test]
1794 fn vram_alloc_free_round_trips_a_page() {
1795 let mut a = VramAllocator::<6, 16>::new(480);
1796 let (tp1, h1) = a.alloc_page_run(1, TextureDepth::Bit4, 0).unwrap();
1797 let (tp2, _h2) = a.alloc_page_run(1, TextureDepth::Bit4, 0).unwrap();
1798 assert_ne!(tp1.x(), tp2.x());
1799 a.free(h1);
1800 let (tp3, _h3) = a.alloc_page_run(1, TextureDepth::Bit4, 0).unwrap();
1801 assert_eq!(tp3.x(), tp1.x(), "freed page is reused");
1802 }
1803
1804 #[test]
1805 fn vram_alloc_window_lands_in_reserved_room_band() {
1806 let mut a = VramAllocator::<2, 16>::new(480);
1807 a.reserve_room_band(640, 0);
1808 let (tp, pl, _h) = a.alloc_window(32, 32).expect("window fits");
1809 assert_eq!(tp.x(), 640, "first window is at room band base");
1810 assert_eq!((pl.origin_u(), pl.origin_v()), (0, 0));
1811 }
1812
1813 #[test]
1814 fn lazy_room_page_returns_physical_backing_after_last_window() {
1815 let mut a = VramAllocator::<6, 16>::new(480);
1816 a.reserve_rect(VramRect::new(0, 0, 320, 480));
1817 a.reserve_room_band(640, 0);
1818 let (_, _, window) = a.alloc_window(64, 64).expect("room window");
1819 assert!(
1820 a.alloc_page_run(6, TextureDepth::Bit4, 0).is_none(),
1821 "live preferred room page interrupts the six-page top run"
1822 );
1823 a.free(window);
1824 assert!(
1825 a.alloc_page_run(6, TextureDepth::Bit4, 0).is_some(),
1826 "last-window release must return the physical room page"
1827 );
1828 }
1829
1830 #[test]
1831 fn model_slots_preserve_indexed_texture_depth() {
1832 let mut a = VramAllocator::<2, 16>::new(480);
1833 let (bit4, _h4) = a.alloc_model_slot(32, TextureDepth::Bit4).unwrap();
1834 let (bit8, _h8) = a.alloc_model_slot(64, TextureDepth::Bit8).unwrap();
1835
1836 assert_eq!(bit4.depth(), TextureDepth::Bit4);
1837 assert_eq!(bit8.depth(), TextureDepth::Bit8);
1838 assert_ne!(bit4.x(), bit8.x());
1839 assert!(a.alloc_model_slot(64, TextureDepth::Bit15).is_none());
1840 }
1841
1842 #[test]
1843 fn clut_row_allocator_packs_and_reuses_slots() {
1844 let mut c = ClutRowAllocator::<4>::new(480);
1845 let a = c.alloc(16).unwrap();
1846 let b = c.alloc(16).unwrap();
1847 assert_eq!((a.x(), a.y()), (0, 480));
1848 assert_eq!((b.x(), b.y()), (16, 480));
1849 let big = c.alloc(256).unwrap(); assert_eq!((big.x(), big.y()), (32, 480));
1851 c.free(a, 16);
1852 let reused = c.alloc(16).unwrap();
1853 assert_eq!((reused.x(), reused.y()), (0, 480), "freed slot reused");
1854 }
1855
1856 #[test]
1857 fn clut_row_allocator_width_limits_each_row() {
1858 let mut c = ClutRowAllocator::<2>::with_width(480, 320);
1859 assert_eq!(c.bounds(), VramRect::new(0, 480, 320, 2));
1860 for slot in 0..20u16 {
1862 let clut = c.alloc(16).unwrap();
1863 assert_eq!((clut.x(), clut.y()), (slot * 16, 480));
1864 }
1865 let next = c.alloc(16).unwrap();
1866 assert_eq!((next.x(), next.y()), (0, 481));
1867 let mut c = ClutRowAllocator::<2>::with_width(480, 320);
1869 assert!(c.alloc(256).is_some());
1870 assert_eq!(c.alloc(256).unwrap().y(), 481);
1871 assert!(c.alloc(256).is_none());
1872 c.free(Clut::new(320, 480), 16);
1874 }
1875
1876 #[test]
1879 fn reserved_clut_band_is_disjoint_from_every_texture_rectangle() {
1880 const BAND: VramRect = VramRect::new(0, 480, 320, 32);
1881 let inside = |r: VramRect, outer: VramRect| {
1882 r.x >= outer.x
1883 && r.y >= outer.y
1884 && r.x + r.w <= outer.x + outer.w
1885 && r.y + r.h <= outer.y + outer.h
1886 };
1887 let mut a = VramAllocator::<6, 32>::with_clut_band(BAND);
1888 assert!(a.clut_band_is_reserved());
1889 assert_eq!(a.clut_bounds(), BAND);
1890 let framebuffer = VramRect::new(0, 0, 320, 480);
1891 a.reserve_rect(framebuffer);
1892 a.reserve_room_band(640, 0);
1893
1894 let mut rects: [Option<VramRect>; 64] = [None; 64];
1895 let mut count = 0;
1896 let mut keep = |handle: VramHandle, rects: &mut [Option<VramRect>; 64]| {
1897 if let VramHandle::Rect(r) = handle {
1898 rects[count] = Some(r);
1899 count += 1;
1900 }
1901 };
1902 for page_y in [0u16, 256] {
1904 while let Some((_, h)) = a.alloc_page_run(1, TextureDepth::Bit4, page_y) {
1905 keep(h, &mut rects);
1906 }
1907 }
1908 assert!(a.alloc_model_slot(64, TextureDepth::Bit4).is_none());
1910 let first_room_page = a.alloc_window(64, 64);
1911 assert!(
1912 first_room_page.is_none(),
1913 "no page is left to back a room window"
1914 );
1915
1916 let mut cluts: [Option<VramRect>; 640] = [None; 640];
1918 let mut n = 0;
1919 while let Some((clut, _)) = a.alloc_clut(16) {
1920 cluts[n] = Some(VramRect::new(clut.x(), clut.y(), 16, 1));
1921 n += 1;
1922 }
1923 assert_eq!(
1924 n,
1925 20 * 32,
1926 "the band holds 20 four-bit CLUTs on each of 32 rows"
1927 );
1928 let mut a8 = VramAllocator::<6, 32>::with_clut_band(BAND);
1929 let mut eight = 0;
1930 while let Some((clut, _)) = a8.alloc_clut(256) {
1931 assert!(inside(VramRect::new(clut.x(), clut.y(), 256, 1), BAND));
1932 eight += 1;
1933 }
1934 assert_eq!(eight, 32);
1935
1936 for clut in cluts[..n].iter().flatten() {
1937 assert!(inside(*clut, BAND), "CLUT inside the band");
1938 assert!(!clut.overlaps(framebuffer));
1939 for page in rects[..count].iter().flatten() {
1940 assert!(!clut.overlaps(*page), "CLUT overlaps a texture page");
1941 }
1942 }
1943 assert!(count > 0);
1944 }
1945
1946 #[test]
1947 fn the_unreserved_full_width_band_overlaps_a_lower_page() {
1948 let mut a = VramAllocator::<6, 16>::new(480);
1951 assert!(!a.clut_band_is_reserved());
1952 let (_, handle) = a.alloc_page_run(1, TextureDepth::Bit4, 256).unwrap();
1953 let VramHandle::Rect(page) = handle else {
1954 panic!("page handle");
1955 };
1956 assert!(page.overlaps(a.clut_bounds()));
1957 }
1958
1959 #[test]
1960 #[should_panic = "overlaps the reserved CLUT band"]
1961 fn reserving_a_rectangle_over_the_clut_band_is_refused() {
1962 let mut a = VramAllocator::<6, 32>::with_clut_band(VramRect::new(0, 480, 320, 32));
1963 a.reserve_rect(VramRect::new(0, 256, 320, 256));
1964 }
1965
1966 #[test]
1967 fn texture_window_atlas_release_frees_for_reuse() {
1968 let mut atlas = TextureWindowAtlas::<1>::new();
1969 let first = atlas.allocate(32, 32).unwrap();
1970 let _second = atlas.allocate(32, 32).unwrap();
1971 atlas.release(first);
1972 let reused = atlas.allocate(32, 32).unwrap();
1973 assert_eq!(
1974 (reused.origin_u(), reused.origin_v()),
1975 (first.origin_u(), first.origin_v()),
1976 "released slot is reused"
1977 );
1978 }
1979
1980 #[test]
1981 fn overlapping_layout_rectangles_are_found_in_listed_order() {
1982 let clean = [
1984 VramRect::new(0, 0, 320, 240),
1985 VramRect::new(0, 240, 320, 240),
1986 VramRect::new(0, 480, 320, 32),
1987 ];
1988 assert_eq!(first_vram_overlap(&clean), None);
1989 assert!(vram_layout_is_disjoint(&clean));
1990
1991 let clashing = [
1994 VramRect::new(0, 0, 320, 240),
1995 VramRect::new(320, 256, 64, 256),
1996 VramRect::new(0, 480, 640, 24),
1997 ];
1998 assert_eq!(first_vram_overlap(&clashing), Some((1, 2)));
1999 assert!(!vram_layout_is_disjoint(&clashing));
2000
2001 let touching = [
2003 VramRect::new(0, 0, 320, 240),
2004 VramRect::new(320, 0, 64, 240),
2005 ];
2006 assert_eq!(first_vram_overlap(&touching), None);
2007 let stacked = [VramRect::new(0, 0, 320, 240), VramRect::new(0, 240, 320, 8)];
2008 assert_eq!(first_vram_overlap(&stacked), None);
2009
2010 assert!(vram_layout_is_disjoint(&[VramRect::new(0, 0, 1, 1)]));
2012 assert!(vram_layout_is_disjoint(&[]));
2013 }
2014}