mirror of
https://github.com/italicsjenga/agb.git
synced 2024-12-23 08:11:33 +11:00
Merge remote-tracking branch 'upstream/master' into crash-page
This commit is contained in:
commit
528fe889fa
|
@ -28,6 +28,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||
- Fixnums are now implemented with `num_traits` trait definitions.
|
||||
- Rather than having our own sync with Statics, use the standard portable
|
||||
atomics crate. These are reexported for convenience.
|
||||
- `Mgba` no longer implements `Write`. You're unlikely to notice as
|
||||
`agb::println!` is unchanged.
|
||||
- Writes of long messages to mgba are split over multiple log messages if they
|
||||
overflow mgba's buffer. On a panic, only the final message will be Fatal with
|
||||
the preceding ones (if needed) being Info.
|
||||
|
||||
## [0.19.1] - 2024/03/06
|
||||
|
||||
|
|
|
@ -32,15 +32,13 @@ pub(crate) fn test_runner_measure_cycles() {
|
|||
NUMBER_OF_CYCLES.set(0);
|
||||
}
|
||||
|
||||
pub struct Mgba {
|
||||
bytes_written: usize,
|
||||
}
|
||||
pub struct Mgba {}
|
||||
|
||||
impl Mgba {
|
||||
#[must_use]
|
||||
pub fn new() -> Option<Self> {
|
||||
if is_running_in_mgba() {
|
||||
Some(Mgba { bytes_written: 0 })
|
||||
Some(Mgba {})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
|
@ -51,31 +49,33 @@ impl Mgba {
|
|||
output: core::fmt::Arguments,
|
||||
level: DebugLevel,
|
||||
) -> Result<(), core::fmt::Error> {
|
||||
write!(self, "{output}")?;
|
||||
let mut writer = MgbaWriter { bytes_written: 0 };
|
||||
write!(&mut writer, "{output}")?;
|
||||
self.set_level(level);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct MgbaWriter {
|
||||
bytes_written: usize,
|
||||
}
|
||||
|
||||
impl Mgba {
|
||||
pub fn set_level(&mut self, level: DebugLevel) {
|
||||
DEBUG_LEVEL.set(DEBUG_FLAG_CODE | level as u16);
|
||||
self.bytes_written = 0;
|
||||
}
|
||||
}
|
||||
|
||||
impl core::fmt::Write for Mgba {
|
||||
impl core::fmt::Write for MgbaWriter {
|
||||
fn write_str(&mut self, s: &str) -> Result<(), core::fmt::Error> {
|
||||
let mut str_iter = s.bytes();
|
||||
while self.bytes_written < 255 {
|
||||
match str_iter.next() {
|
||||
Some(byte) => {
|
||||
OUTPUT_STRING.set(self.bytes_written, byte);
|
||||
for b in s.bytes() {
|
||||
if self.bytes_written > 255 {
|
||||
DEBUG_LEVEL.set(DEBUG_FLAG_CODE | DebugLevel::Info as u16);
|
||||
self.bytes_written = 0;
|
||||
}
|
||||
OUTPUT_STRING.set(self.bytes_written, b);
|
||||
self.bytes_written += 1;
|
||||
}
|
||||
None => return Ok(()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
@ -54,12 +54,11 @@ impl<'bitmap, 'gba> BitmapTextRender<'bitmap, 'gba> {
|
|||
for y in 0..letter.height as usize {
|
||||
for x in 0..letter.width as usize {
|
||||
let rendered = letter.bit_absolute(x, y);
|
||||
if rendered {
|
||||
self.bitmap.draw_point(
|
||||
x as i32 + self.head_position.x,
|
||||
y as i32 + y_position_start,
|
||||
self.colour,
|
||||
);
|
||||
let x = x as i32 + self.head_position.x;
|
||||
let y = y as i32 + y_position_start;
|
||||
|
||||
if rendered && (0..=WIDTH).contains(&x) && (0..=HEIGHT).contains(&y) {
|
||||
self.bitmap.draw_point(x, y, self.colour);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,6 +3,7 @@ use agb::save::{Error, SaveManager};
|
|||
use agb::Gba;
|
||||
|
||||
static HIGH_SCORE: AtomicU32 = AtomicU32::new(0);
|
||||
static SAVE_OFFSET: usize = 1;
|
||||
|
||||
pub fn init_save(gba: &mut Gba) -> Result<(), Error> {
|
||||
gba.save.init_sram();
|
||||
|
@ -18,7 +19,7 @@ pub fn init_save(gba: &mut Gba) -> Result<(), Error> {
|
|||
save_high_score(&mut gba.save, 0)?;
|
||||
} else {
|
||||
let mut buffer = [0; 4];
|
||||
access.read(1, &mut buffer)?;
|
||||
access.read(SAVE_OFFSET, &mut buffer)?;
|
||||
let high_score = u32::from_le_bytes(buffer);
|
||||
|
||||
let score = if high_score > 100 { 0 } else { high_score };
|
||||
|
@ -35,8 +36,8 @@ pub fn load_high_score() -> u32 {
|
|||
|
||||
pub fn save_high_score(save: &mut SaveManager, score: u32) -> Result<(), Error> {
|
||||
save.access()?
|
||||
.prepare_write(1..5)?
|
||||
.write(1, &score.to_le_bytes())?;
|
||||
.prepare_write(SAVE_OFFSET..SAVE_OFFSET + 4)?
|
||||
.write(SAVE_OFFSET, &score.to_le_bytes())?;
|
||||
HIGH_SCORE.store(score, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
@ -121,8 +121,10 @@ pub fn entry(mut gba: agb::Gba) -> ! {
|
|||
oam: unmanaged,
|
||||
};
|
||||
|
||||
let mut current_level = 0;
|
||||
let mut maximum_level = save::load_max_level() as usize;
|
||||
let saved_level = save::load_max_level() as usize;
|
||||
|
||||
let mut current_level = saved_level;
|
||||
let mut maximum_level = saved_level;
|
||||
loop {
|
||||
if current_level >= level::Level::num_levels() {
|
||||
current_level = 0;
|
||||
|
|
|
@ -5,6 +5,7 @@ use agb::{
|
|||
};
|
||||
|
||||
static MAXIMUM_LEVEL: AtomicU32 = AtomicU32::new(0);
|
||||
static SAVE_OFFSET: usize = 0xFF;
|
||||
|
||||
pub fn init_save(gba: &mut Gba) -> Result<(), Error> {
|
||||
gba.save.init_sram();
|
||||
|
@ -20,7 +21,7 @@ pub fn init_save(gba: &mut Gba) -> Result<(), Error> {
|
|||
save_max_level(&mut gba.save, 0)?;
|
||||
} else {
|
||||
let mut buffer = [0; 4];
|
||||
access.read(1, &mut buffer)?;
|
||||
access.read(SAVE_OFFSET, &mut buffer)?;
|
||||
let max_level = u32::from_le_bytes(buffer);
|
||||
|
||||
if max_level > 100 {
|
||||
|
@ -39,8 +40,8 @@ pub fn load_max_level() -> u32 {
|
|||
|
||||
pub fn save_max_level(save: &mut SaveManager, level: u32) -> Result<(), Error> {
|
||||
save.access()?
|
||||
.prepare_write(1..5)?
|
||||
.write(1, &level.to_le_bytes())?;
|
||||
.prepare_write(SAVE_OFFSET..SAVE_OFFSET + 4)?
|
||||
.write(SAVE_OFFSET, &level.to_le_bytes())?;
|
||||
MAXIMUM_LEVEL.store(level, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
|
|
3
justfile
3
justfile
|
@ -103,8 +103,7 @@ build-mgba-wasm:
|
|||
|
||||
build-combo-rom-site:
|
||||
just _build-rom "examples/combo" "AGBGAMES"
|
||||
mkdir -p website/agb/public
|
||||
gzip -9 -c examples/target/examples/combo.gba > website/agb/public/combo.gba.gz
|
||||
gzip -9 -c examples/target/examples/combo.gba > website/agb/src/app/combo.gba.gz
|
||||
|
||||
|
||||
setup-app-build: build-mgba-wasm build-combo-rom-site build-website-backtrace
|
||||
|
|
|
@ -10,12 +10,11 @@ import { GbaKey, KeyBindings } from "./bindings";
|
|||
import { styled } from "styled-components";
|
||||
import { useFrameSkip } from "./useFrameSkip.hook";
|
||||
import { useController } from "./useController.hook";
|
||||
|
||||
type Module = any;
|
||||
import { useLocalStorage } from "./useLocalStorage.hook";
|
||||
|
||||
interface MgbaProps {
|
||||
gameUrl: string;
|
||||
volume?: Number;
|
||||
gameUrl: URL;
|
||||
volume?: number;
|
||||
controls: KeyBindings;
|
||||
paused: boolean;
|
||||
}
|
||||
|
@ -42,10 +41,12 @@ export interface MgbaHandle {
|
|||
buttonRelease: (key: GbaKey) => void;
|
||||
}
|
||||
|
||||
async function downloadGame(gameUrl: string): Promise<ArrayBuffer> {
|
||||
async function downloadGame(gameUrl: URL): Promise<ArrayBuffer> {
|
||||
const game = await fetch(gameUrl);
|
||||
|
||||
if (gameUrl.endsWith(".gz")) {
|
||||
const gameUrlString = gameUrl.toString();
|
||||
|
||||
if (gameUrlString.endsWith(".gz")) {
|
||||
const decompressedStream = (await game.blob())
|
||||
.stream()
|
||||
.pipeThrough(new DecompressionStream("gzip"));
|
||||
|
@ -55,28 +56,73 @@ async function downloadGame(gameUrl: string): Promise<ArrayBuffer> {
|
|||
}
|
||||
}
|
||||
|
||||
interface SaveGame {
|
||||
[gameName: string]: number[];
|
||||
}
|
||||
|
||||
export const Mgba = forwardRef<MgbaHandle, MgbaProps>(
|
||||
({ gameUrl, volume, controls, paused }, ref) => {
|
||||
const canvas = useRef(null);
|
||||
const mgbaModule = useRef<Module>({} as mGBAEmulator);
|
||||
const mgbaModule = useRef<mGBAEmulator>();
|
||||
|
||||
const [saveGame, setSaveGame] = useLocalStorage<SaveGame>(
|
||||
{},
|
||||
"agbrswebplayer/savegames"
|
||||
);
|
||||
const gameUrlString = gameUrl.toString();
|
||||
|
||||
const [state, setState] = useState(MgbaState.Uninitialised);
|
||||
const [gameLoaded, setGameLoaded] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
function beforeUnload() {
|
||||
const gameSplit = gameUrlString.split("/");
|
||||
const gameBaseName = gameSplit[gameSplit.length - 1];
|
||||
|
||||
const save = mgbaModule.current?.getSave();
|
||||
if (!save) return;
|
||||
|
||||
setSaveGame({
|
||||
...saveGame,
|
||||
[gameBaseName]: [...save],
|
||||
});
|
||||
}
|
||||
|
||||
window.addEventListener("beforeunload", beforeUnload);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("beforeunload", beforeUnload);
|
||||
};
|
||||
}, [gameUrlString, saveGame, setSaveGame]);
|
||||
|
||||
useEffect(() => {
|
||||
if (state !== MgbaState.Initialised) return;
|
||||
|
||||
const gameSplit = gameUrlString.split("/");
|
||||
const gameBaseName = gameSplit[gameSplit.length - 1];
|
||||
|
||||
const save = saveGame[gameBaseName];
|
||||
if (!save) return;
|
||||
|
||||
const savePath = `${MGBA_ROM_DIRECTORY}/${gameBaseName}.sav`;
|
||||
|
||||
mgbaModule.current?.FS.writeFile(savePath, new Uint8Array([0, 1, 2, 3]));
|
||||
}, [gameUrlString, saveGame, state]);
|
||||
|
||||
useEffect(() => {
|
||||
if (state !== MgbaState.Initialised) return;
|
||||
(async () => {
|
||||
const gameData = await downloadGame(gameUrl);
|
||||
const gameSplit = gameUrl.split("/");
|
||||
const gameSplit = gameUrlString.split("/");
|
||||
const gameBaseName = gameSplit[gameSplit.length - 1];
|
||||
|
||||
const gamePath = `${MGBA_ROM_DIRECTORY}/${gameBaseName}`;
|
||||
mgbaModule.current.FS.writeFile(gamePath, new Uint8Array(gameData));
|
||||
mgbaModule.current.loadGame(gamePath);
|
||||
mgbaModule.current.setVolume(0.1); // for some reason you have to do this or you get no sound
|
||||
mgbaModule.current?.FS.writeFile(gamePath, new Uint8Array(gameData));
|
||||
mgbaModule.current?.loadGame(gamePath);
|
||||
mgbaModule.current?.setVolume(0.1); // for some reason you have to do this or you get no sound
|
||||
setGameLoaded(true);
|
||||
})();
|
||||
}, [state, gameUrl]);
|
||||
}, [state, gameUrl, gameUrlString]);
|
||||
|
||||
// init mgba
|
||||
useEffect(() => {
|
||||
|
@ -85,22 +131,19 @@ export const Mgba = forwardRef<MgbaHandle, MgbaProps>(
|
|||
if (state !== MgbaState.Uninitialised) return;
|
||||
|
||||
setState(MgbaState.Initialising);
|
||||
mgbaModule.current = {
|
||||
canvas: canvas.current,
|
||||
};
|
||||
|
||||
mGBA(mgbaModule.current).then((module: Module) => {
|
||||
mgbaModule.current = module;
|
||||
module.FSInit();
|
||||
const mModule = await mGBA({ canvas: canvas.current });
|
||||
mgbaModule.current = mModule;
|
||||
await mModule.FSInit();
|
||||
await mModule.FSSync();
|
||||
setState(MgbaState.Initialised);
|
||||
});
|
||||
})();
|
||||
|
||||
if (state === MgbaState.Initialised)
|
||||
return () => {
|
||||
try {
|
||||
mgbaModule.current.quitGame();
|
||||
mgbaModule.current.quitMgba();
|
||||
mgbaModule.current?.quitGame();
|
||||
mgbaModule.current?.quitMgba();
|
||||
} catch {}
|
||||
};
|
||||
}, [state]);
|
||||
|
@ -119,30 +162,31 @@ export const Mgba = forwardRef<MgbaHandle, MgbaProps>(
|
|||
? "Return"
|
||||
: value.toLowerCase().replace("arrow", "").replace("key", "");
|
||||
|
||||
mgbaModule.current.bindKey(binding, key);
|
||||
mgbaModule.current?.bindKey(binding, key);
|
||||
}
|
||||
}, [controls, gameLoaded]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!gameLoaded) return;
|
||||
mgbaModule.current.setVolume(volume ?? 1.0);
|
||||
mgbaModule.current?.setVolume(volume ?? 1.0);
|
||||
}, [gameLoaded, volume]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!gameLoaded) return;
|
||||
|
||||
if (paused) {
|
||||
mgbaModule.current.pauseGame();
|
||||
mgbaModule.current?.pauseGame();
|
||||
} else {
|
||||
mgbaModule.current.resumeGame();
|
||||
mgbaModule.current?.resumeGame();
|
||||
}
|
||||
}, [gameLoaded, paused]);
|
||||
|
||||
useImperativeHandle(ref, () => {
|
||||
return {
|
||||
restart: () => mgbaModule.current.quickReload(),
|
||||
buttonPress: (key: GbaKey) => mgbaModule.current.buttonPress(key),
|
||||
buttonRelease: (key: GbaKey) => mgbaModule.current.buttonUnpress(key),
|
||||
restart: () => mgbaModule.current?.quickReload(),
|
||||
buttonPress: (key: GbaKey) => mgbaModule.current?.buttonPress(key),
|
||||
buttonRelease: (key: GbaKey) => mgbaModule.current?.buttonUnpress(key),
|
||||
saveGame: () => {},
|
||||
};
|
||||
});
|
||||
|
||||
|
|
|
@ -60,7 +60,7 @@ const StartButtonWrapper = styled.button`
|
|||
`;
|
||||
|
||||
interface MgbaWrapperProps {
|
||||
gameUrl: string;
|
||||
gameUrl: URL;
|
||||
isPlaying?: boolean;
|
||||
setIsPlaying?: (isPlaying: boolean) => void;
|
||||
}
|
||||
|
@ -103,7 +103,6 @@ export const MgbaWrapper = forwardRef<MgbaHandle, MgbaWrapperProps>(
|
|||
restart: () => mgbaRef.current?.restart(),
|
||||
buttonPress: (key: GbaKey) => mgbaRef.current?.buttonPress(key),
|
||||
buttonRelease: (key: GbaKey) => mgbaRef.current?.buttonRelease(key),
|
||||
hardReset: () => setMgbaId((id) => id + 1),
|
||||
}));
|
||||
|
||||
useAvoidItchIoScrolling();
|
||||
|
@ -123,7 +122,6 @@ export const MgbaWrapper = forwardRef<MgbaHandle, MgbaWrapperProps>(
|
|||
)}
|
||||
{isPlaying ? (
|
||||
<Mgba
|
||||
key={mgbaId}
|
||||
ref={mgbaRef}
|
||||
gameUrl={gameUrl}
|
||||
volume={volume}
|
||||
|
|
|
@ -2,7 +2,9 @@ import { MutableRefObject, useEffect } from "react";
|
|||
import { mGBAEmulator } from "./vendor/mgba";
|
||||
import { GbaKey } from "./bindings";
|
||||
|
||||
export function useController(mgbaModule: MutableRefObject<mGBAEmulator>) {
|
||||
export function useController(
|
||||
mgbaModule: MutableRefObject<mGBAEmulator | undefined>
|
||||
) {
|
||||
useEffect(() => {
|
||||
let stopped = false;
|
||||
|
||||
|
@ -64,13 +66,13 @@ export function useController(mgbaModule: MutableRefObject<mGBAEmulator>) {
|
|||
|
||||
for (let oldButton of previouslyPressedButtons) {
|
||||
if (!currentlyPressed.has(oldButton)) {
|
||||
mgbaModule.current.buttonUnpress(oldButton);
|
||||
mgbaModule.current?.buttonUnpress(oldButton);
|
||||
}
|
||||
}
|
||||
|
||||
for (let newButton of currentlyPressed) {
|
||||
if (!previouslyPressedButtons.has(newButton)) {
|
||||
mgbaModule.current.buttonPress(newButton);
|
||||
mgbaModule.current?.buttonPress(newButton);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,7 +1,9 @@
|
|||
import { MutableRefObject, useEffect } from "react";
|
||||
import { mGBAEmulator } from "./vendor/mgba";
|
||||
|
||||
export function useFrameSkip(mgbaModule: MutableRefObject<mGBAEmulator>) {
|
||||
export function useFrameSkip(
|
||||
mgbaModule: MutableRefObject<mGBAEmulator | undefined>
|
||||
) {
|
||||
useEffect(() => {
|
||||
let previous: number | undefined = undefined;
|
||||
let stopped = false;
|
||||
|
@ -23,12 +25,12 @@ export function useFrameSkip(mgbaModule: MutableRefObject<mGBAEmulator>) {
|
|||
if (totalTime >= 1 / 60) {
|
||||
totalTime -= 1 / 60;
|
||||
if (paused) {
|
||||
mgbaModule.current.resumeGame();
|
||||
mgbaModule.current?.resumeGame();
|
||||
paused = false;
|
||||
}
|
||||
} else {
|
||||
if (!paused) {
|
||||
mgbaModule.current.pauseGame();
|
||||
mgbaModule.current?.pauseGame();
|
||||
paused = true;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -78,6 +78,8 @@ function shouldStartPlaying(isTouchScreen: boolean | undefined) {
|
|||
return !isTouchScreen;
|
||||
}
|
||||
|
||||
const COMBO_GAME = new URL("combo.gba.gz", import.meta.url);
|
||||
|
||||
function MgbaWithControllerSides() {
|
||||
const mgba = useRef<MgbaHandle>(null);
|
||||
|
||||
|
@ -105,7 +107,7 @@ function MgbaWithControllerSides() {
|
|||
</GameSide>
|
||||
<GameDisplayWindow>
|
||||
<MgbaWrapper
|
||||
gameUrl="combo.gba.gz"
|
||||
gameUrl={COMBO_GAME}
|
||||
ref={mgba}
|
||||
isPlaying={playEmulator}
|
||||
setIsPlaying={setIsPlaying}
|
||||
|
|
Loading…
Reference in a new issue