mirror of
https://github.com/italicsjenga/agb.git
synced 2024-12-23 08:11:33 +11:00
Get saving working (#631)
- [ ] Changelog updated / no changelog update needed
This commit is contained in:
commit
b317602c6b
|
@ -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
|
@ -94,10 +94,9 @@ build-mgba-wasm:
|
|||
|
||||
build-combo-rom-site:
|
||||
just _build-rom "examples/combo" "AGBGAMES"
|
||||
gzip -9 -c examples/target/examples/combo.gba > website/agb/src/app/combo.gba.gz
|
||||
|
||||
build-site-app: build-mgba-wasm build-combo-rom-site
|
||||
mkdir -p website/agb/public
|
||||
gzip -9 -c examples/target/examples/combo.gba > website/agb/public/combo.gba.gz
|
||||
(cd website/agb && npm install --no-save --prefer-offline --no-audit)
|
||||
(cd website/agb && npm run build)
|
||||
|
||||
|
|
|
@ -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();
|
||||
setState(MgbaState.Initialised);
|
||||
});
|
||||
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