13 Commits

Author SHA1 Message Date
aa4cc58b42 expand doom memory for pimoroni 2025-10-31 17:59:48 -06:00
85e888193d Merge branch 'main' into doom 2025-10-31 17:51:18 -06:00
7fcc5291e6 fix build 2025-10-31 17:46:52 -06:00
9afec60033 set rp2350 as kernel default target 2025-10-31 17:46:02 -06:00
382e2e73ef fix rp2350 2025-10-31 17:41:36 -06:00
1d7ab3fb42 move fb to psram to save 200KB for user apps 2025-10-31 17:28:16 -06:00
beee2392ae Merge branch 'main' into doom 2025-10-31 14:15:53 -06:00
2226541813 fix release 2025-10-31 14:15:47 -06:00
46bfa89e18 doom compiles but is BIG 2025-10-31 13:39:16 -06:00
970d021a9a layout 2025-10-29 17:49:14 -06:00
05198c716d increase clock speed of display 2025-10-29 08:07:58 -06:00
ba426f5baa center gif 2025-10-28 19:06:32 -06:00
7bc6aeb998 forgot display lock 2025-10-28 17:44:31 -06:00
22 changed files with 717 additions and 210 deletions

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "user-apps/doom/doomgeneric"]
path = user-apps/doom/doomgeneric
url = https://github.com/ozkl/doomgeneric

209
Cargo.lock generated
View File

@@ -124,7 +124,7 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5deb64efa5bd81e31fcd1938615a6d98c82eafcbcd787162b6f63b91d6bac5b3" checksum = "5deb64efa5bd81e31fcd1938615a6d98c82eafcbcd787162b6f63b91d6bac5b3"
dependencies = [ dependencies = [
"rustc_version 0.2.3", "rustc_version",
] ]
[[package]] [[package]]
@@ -133,6 +133,26 @@ version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
[[package]]
name = "bindgen"
version = "0.71.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3"
dependencies = [
"bitflags 2.9.4",
"cexpr",
"clang-sys",
"itertools 0.10.5",
"log",
"prettyplease",
"proc-macro2",
"quote",
"regex",
"rustc-hash",
"shlex",
"syn 2.0.104",
]
[[package]] [[package]]
name = "bit-set" name = "bit-set"
version = "0.5.3" version = "0.5.3"
@@ -225,7 +245,7 @@ dependencies = [
"embedded-io", "embedded-io",
"embedded-io-async", "embedded-io-async",
"futures-intrusive", "futures-intrusive",
"heapless 0.8.0", "heapless",
"uuid", "uuid",
] ]
@@ -275,12 +295,42 @@ dependencies = [
"toml", "toml",
] ]
[[package]]
name = "cc"
version = "1.2.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "739eb0f94557554b3ca9a86d2d37bebd49c5e6d0c1d2bda35ba5bdac830befc2"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cexpr"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
dependencies = [
"nom",
]
[[package]] [[package]]
name = "cfg-if" name = "cfg-if"
version = "1.0.1" version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268" checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
[[package]]
name = "clang-sys"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
dependencies = [
"glob",
"libc",
"libloading",
]
[[package]] [[package]]
name = "clap" name = "clap"
version = "3.2.25" version = "3.2.25"
@@ -409,7 +459,7 @@ dependencies = [
"embedded-hal 1.0.0", "embedded-hal 1.0.0",
"embedded-io-async", "embedded-io-async",
"futures", "futures",
"heapless 0.8.0", "heapless",
"num_enum 0.5.11", "num_enum 0.5.11",
] ]
@@ -564,6 +614,16 @@ dependencies = [
"litrs", "litrs",
] ]
[[package]]
name = "doom"
version = "0.1.0"
dependencies = [
"abi",
"bindgen",
"cc",
"embedded-graphics",
]
[[package]] [[package]]
name = "either" name = "either"
version = "1.15.0" version = "1.15.0"
@@ -788,7 +848,7 @@ dependencies = [
"embedded-io-async", "embedded-io-async",
"futures-sink", "futures-sink",
"futures-util", "futures-util",
"heapless 0.8.0", "heapless",
] ]
[[package]] [[package]]
@@ -803,7 +863,7 @@ dependencies = [
"embedded-io-async", "embedded-io-async",
"futures-core", "futures-core",
"futures-sink", "futures-sink",
"heapless 0.8.0", "heapless",
] ]
[[package]] [[package]]
@@ -856,7 +916,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80e2ee86063bd028a420a5fb5898c18c87a8898026da1d4c852af2c443d0a454" checksum = "80e2ee86063bd028a420a5fb5898c18c87a8898026da1d4c852af2c443d0a454"
dependencies = [ dependencies = [
"embassy-executor-timer-queue", "embassy-executor-timer-queue",
"heapless 0.8.0", "heapless",
] ]
[[package]] [[package]]
@@ -870,7 +930,7 @@ dependencies = [
"embassy-sync 0.7.2", "embassy-sync 0.7.2",
"embassy-usb-driver 0.2.0", "embassy-usb-driver 0.2.0",
"embedded-io-async", "embedded-io-async",
"heapless 0.8.0", "heapless",
"ssmarshal", "ssmarshal",
"usbd-hid", "usbd-hid",
] ]
@@ -1032,7 +1092,7 @@ dependencies = [
"defmt 0.3.100", "defmt 0.3.100",
"embedded-hal 1.0.0", "embedded-hal 1.0.0",
"embedded-io", "embedded-io",
"heapless 0.8.0", "heapless",
] ]
[[package]] [[package]]
@@ -1107,6 +1167,12 @@ version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "find-msvc-tools"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52051878f80a721bb68ebfbc930e07b65ba72f2da88968ea5c06fd6ca3d3a127"
[[package]] [[package]]
name = "fixed" name = "fixed"
version = "1.29.0" version = "1.29.0"
@@ -1292,6 +1358,12 @@ dependencies = [
"tinygif", "tinygif",
] ]
[[package]]
name = "glob"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
[[package]] [[package]]
name = "goblin" name = "goblin"
version = "0.10.2" version = "0.10.2"
@@ -1312,15 +1384,6 @@ dependencies = [
"crunchy", "crunchy",
] ]
[[package]]
name = "hash32"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67"
dependencies = [
"byteorder",
]
[[package]] [[package]]
name = "hash32" name = "hash32"
version = "0.3.1" version = "0.3.1"
@@ -1351,26 +1414,13 @@ version = "0.15.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5971ac85611da7067dbfcabef3c70ebb5606018acd9e2a3903a0da507521e0d5" checksum = "5971ac85611da7067dbfcabef3c70ebb5606018acd9e2a3903a0da507521e0d5"
[[package]]
name = "heapless"
version = "0.7.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f"
dependencies = [
"atomic-polyfill",
"hash32 0.2.1",
"rustc_version 0.4.1",
"spin 0.9.8",
"stable_deref_trait",
]
[[package]] [[package]]
name = "heapless" name = "heapless"
version = "0.8.0" version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
dependencies = [ dependencies = [
"hash32 0.3.1", "hash32",
"serde", "serde",
"stable_deref_trait", "stable_deref_trait",
] ]
@@ -1524,14 +1574,14 @@ dependencies = [
"embedded-sdmmc", "embedded-sdmmc",
"embedded-text", "embedded-text",
"goblin", "goblin",
"heapless 0.8.0", "heapless",
"kolibri-embedded-gui", "kolibri-embedded-gui",
"num_enum 0.7.4", "num_enum 0.7.4",
"once_cell", "once_cell",
"panic-probe", "panic-probe",
"portable-atomic", "portable-atomic",
"rand", "rand",
"spin 0.10.0", "spin",
"st7365p-lcd", "st7365p-lcd",
"static_cell", "static_cell",
"strum", "strum",
@@ -1548,7 +1598,7 @@ dependencies = [
"embedded-graphics", "embedded-graphics",
"embedded-iconoir", "embedded-iconoir",
"foldhash", "foldhash",
"heapless 0.8.0", "heapless",
] ]
[[package]] [[package]]
@@ -1626,6 +1676,16 @@ version = "0.2.174"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776" checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"
[[package]]
name = "libloading"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
dependencies = [
"cfg-if",
"windows-link",
]
[[package]] [[package]]
name = "libredox" name = "libredox"
version = "0.1.4" version = "0.1.4"
@@ -1682,6 +1742,12 @@ version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3c8dda44ff03a2f238717214da50f65d5a53b45cd213a7370424ffdb6fae815" checksum = "c3c8dda44ff03a2f238717214da50f65d5a53b45cd213a7370424ffdb6fae815"
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]] [[package]]
name = "nb" name = "nb"
version = "0.1.3" version = "0.1.3"
@@ -1703,6 +1769,16 @@ version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]] [[package]]
name = "num-traits" name = "num-traits"
version = "0.2.19" version = "0.2.19"
@@ -1966,6 +2042,16 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
[[package]]
name = "prettyplease"
version = "0.2.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff24dfcda44452b9816fff4cd4227e1bb73ff5a2f1bc1105aa92fb8565ce44d2"
dependencies = [
"proc-macro2",
"syn 2.0.104",
]
[[package]] [[package]]
name = "proc-macro-error" name = "proc-macro-error"
version = "1.0.4" version = "1.0.4"
@@ -2158,22 +2244,19 @@ dependencies = [
"crc-any", "crc-any",
] ]
[[package]]
name = "rustc-hash"
version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
[[package]] [[package]]
name = "rustc_version" name = "rustc_version"
version = "0.2.3" version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"
dependencies = [ dependencies = [
"semver 0.9.0", "semver",
]
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver 1.0.27",
] ]
[[package]] [[package]]
@@ -2231,12 +2314,6 @@ dependencies = [
"semver-parser", "semver-parser",
] ]
[[package]]
name = "semver"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
[[package]] [[package]]
name = "semver-parser" name = "semver-parser"
version = "0.7.0" version = "0.7.0"
@@ -2302,6 +2379,12 @@ dependencies = [
"keccak", "keccak",
] ]
[[package]]
name = "shlex"
version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]] [[package]]
name = "siphasher" name = "siphasher"
version = "1.0.1" version = "1.0.1"
@@ -2342,15 +2425,6 @@ dependencies = [
"rand", "rand",
] ]
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
dependencies = [
"lock_api",
]
[[package]] [[package]]
name = "spin" name = "spin"
version = "0.10.0" version = "0.10.0"
@@ -2379,7 +2453,7 @@ dependencies = [
"embedded-graphics-core", "embedded-graphics-core",
"embedded-hal 1.0.0", "embedded-hal 1.0.0",
"embedded-hal-async", "embedded-hal-async",
"heapless 0.8.0", "heapless",
"nb 1.1.0", "nb 1.1.0",
] ]
@@ -2609,11 +2683,10 @@ dependencies = [
[[package]] [[package]]
name = "tinygif" name = "tinygif"
version = "0.0.4" version = "0.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "git+https://github.com/LegitCamper/tinygif#083c0efbdbeb21835de30425e234247340f6e370"
checksum = "09f1406b710986188de8d393c810213d4bbf940e327d90d52cff9930d007a248"
dependencies = [ dependencies = [
"embedded-graphics", "embedded-graphics",
"heapless 0.7.17", "heapless",
] ]
[[package]] [[package]]
@@ -2637,7 +2710,7 @@ dependencies = [
"embassy-time 0.4.0", "embassy-time 0.4.0",
"embedded-io", "embedded-io",
"futures", "futures",
"heapless 0.8.0", "heapless",
"rand_core 0.6.4", "rand_core 0.6.4",
"static_cell", "static_cell",
"trouble-host-macros", "trouble-host-macros",
@@ -2688,7 +2761,7 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "98816b1accafbb09085168b90f27e93d790b4bfa19d883466b5e53315b5f06a6" checksum = "98816b1accafbb09085168b90f27e93d790b4bfa19d883466b5e53315b5f06a6"
dependencies = [ dependencies = [
"heapless 0.8.0", "heapless",
"portable-atomic", "portable-atomic",
] ]
@@ -2880,6 +2953,12 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.59.0" version = "0.59.0"

View File

@@ -8,6 +8,7 @@ members = [
"user-apps/snake", "user-apps/snake",
"user-apps/gallery", "user-apps/gallery",
"user-apps/gif", "user-apps/gif",
"user-apps/doom",
] ]
[profile.release] [profile.release]

View File

@@ -46,7 +46,6 @@ pub fn get_key() -> KeyEvent {
pub mod display { pub mod display {
use abi_sys::CPixel; use abi_sys::CPixel;
// use alloc::{vec, vec::Vec};
use embedded_graphics::{ use embedded_graphics::{
Pixel, Pixel,
geometry::{Dimensions, Point}, geometry::{Dimensions, Point},
@@ -54,7 +53,6 @@ pub mod display {
prelude::{DrawTarget, Size}, prelude::{DrawTarget, Size},
primitives::Rectangle, primitives::Rectangle,
}; };
// use once_cell::unsync::Lazy;
pub const SCREEN_WIDTH: usize = 320; pub const SCREEN_WIDTH: usize = 320;
pub const SCREEN_HEIGHT: usize = 320; pub const SCREEN_HEIGHT: usize = 320;

View File

@@ -46,7 +46,7 @@ pub struct CLayout {
#[cfg(feature = "alloc")] #[cfg(feature = "alloc")]
impl Into<Layout> for CLayout { impl Into<Layout> for CLayout {
fn into(self) -> Layout { fn into(self) -> Layout {
Layout::from_size_align(self.size, self.alignment).unwrap() unsafe { Layout::from_size_align_unchecked(self.size, self.alignment) }
} }
} }

View File

@@ -17,3 +17,4 @@ userapps: cbindgen
just userapp snake just userapp snake
just userapp gallery just userapp gallery
just userapp gif just userapp gif
just userapp doom

View File

@@ -11,7 +11,7 @@ doctest = false
bench = false bench = false
[features] [features]
default = ["rp235x", "defmt", "pimoroni2w"] default = ["rp235x", "defmt"]
pimoroni2w = ["rp235x"] pimoroni2w = ["rp235x"]
rp2040 = ["embassy-rp/rp2040"] rp2040 = ["embassy-rp/rp2040"]
rp235x = ["embassy-rp/rp235xb"] rp235x = ["embassy-rp/rp235xb"]

View File

@@ -3,7 +3,7 @@ use abi_sys::{
PrintAbi, ReadFile, RngRequest, SleepMsAbi, keyboard::*, PrintAbi, ReadFile, RngRequest, SleepMsAbi, keyboard::*,
}; };
use alloc::{string::ToString, vec::Vec}; use alloc::{string::ToString, vec::Vec};
use core::{alloc::GlobalAlloc, ops::DerefMut, sync::atomic::Ordering}; use core::{alloc::GlobalAlloc, sync::atomic::Ordering};
use embassy_rp::clocks::{RoscRng, clk_sys_freq}; use embassy_rp::clocks::{RoscRng, clk_sys_freq};
use embassy_time::Instant; use embassy_time::Instant;
use embedded_graphics::draw_target::DrawTarget; use embedded_graphics::draw_target::DrawTarget;
@@ -11,7 +11,8 @@ use embedded_sdmmc::{DirEntry, LfnBuffer};
use heapless::spsc::Queue; use heapless::spsc::Queue;
use crate::{ use crate::{
display::{FRAMEBUFFER, FRAMEBUFFER2, WRITE_FRAMEBUFFER2}, display::FRAMEBUFFER,
framebuffer::FB_PAUSED,
storage::{Dir, File, SDCARD}, storage::{Dir, File, SDCARD},
}; };
@@ -79,19 +80,9 @@ pub extern "C" fn draw_iter(cpixels: *const CPixel, len: usize) {
let iter = cpixels.iter().copied().map(|c: CPixel| c.into()); let iter = cpixels.iter().copied().map(|c: CPixel| c.into());
let fb = if cfg!(feature = "pimoroni2w") { FB_PAUSED.store(true, Ordering::Release);
if WRITE_FRAMEBUFFER2.load(Ordering::Acquire) { unsafe { FRAMEBUFFER.as_mut().unwrap().draw_iter(iter).unwrap() }
unsafe { FRAMEBUFFER2.deref_mut() } FB_PAUSED.store(false, Ordering::Release);
} else {
unsafe { &mut FRAMEBUFFER }
}
} else {
unsafe { &mut FRAMEBUFFER }
};
fb.draw_iter(iter).unwrap();
WRITE_FRAMEBUFFER2.fetch_not(Ordering::AcqRel);
} }
pub static mut KEY_CACHE: Queue<KeyEvent, 32> = Queue::new(); pub static mut KEY_CACHE: Queue<KeyEvent, 32> = Queue::new();

View File

@@ -1,9 +1,5 @@
use crate::framebuffer::{self, AtomicFrameBuffer}; use crate::framebuffer::{self, AtomicFrameBuffer, FB_PAUSED};
use alloc::vec; use core::alloc::{GlobalAlloc, Layout};
use core::alloc::GlobalAlloc;
use core::alloc::Layout;
#[cfg(feature = "pimoroni2w")]
use core::sync::atomic::AtomicBool;
use core::sync::atomic::Ordering; use core::sync::atomic::Ordering;
use embassy_rp::{ use embassy_rp::{
Peri, Peri,
@@ -12,8 +8,11 @@ use embassy_rp::{
spi::{Async, Spi}, spi::{Async, Spi},
}; };
use embassy_time::{Delay, Timer}; use embassy_time::{Delay, Timer};
use embedded_graphics::{
pixelcolor::Rgb565,
prelude::{DrawTarget, RgbColor},
};
use embedded_hal_bus::spi::ExclusiveDevice; use embedded_hal_bus::spi::ExclusiveDevice;
use once_cell::unsync::Lazy;
use st7365p_lcd::ST7365P; use st7365p_lcd::ST7365P;
type DISPLAY = ST7365P< type DISPLAY = ST7365P<
@@ -26,33 +25,24 @@ type DISPLAY = ST7365P<
pub const SCREEN_WIDTH: usize = 320; pub const SCREEN_WIDTH: usize = 320;
pub const SCREEN_HEIGHT: usize = 320; pub const SCREEN_HEIGHT: usize = 320;
// used to switch which fb is being used for read/write pub static mut FRAMEBUFFER: Option<AtomicFrameBuffer> = None;
#[cfg(feature = "pimoroni2w")]
pub static WRITE_FRAMEBUFFER2: AtomicBool = AtomicBool::new(false);
// the default screen buffer - the only one on boards without extra ram or psram fn init_fb() {
pub static mut FRAMEBUFFER: Lazy<AtomicFrameBuffer> = Lazy::new(|| { unsafe {
static mut BUF: [u16; framebuffer::SIZE] = [0; framebuffer::SIZE]; FRAMEBUFFER = Some(if cfg!(not(feature = "pimoroni2w")) {
AtomicFrameBuffer::new(unsafe { &mut BUF }) static mut BUF: [u16; framebuffer::SIZE] = [0; framebuffer::SIZE];
}); AtomicFrameBuffer::new(&mut BUF)
} else {
let slab = crate::heap::HEAP.alloc(Layout::array::<u16>(framebuffer::SIZE).unwrap())
as *mut u16;
let buf = core::slice::from_raw_parts_mut(slab, framebuffer::SIZE);
#[cfg(feature = "pimoroni2w")] let mut fb = AtomicFrameBuffer::new(buf);
pub static mut FRAMEBUFFER2: Lazy<AtomicFrameBuffer> = Lazy::new(|| { fb.clear(Rgb565::BLACK).unwrap();
use embedded_graphics::{ fb
pixelcolor::Rgb565, });
prelude::{DrawTarget, RgbColor}, }
}; }
let buf = unsafe {
let slab =
crate::heap::HEAP.alloc(Layout::array::<u16>(framebuffer::SIZE).unwrap()) as *mut u16;
core::slice::from_raw_parts_mut(slab, framebuffer::SIZE)
};
let mut fb = AtomicFrameBuffer::new(buf);
fb.set_all_tiles(false);
fb.clear(Rgb565::BLACK).unwrap();
fb
});
pub async fn init_display( pub async fn init_display(
spi: Spi<'static, SPI1, Async>, spi: Spi<'static, SPI1, Async>,
@@ -60,6 +50,8 @@ pub async fn init_display(
data: Peri<'static, PIN_14>, data: Peri<'static, PIN_14>,
reset: Peri<'static, PIN_15>, reset: Peri<'static, PIN_15>,
) -> DISPLAY { ) -> DISPLAY {
init_fb();
let spi_device = ExclusiveDevice::new(spi, Output::new(cs, Level::Low), Delay).unwrap(); let spi_device = ExclusiveDevice::new(spi, Output::new(cs, Level::Low), Delay).unwrap();
let mut display = ST7365P::new( let mut display = ST7365P::new(
spi_device, spi_device,
@@ -71,7 +63,14 @@ pub async fn init_display(
); );
display.init().await.unwrap(); display.init().await.unwrap();
display.set_custom_orientation(0x40).await.unwrap(); display.set_custom_orientation(0x40).await.unwrap();
unsafe { FRAMEBUFFER.draw(&mut display).await.unwrap() } unsafe {
FRAMEBUFFER
.as_mut()
.unwrap()
.draw(&mut display)
.await
.unwrap()
}
display.set_on().await.unwrap(); display.set_on().await.unwrap();
display display
@@ -80,18 +79,18 @@ pub async fn init_display(
#[embassy_executor::task] #[embassy_executor::task]
pub async fn display_handler(mut display: DISPLAY) { pub async fn display_handler(mut display: DISPLAY) {
loop { loop {
let fb = if cfg!(feature = "pimoroni2w") { if !FB_PAUSED.load(Ordering::Acquire) {
if WRITE_FRAMEBUFFER2.load(Ordering::Acquire) { unsafe {
unsafe { &mut FRAMEBUFFER } FRAMEBUFFER
} else { .as_mut()
unsafe { &mut FRAMEBUFFER2 } .unwrap()
} .safe_draw(&mut display)
} else { .await
unsafe { &mut FRAMEBUFFER } .unwrap()
}; };
fb.safe_draw(&mut display).await.unwrap(); }
// small yield to allow other tasks to run // small yield to allow other tasks to run
Timer::after_nanos(100).await; Timer::after_nanos(500).await;
} }
} }

View File

@@ -23,29 +23,23 @@ type MetaTileVec = heapless::Vec<Rectangle, { TILE_COUNT / MAX_META_TILES }>;
pub const SIZE: usize = SCREEN_HEIGHT * SCREEN_WIDTH; pub const SIZE: usize = SCREEN_HEIGHT * SCREEN_WIDTH;
pub static FB_PAUSED: AtomicBool = AtomicBool::new(false);
static mut DIRTY_TILES: LazyLock<heapless::Vec<AtomicBool, TILE_COUNT>> = LazyLock::new(|| {
let mut tiles = heapless::Vec::new();
for _ in 0..TILE_COUNT {
tiles.push(AtomicBool::new(true)).unwrap();
}
tiles
});
#[allow(dead_code)] #[allow(dead_code)]
pub struct AtomicFrameBuffer<'a> { pub struct AtomicFrameBuffer<'a>(&'a mut [u16]);
fb: &'a mut [u16],
dirty_tiles: heapless::Vec<AtomicBool, TILE_COUNT>,
}
impl<'a> AtomicFrameBuffer<'a> { impl<'a> AtomicFrameBuffer<'a> {
pub fn new(buffer: &'a mut [u16]) -> Self { pub fn new(buffer: &'a mut [u16]) -> Self {
assert!(buffer.len() == SIZE); assert!(buffer.len() == SIZE);
let mut dirty_tiles = heapless::Vec::new(); Self(buffer)
for _ in 0..TILE_COUNT {
dirty_tiles.push(AtomicBool::new(true)).unwrap()
}
Self {
fb: buffer,
dirty_tiles,
}
}
pub fn set_all_tiles(&mut self, set: bool) {
for t in self.dirty_tiles.iter_mut() {
t.store(set, Ordering::Release);
}
} }
fn mark_tiles_dirty(&mut self, rect: Rectangle) { fn mark_tiles_dirty(&mut self, rect: Rectangle) {
@@ -58,7 +52,7 @@ impl<'a> AtomicFrameBuffer<'a> {
for ty in start_ty..=end_ty { for ty in start_ty..=end_ty {
for tx in start_tx..=end_tx { for tx in start_tx..=end_tx {
let tile_idx = ty * tiles_x + tx; let tile_idx = ty * tiles_x + tx;
self.dirty_tiles[tile_idx].store(true, Ordering::Release); unsafe { DIRTY_TILES.get_mut()[tile_idx].store(true, Ordering::Release) };
} }
} }
} }
@@ -84,7 +78,7 @@ impl<'a> AtomicFrameBuffer<'a> {
for y in sy..=ey { for y in sy..=ey {
for x in sx..=ex { for x in sx..=ex {
if let Some(color) = color_iter.next() { if let Some(color) = color_iter.next() {
self.fb[(y as usize * SCREEN_WIDTH) + x as usize] = color; self.0[(y as usize * SCREEN_WIDTH) + x as usize] = color;
} else { } else {
return Err(()); // Not enough data return Err(()); // Not enough data
} }
@@ -107,7 +101,7 @@ impl<'a> AtomicFrameBuffer<'a> {
let mut tx = 0; let mut tx = 0;
while tx < tiles_x { while tx < tiles_x {
let idx = ty * tiles_x + tx; let idx = ty * tiles_x + tx;
if !self.dirty_tiles[idx].load(Ordering::Acquire) { if !unsafe { DIRTY_TILES.get()[idx].load(Ordering::Acquire) } {
tx += 1; tx += 1;
continue; continue;
} }
@@ -119,7 +113,7 @@ impl<'a> AtomicFrameBuffer<'a> {
// Grow horizontally, but keep under MAX_TILES_PER_METATILE // Grow horizontally, but keep under MAX_TILES_PER_METATILE
while tx + width_tiles < tiles_x while tx + width_tiles < tiles_x
&& unsafe { && unsafe {
self.dirty_tiles[ty * tiles_x + tx + width_tiles].load(Ordering::Acquire) DIRTY_TILES.get()[ty * tiles_x + tx + width_tiles].load(Ordering::Acquire)
} }
&& (width_tiles + height_tiles) <= MAX_META_TILES && (width_tiles + height_tiles) <= MAX_META_TILES
{ {
@@ -130,7 +124,8 @@ impl<'a> AtomicFrameBuffer<'a> {
for x_off in 0..width_tiles { for x_off in 0..width_tiles {
unsafe { unsafe {
self.dirty_tiles[ty * tiles_x + tx + x_off].store(false, Ordering::Release); DIRTY_TILES.get()[ty * tiles_x + tx + x_off]
.store(false, Ordering::Release);
}; };
} }
@@ -170,12 +165,12 @@ impl<'a> AtomicFrameBuffer<'a> {
0, 0,
self.size().width as u16 - 1, self.size().width as u16 - 1,
self.size().height as u16 - 1, self.size().height as u16 - 1,
&self.fb[..], &self.0[..],
) )
.await?; .await?;
unsafe { unsafe {
for tile in self.dirty_tiles.iter() { for tile in DIRTY_TILES.get_mut().iter() {
tile.store(false, Ordering::Release); tile.store(false, Ordering::Release);
} }
}; };
@@ -196,10 +191,11 @@ impl<'a> AtomicFrameBuffer<'a> {
let tiles_x = SCREEN_WIDTH / TILE_SIZE; let tiles_x = SCREEN_WIDTH / TILE_SIZE;
let _tiles_y = SCREEN_HEIGHT / TILE_SIZE; let _tiles_y = SCREEN_HEIGHT / TILE_SIZE;
let tiles = unsafe { DIRTY_TILES.get_mut() };
let mut pixel_buffer: heapless::Vec<u16, { TILE_SIZE * TILE_SIZE }> = heapless::Vec::new(); let mut pixel_buffer: heapless::Vec<u16, { TILE_SIZE * TILE_SIZE }> = heapless::Vec::new();
for tile_idx in 0..TILE_COUNT { for tile_idx in 0..TILE_COUNT {
if self.dirty_tiles[tile_idx].swap(false, Ordering::AcqRel) { if tiles[tile_idx].swap(false, Ordering::AcqRel) {
let tx = tile_idx % tiles_x; let tx = tile_idx % tiles_x;
let ty = tile_idx / tiles_x; let ty = tile_idx / tiles_x;
@@ -214,9 +210,7 @@ impl<'a> AtomicFrameBuffer<'a> {
for y in y_start..y_end { for y in y_start..y_end {
let start = y * SCREEN_WIDTH + x_start; let start = y * SCREEN_WIDTH + x_start;
let end = y * SCREEN_WIDTH + x_end; let end = y * SCREEN_WIDTH + x_end;
pixel_buffer pixel_buffer.extend_from_slice(&self.0[start..end]).unwrap();
.extend_from_slice(&self.fb[start..end])
.unwrap();
} }
display display
@@ -246,7 +240,7 @@ impl<'a> AtomicFrameBuffer<'a> {
RST: OutputPin, RST: OutputPin,
DELAY: DelayNs, DELAY: DelayNs,
{ {
if unsafe { self.dirty_tiles.iter().any(|p| p.load(Ordering::Acquire)) } { if unsafe { DIRTY_TILES.get().iter().any(|p| p.load(Ordering::Acquire)) } {
let tiles_x = (SCREEN_WIDTH + TILE_SIZE - 1) / TILE_SIZE; let tiles_x = (SCREEN_WIDTH + TILE_SIZE - 1) / TILE_SIZE;
let tiles_y = (SCREEN_HEIGHT + TILE_SIZE - 1) / TILE_SIZE; let tiles_y = (SCREEN_HEIGHT + TILE_SIZE - 1) / TILE_SIZE;
@@ -270,9 +264,7 @@ impl<'a> AtomicFrameBuffer<'a> {
let end = start + rect_width; let end = start + rect_width;
// Safe: we guarantee buffer will not exceed MAX_META_TILE_PIXELS // Safe: we guarantee buffer will not exceed MAX_META_TILE_PIXELS
pixel_buffer pixel_buffer.extend_from_slice(&self.0[start..end]).unwrap();
.extend_from_slice(&self.fb[start..end])
.unwrap();
} }
display display
@@ -294,7 +286,7 @@ impl<'a> AtomicFrameBuffer<'a> {
for ty in start_ty..=end_ty { for ty in start_ty..=end_ty {
for tx in start_tx..=end_tx { for tx in start_tx..=end_tx {
let tile_idx = ty * tiles_x + tx; let tile_idx = ty * tiles_x + tx;
self.dirty_tiles[tile_idx].store(false, Ordering::Release); unsafe { DIRTY_TILES.get_mut()[tile_idx].store(false, Ordering::Release) };
} }
} }
} }
@@ -323,8 +315,8 @@ impl<'a> DrawTarget for AtomicFrameBuffer<'a> {
if (x as usize) < SCREEN_WIDTH && (y as usize) < SCREEN_HEIGHT { if (x as usize) < SCREEN_WIDTH && (y as usize) < SCREEN_HEIGHT {
let idx = (y as usize) * SCREEN_WIDTH + (x as usize); let idx = (y as usize) * SCREEN_WIDTH + (x as usize);
let raw_color = RawU16::from(color).into_inner(); let raw_color = RawU16::from(color).into_inner();
if self.fb[idx] != raw_color { if self.0[idx] != raw_color {
self.fb[idx] = raw_color; self.0[idx] = raw_color;
changed = true; changed = true;
} }
@@ -373,8 +365,8 @@ impl<'a> DrawTarget for AtomicFrameBuffer<'a> {
if let Some(color) = colors.next() { if let Some(color) = colors.next() {
let idx = (p.y as usize * SCREEN_WIDTH) + (p.x as usize); let idx = (p.y as usize * SCREEN_WIDTH) + (p.x as usize);
let raw_color = RawU16::from(color).into_inner(); let raw_color = RawU16::from(color).into_inner();
if self.fb[idx] != raw_color { if self.0[idx] != raw_color {
self.fb[idx] = raw_color; self.0[idx] = raw_color;
changed = true; changed = true;
} }
} else { } else {
@@ -412,7 +404,7 @@ impl<'a> DrawTarget for AtomicFrameBuffer<'a> {
.take((self.size().width * self.size().height) as usize), .take((self.size().width * self.size().height) as usize),
)?; )?;
for tile in self.dirty_tiles.iter() { for tile in unsafe { DIRTY_TILES.get_mut() }.iter() {
tile.store(true, Ordering::Release); tile.store(true, Ordering::Release);
} }

View File

@@ -80,7 +80,10 @@ static mut CORE1_STACK: Stack<16384> = Stack::new();
static EXECUTOR0: StaticCell<Executor> = StaticCell::new(); static EXECUTOR0: StaticCell<Executor> = StaticCell::new();
static EXECUTOR1: StaticCell<Executor> = StaticCell::new(); static EXECUTOR1: StaticCell<Executor> = StaticCell::new();
#[cfg(not(feature = "pimoroni2w"))]
static mut ARENA: [u8; 250 * 1024] = [0; 250 * 1024]; static mut ARENA: [u8; 250 * 1024] = [0; 250 * 1024];
#[cfg(feature = "pimoroni2w")]
static mut ARENA: [u8; 400 * 1024] = [0; 400 * 1024];
#[global_allocator] #[global_allocator]
static ALLOCATOR: Talck<spin::Mutex<()>, ClaimOnOom> = static ALLOCATOR: Talck<spin::Mutex<()>, ClaimOnOom> =
@@ -90,11 +93,12 @@ static ALLOCATOR: Talck<spin::Mutex<()>, ClaimOnOom> =
#[embassy_executor::task] #[embassy_executor::task]
async fn watchdog_task(mut watchdog: Watchdog) { async fn watchdog_task(mut watchdog: Watchdog) {
if let Some(reason) = watchdog.reset_reason() { if let Some(reason) = watchdog.reset_reason() {
let reason = match reason { let _reason = match reason {
ResetReason::Forced => "forced", ResetReason::Forced => "forced",
ResetReason::TimedOut => "timed out", ResetReason::TimedOut => "timed out",
}; };
defmt::error!("Watchdog reset reason: {}", reason); #[cfg(feature = "debug")]
defmt::error!("Watchdog reset reason: {}", _reason);
} }
watchdog.start(Duration::from_secs(3)); watchdog.start(Duration::from_secs(3));
@@ -194,7 +198,7 @@ async fn userland_task() {
{ {
ENABLE_UI.store(true, Ordering::Release); ENABLE_UI.store(true, Ordering::Release);
UI_CHANGE.signal(()); UI_CHANGE.signal(());
unsafe { FRAMEBUFFER.clear(Rgb565::BLACK).unwrap() }; unsafe { FRAMEBUFFER.as_mut().unwrap().clear(Rgb565::BLACK).unwrap() };
let mut selections = SELECTIONS.lock().await; let mut selections = SELECTIONS.lock().await;
selections.set_changed(true); selections.set_changed(true);
@@ -246,7 +250,7 @@ async fn setup_mcu(mcu: Mcu) {
async fn setup_display(display: Display, spawner: Spawner) { async fn setup_display(display: Display, spawner: Spawner) {
let mut config = spi::Config::default(); let mut config = spi::Config::default();
config.frequency = 16_000_000; config.frequency = 64_000_000;
let spi = Spi::new( let spi = Spi::new(
display.spi, display.spi,
display.clk, display.clk,
@@ -279,20 +283,18 @@ async fn setup_psram(psram: Psram) {
#[cfg(feature = "pimoroni2w")] #[cfg(feature = "pimoroni2w")]
async fn setup_qmi_psram() { async fn setup_qmi_psram() {
let mut tries = 5;
Timer::after_millis(250).await; Timer::after_millis(250).await;
while tries > 1 { let psram_qmi_size = init_psram_qmi(&embassy_rp::pac::QMI, &embassy_rp::pac::XIP_CTRL);
let psram_qmi_size = init_psram_qmi(&embassy_rp::pac::QMI, &embassy_rp::pac::XIP_CTRL); #[cfg(feature = "debug")]
defmt::info!("size: {}", psram_qmi_size); defmt::info!("size: {}", psram_qmi_size);
Timer::after_millis(100).await; Timer::after_millis(100).await;
if psram_qmi_size > 0 {
init_qmi_psram_heap(psram_qmi_size); if psram_qmi_size > 0 {
return; init_qmi_psram_heap(psram_qmi_size);
} return;
defmt::info!("failed to init qmi psram... trying again"); } else {
tries -= 1; panic!("qmi psram not initialized");
} }
panic!("qmi psram not initialized");
} }
async fn setup_sd(sd: Sd) { async fn setup_sd(sd: Sd) {
@@ -324,11 +326,12 @@ async fn kernel_task(
.spawn(watchdog_task(Watchdog::new(watchdog))) .spawn(watchdog_task(Watchdog::new(watchdog)))
.unwrap(); .unwrap();
setup_mcu(mcu).await;
// setup_psram(psram).await; // setup_psram(psram).await;
#[cfg(feature = "pimoroni2w")] #[cfg(feature = "pimoroni2w")]
setup_qmi_psram().await; setup_qmi_psram().await;
setup_mcu(mcu).await;
setup_display(display, spawner).await; setup_display(display, spawner).await;
setup_sd(sd).await; setup_sd(sd).await;

View File

@@ -526,6 +526,7 @@ pub fn init_psram_qmi(
let psram_size = detect_psram_qmi(qmi); let psram_size = detect_psram_qmi(qmi);
if psram_size == 0 { if psram_size == 0 {
#[cfg(feature = "debug")]
defmt::error!("qmi psram size 0"); defmt::error!("qmi psram size 0");
return 0; return 0;
} }

View File

@@ -1,13 +1,10 @@
use crate::{ use crate::{
BINARY_CH, BINARY_CH, display::FRAMEBUFFER, elf::load_binary, framebuffer::FB_PAUSED,
display::{FRAMEBUFFER, FRAMEBUFFER2, WRITE_FRAMEBUFFER2}, peripherals::keyboard, storage::FileName,
elf::load_binary,
peripherals::keyboard,
storage::FileName,
}; };
use abi_sys::keyboard::{KeyCode, KeyState}; use abi_sys::keyboard::{KeyCode, KeyState};
use alloc::{str::FromStr, string::String, vec::Vec}; use alloc::{str::FromStr, string::String, vec::Vec};
use core::{ops::DerefMut, sync::atomic::Ordering}; use core::sync::atomic::Ordering;
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex}; use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex};
use embedded_graphics::{ use embedded_graphics::{
Drawable, Drawable,
@@ -71,7 +68,7 @@ pub async fn clear_selection() {
if let Some(area) = sel.last_bounds { if let Some(area) = sel.last_bounds {
Rectangle::new(area.top_left, area.size) Rectangle::new(area.top_left, area.size)
.into_styled(PrimitiveStyle::with_fill(Rgb565::BLACK)) .into_styled(PrimitiveStyle::with_fill(Rgb565::BLACK))
.draw(unsafe { &mut *FRAMEBUFFER }) .draw(unsafe { &mut *FRAMEBUFFER.as_mut().unwrap() })
.unwrap(); .unwrap();
} }
} }
@@ -81,20 +78,12 @@ async fn draw_selection() {
let file_names = &guard.selections.clone(); let file_names = &guard.selections.clone();
let text_style = MonoTextStyle::new(&FONT_10X20, Rgb565::WHITE); let text_style = MonoTextStyle::new(&FONT_10X20, Rgb565::WHITE);
let display_area = unsafe { FRAMEBUFFER.bounding_box() }; let display_area = unsafe { FRAMEBUFFER.as_mut().unwrap().bounding_box() };
const NO_BINS: &str = "No Programs found on SD Card. Ensure programs end with '.bin', and are located in the root directory"; const NO_BINS: &str = "No Programs found on SD Card. Ensure programs end with '.bin', and are located in the root directory";
let no_bins = String::from_str(NO_BINS).unwrap(); let no_bins = String::from_str(NO_BINS).unwrap();
let mut fb = if cfg!(feature = "pimoroni2w") { FB_PAUSED.store(true, Ordering::Release); // ensure all elements show up at once
if WRITE_FRAMEBUFFER2.load(Ordering::Acquire) {
unsafe { FRAMEBUFFER2.deref_mut() }
} else {
unsafe { &mut FRAMEBUFFER }
}
} else {
unsafe { &mut FRAMEBUFFER }
};
if file_names.is_empty() { if file_names.is_empty() {
TextBox::new( TextBox::new(
@@ -105,7 +94,7 @@ async fn draw_selection() {
), ),
text_style, text_style,
) )
.draw(fb.deref_mut()) .draw(unsafe { &mut *FRAMEBUFFER.as_mut().unwrap() })
.unwrap(); .unwrap();
} else { } else {
let mut views: alloc::vec::Vec<Text<MonoTextStyle<Rgb565>>> = Vec::new(); let mut views: alloc::vec::Vec<Text<MonoTextStyle<Rgb565>>> = Vec::new();
@@ -130,17 +119,18 @@ async fn draw_selection() {
.bounding_box(); .bounding_box();
Rectangle::new(selected_bounds.top_left, selected_bounds.size) Rectangle::new(selected_bounds.top_left, selected_bounds.size)
.into_styled(PrimitiveStyle::with_stroke(Rgb565::WHITE, 1)) .into_styled(PrimitiveStyle::with_stroke(Rgb565::WHITE, 1))
.draw(fb.deref_mut()) .draw(unsafe { &mut *FRAMEBUFFER.as_mut().unwrap() })
.unwrap(); .unwrap();
guard.last_bounds = Some(layout.bounds()); guard.last_bounds = Some(layout.bounds());
layout.draw(fb.deref_mut()).unwrap(); layout
.draw(unsafe { &mut *FRAMEBUFFER.as_mut().unwrap() })
.unwrap();
} }
guard.changed = false; guard.changed = false;
FB_PAUSED.store(false, Ordering::Release); // ensure all elements show up at once
WRITE_FRAMEBUFFER2.fetch_not(Ordering::AcqRel);
} }
#[derive(Clone)] #[derive(Clone)]

12
user-apps/doom/Cargo.toml Normal file
View File

@@ -0,0 +1,12 @@
[package]
name = "doom"
version = "0.1.0"
edition = "2024"
[dependencies]
abi = { path = "../../abi" }
embedded-graphics = "0.8.1"
[build-dependencies]
bindgen = "0.71.0"
cc = "1.0"

126
user-apps/doom/build.rs Normal file
View File

@@ -0,0 +1,126 @@
//! This build script copies the `memory.x` file from the crate root into
//! a directory where the linker can always find it at build time.
//! For many projects this is optional, as the linker always searches the
//! project root directory -- wherever `Cargo.toml` is. However, if you
//! are using a workspace or have a more complicated build setup, this
//! build script becomes required. Additionally, by requesting that
//! Cargo re-run the build script whenever `memory.x` is changed,
//! updating `memory.x` ensures a rebuild of the application with the
//! new memory settings.
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
fn main() {
build_newlib();
build_doom();
// Put `memory.x` in our output directory and ensure it's
// on the linker search path.
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
File::create(out.join("memory.x"))
.unwrap()
.write_all(include_bytes!("memory.x"))
.unwrap();
println!("cargo:rustc-link-search={}", out.display());
println!("cargo:rerun-if-changed=memory.x");
println!("cargo:rustc-link-arg-bins=-Tmemory.x");
}
// TODO: use target to change newlib build - only workds for rp2350 right now
fn build_newlib() {
let out_dir = std::env::var("OUT_DIR").unwrap();
let picolibc_dir = format!("{}/picolibc", out_dir);
if !Path::new(&picolibc_dir).exists() {
let status = Command::new("git")
.args(&[
"clone",
"https://github.com/picolibc/picolibc",
&picolibc_dir,
])
.status()
.expect("Failed to clone picolibc");
assert!(status.success());
}
let build_dir = format!("{}/build", picolibc_dir);
std::fs::create_dir_all(&build_dir).unwrap();
let status = Command::new(&format!("{picolibc_dir}/scripts/do-configure"))
.current_dir(&build_dir)
.args(&[
"thumbv8m_main_fp-none-eabi",
"--buildtype=minsize",
"-Dtests=true",
"-Dtinystdio=false",
"-Dsingle-thread=true",
"-Db_pie=true",
"-Ddefault_library=static",
"-Dtinystdio=false",
"-Dmultilib=false",
".",
])
.status()
.expect("Failed to run Meson configure");
assert!(status.success());
let status = Command::new("ninja")
.current_dir(&build_dir)
.status()
.expect("Failed to run Ninja build");
assert!(status.success());
println!("cargo:rustc-link-search={}/newlib", build_dir);
println!("cargo:rustc-link-lib=c");
println!("cargo:rustc-link-lib=m");
}
fn build_doom() {
let ref dg_src_dir = std::path::PathBuf::from("doomgeneric/doomgeneric");
let mut dg_c_paths = vec![];
let mut dg_h_paths = vec![];
// Find most c and h files
for entry in std::fs::read_dir(dg_src_dir).unwrap() {
let entry = entry.unwrap();
if let Some(filename) = entry.file_name().to_str() {
if filename.starts_with("doomgeneric")
|| filename.contains("_allegro")
|| filename.contains("_sdl")
|| filename.contains("net_")
|| filename == "i_main.c"
{
continue;
}
if filename.ends_with(".h") {
dg_h_paths.push(dg_src_dir.join(filename));
} else if filename.ends_with(".c") {
dg_c_paths.push(dg_src_dir.join(filename));
}
}
}
dg_c_paths
.iter()
.chain(dg_h_paths.iter())
.for_each(|path| println!("cargo:rerun-if-changed={}", path.to_str().unwrap()));
cc::Build::new()
.compiler("arm-none-eabi-gcc")
.flag("-w") // silence warnings
.flag("-Os") // optimize for size
.flag("-ffunction-sections")
.flag("-fdata-sections")
.define("CMAP256", None)
.define("DOOMGENERIC_RESX", Some("320"))
.define("DOOMGENERIC_RESY", Some("200"))
.flag_if_supported("-std=gnu99")
.define("_POSIX_C_SOURCE", Some("200809L"))
.files(dg_c_paths)
.compile("doomgeneric");
}

31
user-apps/doom/memory.x Normal file
View File

@@ -0,0 +1,31 @@
MEMORY
{
RAM : ORIGIN = 0x0, LENGTH = 400K
}
SECTIONS
{
.text : ALIGN(4)
{
*(.text .text.*);
*(.rodata .rodata.*);
} > RAM
.data : ALIGN(4)
{
*(.data .data.*);
} > RAM
.bss : ALIGN(4)
{
*(.bss .bss.*);
*(COMMON);
} > RAM
.syscall_table (NOLOAD) : ALIGN(4)
{
__user_reloc_start = .;
KEEP(*(.user_reloc*));
__user_reloc_end = .;
} > RAM
}

112
user-apps/doom/src/doom.rs Normal file
View File

@@ -0,0 +1,112 @@
use abi::{
abi_sys::{get_ms, sleep},
display::Display,
};
use core::ffi::{c_int, c_uchar};
use embedded_graphics::{
Drawable, Pixel,
draw_target::DrawTarget,
pixelcolor::Rgb565,
prelude::{Point, RgbColor},
};
#[unsafe(no_mangle)]
#[allow(non_snake_case)]
static mut DG_ScreenBuffer: *const u8 = core::ptr::null();
#[repr(C)]
#[derive(Clone, Copy, Debug)]
pub struct RGBA {
pub b: u8,
pub g: u8,
pub r: u8,
pub a: u8,
}
unsafe extern "C" {
fn D_DoomMain();
fn doomgeneric_Tick();
fn M_FindResponseFile();
pub static colors: [RGBA; 256];
}
pub fn tick() {
unsafe { doomgeneric_Tick() };
}
pub struct ScreenBuffer<const RESX: usize, const RESY: usize, const SIZE: usize>(pub [u8; SIZE]);
impl<const RESX: usize, const RESY: usize, const SIZE: usize> ScreenBuffer<RESX, RESY, SIZE> {
#[allow(dead_code)]
const NA: () = assert!(SIZE == RESX * RESY);
pub const fn new() -> Self {
Self([0_u8; SIZE])
}
}
#[unsafe(no_mangle)]
extern "C" fn DG_SetWindowTitle() {}
pub fn create<const RESX: usize, const RESY: usize, const SIZE: usize>(
screenbuffer: &ScreenBuffer<RESX, RESY, SIZE>,
) {
unsafe {
M_FindResponseFile();
DG_ScreenBuffer = screenbuffer.0.as_ptr();
D_DoomMain();
}
}
const X: usize = 320;
const Y: usize = 200;
const SIZE: usize = X * Y;
pub static mut DISPLAY: Option<Display> = None;
pub static mut SCREEN_BUFFER: ScreenBuffer<X, Y, SIZE> = ScreenBuffer::new();
#[unsafe(no_mangle)]
extern "C" fn DG_DrawFrame() {
let palette565: [Rgb565; 256] = unsafe {
colors.map(|c| {
Rgb565::new(
((c.r as u16 * 31) / 255) as u8, // red 5 bits
((c.g as u16 * 63) / 255) as u8, // green 6 bits
((c.b as u16 * 31) / 255) as u8, // blue 5 bits
)
})
};
let buf = unsafe { &SCREEN_BUFFER.0 };
let display = unsafe { DISPLAY.as_mut().unwrap() };
display.clear(Rgb565::BLACK).unwrap();
for y in 0..Y {
for x in 0..X {
let idx = y * X + x;
let color = palette565[buf[idx] as usize];
Pixel(Point::new(x as i32, y as i32), color)
.draw(display)
.unwrap();
}
}
}
#[unsafe(no_mangle)]
extern "C" fn DG_GetTicksMs() -> u32 {
get_ms() as u32
}
#[unsafe(no_mangle)]
extern "C" fn DG_GetKey(pressed: *mut c_int, key: *mut c_uchar) -> c_int {
0
}
#[unsafe(no_mangle)]
extern "C" fn DG_SleepMs(ms: u32) {
sleep(ms.into());
}

118
user-apps/doom/src/libc.rs Normal file
View File

@@ -0,0 +1,118 @@
use core::ffi::{c_char, c_int, c_uchar, c_void};
use core::ptr;
#[unsafe(no_mangle)]
pub static _ctype_: [c_uchar; 256] = [0u8; 256];
#[repr(C)]
pub struct Reent {
pub errno: c_int,
_reserved: [u8; 32],
}
#[unsafe(no_mangle)]
pub static mut _reent_data: Reent = Reent {
errno: 0,
_reserved: [0; 32],
};
#[unsafe(no_mangle)]
pub static mut _impure_ptr: *mut Reent = unsafe { &mut _reent_data as *mut Reent };
#[unsafe(no_mangle)]
pub extern "C" fn __errno() -> *mut c_int {
unsafe { &mut (*_impure_ptr).errno as *mut c_int }
}
#[unsafe(no_mangle)]
pub extern "C" fn exit(_status: i32) -> ! {
loop {}
}
#[unsafe(no_mangle)]
pub extern "C" fn close(_file: i32) -> i32 {
-1
}
#[repr(C)]
pub struct Stat {
st_mode: u32,
}
#[unsafe(no_mangle)]
pub extern "C" fn fstat(_file: i32, st: *mut Stat) -> i32 {
unsafe {
if !st.is_null() {
(*st).st_mode = 0x2000; // S_IFCHR
}
}
0
}
#[unsafe(no_mangle)]
pub extern "C" fn isatty(_file: i32) -> i32 {
1
}
#[unsafe(no_mangle)]
pub extern "C" fn lseek(_file: i32, _ptr: i32, _dir: i32) -> i32 {
0
}
#[unsafe(no_mangle)]
pub extern "C" fn lseek64(_fd: c_int, _offset: i64, _whence: c_int) -> i64 {
0
}
#[unsafe(no_mangle)]
pub extern "C" fn open(_name: *const u8, _flags: i32, _mode: i32) -> i32 {
-1
}
#[unsafe(no_mangle)]
pub extern "C" fn read(_file: i32, _ptr: *mut u8, len: usize) -> i32 {
len as i32
}
#[unsafe(no_mangle)]
pub extern "C" fn write(_file: i32, _ptr: *const u8, len: usize) -> i32 {
len as i32
}
#[unsafe(no_mangle)]
pub extern "C" fn rename(_old: *const c_char, _new: *const c_char) -> c_int {
-1
}
#[unsafe(no_mangle)]
pub extern "C" fn kill(_pid: i32, _sig: i32) -> i32 {
-1
}
#[unsafe(no_mangle)]
pub extern "C" fn getpid() -> i32 {
1
}
#[unsafe(no_mangle)]
pub extern "C" fn link(_old: *const u8, _new: *const u8) -> i32 {
-1
}
#[unsafe(no_mangle)]
pub extern "C" fn unlink(_name: *const u8) -> i32 {
-1
}
#[unsafe(no_mangle)]
pub extern "C" fn mkdir(_path: *const u8, _mode: u32) -> i32 {
0
}
#[unsafe(no_mangle)]
pub extern "C" fn sbrk(incr: isize) -> *mut c_void {
core::ptr::null_mut()
}
#[unsafe(no_mangle)]
pub extern "C" fn fini() {}

View File

@@ -0,0 +1,43 @@
#![no_std]
#![no_main]
#![allow(static_mut_refs)]
#![feature(c_variadic)]
extern crate alloc;
use abi::{
display::Display,
fs::{file_len, read_file},
get_key, get_ms,
keyboard::{KeyCode, KeyState},
print, sleep,
};
use alloc::vec;
use core::panic::PanicInfo;
use embedded_graphics::{pixelcolor::Rgb565, prelude::Point};
mod doom;
use crate::doom::{DISPLAY, SCREEN_BUFFER, create, tick};
mod libc;
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
print!("user panic: {} @ {:?}", info.message(), info.location(),);
loop {}
}
#[unsafe(no_mangle)]
pub extern "Rust" fn _start() {
main()
}
pub fn main() {
print!("Starting Doom app");
let display = Display;
unsafe { DISPLAY = Some(display) };
unsafe { create(&SCREEN_BUFFER) };
loop {
tick();
}
}

View File

@@ -6,4 +6,4 @@ edition = "2024"
[dependencies] [dependencies]
abi = { path = "../../abi" } abi = { path = "../../abi" }
embedded-graphics = "0.8.1" embedded-graphics = "0.8.1"
tinygif = "0.0.4" tinygif = { git = "https://github.com/LegitCamper/tinygif" }

View File

@@ -11,7 +11,9 @@ use abi::{
}; };
use alloc::vec; use alloc::vec;
use core::panic::PanicInfo; use core::panic::PanicInfo;
use embedded_graphics::{image::ImageDrawable, pixelcolor::Rgb565}; use embedded_graphics::{
image::ImageDrawable, pixelcolor::Rgb565, prelude::Point, transform::Transform,
};
use tinygif::Gif; use tinygif::Gif;
#[panic_handler] #[panic_handler]
@@ -36,13 +38,17 @@ pub fn main() {
assert!(read == size); assert!(read == size);
let gif = Gif::<Rgb565>::from_slice(&buf).unwrap(); let gif = Gif::<Rgb565>::from_slice(&buf).unwrap();
let height = gif.height();
let mut frame_num = 0; let mut frame_num = 0;
loop { loop {
for frame in gif.frames() { for mut frame in gif.frames() {
let start = get_ms(); let start = get_ms();
frame.draw(&mut display).unwrap(); frame
.translate_mut(Point::new(0, (320 - height as i32) / 2))
.draw(&mut display)
.unwrap();
frame_num += 1; frame_num += 1;
if frame_num % 100 == 0 { if frame_num % 100 == 0 {