-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmod.rs
2133 lines (1999 loc) · 71.4 KB
/
mod.rs
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # VGA Driver for the Neotron Pico
//!
//! VGA output on the Neotron Pico uses 14 GPIO pins and two PIO state machines.
//!
//! It can generate 640x480@60Hz and 640x400@70Hz standard VGA video, with a
//! 25.2 MHz pixel clock. The spec is 25.175 MHz, so we are 0.1% off). The
//! assumption is that the CPU is clocked at 151.2 MHz, i.e. 6x the pixel clock.
//! All of the PIO code relies on this assumption!
//!
//! Currently 80x25, 80x30, 80x50 and 80x60 modes are supported in colour.
// -----------------------------------------------------------------------------
// Licence Statement
// -----------------------------------------------------------------------------
// Copyright (c) Jonathan 'theJPster' Pallant and the Neotron Developers, 2023
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation, either version 3 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/>.
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Sub-modules
// -----------------------------------------------------------------------------
mod font16;
mod font8;
mod rgb;
// -----------------------------------------------------------------------------
// Imports
// -----------------------------------------------------------------------------
use crate::hal::{self, pac::interrupt, pio::PIOExt};
use core::{
cell::{RefCell, UnsafeCell},
ptr::addr_of_mut,
sync::atomic::{AtomicBool, AtomicU16, AtomicU32, Ordering},
};
use defmt::{debug, trace};
use neotron_common_bios::video::{Attr, GlyphAttr, TextBackgroundColour, TextForegroundColour};
pub use rgb::{RGBColour, RGBPair};
// -----------------------------------------------------------------------------
// Types
// -----------------------------------------------------------------------------
/// A font
pub struct Font<'a> {
data: &'a [u8],
}
/// Holds a video mode and its framebuffer pointer as a pair.
#[derive(Copy, Clone)]
pub struct ModeInfo {
pub mode: neotron_common_bios::video::Mode,
pub ptr: *mut u32,
}
/// Holds a video mode and a pointer, but as an atomic value suitable for use in
/// a `static`.
pub struct VideoMode {
inner: critical_section::Mutex<RefCell<ModeInfo>>,
}
unsafe impl Sync for VideoMode {}
impl VideoMode {
/// Construct a new [`NewModeWrapper`] with the given mode.
const fn new() -> VideoMode {
VideoMode {
inner: critical_section::Mutex::new(RefCell::new(ModeInfo {
mode: neotron_common_bios::video::Mode::new(
neotron_common_bios::video::Timing::T640x480,
neotron_common_bios::video::Format::Text8x16,
),
ptr: core::ptr::null_mut(),
})),
}
}
/// Set a new video mode.
pub fn set_mode(&self, mut modeinfo: ModeInfo) {
if modeinfo.ptr.is_null() {
modeinfo.ptr = GLYPH_ATTR_ARRAY.as_ptr() as *mut u32;
}
critical_section::with(|cs| {
self.inner.replace(cs, modeinfo);
})
}
/// Get the current video mode.
pub fn get_mode(&self) -> ModeInfo {
let mut modeinfo = critical_section::with(|cs| {
let info = self.inner.borrow_ref(cs);
*info
});
if modeinfo.ptr.is_null() {
modeinfo.ptr = GLYPH_ATTR_ARRAY.as_ptr() as *mut u32;
}
modeinfo
}
}
/// Describes the polarity of a sync pulse.
///
/// Some pulses are positive (active-high), some are negative (active-low).
enum SyncPolarity {
/// An active-high pulse
Positive,
/// An active-low pulse
Negative,
}
impl SyncPolarity {
const fn enabled(&self) -> bool {
match self {
SyncPolarity::Positive => true,
SyncPolarity::Negative => false,
}
}
const fn disabled(&self) -> bool {
match self {
SyncPolarity::Positive => false,
SyncPolarity::Negative => true,
}
}
}
/// Holds some data necessary to run the Video.
///
/// This structure is owned entirely by the main thread (or the drawing
/// thread). Data handled under interrupt is stored in various other places.
struct RenderEngine {
/// How many frames have been drawn
frame_count: u32,
/// The current video mode
current_video_mode: neotron_common_bios::video::Mode,
/// The current framebuffer pointer
current_video_ptr: *const u32,
/// How many rows of text are we showing right now
num_text_rows: usize,
/// How many columns of text are we showing right now
num_text_cols: usize,
}
impl RenderEngine {
// Initialise the main-thread resources
pub fn new() -> RenderEngine {
RenderEngine {
frame_count: 0,
// Should match the default value of TIMING_BUFFER and VIDEO_MODE
current_video_mode: unsafe { neotron_common_bios::video::Mode::from_u8(0) },
current_video_ptr: core::ptr::null_mut(),
// Should match the mode above
num_text_cols: 80,
num_text_rows: 30,
}
}
/// Do the start-of-frame setup
fn frame_start(&mut self) {
trace!("Frame {}", self.frame_count);
self.frame_count += 1;
// Update video mode only on first line of video
let modeinfo = VIDEO_MODE.get_mode();
self.current_video_ptr = modeinfo.ptr;
self.current_video_mode = modeinfo.mode;
match self.current_video_mode.timing() {
neotron_common_bios::video::Timing::T640x400 => unsafe {
TIMING_BUFFER = TimingBuffer::make_640x400();
},
neotron_common_bios::video::Timing::T640x480 => unsafe {
TIMING_BUFFER = TimingBuffer::make_640x480();
},
neotron_common_bios::video::Timing::T800x600 => {
panic!("Can't do 800x600");
}
}
self.num_text_cols = self.current_video_mode.text_width().unwrap_or(0) as usize;
self.num_text_rows = self.current_video_mode.text_height().unwrap_or(0) as usize;
}
/// Draw a line of pixels into the relevant pixel buffer (either
/// [`PIXEL_DATA_BUFFER_ODD`] or [`PIXEL_DATA_BUFFER_EVEN`]).
///
/// The `current_line_num` goes from `0..NUM_LINES`.
#[link_section = ".data"]
pub fn draw_next_line(&mut self, current_line_num: u16) {
// Pick a buffer to render into based on the line number we are drawing.
// It's safe to write to this buffer because it's the the other one that
// is currently being DMA'd out to the Pixel SM.
let scan_line_buffer = if (current_line_num & 1) == 0 {
&PIXEL_DATA_BUFFER_EVEN
} else {
&PIXEL_DATA_BUFFER_ODD
};
match self.current_video_mode.format() {
neotron_common_bios::video::Format::Text8x16 => {
// Text with 8x16 glyphs
self.draw_next_line_text::<16>(&font16::FONT, scan_line_buffer, current_line_num)
}
neotron_common_bios::video::Format::Text8x8 => {
// Text with 8x8 glyphs
self.draw_next_line_text::<8>(&font8::FONT, scan_line_buffer, current_line_num)
}
neotron_common_bios::video::Format::Chunky1 => {
// Bitmap with 1 bit per pixel
self.draw_next_line_chunky1(scan_line_buffer, current_line_num);
}
neotron_common_bios::video::Format::Chunky2 => {
// Bitmap with 2 bit per pixel
self.draw_next_line_chunky2(scan_line_buffer, current_line_num);
}
neotron_common_bios::video::Format::Chunky4 => {
// Bitmap with 4 bits per pixel
self.draw_next_line_chunky4(scan_line_buffer, current_line_num);
}
_ => {
// Draw nothing
}
};
}
/// Draw a line of 1-bpp bitmap as pixels.
///
/// Writes into the relevant pixel buffer (either [`PIXEL_DATA_BUFFER_ODD`]
/// or [`PIXEL_DATA_BUFFER_EVEN`]) assuming the framebuffer is a bitmap.
///
/// The `current_line_num` goes from `0..NUM_LINES`.
#[link_section = ".data"]
pub fn draw_next_line_chunky1(&mut self, scan_line_buffer: &LineBuffer, current_line_num: u16) {
let base_ptr = self.current_video_ptr as *const u8;
let line_len_bytes = self.current_video_mode.line_size_bytes();
let is_double = self.current_video_mode.is_horiz_2x();
let offset = usize::from(current_line_num) * line_len_bytes;
let line_start = unsafe { base_ptr.add(offset) };
// Get a pointer into our scan-line buffer
let mut scan_line_buffer_ptr = scan_line_buffer.pixel_ptr();
let black_pixel = RGBColour(VIDEO_PALETTE[0].load(Ordering::Relaxed));
let white_pixel = RGBColour(VIDEO_PALETTE[1].load(Ordering::Relaxed));
if is_double {
// double-width mode.
// sixteen RGB pixels (eight pairs) per byte
let white_pair = RGBPair::from_pixels(white_pixel, white_pixel);
let black_pair = RGBPair::from_pixels(black_pixel, black_pixel);
for col in 0..line_len_bytes {
let mono_pixels = unsafe { line_start.add(col).read() };
unsafe {
// 0bX-------
let pixel = (mono_pixels & 1 << 7) != 0;
scan_line_buffer_ptr.offset(0).write(if pixel {
white_pair
} else {
black_pair
});
// 0b-X------
let pixel = (mono_pixels & 1 << 6) != 0;
scan_line_buffer_ptr.offset(1).write(if pixel {
white_pair
} else {
black_pair
});
// 0b--X-----
let pixel = (mono_pixels & 1 << 5) != 0;
scan_line_buffer_ptr.offset(2).write(if pixel {
white_pair
} else {
black_pair
});
// 0b---X----
let pixel = (mono_pixels & 1 << 4) != 0;
scan_line_buffer_ptr.offset(3).write(if pixel {
white_pair
} else {
black_pair
});
// 0b----X---
let pixel = (mono_pixels & 1 << 3) != 0;
scan_line_buffer_ptr.offset(4).write(if pixel {
white_pair
} else {
black_pair
});
// 0b-----X--
let pixel = (mono_pixels & 1 << 2) != 0;
scan_line_buffer_ptr.offset(5).write(if pixel {
white_pair
} else {
black_pair
});
// 0b------X-
let pixel = (mono_pixels & 1 << 1) != 0;
scan_line_buffer_ptr.offset(6).write(if pixel {
white_pair
} else {
black_pair
});
// 0b-------X
let pixel = (mono_pixels & 1) != 0;
scan_line_buffer_ptr.offset(7).write(if pixel {
white_pair
} else {
black_pair
});
// move pointer along 16 pixels / 8 pairs
scan_line_buffer_ptr = scan_line_buffer_ptr.add(8);
}
}
} else {
// Non-double-width mode.
// eight RGB pixels (four pairs) per byte
let attr = Attr::new(
TextForegroundColour::White,
TextBackgroundColour::Black,
false,
);
for col in 0..line_len_bytes {
let mono_pixels = unsafe { line_start.add(col).read() };
unsafe {
// 0bXX------
let pair = TEXT_COLOUR_LOOKUP.lookup(attr, mono_pixels >> 6);
scan_line_buffer_ptr.write(pair);
// 0b--XX----
let pair = TEXT_COLOUR_LOOKUP.lookup(attr, mono_pixels >> 4);
scan_line_buffer_ptr.add(1).write(pair);
// 0b----XX--
let pair = TEXT_COLOUR_LOOKUP.lookup(attr, mono_pixels >> 2);
scan_line_buffer_ptr.add(2).write(pair);
// 0b------XX
let pair = TEXT_COLOUR_LOOKUP.lookup(attr, mono_pixels);
scan_line_buffer_ptr.add(3).write(pair);
scan_line_buffer_ptr = scan_line_buffer_ptr.add(4);
}
}
}
}
/// Draw a line of 2-bpp bitmap as pixels.
///
/// Writes into the relevant pixel buffer (either [`PIXEL_DATA_BUFFER_ODD`]
/// or [`PIXEL_DATA_BUFFER_EVEN`]) assuming the framebuffer is a bitmap.
///
/// The `current_line_num` goes from `0..NUM_LINES`.
#[link_section = ".data"]
pub fn draw_next_line_chunky2(&mut self, scan_line_buffer: &LineBuffer, current_line_num: u16) {
let is_double = self.current_video_mode.is_horiz_2x();
let base_ptr = self.current_video_ptr as *const u8;
let line_len_bytes = self.current_video_mode.line_size_bytes();
let offset = usize::from(current_line_num) * line_len_bytes;
let line_start = unsafe { base_ptr.add(offset) };
// Get a pointer into our scan-line buffer
let mut scan_line_buffer_ptr = scan_line_buffer.pixel_ptr();
let pixel_colours = [
RGBColour(VIDEO_PALETTE[0].load(Ordering::Relaxed)),
RGBColour(VIDEO_PALETTE[1].load(Ordering::Relaxed)),
RGBColour(VIDEO_PALETTE[2].load(Ordering::Relaxed)),
RGBColour(VIDEO_PALETTE[3].load(Ordering::Relaxed)),
];
if is_double {
let pixel_pairs = [
RGBPair::from_pixels(pixel_colours[0], pixel_colours[0]),
RGBPair::from_pixels(pixel_colours[1], pixel_colours[1]),
RGBPair::from_pixels(pixel_colours[2], pixel_colours[2]),
RGBPair::from_pixels(pixel_colours[3], pixel_colours[3]),
];
let pixel_pairs_ptr = pixel_pairs.as_ptr();
// Double-width mode.
// eight RGB pixels (four pairs) per byte
for col in 0..line_len_bytes {
let chunky_pixels = unsafe { line_start.add(col).read() } as usize;
unsafe {
let pair = pixel_pairs_ptr.add((chunky_pixels >> 6) & 0x03);
scan_line_buffer_ptr.write(*pair);
let pair = pixel_pairs_ptr.add((chunky_pixels >> 4) & 0x03);
scan_line_buffer_ptr.add(1).write(*pair);
let pair = pixel_pairs_ptr.add((chunky_pixels >> 2) & 0x03);
scan_line_buffer_ptr.add(2).write(*pair);
let pair = pixel_pairs_ptr.add(chunky_pixels & 0x03);
scan_line_buffer_ptr.add(3).write(*pair);
scan_line_buffer_ptr = scan_line_buffer_ptr.add(4);
}
}
} else {
let pixel_pairs = [
RGBPair::from_pixels(pixel_colours[0], pixel_colours[0]),
RGBPair::from_pixels(pixel_colours[0], pixel_colours[1]),
RGBPair::from_pixels(pixel_colours[0], pixel_colours[2]),
RGBPair::from_pixels(pixel_colours[0], pixel_colours[3]),
RGBPair::from_pixels(pixel_colours[1], pixel_colours[0]),
RGBPair::from_pixels(pixel_colours[1], pixel_colours[1]),
RGBPair::from_pixels(pixel_colours[1], pixel_colours[2]),
RGBPair::from_pixels(pixel_colours[1], pixel_colours[3]),
RGBPair::from_pixels(pixel_colours[2], pixel_colours[0]),
RGBPair::from_pixels(pixel_colours[2], pixel_colours[1]),
RGBPair::from_pixels(pixel_colours[2], pixel_colours[2]),
RGBPair::from_pixels(pixel_colours[2], pixel_colours[3]),
RGBPair::from_pixels(pixel_colours[3], pixel_colours[0]),
RGBPair::from_pixels(pixel_colours[3], pixel_colours[1]),
RGBPair::from_pixels(pixel_colours[3], pixel_colours[2]),
RGBPair::from_pixels(pixel_colours[3], pixel_colours[3]),
];
let pixel_pairs_ptr = pixel_pairs.as_ptr();
// Non-double-width mode.
// four RGB pixels (two pairs) per byte
for col in 0..line_len_bytes {
let chunky_pixels = unsafe { line_start.add(col).read() } as usize;
unsafe {
let pair = pixel_pairs_ptr.add(chunky_pixels >> 4);
scan_line_buffer_ptr.write(*pair);
scan_line_buffer_ptr = scan_line_buffer_ptr.add(1);
let pair = pixel_pairs_ptr.add(chunky_pixels & 0x0F);
scan_line_buffer_ptr.write(*pair);
scan_line_buffer_ptr = scan_line_buffer_ptr.add(1);
}
}
}
}
/// Draw a line of 4-bpp bitmap as pixels.
///
/// Writes into the relevant pixel buffer (either [`PIXEL_DATA_BUFFER_ODD`]
/// or [`PIXEL_DATA_BUFFER_EVEN`]) assuming the framebuffer is a bitmap.
///
/// The `current_line_num` goes from `0..NUM_LINES`.
#[link_section = ".data"]
pub fn draw_next_line_chunky4(&mut self, scan_line_buffer: &LineBuffer, current_line_num: u16) {
let is_double = self.current_video_mode.is_horiz_2x();
let base_ptr = self.current_video_ptr as *const u8;
let line_len_bytes = self.current_video_mode.line_size_bytes();
let line_start_offset_bytes = usize::from(current_line_num) * line_len_bytes;
let line_start_bytes = unsafe { base_ptr.add(line_start_offset_bytes) };
// Get a pointer into our scan-line buffer
let mut scan_line_buffer_ptr = scan_line_buffer.pixel_ptr();
if is_double {
let palette_ptr = VIDEO_PALETTE.as_ptr() as *const RGBColour;
// Double-width mode.
// four RGB pixels (two pairs) per byte
for col in 0..line_len_bytes {
unsafe {
let chunky_pixels = line_start_bytes.add(col).read() as usize;
let left = palette_ptr.add((chunky_pixels >> 4) & 0x0F).read();
let right = palette_ptr.add(chunky_pixels & 0x0F).read();
scan_line_buffer_ptr.write(RGBPair::from_pixels(left, left));
scan_line_buffer_ptr
.add(1)
.write(RGBPair::from_pixels(right, right));
scan_line_buffer_ptr = scan_line_buffer_ptr.add(2);
}
}
} else {
for col in 0..line_len_bytes {
unsafe {
let pixel_pair = line_start_bytes.add(col).read();
let pair = CHUNKY4_COLOUR_LOOKUP.lookup(pixel_pair);
scan_line_buffer_ptr.write(pair);
scan_line_buffer_ptr = scan_line_buffer_ptr.add(1);
}
}
}
}
/// Draw a line text as pixels.
///
/// Writes into the relevant pixel buffer (either [`PIXEL_DATA_BUFFER_ODD`]
/// or [`PIXEL_DATA_BUFFER_EVEN`]) using the 8x16 font.
///
/// The `current_line_num` goes from `0..NUM_LINES`.
#[link_section = ".data"]
pub fn draw_next_line_text<const GLYPH_HEIGHT: usize>(
&mut self,
font: &Font,
scan_line_buffer: &LineBuffer,
current_line_num: u16,
) {
// Convert our position in scan-lines to a text row, and a line within each glyph on that row
let text_row = current_line_num as usize / GLYPH_HEIGHT;
let font_row = current_line_num as usize % GLYPH_HEIGHT;
if text_row >= self.num_text_rows {
return;
}
// Note (unsafe): We are using whatever memory we were given and we
// assume there is good data there and there is enough data there. To
// try and avoid Undefined Behaviour, we only access through a pointer
// and never make a reference to the data.
let fb_ptr = self.current_video_ptr as *const GlyphAttr;
let row_ptr = unsafe { fb_ptr.add(text_row * self.num_text_cols) };
// Every font look-up we are about to do for this row will
// involve offsetting by the row within each glyph. As this
// is the same for every glyph on this row, we calculate a
// new pointer once, in advance, and save ourselves an
// addition each time around the loop.
let font_ptr = unsafe { font.data.as_ptr().add(font_row) };
// Get a pointer into our scan-line buffer
let mut scan_line_buffer_ptr = scan_line_buffer.pixel_ptr();
// Convert from characters to coloured pixels, using the font as a look-up table.
for col in 0..self.num_text_cols {
unsafe {
// Note (unsafe): We use pointer arithmetic here because we
// can't afford a bounds-check on an array. This is safe
// because the font is `256 * width` bytes long and we can't
// index more than `255 * width` bytes into it.
let glyphattr = row_ptr.add(col).read();
let index = (glyphattr.glyph().0 as usize) * GLYPH_HEIGHT;
let attr = glyphattr.attr();
let mono_pixels = *font_ptr.add(index);
// 0bXX------
let pair = TEXT_COLOUR_LOOKUP.lookup(attr, mono_pixels >> 6);
scan_line_buffer_ptr.write(pair);
// 0b--XX----
let pair = TEXT_COLOUR_LOOKUP.lookup(attr, mono_pixels >> 4);
scan_line_buffer_ptr.add(1).write(pair);
// 0b----XX--
let pair = TEXT_COLOUR_LOOKUP.lookup(attr, mono_pixels >> 2);
scan_line_buffer_ptr.add(2).write(pair);
// 0b------XX
let pair = TEXT_COLOUR_LOOKUP.lookup(attr, mono_pixels);
scan_line_buffer_ptr.add(3).write(pair);
scan_line_buffer_ptr = scan_line_buffer_ptr.add(4);
}
}
}
}
impl Default for RenderEngine {
fn default() -> Self {
RenderEngine::new()
}
}
/// Describes one scan-line's worth of pixels, including the length word required by the Pixel FIFO.
#[repr(C, align(16))]
struct LineBuffer {
/// Must be one less than the number of pixel-pairs in `pixels`
length: u32,
/// Pixels to be displayed, grouped into pairs (to save FIFO space and reduce DMA bandwidth)
pixels: UnsafeCell<[RGBPair; MAX_NUM_PIXEL_PAIRS_PER_LINE]>,
}
impl LineBuffer {
/// Make a new LineBuffer
///
/// Use this for the even lines, so you get a checkerboard
const fn new_even() -> LineBuffer {
LineBuffer {
length: (MAX_NUM_PIXEL_PAIRS_PER_LINE as u32) - 1,
pixels: UnsafeCell::new(
[RGBPair::from_pixels(RGBColour::WHITE, RGBColour::BLACK);
MAX_NUM_PIXEL_PAIRS_PER_LINE],
),
}
}
/// Make a new LineBuffer
///
/// Use this for the odd lines, so you get a checkerboard
const fn new_odd() -> LineBuffer {
LineBuffer {
length: (MAX_NUM_PIXEL_PAIRS_PER_LINE as u32) - 1,
pixels: UnsafeCell::new(
[RGBPair::from_pixels(RGBColour::BLACK, RGBColour::WHITE);
MAX_NUM_PIXEL_PAIRS_PER_LINE],
),
}
}
/// Get a pointer to the entire linebuffer.
///
/// This produces a 32-bit address that the DMA engine understands.
fn as_ptr(&self) -> u32 {
self as *const _ as usize as u32
}
/// Get a pointer to the pixel data
fn pixel_ptr(&self) -> *mut RGBPair {
self.pixels.get() as *mut RGBPair
}
}
unsafe impl Sync for LineBuffer {}
/// The kind of IRQ we want to raise
#[derive(Debug, Copy, Clone)]
enum RaiseIrq {
None,
Irq0,
Irq1,
}
impl RaiseIrq {
const IRQ0_INSTR: u16 = pio::InstructionOperands::IRQ {
clear: false,
wait: false,
index: 0,
relative: false,
}
.encode();
const IRQ1_INSTR: u16 = pio::InstructionOperands::IRQ {
clear: false,
wait: false,
index: 1,
relative: false,
}
.encode();
const IRQ_NONE_INSTR: u16 = pio::InstructionOperands::MOV {
destination: pio::MovDestination::Y,
op: pio::MovOperation::None,
source: pio::MovSource::Y,
}
.encode();
/// Produces a PIO command that raises the appropriate IRQ
#[inline]
pub const fn into_command(self) -> u16 {
match self {
RaiseIrq::None => Self::IRQ_NONE_INSTR,
RaiseIrq::Irq0 => Self::IRQ0_INSTR,
RaiseIrq::Irq1 => Self::IRQ1_INSTR,
}
}
}
/// Holds the four scan-line timing FIFO words we need for one scan-line.
///
/// See `make_timing` for a function which can generate these words. We DMA
/// them into the timing FIFO, so they must sit on a 16-byte boundary.
#[repr(C, align(16))]
struct ScanlineTimingBuffer {
data: [u32; 4],
}
impl ScanlineTimingBuffer {
const CLOCKS_PER_PIXEL: u32 = 6;
/// Create a timing buffer for each scan-line in the V-Sync visible portion.
///
/// The timings are in the order (front-porch, sync, back-porch, visible) and are in pixel clocks.
#[inline]
const fn new_v_visible(
hsync: SyncPolarity,
vsync: SyncPolarity,
timings: (u32, u32, u32, u32),
) -> ScanlineTimingBuffer {
ScanlineTimingBuffer {
data: [
// Front porch (as per the spec)
Self::make_timing(
timings.0 * Self::CLOCKS_PER_PIXEL,
hsync.disabled(),
vsync.disabled(),
RaiseIrq::Irq1,
),
// Sync pulse (as per the spec)
Self::make_timing(
timings.1 * Self::CLOCKS_PER_PIXEL,
hsync.enabled(),
vsync.disabled(),
RaiseIrq::None,
),
// Back porch. Adjusted by a few clocks to account for interrupt +
// PIO SM start latency.
Self::make_timing(
(timings.2 * Self::CLOCKS_PER_PIXEL) - 5,
hsync.disabled(),
vsync.disabled(),
RaiseIrq::None,
),
// Visible portion. It also triggers the IRQ to start pixels
// moving. Adjusted to compensate for changes made to previous
// period to ensure scan-line remains at correct length.
Self::make_timing(
(timings.3 * Self::CLOCKS_PER_PIXEL) + 5,
hsync.disabled(),
vsync.disabled(),
RaiseIrq::Irq0,
),
],
}
}
/// Create a timing buffer for each scan-line in the V-Sync front-porch and back-porch
#[inline]
const fn new_v_porch(
hsync: SyncPolarity,
vsync: SyncPolarity,
timings: (u32, u32, u32, u32),
) -> ScanlineTimingBuffer {
ScanlineTimingBuffer {
data: [
// Front porch (as per the spec)
Self::make_timing(
timings.0 * Self::CLOCKS_PER_PIXEL,
hsync.disabled(),
vsync.disabled(),
RaiseIrq::Irq1,
),
// Sync pulse (as per the spec)
Self::make_timing(
timings.1 * Self::CLOCKS_PER_PIXEL,
hsync.enabled(),
vsync.disabled(),
RaiseIrq::None,
),
// Back porch.
Self::make_timing(
timings.2 * Self::CLOCKS_PER_PIXEL,
hsync.disabled(),
vsync.disabled(),
RaiseIrq::None,
),
// Visible portion.
Self::make_timing(
timings.3 * Self::CLOCKS_PER_PIXEL,
hsync.disabled(),
vsync.disabled(),
RaiseIrq::None,
),
],
}
}
/// Create a timing buffer for each scan-line in the V-Sync pulse
#[inline]
const fn new_v_pulse(
hsync: SyncPolarity,
vsync: SyncPolarity,
timings: (u32, u32, u32, u32),
) -> ScanlineTimingBuffer {
ScanlineTimingBuffer {
data: [
// Front porch (as per the spec)
Self::make_timing(
timings.0 * Self::CLOCKS_PER_PIXEL,
hsync.disabled(),
vsync.enabled(),
RaiseIrq::Irq1,
),
// Sync pulse (as per the spec)
Self::make_timing(
timings.1 * Self::CLOCKS_PER_PIXEL,
hsync.enabled(),
vsync.enabled(),
RaiseIrq::None,
),
// Back porch.
Self::make_timing(
timings.2 * Self::CLOCKS_PER_PIXEL,
hsync.disabled(),
vsync.enabled(),
RaiseIrq::None,
),
// Visible portion.
Self::make_timing(
timings.3 * Self::CLOCKS_PER_PIXEL,
hsync.disabled(),
vsync.enabled(),
RaiseIrq::None,
),
],
}
}
/// Generate a 32-bit value we can send to the Timing FIFO.
///
/// * `period` - The length of this portion of the scan-line, in system clock ticks
/// * `hsync` - true if the H-Sync pin should be high during this period, else false
/// * `vsync` - true if the H-Sync pin should be high during this period, else false
/// * `raise_irq` - true the timing statemachine should raise an IRQ at the start of this period
///
/// Returns a 32-bit value you can post to the Timing FIFO.
#[inline]
const fn make_timing(period: u32, hsync: bool, vsync: bool, raise_irq: RaiseIrq) -> u32 {
let command = raise_irq.into_command() as u32;
let mut value: u32 = 0;
if hsync {
value |= 1 << 0;
}
if vsync {
value |= 1 << 1;
}
value |= (period - 6) << 2;
value | command << 16
}
}
/// Holds the different kinds of scan-line timing buffers we need for various
/// portions of the screen.
struct TimingBuffer {
/// We use this when there are visible pixels on screen
visible_line: ScanlineTimingBuffer,
/// We use this during the v-sync front-porch and v-sync back-porch
vblank_porch_buffer: ScanlineTimingBuffer,
/// We use this during the v-sync sync pulse
vblank_sync_buffer: ScanlineTimingBuffer,
/// The last visible scan-line,
visible_lines_ends_at: u16,
/// The last scan-line of the front porch
front_porch_end_at: u16,
/// The last scan-line of the sync pulse
sync_pulse_ends_at: u16,
/// The last scan-line of the back-porch (and the frame)
back_porch_ends_at: u16,
}
impl TimingBuffer {
/// Make a timing buffer suitable for 640 x 400 @ 70 Hz
const fn make_640x400() -> TimingBuffer {
TimingBuffer {
visible_line: ScanlineTimingBuffer::new_v_visible(
SyncPolarity::Negative,
SyncPolarity::Positive,
(16, 96, 48, 640),
),
vblank_porch_buffer: ScanlineTimingBuffer::new_v_porch(
SyncPolarity::Negative,
SyncPolarity::Positive,
(16, 96, 48, 640),
),
vblank_sync_buffer: ScanlineTimingBuffer::new_v_pulse(
SyncPolarity::Negative,
SyncPolarity::Positive,
(16, 96, 48, 640),
),
visible_lines_ends_at: 399,
front_porch_end_at: 399 + 12,
sync_pulse_ends_at: 399 + 12 + 2,
back_porch_ends_at: 399 + 12 + 2 + 35,
}
}
/// Make a timing buffer suitable for 640 x 480 @ 60 Hz
pub const fn make_640x480() -> TimingBuffer {
TimingBuffer {
visible_line: ScanlineTimingBuffer::new_v_visible(
SyncPolarity::Negative,
SyncPolarity::Negative,
(16, 96, 48, 640),
),
vblank_porch_buffer: ScanlineTimingBuffer::new_v_porch(
SyncPolarity::Negative,
SyncPolarity::Negative,
(16, 96, 48, 640),
),
vblank_sync_buffer: ScanlineTimingBuffer::new_v_pulse(
SyncPolarity::Negative,
SyncPolarity::Negative,
(16, 96, 48, 640),
),
visible_lines_ends_at: 479,
front_porch_end_at: 479 + 10,
sync_pulse_ends_at: 479 + 10 + 2,
back_porch_ends_at: 479 + 10 + 2 + 33,
}
}
}
/// See [`TEXT_COLOUR_LOOKUP`]
struct TextColourLookup {
entries: [AtomicU32; 512],
}
impl TextColourLookup {
const FOREGROUND: [TextForegroundColour; 16] = [
TextForegroundColour::Black,
TextForegroundColour::Blue,
TextForegroundColour::Green,
TextForegroundColour::Cyan,
TextForegroundColour::Red,
TextForegroundColour::Magenta,
TextForegroundColour::Brown,
TextForegroundColour::LightGray,
TextForegroundColour::DarkGray,
TextForegroundColour::LightBlue,
TextForegroundColour::LightGreen,
TextForegroundColour::LightCyan,
TextForegroundColour::LightRed,
TextForegroundColour::Pink,
TextForegroundColour::Yellow,
TextForegroundColour::White,
];
const BACKGROUND: [TextBackgroundColour; 8] = [
TextBackgroundColour::Black,
TextBackgroundColour::Blue,
TextBackgroundColour::Green,
TextBackgroundColour::Cyan,
TextBackgroundColour::Red,
TextBackgroundColour::Magenta,
TextBackgroundColour::Brown,
TextBackgroundColour::LightGray,
];
const fn blank() -> TextColourLookup {
#[allow(clippy::declare_interior_mutable_const)]
const ZERO: AtomicU32 = AtomicU32::new(0);
TextColourLookup {
entries: [ZERO; 512],
}
}
fn init(&self, palette: &[AtomicU16]) {
for (fg, fg_colour) in Self::FOREGROUND.iter().zip(palette.iter()) {
for (bg, bg_colour) in Self::BACKGROUND.iter().zip(palette.iter()) {
let attr = Attr::new(*fg, *bg, false);
for pixels in 0..=3 {
let index: usize = (((attr.0 & 0x7F) as usize) << 2) | (pixels & 0x03) as usize;
let pair = RGBPair::from_pixels(
if pixels & 0x02 == 0x02 {
RGBColour(fg_colour.load(Ordering::Relaxed))
} else {
RGBColour(bg_colour.load(Ordering::Relaxed))
},
if pixels & 0x01 == 0x01 {
RGBColour(fg_colour.load(Ordering::Relaxed))
} else {
RGBColour(bg_colour.load(Ordering::Relaxed))
},
);
self.entries[index].store(pair.0, Ordering::Relaxed);
}
}
}
}
fn update_index(&self, updated_palette_entry: u8, palette: &[AtomicU16]) {
for (fg, (fg_colour_idx, fg_colour)) in
Self::FOREGROUND.iter().zip(palette.iter().enumerate())
{
for (bg, (bg_colour_idx, bg_colour)) in
Self::BACKGROUND.iter().zip(palette.iter().enumerate())
{
if fg_colour_idx != usize::from(updated_palette_entry)
&& bg_colour_idx != usize::from(updated_palette_entry)
{
// skip this one - it didn't change
continue;
}
let attr = Attr::new(*fg, *bg, false);
for pixels in 0..=3 {
let index: usize = (((attr.0 & 0x7F) as usize) << 2) | (pixels & 0x03) as usize;
let pair = RGBPair::from_pixels(
if pixels & 0x02 == 0x02 {
RGBColour(fg_colour.load(Ordering::Relaxed))
} else {
RGBColour(bg_colour.load(Ordering::Relaxed))
},
if pixels & 0x01 == 0x01 {
RGBColour(fg_colour.load(Ordering::Relaxed))
} else {
RGBColour(bg_colour.load(Ordering::Relaxed))
},
);
self.entries[index].store(pair.0, Ordering::Relaxed);
}
}
}
}
#[inline]
fn lookup(&self, attr: Attr, pixels: u8) -> RGBPair {
let index: usize = (((attr.0 & 0x7F) as usize) << 2) | (pixels & 0x03) as usize;
RGBPair(self.entries[index].load(Ordering::Relaxed))
}
}
/// Holds a screen full of characters and colour attributes.
///
/// It is 32-bit (4 byte) aligned.
#[repr(align(4))]
pub struct TextBuffer {
inner: UnsafeCell<[GlyphAttr; MAX_TEXT_COLS * MAX_TEXT_ROWS]>,
}
impl TextBuffer {
const fn new() -> TextBuffer {
TextBuffer {
inner: UnsafeCell::new([GlyphAttr(0); MAX_TEXT_COLS * MAX_TEXT_ROWS]),
}