mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
feat: add browser PICO-8 player
Add v2 browser playback for .p8 and .p8.png cartridges, backed by the FAKE-08 WebAssembly runtime, with canvas rendering, audio, fullscreen and keyboard, gamepad, mouse and touch input. Wires up platform detection, play actions, routing, localization, gallery navigation, play-session tracking and lifecycle cleanup. The runtime is fetched in the emulator stage of docker/Dockerfile, pinned by source commit and verified with sha256, so it is provisioned the same way as EmulatorJS, Ruffle and js-dos rather than committed to the repo. DISABLE_PICO8 gates the player, matching the existing DISABLE_EMULATOR_JS, DISABLE_RUFFLE_RS and DISABLE_JSDOS toggles. Based on #4383. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
committed by
Georges-Antoine Assi
parent
08f294d0fa
commit
f50eacfcbd
@@ -319,6 +319,7 @@ SYNC_SSH_KNOWN_HOSTS_PATH: Final[str] = _get_env(
|
||||
DISABLE_EMULATOR_JS: Final[bool] = safe_str_to_bool(_get_env("DISABLE_EMULATOR_JS"))
|
||||
DISABLE_RUFFLE_RS: Final[bool] = safe_str_to_bool(_get_env("DISABLE_RUFFLE_RS"))
|
||||
DISABLE_JSDOS: Final[bool] = safe_str_to_bool(_get_env("DISABLE_JSDOS"))
|
||||
DISABLE_PICO8: Final[bool] = safe_str_to_bool(_get_env("DISABLE_PICO8"))
|
||||
|
||||
# FRONTEND
|
||||
KIOSK_MODE: Final[bool] = safe_str_to_bool(_get_env("KIOSK_MODE"))
|
||||
|
||||
@@ -11,6 +11,7 @@ from config import (
|
||||
DISABLE_EMULATOR_JS,
|
||||
DISABLE_JSDOS,
|
||||
DISABLE_LOGS_VIEWER,
|
||||
DISABLE_PICO8,
|
||||
DISABLE_RUFFLE_RS,
|
||||
DISABLE_SETUP_WIZARD,
|
||||
DISABLE_USERPASS_LOGIN,
|
||||
@@ -157,6 +158,7 @@ async def heartbeat() -> HeartbeatResponse:
|
||||
"DISABLE_EMULATOR_JS": DISABLE_EMULATOR_JS,
|
||||
"DISABLE_RUFFLE_RS": DISABLE_RUFFLE_RS,
|
||||
"DISABLE_JSDOS": DISABLE_JSDOS,
|
||||
"DISABLE_PICO8": DISABLE_PICO8,
|
||||
},
|
||||
"FRONTEND": {
|
||||
"DISABLE_USERPASS_LOGIN": DISABLE_USERPASS_LOGIN,
|
||||
|
||||
@@ -36,6 +36,7 @@ class EmulationDict(TypedDict):
|
||||
DISABLE_EMULATOR_JS: bool
|
||||
DISABLE_RUFFLE_RS: bool
|
||||
DISABLE_JSDOS: bool
|
||||
DISABLE_PICO8: bool
|
||||
|
||||
|
||||
class FrontendDict(TypedDict):
|
||||
|
||||
@@ -48,6 +48,7 @@ def test_heartbeat(client):
|
||||
assert isinstance(emulation["DISABLE_EMULATOR_JS"], bool)
|
||||
assert isinstance(emulation["DISABLE_RUFFLE_RS"], bool)
|
||||
assert isinstance(emulation["DISABLE_JSDOS"], bool)
|
||||
assert isinstance(emulation["DISABLE_PICO8"], bool)
|
||||
|
||||
assert "FRONTEND" in heartbeat
|
||||
frontend = heartbeat["FRONTEND"]
|
||||
|
||||
@@ -133,7 +133,7 @@ RUN git clone --filter=blob:none https://github.com/rommforge/argosy-sigil.git &
|
||||
cp ./sigil/*.py ./sigil/_sigil.*.so /sigil-pkg/
|
||||
|
||||
|
||||
# FETCH EMULATORJS, RUFFLE AND JS-DOS
|
||||
# FETCH EMULATORJS, RUFFLE, JS-DOS AND FAKE-08
|
||||
FROM alpine:${ALPINE_VERSION}@sha256:${ALPINE_SHA256} AS emulator-stage
|
||||
|
||||
RUN apk add --no-cache \
|
||||
@@ -170,6 +170,20 @@ RUN wget "https://github.com/caiiiycuk/js-dos/releases/download/v${JSDOS_VERSION
|
||||
rm -rf /jsdos/dist/index.html /jsdos/dist/emulators/types && \
|
||||
find /jsdos/dist \( -name '*.map' -o -name '*.symbols' \) -exec rm -f {} +
|
||||
|
||||
ARG FAKE08_P3A_COMMIT=6519efd9dd1ca853e5c66f7ae9146ace0b7073dc
|
||||
ARG FAKE08_JS_SHA256=fd2cd4677956037e41a91dbd40fc1a9c4f5979355d55ce3f9312400e11da463e
|
||||
ARG FAKE08_WASM_SHA256=4339a77e0aa5aa6f4a5bce9fd8286053eedf7f23f2d853db7f4900f6fff4c93a
|
||||
ARG FAKE08_P3A_RAW=https://raw.githubusercontent.com/fabkury/p3a/${FAKE08_P3A_COMMIT}/webui/pico8
|
||||
|
||||
# FAKE-08 (MIT, https://github.com/jtothebell/fake-08) publishes no web build, so the
|
||||
# browser artifacts come from p3a (Apache-2.0, https://github.com/fabkury/p3a), which
|
||||
# compiled them. Pinned by commit and checksum because that tree has no tagged releases.
|
||||
RUN mkdir -p /fake08 && \
|
||||
wget "${FAKE08_P3A_RAW}/fake08.js" -O /fake08/fake08.js && \
|
||||
wget "${FAKE08_P3A_RAW}/fake08.wasm" -O /fake08/fake08.wasm && \
|
||||
echo "${FAKE08_JS_SHA256} /fake08/fake08.js" | sha256sum -c - && \
|
||||
echo "${FAKE08_WASM_SHA256} /fake08/fake08.wasm" | sha256sum -c -
|
||||
|
||||
|
||||
# BUILD NGINX MODULE WITH MOD_ZIP
|
||||
FROM alpine:${ALPINE_VERSION}@sha256:${ALPINE_SHA256} AS nginx-build
|
||||
@@ -302,6 +316,7 @@ ARG WEBSERVER_FOLDER=/var/www/html
|
||||
COPY --from=emulator-stage /emulatorjs ${WEBSERVER_FOLDER}/assets/emulatorjs
|
||||
COPY --from=emulator-stage /ruffle ${WEBSERVER_FOLDER}/assets/ruffle
|
||||
COPY --from=emulator-stage /jsdos/dist ${WEBSERVER_FOLDER}/assets/jsdos
|
||||
COPY --from=emulator-stage /fake08 ${WEBSERVER_FOLDER}/assets/pico8
|
||||
|
||||
|
||||
FROM slim-image AS dev-slim
|
||||
|
||||
@@ -1621,6 +1621,7 @@ Falls back to `FakeRedis` in test mode.
|
||||
| `DISABLE_EMULATOR_JS` | `false` | Hide EmulatorJS player |
|
||||
| `DISABLE_RUFFLE_RS` | `false` | Hide Ruffle Flash player |
|
||||
| `DISABLE_JSDOS` | `false` | Hide js-dos player |
|
||||
| `DISABLE_PICO8` | `false` | Hide PICO-8 player |
|
||||
|
||||
#### Task Scheduling
|
||||
|
||||
|
||||
@@ -508,7 +508,7 @@ Server capability flags used throughout the UI:
|
||||
|
||||
```typescript
|
||||
METADATA_SOURCES: { IGDB, SS, MOBY, RA, STEAMGRIDDB, LAUNCHBOX, ... }
|
||||
EMULATION: { DISABLE_EMULATOR_JS, DISABLE_RUFFLE_RS, DISABLE_JSDOS }
|
||||
EMULATION: { DISABLE_EMULATOR_JS, DISABLE_RUFFLE_RS, DISABLE_JSDOS, DISABLE_PICO8 }
|
||||
FRONTEND: { DISABLE_USERPASS_LOGIN, DISABLE_LOGS_VIEWER, YOUTUBE_BASE_URL }
|
||||
OIDC: { ENABLED, AUTOLOGIN, PROVIDER, RP_INITIATED_LOGOUT }
|
||||
TASKS: { scheduled task configurations }
|
||||
|
||||
@@ -115,6 +115,7 @@ SYNC_SSH_KNOWN_HOSTS_PATH= # Path to SSH known_hosts (defaults to $ROMM_BASE_PA
|
||||
DISABLE_EMULATOR_JS=false # Disable in-browser play via EmulatorJS
|
||||
DISABLE_RUFFLE_RS=false # Disable in-browser Flash playback via RuffleRS
|
||||
DISABLE_JSDOS=false # Disable in-browser Win3.x and Win9.x playback via js-dos
|
||||
DISABLE_PICO8=false # Disable in-browser PICO-8 playback via FAKE-08
|
||||
|
||||
# Integrations
|
||||
YOUTUBE_BASE_URL=https://www.youtube.com # Base URL for alternate YouTube frontends (Piped, Invidious, etc.)
|
||||
|
||||
@@ -6,5 +6,6 @@ export type EmulationDict = {
|
||||
DISABLE_EMULATOR_JS: boolean;
|
||||
DISABLE_RUFFLE_RS: boolean;
|
||||
DISABLE_JSDOS: boolean;
|
||||
DISABLE_PICO8: boolean;
|
||||
};
|
||||
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "Може да се играе в браузъра чрез DOSBox",
|
||||
"playable-browser-emulatorjs": "Може да се играе в браузъра чрез EmulatorJS",
|
||||
"playable-browser-jsdos": "Може да се играе в браузъра чрез js-dos",
|
||||
"playable-browser-pico8": "Може да се играе в браузъра чрез PICO-8",
|
||||
"playable-browser-ruffle": "Може да се играе в браузъра чрез Ruffle",
|
||||
"playable-none": "Не може да се играе в браузъра или чрез стрийминг",
|
||||
"playable-stream": "Може да се стриймва от {label}",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "Hratelné v prohlížeči přes DOSBox",
|
||||
"playable-browser-emulatorjs": "Hratelné v prohlížeči přes EmulatorJS",
|
||||
"playable-browser-jsdos": "Hratelné v prohlížeči přes js-dos",
|
||||
"playable-browser-pico8": "Hratelné v prohlížeči přes PICO-8",
|
||||
"playable-browser-ruffle": "Hratelné v prohlížeči přes Ruffle",
|
||||
"playable-none": "Nelze hrát v prohlížeči ani streamovat",
|
||||
"playable-stream": "Streamovatelné z {label}",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "Im Browser spielbar über DOSBox",
|
||||
"playable-browser-emulatorjs": "Im Browser spielbar über EmulatorJS",
|
||||
"playable-browser-jsdos": "Im Browser spielbar über js-dos",
|
||||
"playable-browser-pico8": "Im Browser spielbar über PICO-8",
|
||||
"playable-browser-ruffle": "Im Browser spielbar über Ruffle",
|
||||
"playable-none": "Weder im Browser spielbar noch streambar",
|
||||
"playable-stream": "Streambar über {label}",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "Playable in browser through DOSBox",
|
||||
"playable-browser-emulatorjs": "Playable in browser through EmulatorJS",
|
||||
"playable-browser-jsdos": "Playable in browser through js-dos",
|
||||
"playable-browser-pico8": "Playable in browser through PICO-8",
|
||||
"playable-browser-ruffle": "Playable in browser through Ruffle",
|
||||
"playable-none": "Not playable in browser or by streaming",
|
||||
"playable-stream": "Streamable from {label}",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "Playable in browser through DOSBox",
|
||||
"playable-browser-emulatorjs": "Playable in browser through EmulatorJS",
|
||||
"playable-browser-jsdos": "Playable in browser through js-dos",
|
||||
"playable-browser-pico8": "Playable in browser through PICO-8",
|
||||
"playable-browser-ruffle": "Playable in browser through Ruffle",
|
||||
"playable-none": "Not playable in browser or by streaming",
|
||||
"playable-stream": "Streamable from {label}",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "Jugable en el navegador mediante DOSBox",
|
||||
"playable-browser-emulatorjs": "Jugable en el navegador mediante EmulatorJS",
|
||||
"playable-browser-jsdos": "Jugable en el navegador mediante js-dos",
|
||||
"playable-browser-pico8": "Jugable en el navegador mediante PICO-8",
|
||||
"playable-browser-ruffle": "Jugable en el navegador mediante Ruffle",
|
||||
"playable-none": "No jugable en el navegador ni por transmisión",
|
||||
"playable-stream": "Transmisible desde {label}",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "Jouable dans le navigateur via DOSBox",
|
||||
"playable-browser-emulatorjs": "Jouable dans le navigateur via EmulatorJS",
|
||||
"playable-browser-jsdos": "Jouable dans le navigateur via js-dos",
|
||||
"playable-browser-pico8": "Jouable dans le navigateur via PICO-8",
|
||||
"playable-browser-ruffle": "Jouable dans le navigateur via Ruffle",
|
||||
"playable-none": "Ni jouable dans le navigateur ni diffusable",
|
||||
"playable-stream": "Diffusable depuis {label}",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "Böngészőben játszható DOSBox segítségével",
|
||||
"playable-browser-emulatorjs": "Böngészőben játszható EmulatorJS segítségével",
|
||||
"playable-browser-jsdos": "Böngészőben játszható js-dos segítségével",
|
||||
"playable-browser-pico8": "Böngészőben játszható PICO-8 segítségével",
|
||||
"playable-browser-ruffle": "Böngészőben játszható Ruffle segítségével",
|
||||
"playable-none": "Böngészőben nem játszható és nem streamelhető",
|
||||
"playable-stream": "Streamelhető innen: {label}",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "Giocabile nel browser tramite DOSBox",
|
||||
"playable-browser-emulatorjs": "Giocabile nel browser tramite EmulatorJS",
|
||||
"playable-browser-jsdos": "Giocabile nel browser tramite js-dos",
|
||||
"playable-browser-pico8": "Giocabile nel browser tramite PICO-8",
|
||||
"playable-browser-ruffle": "Giocabile nel browser tramite Ruffle",
|
||||
"playable-none": "Non giocabile nel browser né in streaming",
|
||||
"playable-stream": "Trasmissibile da {label}",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "DOSBox によりブラウザでプレイ可能",
|
||||
"playable-browser-emulatorjs": "EmulatorJS によりブラウザでプレイ可能",
|
||||
"playable-browser-jsdos": "js-dos によりブラウザでプレイ可能",
|
||||
"playable-browser-pico8": "PICO-8 によりブラウザでプレイ可能",
|
||||
"playable-browser-ruffle": "Ruffle によりブラウザでプレイ可能",
|
||||
"playable-none": "ブラウザでもストリーミングでもプレイできません",
|
||||
"playable-stream": "{label} からストリーミング可能",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "DOSBox를 통해 브라우저에서 플레이 가능",
|
||||
"playable-browser-emulatorjs": "EmulatorJS를 통해 브라우저에서 플레이 가능",
|
||||
"playable-browser-jsdos": "js-dos를 통해 브라우저에서 플레이 가능",
|
||||
"playable-browser-pico8": "PICO-8을 통해 브라우저에서 플레이 가능",
|
||||
"playable-browser-ruffle": "Ruffle을 통해 브라우저에서 플레이 가능",
|
||||
"playable-none": "브라우저에서도 스트리밍으로도 플레이할 수 없음",
|
||||
"playable-stream": "{label}에서 스트리밍 가능",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "Grywalne w przeglądarce przez DOSBox",
|
||||
"playable-browser-emulatorjs": "Grywalne w przeglądarce przez EmulatorJS",
|
||||
"playable-browser-jsdos": "Grywalne w przeglądarce przez js-dos",
|
||||
"playable-browser-pico8": "Grywalne w przeglądarce przez PICO-8",
|
||||
"playable-browser-ruffle": "Grywalne w przeglądarce przez Ruffle",
|
||||
"playable-none": "Niegrywalne w przeglądarce ani przez streaming",
|
||||
"playable-stream": "Dostępne w streamingu z {label}",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "Jogável no navegador via DOSBox",
|
||||
"playable-browser-emulatorjs": "Jogável no navegador via EmulatorJS",
|
||||
"playable-browser-jsdos": "Jogável no navegador via js-dos",
|
||||
"playable-browser-pico8": "Jogável no navegador via PICO-8",
|
||||
"playable-browser-ruffle": "Jogável no navegador via Ruffle",
|
||||
"playable-none": "Não jogável no navegador nem por transmissão",
|
||||
"playable-stream": "Transmissível de {label}",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "Se poate juca în browser prin DOSBox",
|
||||
"playable-browser-emulatorjs": "Se poate juca în browser prin EmulatorJS",
|
||||
"playable-browser-jsdos": "Se poate juca în browser prin js-dos",
|
||||
"playable-browser-pico8": "Se poate juca în browser prin PICO-8",
|
||||
"playable-browser-ruffle": "Se poate juca în browser prin Ruffle",
|
||||
"playable-none": "Nu se poate juca în browser și nici prin streaming",
|
||||
"playable-stream": "Se poate transmite de pe {label}",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "Запускается в браузере через DOSBox",
|
||||
"playable-browser-emulatorjs": "Запускается в браузере через EmulatorJS",
|
||||
"playable-browser-jsdos": "Запускается в браузере через js-dos",
|
||||
"playable-browser-pico8": "Запускается в браузере через PICO-8",
|
||||
"playable-browser-ruffle": "Запускается в браузере через Ruffle",
|
||||
"playable-none": "Не запускается ни в браузере, ни через трансляцию",
|
||||
"playable-stream": "Транслируется с {label}",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "DOSBox ile tarayıcıda oynanabilir",
|
||||
"playable-browser-emulatorjs": "EmulatorJS ile tarayıcıda oynanabilir",
|
||||
"playable-browser-jsdos": "js-dos ile tarayıcıda oynanabilir",
|
||||
"playable-browser-pico8": "PICO-8 ile tarayıcıda oynanabilir",
|
||||
"playable-browser-ruffle": "Ruffle ile tarayıcıda oynanabilir",
|
||||
"playable-none": "Tarayıcıda oynanamaz ve yayınlanamaz",
|
||||
"playable-stream": "{label} üzerinden yayınlanabilir",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "可通过 DOSBox 在浏览器中游玩",
|
||||
"playable-browser-emulatorjs": "可通过 EmulatorJS 在浏览器中游玩",
|
||||
"playable-browser-jsdos": "可通过 js-dos 在浏览器中游玩",
|
||||
"playable-browser-pico8": "可通过 PICO-8 在浏览器中游玩",
|
||||
"playable-browser-ruffle": "可通过 Ruffle 在浏览器中游玩",
|
||||
"playable-none": "无法在浏览器中游玩,也无法串流",
|
||||
"playable-stream": "可从 {label} 串流",
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
"playable-browser-dosbox": "可透過 DOSBox 在瀏覽器中遊玩",
|
||||
"playable-browser-emulatorjs": "可透過 EmulatorJS 在瀏覽器中遊玩",
|
||||
"playable-browser-jsdos": "可透過 js-dos 在瀏覽器中遊玩",
|
||||
"playable-browser-pico8": "可透過 PICO-8 在瀏覽器中遊玩",
|
||||
"playable-browser-ruffle": "可透過 Ruffle 在瀏覽器中遊玩",
|
||||
"playable-none": "無法在瀏覽器中遊玩,也無法串流",
|
||||
"playable-stream": "可從 {label} 串流",
|
||||
|
||||
@@ -35,6 +35,7 @@ export const ROUTES = {
|
||||
ROM: "rom",
|
||||
EMULATORJS: "emulatorjs",
|
||||
JSDOS: "jsdos",
|
||||
PICO8: "pico8",
|
||||
RUFFLE: "ruffle",
|
||||
STREAM: "stream",
|
||||
STREAM_DESKTOP: "stream-desktop",
|
||||
@@ -274,6 +275,14 @@ const routes = [
|
||||
v2: v2For(ROUTES.JSDOS),
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "rom/:rom/pico8",
|
||||
name: ROUTES.PICO8,
|
||||
components: {
|
||||
default: () => import("@/views/Home.vue"),
|
||||
v2: v2For(ROUTES.PICO8),
|
||||
},
|
||||
},
|
||||
{
|
||||
path: "rom/:rom/ruffle",
|
||||
name: ROUTES.RUFFLE,
|
||||
|
||||
@@ -45,6 +45,7 @@ const defaultHeartbeat: Heartbeat = {
|
||||
DISABLE_EMULATOR_JS: false,
|
||||
DISABLE_RUFFLE_RS: false,
|
||||
DISABLE_JSDOS: false,
|
||||
DISABLE_PICO8: false,
|
||||
},
|
||||
FRONTEND: {
|
||||
DISABLE_USERPASS_LOGIN: false,
|
||||
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
getDownloadPath,
|
||||
isJsDosBundle,
|
||||
isJsDosEmulationSupported,
|
||||
isPico8EmulationSupported,
|
||||
isPico8Rom,
|
||||
} from "./index";
|
||||
|
||||
function makeRom(overrides: Partial<SimpleRom>): SimpleRom {
|
||||
@@ -102,6 +104,7 @@ function makeHeartbeat(
|
||||
DISABLE_EMULATOR_JS: false,
|
||||
DISABLE_RUFFLE_RS: false,
|
||||
DISABLE_JSDOS: false,
|
||||
DISABLE_PICO8: false,
|
||||
...emulation,
|
||||
},
|
||||
} as Heartbeat;
|
||||
@@ -167,3 +170,32 @@ describe("isJsDosBundle", () => {
|
||||
expect(isJsDosBundle(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("PICO-8 support", () => {
|
||||
const withExt = (fs_extension: string) => makeRom({ fs_extension });
|
||||
|
||||
it("supports the pico platform and configured remaps", () => {
|
||||
expect(isPico8EmulationSupported("pico", makeHeartbeat())).toBe(true);
|
||||
expect(
|
||||
isPico8EmulationSupported(
|
||||
"custom-pico",
|
||||
makeHeartbeat(),
|
||||
makeConfig({ "custom-pico": "pico" }),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(isPico8EmulationSupported("snes", makeHeartbeat())).toBe(false);
|
||||
});
|
||||
|
||||
it("respects the DISABLE_PICO8 admin toggle", () => {
|
||||
expect(
|
||||
isPico8EmulationSupported("pico", makeHeartbeat({ DISABLE_PICO8: true })),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts .p8 and .p8.png cartridges only", () => {
|
||||
expect(isPico8Rom(withExt("p8"))).toBe(true);
|
||||
expect(isPico8Rom(withExt("P8.PNG"))).toBe(true);
|
||||
expect(isPico8Rom(withExt("zip"))).toBe(false);
|
||||
expect(isPico8Rom(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -734,6 +734,36 @@ export function isJsDosBundle(rom: SimpleRom | null | undefined) {
|
||||
return rom?.fs_extension.toLowerCase() === "jsdos";
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if PICO-8 emulation is supported for a given platform.
|
||||
*
|
||||
* @param platformSlug The platform slug.
|
||||
* @param heartbeat The heartbeat object.
|
||||
* @param config Optional configuration object.
|
||||
* @returns True if supported, false otherwise.
|
||||
*/
|
||||
export function isPico8EmulationSupported(
|
||||
platformSlug: string,
|
||||
heartbeat: Heartbeat,
|
||||
config?: Config,
|
||||
) {
|
||||
if (heartbeat.EMULATION.DISABLE_PICO8) return false;
|
||||
|
||||
const slug = resolvePlatformSlug(platformSlug, config);
|
||||
return slug.toLowerCase() === "pico";
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a ROM file is a PICO-8 cartridge.
|
||||
*
|
||||
* @param rom The ROM to check.
|
||||
* @returns True if the file is a PICO-8 cartridge, false otherwise.
|
||||
*/
|
||||
export function isPico8Rom(rom: SimpleRom | null | undefined) {
|
||||
const extension = rom?.fs_extension.toLowerCase();
|
||||
return extension === "p8" || extension === "p8.png";
|
||||
}
|
||||
|
||||
export type PlayingStatus =
|
||||
RomUserStatus | "backlogged" | "now_playing" | "hidden";
|
||||
|
||||
|
||||
@@ -8,6 +8,8 @@ import { useCanPlay } from "./index";
|
||||
const support = vi.hoisted(() => ({
|
||||
ejs: vi.fn(() => false),
|
||||
jsDos: vi.fn(() => false),
|
||||
pico8: vi.fn(() => false),
|
||||
pico8Rom: vi.fn(() => false),
|
||||
ruffle: vi.fn(() => false),
|
||||
// js-dos also demands its own bundle format; on by default so the engine
|
||||
// stubs stay the only variable.
|
||||
@@ -32,6 +34,8 @@ vi.mock("@/stores/streaming", () => ({
|
||||
vi.mock("@/utils", () => ({
|
||||
isEJSEmulationSupported: support.ejs,
|
||||
isJsDosEmulationSupported: support.jsDos,
|
||||
isPico8EmulationSupported: support.pico8,
|
||||
isPico8Rom: support.pico8Rom,
|
||||
isRuffleEmulationSupported: support.ruffle,
|
||||
isJsDosBundle: support.jsDosBundle,
|
||||
}));
|
||||
@@ -49,10 +53,14 @@ function makeRom(overrides: Partial<SimpleRom> = {}): SimpleRom {
|
||||
beforeEach(() => {
|
||||
support.ejs.mockReturnValue(false);
|
||||
support.jsDos.mockReturnValue(false);
|
||||
support.pico8.mockReturnValue(false);
|
||||
support.pico8Rom.mockReturnValue(false);
|
||||
support.ruffle.mockReturnValue(false);
|
||||
support.jsDosBundle.mockReturnValue(true);
|
||||
support.ejs.mockClear();
|
||||
support.jsDos.mockClear();
|
||||
support.pico8.mockClear();
|
||||
support.pico8Rom.mockClear();
|
||||
support.ruffle.mockClear();
|
||||
support.jsDosBundle.mockClear();
|
||||
streamContainer.value = null;
|
||||
@@ -62,9 +70,11 @@ describe("useCanPlay", () => {
|
||||
it.each([
|
||||
["EJS", "ejs", "canPlayEJS"],
|
||||
["js-dos", "jsDos", "canPlayJsDos"],
|
||||
["PICO-8", "pico8", "canPlayPico8"],
|
||||
["Ruffle", "ruffle", "canPlayRuffle"],
|
||||
] as const)("reports %s support on its own flag", (_label, stub, flag) => {
|
||||
support[stub].mockReturnValue(true);
|
||||
if (stub === "pico8") support.pico8Rom.mockReturnValue(true);
|
||||
const result = useCanPlay(() => makeRom());
|
||||
|
||||
expect(result[flag].value).toBe(true);
|
||||
@@ -73,7 +83,7 @@ describe("useCanPlay", () => {
|
||||
|
||||
// A physical game, or one whose file vanished from the library, has nothing
|
||||
// to hand the emulator: every route boots from the download endpoint.
|
||||
it.each(["ejs", "jsDos", "ruffle"] as const)(
|
||||
it.each(["ejs", "jsDos", "pico8", "ruffle"] as const)(
|
||||
"refuses %s for a rom with no file on disk",
|
||||
(stub) => {
|
||||
support[stub].mockReturnValue(true);
|
||||
@@ -89,14 +99,23 @@ describe("useCanPlay", () => {
|
||||
it("refuses every route when there is no rom", () => {
|
||||
support.ejs.mockReturnValue(true);
|
||||
support.jsDos.mockReturnValue(true);
|
||||
support.pico8.mockReturnValue(true);
|
||||
support.pico8Rom.mockReturnValue(true);
|
||||
support.ruffle.mockReturnValue(true);
|
||||
streamContainer.value = {};
|
||||
const { canPlay, canPlayEJS, canPlayJsDos, canPlayRuffle, canPlayStream } =
|
||||
useCanPlay(() => null);
|
||||
const {
|
||||
canPlay,
|
||||
canPlayEJS,
|
||||
canPlayJsDos,
|
||||
canPlayPico8,
|
||||
canPlayRuffle,
|
||||
canPlayStream,
|
||||
} = useCanPlay(() => null);
|
||||
|
||||
expect(canPlay.value).toBe(false);
|
||||
expect(canPlayEJS.value).toBe(false);
|
||||
expect(canPlayJsDos.value).toBe(false);
|
||||
expect(canPlayPico8.value).toBe(false);
|
||||
expect(canPlayRuffle.value).toBe(false);
|
||||
expect(canPlayStream.value).toBe(false);
|
||||
});
|
||||
@@ -134,6 +153,15 @@ describe("useCanPlay", () => {
|
||||
expect(canPlay.value).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses PICO-8 for a rom with another extension", () => {
|
||||
support.pico8.mockReturnValue(true);
|
||||
support.pico8Rom.mockReturnValue(false);
|
||||
const { canPlay, canPlayPico8 } = useCanPlay(() => makeRom());
|
||||
|
||||
expect(canPlayPico8.value).toBe(false);
|
||||
expect(canPlay.value).toBe(false);
|
||||
});
|
||||
|
||||
it("stays unplayable when no engine supports the platform", () => {
|
||||
const { canPlay } = useCanPlay(() => makeRom());
|
||||
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
// inside PlayBtn.vue; v2 lifts it to a composable so the card overlay
|
||||
// and the menu item agree with the details-header CTA.
|
||||
//
|
||||
// "Playable" means EJS, js-dos, or Ruffle can run the platform on this
|
||||
// "Playable" means EJS, js-dos, PICO-8, or Ruffle can run the platform on this
|
||||
// server (admin toggles + platform support + WebGL availability) and there
|
||||
// is a file to boot, or a streaming container is configured for the
|
||||
// platform. A physical game or one missing from the filesystem has nothing
|
||||
// to hand the emulator, and js-dos additionally needs the file to be one of
|
||||
// its own bundles. The individual flags are exposed so the play action can
|
||||
// pick the right route (EJS vs js-dos vs Ruffle vs Stream).
|
||||
// pick the right route (EJS vs js-dos vs PICO-8 vs Ruffle vs Stream).
|
||||
import { storeToRefs } from "pinia";
|
||||
import { computed, type ComputedRef } from "vue";
|
||||
import storeConfig from "@/stores/config";
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
isEJSEmulationSupported,
|
||||
isJsDosBundle,
|
||||
isJsDosEmulationSupported,
|
||||
isPico8EmulationSupported,
|
||||
isPico8Rom,
|
||||
isRuffleEmulationSupported,
|
||||
} from "@/utils";
|
||||
|
||||
@@ -27,6 +29,7 @@ export function useCanPlay(getRom: () => SimpleRom | null | undefined): {
|
||||
canPlay: ComputedRef<boolean>;
|
||||
canPlayEJS: ComputedRef<boolean>;
|
||||
canPlayJsDos: ComputedRef<boolean>;
|
||||
canPlayPico8: ComputedRef<boolean>;
|
||||
canPlayRuffle: ComputedRef<boolean>;
|
||||
canPlayStream: ComputedRef<boolean>;
|
||||
} {
|
||||
@@ -52,6 +55,11 @@ export function useCanPlay(getRom: () => SimpleRom | null | undefined): {
|
||||
() => onJsDosPlatform.value && isJsDosBundle(getRom()),
|
||||
);
|
||||
|
||||
const onPico8Platform = supportedBy(isPico8EmulationSupported);
|
||||
const canPlayPico8 = computed(
|
||||
() => onPico8Platform.value && isPico8Rom(getRom()),
|
||||
);
|
||||
|
||||
// The broker is handed the ROM file, so a physical game or one missing
|
||||
// from the filesystem has nothing to stream any more than it has to boot.
|
||||
const canPlayStream = computed(() => {
|
||||
@@ -64,9 +72,17 @@ export function useCanPlay(getRom: () => SimpleRom | null | undefined): {
|
||||
() =>
|
||||
canPlayEJS.value ||
|
||||
canPlayJsDos.value ||
|
||||
canPlayPico8.value ||
|
||||
canPlayRuffle.value ||
|
||||
canPlayStream.value,
|
||||
);
|
||||
|
||||
return { canPlay, canPlayEJS, canPlayJsDos, canPlayRuffle, canPlayStream };
|
||||
return {
|
||||
canPlay,
|
||||
canPlayEJS,
|
||||
canPlayJsDos,
|
||||
canPlayPico8,
|
||||
canPlayRuffle,
|
||||
canPlayStream,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ function makeRouter() {
|
||||
{ path: "/platform/:platform", name: ROUTES.PLATFORM, component: blank },
|
||||
{ path: "/rom/:rom", name: ROUTES.ROM, component: blank },
|
||||
{ path: "/play/:rom", name: ROUTES.EMULATORJS, component: blank },
|
||||
{ path: "/pico/:rom", name: ROUTES.PICO8, component: blank },
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -59,7 +60,7 @@ describe("useGalleryProvenance", () => {
|
||||
expect(mod.useGalleryProvenance().enteredFromGallery.value).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the arming across rom → rom hops and a play session", async () => {
|
||||
it("keeps the arming across rom hops and a PICO-8 session", async () => {
|
||||
const mod = await loadFresh();
|
||||
const router = makeRouter();
|
||||
mod.installGalleryProvenance(router);
|
||||
@@ -67,7 +68,7 @@ describe("useGalleryProvenance", () => {
|
||||
await router.push("/platform/1");
|
||||
await router.push("/rom/10");
|
||||
await router.push("/rom/11");
|
||||
await router.push("/play/11");
|
||||
await router.push("/pico/11");
|
||||
await router.push("/rom/11");
|
||||
|
||||
expect(mod.useGalleryProvenance().enteredFromGallery.value).toBe(true);
|
||||
|
||||
@@ -29,6 +29,7 @@ const GALLERY_ROUTES: ReadonlySet<string> = new Set([
|
||||
const CHAIN_ROUTES: ReadonlySet<string> = new Set([
|
||||
ROUTES.ROM,
|
||||
ROUTES.EMULATORJS,
|
||||
ROUTES.PICO8,
|
||||
ROUTES.RUFFLE,
|
||||
ROUTES.STREAM,
|
||||
]);
|
||||
|
||||
@@ -20,6 +20,7 @@ const snackbarInfo = vi.fn();
|
||||
const confirmProtectedLaunch = { value: true };
|
||||
const canPlayEJS = { value: true };
|
||||
const canPlayJsDos = { value: false };
|
||||
const canPlayPico8 = { value: false };
|
||||
const canPlayRuffle = { value: false };
|
||||
const streamContainer = { value: null as object | null };
|
||||
const joinableSession = {
|
||||
@@ -85,6 +86,7 @@ vi.mock("@/v2/composables/useCanPlay", () => ({
|
||||
useCanPlay: (getRom: () => SimpleRom | null | undefined) => ({
|
||||
canPlayEJS,
|
||||
canPlayJsDos,
|
||||
canPlayPico8,
|
||||
canPlayRuffle,
|
||||
canPlayStream: {
|
||||
get value() {
|
||||
@@ -156,6 +158,7 @@ beforeEach(() => {
|
||||
confirmProtectedLaunch.value = true;
|
||||
canPlayEJS.value = true;
|
||||
canPlayJsDos.value = false;
|
||||
canPlayPico8.value = false;
|
||||
canPlayRuffle.value = false;
|
||||
streamContainer.value = null;
|
||||
joinableSession.value = null;
|
||||
@@ -353,6 +356,17 @@ describe("useGameActions.play — launch confirmation", () => {
|
||||
expect(locationAssign).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps SPA navigation for PICO-8", async () => {
|
||||
canPlayEJS.value = false;
|
||||
canPlayPico8.value = true;
|
||||
const actions = useGameActions(() => makeRom());
|
||||
|
||||
await actions.play();
|
||||
|
||||
expect(push).toHaveBeenCalledWith("/rom/1/pico8");
|
||||
expect(locationAssign).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("full-loads js-dos ahead of EmulatorJS for its platforms", async () => {
|
||||
canPlayJsDos.value = true;
|
||||
const actions = useGameActions(() => makeRom());
|
||||
|
||||
@@ -83,14 +83,24 @@ export function useGameActions(
|
||||
const canDelete = computed(() => hasDeleteGrant.value && canEdit.value);
|
||||
const { isFavorite, toggleFavorite } = useFavoriteToggle(emitter);
|
||||
const { startScan } = useScanTrigger();
|
||||
const { canPlay, canPlayEJS, canPlayJsDos, canPlayRuffle, canPlayStream } =
|
||||
useCanPlay(getRom);
|
||||
const {
|
||||
canPlay,
|
||||
canPlayEJS,
|
||||
canPlayJsDos,
|
||||
canPlayPico8,
|
||||
canPlayRuffle,
|
||||
canPlayStream,
|
||||
} = useCanPlay(getRom);
|
||||
const streamingStore = useStreamingStore();
|
||||
|
||||
// Streaming is offered as its own action rather than as the winner of a
|
||||
// precedence rule, so each player needs a gate of its own.
|
||||
const canPlayInBrowser = computed(
|
||||
() => canPlayEJS.value || canPlayJsDos.value || canPlayRuffle.value,
|
||||
() =>
|
||||
canPlayEJS.value ||
|
||||
canPlayJsDos.value ||
|
||||
canPlayPico8.value ||
|
||||
canPlayRuffle.value,
|
||||
);
|
||||
|
||||
// Download, the copied link and the QR code all resolve to the download
|
||||
@@ -332,6 +342,7 @@ export function useGameActions(
|
||||
// immediate here.
|
||||
let path: string | null = null;
|
||||
if (streaming && canPlayStream.value) path = `/rom/${rom.id}/stream`;
|
||||
else if (inBrowser && canPlayPico8.value) path = `/rom/${rom.id}/pico8`;
|
||||
else if (inBrowser && canPlayRuffle.value) path = `/rom/${rom.id}/ruffle`;
|
||||
if (!path) return;
|
||||
const target = path;
|
||||
|
||||
@@ -11,12 +11,14 @@ const ejsSlugs = new Set<string>();
|
||||
const ruffleSlugs = new Set<string>();
|
||||
const dosboxSlugs = new Set<string>();
|
||||
const jsDosSlugs = new Set<string>();
|
||||
const pico8Slugs = new Set<string>();
|
||||
const streamContainers = new Map<string, { label: string; emulator: string }>();
|
||||
const streamingEnabled = { value: true };
|
||||
|
||||
vi.mock("@/utils", () => ({
|
||||
isEJSEmulationSupported: (slug: string) => ejsSlugs.has(slug),
|
||||
isJsDosEmulationSupported: (slug: string) => jsDosSlugs.has(slug),
|
||||
isPico8EmulationSupported: (slug: string) => pico8Slugs.has(slug),
|
||||
isRuffleEmulationSupported: (slug: string) => ruffleSlugs.has(slug),
|
||||
getSupportedEJSCores: (slug: string) =>
|
||||
dosboxSlugs.has(slug) ? ["dosbox_pure"] : ["snes9x"],
|
||||
@@ -68,6 +70,7 @@ beforeEach(() => {
|
||||
ruffleSlugs.clear();
|
||||
dosboxSlugs.clear();
|
||||
jsDosSlugs.clear();
|
||||
pico8Slugs.clear();
|
||||
streamContainers.clear();
|
||||
streamingEnabled.value = true;
|
||||
});
|
||||
@@ -80,6 +83,13 @@ describe("usePlatformPlayable", () => {
|
||||
expect(playable.value).toBe(true);
|
||||
});
|
||||
|
||||
it("resolves PICO-8 as a browser player", () => {
|
||||
pico8Slugs.add("pico");
|
||||
const { mode, emulator } = usePlatformPlayable(() => "pico");
|
||||
expect(mode.value).toBe("browser");
|
||||
expect(emulator.value).toBe("pico8");
|
||||
});
|
||||
|
||||
it("resolves streaming-only as stream and carries the container label", () => {
|
||||
streamContainers.set("ps2", { label: "PCSX2", emulator: "pcsx2" });
|
||||
const { mode, playable, streamLabel } = usePlatformPlayable(() => "ps2");
|
||||
@@ -150,6 +160,9 @@ describe("playTooltip", () => {
|
||||
expect(playTooltip("browser", "dosbox", null)).toBe(
|
||||
"platform.playable-browser-dosbox",
|
||||
);
|
||||
expect(playTooltip("browser", "pico8", null)).toBe(
|
||||
"platform.playable-browser-pico8",
|
||||
);
|
||||
expect(playTooltip("browser", "emulatorjs", null)).toBe(
|
||||
"platform.playable-browser-emulatorjs",
|
||||
);
|
||||
|
||||
@@ -9,7 +9,8 @@
|
||||
// slugs at once (sort comparators, group-by buckets in PlatformsIndex).
|
||||
//
|
||||
// `emulator` resolves to the in-browser engine that actually drives the
|
||||
// platform: "ruffle" for Flash, "jsdos" for Windows 3.x/9x, "dosbox"
|
||||
// platform: "ruffle" for Flash, "jsdos" for Windows 3.x/9x, "pico8" for
|
||||
// PICO-8, "dosbox"
|
||||
// when the EJS catalogue picks the dosbox_pure core (DOS is wrapped by
|
||||
// EJS but distinctive enough to surface by name in the UI),
|
||||
// "emulatorjs" for everything else playable, and `null` when nothing on
|
||||
@@ -29,12 +30,13 @@ import {
|
||||
getSupportedEJSCores,
|
||||
isEJSEmulationSupported,
|
||||
isJsDosEmulationSupported,
|
||||
isPico8EmulationSupported,
|
||||
isRuffleEmulationSupported,
|
||||
resolvePlatformSlug,
|
||||
} from "@/utils";
|
||||
|
||||
export type PlatformEmulator =
|
||||
"emulatorjs" | "ruffle" | "jsdos" | "dosbox" | null;
|
||||
"emulatorjs" | "ruffle" | "jsdos" | "pico8" | "dosbox" | null;
|
||||
|
||||
export type PlatformPlayMode = "browser" | "stream" | "both" | null;
|
||||
|
||||
@@ -56,6 +58,7 @@ function resolveEmulator(
|
||||
if (!slug) return null;
|
||||
if (isRuffleEmulationSupported(slug, heartbeat, config)) return "ruffle";
|
||||
if (isJsDosEmulationSupported(slug, heartbeat, config)) return "jsdos";
|
||||
if (isPico8EmulationSupported(slug, heartbeat, config)) return "pico8";
|
||||
if (!isEJSEmulationSupported(slug, heartbeat, config)) return null;
|
||||
const cores = getSupportedEJSCores(resolvePlatformSlug(slug, config));
|
||||
if (cores.includes("dosbox_pure")) return "dosbox";
|
||||
@@ -155,6 +158,8 @@ export function playTooltip(
|
||||
return t("platform.playable-browser-ruffle");
|
||||
case "jsdos":
|
||||
return t("platform.playable-browser-jsdos");
|
||||
case "pico8":
|
||||
return t("platform.playable-browser-pico8");
|
||||
case "dosbox":
|
||||
return t("platform.playable-browser-dosbox");
|
||||
default:
|
||||
|
||||
@@ -97,11 +97,15 @@ export function useViewTransition() {
|
||||
function morphNameForRoute(route: RouteLocationNormalized): string | null {
|
||||
const name = route.name;
|
||||
const params = route.params as Record<string, string | string[]>;
|
||||
// `rom` (detail) and the players (`emulatorjs` / `ruffle`) all own a
|
||||
// `rom` (detail) and the players all own a
|
||||
// `rom-cover-<id>` hero, so morph between any of them and the gallery /
|
||||
// each other.
|
||||
if (
|
||||
(name === "rom" || name === "emulatorjs" || name === "ruffle") &&
|
||||
(name === "rom" ||
|
||||
name === "emulatorjs" ||
|
||||
name === "jsdos" ||
|
||||
name === "pico8" ||
|
||||
name === "ruffle") &&
|
||||
params.rom
|
||||
) {
|
||||
return `rom-cover-${params.rom}`;
|
||||
|
||||
@@ -38,6 +38,7 @@ export const v2RouteComponents: Partial<Record<string, V2Route>> = {
|
||||
// Wave 5 — Players
|
||||
emulatorjs: () => import("@/v2/views/Player/EmulatorJS.vue"),
|
||||
jsdos: () => import("@/v2/views/Player/JsDos.vue"),
|
||||
pico8: () => import("@/v2/views/Player/Pico8.vue"),
|
||||
ruffle: () => import("@/v2/views/Player/Ruffle.vue"),
|
||||
stream: () => import("@/v2/views/Player/Stream.vue"),
|
||||
"stream-desktop": () => import("@/v2/views/Player/Desktop.vue"),
|
||||
|
||||
615
frontend/src/v2/views/Player/Pico8.vue
Normal file
615
frontend/src/v2/views/Player/Pico8.vue
Normal file
@@ -0,0 +1,615 @@
|
||||
<script setup lang="ts">
|
||||
import { RBtn, RSpinner, RSwitch } from "@v2/lib";
|
||||
import { useEventListener } from "@vueuse/core";
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, shallowRef } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import romApi from "@/services/api/rom";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import type { DetailedRom } from "@/stores/roms";
|
||||
import { getDownloadPath } from "@/utils";
|
||||
import PlayerShell from "@/v2/components/Player/PlayerShell.vue";
|
||||
import { useFullscreenPref } from "@/v2/composables/useFullscreenPref";
|
||||
import { useInputModality } from "@/v2/composables/useInputModality";
|
||||
import { usePlaySession } from "@/v2/composables/usePlaySession";
|
||||
import { usePlayerHero } from "@/v2/composables/usePlayerHero";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import { useUnloadGuard } from "@/v2/composables/useUnloadGuard";
|
||||
import {
|
||||
createPico8Runtime,
|
||||
PICO8_FRAME_RATE,
|
||||
PICO8_INPUT_BITS,
|
||||
type Pico8Runtime,
|
||||
} from "./pico8Runtime";
|
||||
|
||||
const { t } = useI18n();
|
||||
const playingStore = storePlaying();
|
||||
const playSession = usePlaySession();
|
||||
const snackbar = useSnackbar();
|
||||
const { fullscreenOnPlay } = useFullscreenPref();
|
||||
const { modality } = useInputModality();
|
||||
|
||||
const rom = shallowRef<DetailedRom | null>(null);
|
||||
const gameRunning = ref(false);
|
||||
const loading = ref(false);
|
||||
const stage = ref<HTMLDivElement | null>(null);
|
||||
const canvas = ref<HTMLCanvasElement | null>(null);
|
||||
const touchMask = ref(0);
|
||||
|
||||
const { romId, heroRom, title, platformLabel } = usePlayerHero(rom);
|
||||
|
||||
let runtime: Pico8Runtime | null = null;
|
||||
let animationFrame = 0;
|
||||
let lastFrameTime = 0;
|
||||
let frameAccumulator = 0;
|
||||
let previousHeld = 0;
|
||||
let keyboardMask = 0;
|
||||
let mouseX = 0;
|
||||
let mouseY = 0;
|
||||
let mouseButtons = 0;
|
||||
let audioContext: AudioContext | null = null;
|
||||
let audioGain: GainNode | null = null;
|
||||
let nextAudioTime = 0;
|
||||
let viewAlive = true;
|
||||
|
||||
const keyboardMap: Record<string, number> = {
|
||||
ArrowLeft: PICO8_INPUT_BITS.left,
|
||||
ArrowRight: PICO8_INPUT_BITS.right,
|
||||
ArrowUp: PICO8_INPUT_BITS.up,
|
||||
ArrowDown: PICO8_INPUT_BITS.down,
|
||||
KeyZ: PICO8_INPUT_BITS.a,
|
||||
KeyX: PICO8_INPUT_BITS.b,
|
||||
};
|
||||
|
||||
const directionControls = [
|
||||
{
|
||||
bit: PICO8_INPUT_BITS.up,
|
||||
icon: "mdi-menu-up",
|
||||
className: "r-v2-pico8__control--up",
|
||||
label: "up",
|
||||
},
|
||||
{
|
||||
bit: PICO8_INPUT_BITS.left,
|
||||
icon: "mdi-menu-left",
|
||||
className: "r-v2-pico8__control--left",
|
||||
label: "left",
|
||||
},
|
||||
{
|
||||
bit: PICO8_INPUT_BITS.right,
|
||||
icon: "mdi-menu-right",
|
||||
className: "r-v2-pico8__control--right",
|
||||
label: "right",
|
||||
},
|
||||
{
|
||||
bit: PICO8_INPUT_BITS.down,
|
||||
icon: "mdi-menu-down",
|
||||
className: "r-v2-pico8__control--down",
|
||||
label: "down",
|
||||
},
|
||||
] as const;
|
||||
|
||||
const faceControls = [
|
||||
{ bit: PICO8_INPUT_BITS.a, color: "danger", label: "A" },
|
||||
{ bit: PICO8_INPUT_BITS.b, color: "primary", label: "B" },
|
||||
] as const;
|
||||
|
||||
useUnloadGuard(gameRunning);
|
||||
|
||||
function focusPlayButton() {
|
||||
document.querySelector<HTMLElement>(".r-v2-player__play")?.focus({
|
||||
preventScroll: true,
|
||||
});
|
||||
}
|
||||
|
||||
function onKeyDown(event: KeyboardEvent) {
|
||||
if (!gameRunning.value) return;
|
||||
const bit = keyboardMap[event.code];
|
||||
if (!bit) return;
|
||||
event.preventDefault();
|
||||
keyboardMask |= bit;
|
||||
}
|
||||
|
||||
function onKeyUp(event: KeyboardEvent) {
|
||||
const bit = keyboardMap[event.code];
|
||||
if (bit) keyboardMask &= ~bit;
|
||||
}
|
||||
|
||||
function readGamepadMask() {
|
||||
let mask = 0;
|
||||
const gamepads = navigator.getGamepads?.() ?? [];
|
||||
for (const gamepad of gamepads) {
|
||||
if (!gamepad) continue;
|
||||
if (gamepad.buttons[14]?.pressed) mask |= PICO8_INPUT_BITS.left;
|
||||
if (gamepad.buttons[15]?.pressed) mask |= PICO8_INPUT_BITS.right;
|
||||
if (gamepad.buttons[12]?.pressed) mask |= PICO8_INPUT_BITS.up;
|
||||
if (gamepad.buttons[13]?.pressed) mask |= PICO8_INPUT_BITS.down;
|
||||
if (gamepad.buttons[0]?.pressed) mask |= PICO8_INPUT_BITS.a;
|
||||
if (gamepad.buttons[1]?.pressed) mask |= PICO8_INPUT_BITS.b;
|
||||
if ((gamepad.axes[0] ?? 0) < -0.5) mask |= PICO8_INPUT_BITS.left;
|
||||
if ((gamepad.axes[0] ?? 0) > 0.5) mask |= PICO8_INPUT_BITS.right;
|
||||
if ((gamepad.axes[1] ?? 0) < -0.5) mask |= PICO8_INPUT_BITS.up;
|
||||
if ((gamepad.axes[1] ?? 0) > 0.5) mask |= PICO8_INPUT_BITS.down;
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
|
||||
function getInput() {
|
||||
const held = keyboardMask | touchMask.value | readGamepadMask();
|
||||
const keyDown = held & ~previousHeld;
|
||||
previousHeld = held;
|
||||
return { keyDown, keyHeld: held, mouseX, mouseY, mouseButtons };
|
||||
}
|
||||
|
||||
function updateMousePosition(event: PointerEvent) {
|
||||
const element = canvas.value;
|
||||
if (!element) return;
|
||||
const rect = element.getBoundingClientRect();
|
||||
if (rect.width === 0 || rect.height === 0) return;
|
||||
mouseX = Math.max(
|
||||
0,
|
||||
Math.min(127, Math.floor(((event.clientX - rect.left) / rect.width) * 128)),
|
||||
);
|
||||
mouseY = Math.max(
|
||||
0,
|
||||
Math.min(127, Math.floor(((event.clientY - rect.top) / rect.height) * 128)),
|
||||
);
|
||||
}
|
||||
|
||||
function getMouseButtonMask(button: number) {
|
||||
if (button === 0) return 0x01;
|
||||
if (button === 1) return 0x04;
|
||||
if (button === 2) return 0x02;
|
||||
return 0;
|
||||
}
|
||||
|
||||
function onCanvasPointerMove(event: PointerEvent) {
|
||||
if (!gameRunning.value) return;
|
||||
updateMousePosition(event);
|
||||
}
|
||||
|
||||
function onCanvasPointerDown(event: PointerEvent) {
|
||||
if (!gameRunning.value) return;
|
||||
event.preventDefault();
|
||||
updateMousePosition(event);
|
||||
mouseButtons |= getMouseButtonMask(event.button);
|
||||
canvas.value?.setPointerCapture(event.pointerId);
|
||||
}
|
||||
|
||||
function onCanvasPointerUp(event: PointerEvent) {
|
||||
updateMousePosition(event);
|
||||
mouseButtons &= ~getMouseButtonMask(event.button);
|
||||
}
|
||||
|
||||
function onCanvasPointerCancel() {
|
||||
mouseButtons = 0;
|
||||
}
|
||||
|
||||
function onControlPointerDown(bit: number, event: PointerEvent) {
|
||||
if (!gameRunning.value) return;
|
||||
event.preventDefault();
|
||||
touchMask.value |= bit;
|
||||
(event.currentTarget as HTMLElement).setPointerCapture?.(event.pointerId);
|
||||
}
|
||||
|
||||
function onControlPointerUp(bit: number, event: PointerEvent) {
|
||||
event.preventDefault();
|
||||
touchMask.value &= ~bit;
|
||||
}
|
||||
|
||||
function onControlKeyDown(bit: number, event: KeyboardEvent) {
|
||||
if (!gameRunning.value || !["Enter", "Space"].includes(event.code)) return;
|
||||
event.preventDefault();
|
||||
touchMask.value |= bit;
|
||||
}
|
||||
|
||||
function onControlKeyUp(bit: number) {
|
||||
touchMask.value &= ~bit;
|
||||
}
|
||||
|
||||
function scheduleAudio(samples: Int16Array) {
|
||||
if (!audioContext || !audioGain || samples.length === 0) return;
|
||||
const buffer = audioContext.createBuffer(
|
||||
1,
|
||||
samples.length,
|
||||
runtime?.audioSampleRate ?? 22050,
|
||||
);
|
||||
const channel = buffer.getChannelData(0);
|
||||
for (let index = 0; index < samples.length; index += 1) {
|
||||
channel[index] = samples[index] / 32768;
|
||||
}
|
||||
const source = audioContext.createBufferSource();
|
||||
source.buffer = buffer;
|
||||
source.connect(audioGain);
|
||||
const startAt = Math.max(audioContext.currentTime, nextAudioTime);
|
||||
source.start(startAt);
|
||||
nextAudioTime = startAt + buffer.duration;
|
||||
}
|
||||
|
||||
function runFrame(timestamp: number) {
|
||||
if (!gameRunning.value || !runtime) return;
|
||||
const frameDuration = 1000 / (runtime.frameRate || PICO8_FRAME_RATE);
|
||||
const elapsed = Math.min(timestamp - lastFrameTime, 250);
|
||||
lastFrameTime = timestamp;
|
||||
frameAccumulator += elapsed;
|
||||
|
||||
let steps = 0;
|
||||
try {
|
||||
while (frameAccumulator >= frameDuration && steps < 3) {
|
||||
runtime.step(getInput());
|
||||
scheduleAudio(runtime.getAudioSamples());
|
||||
frameAccumulator -= frameDuration;
|
||||
steps += 1;
|
||||
}
|
||||
} catch (error) {
|
||||
showPlayError(error);
|
||||
return;
|
||||
}
|
||||
animationFrame = requestAnimationFrame(runFrame);
|
||||
}
|
||||
|
||||
function startLoop() {
|
||||
lastFrameTime = performance.now();
|
||||
frameAccumulator = 1000 / (runtime?.frameRate || PICO8_FRAME_RATE);
|
||||
animationFrame = requestAnimationFrame(runFrame);
|
||||
}
|
||||
|
||||
function closeAudio() {
|
||||
const context = audioContext;
|
||||
audioContext = null;
|
||||
audioGain = null;
|
||||
nextAudioTime = 0;
|
||||
if (context) void context.close().catch(() => {});
|
||||
}
|
||||
|
||||
function releaseGame() {
|
||||
cancelAnimationFrame(animationFrame);
|
||||
animationFrame = 0;
|
||||
runtime?.dispose();
|
||||
runtime = null;
|
||||
closeAudio();
|
||||
previousHeld = 0;
|
||||
keyboardMask = 0;
|
||||
mouseX = 0;
|
||||
mouseY = 0;
|
||||
mouseButtons = 0;
|
||||
touchMask.value = 0;
|
||||
playSession.flush();
|
||||
playingStore.setPlaying(false);
|
||||
gameRunning.value = false;
|
||||
loading.value = false;
|
||||
}
|
||||
|
||||
function showPlayError(error: unknown) {
|
||||
console.error("[PICO-8] Playback failed", error);
|
||||
snackbar.error(t("play.stream-error-generic"));
|
||||
releaseGame();
|
||||
}
|
||||
|
||||
async function onPlay() {
|
||||
const currentRom = rom.value;
|
||||
if (!currentRom || gameRunning.value) return;
|
||||
|
||||
gameRunning.value = true;
|
||||
loading.value = true;
|
||||
playingStore.setPlaying(true);
|
||||
await nextTick();
|
||||
|
||||
if (!viewAlive || !gameRunning.value) return;
|
||||
const canvasElement = canvas.value;
|
||||
if (!canvasElement) {
|
||||
showPlayError(new Error("PICO-8 canvas is unavailable"));
|
||||
return;
|
||||
}
|
||||
|
||||
let nextRuntime: Pico8Runtime | null = null;
|
||||
try {
|
||||
nextRuntime = await createPico8Runtime(canvasElement);
|
||||
if (!viewAlive || !gameRunning.value) {
|
||||
nextRuntime.dispose();
|
||||
nextRuntime = null;
|
||||
return;
|
||||
}
|
||||
const response = await fetch(getDownloadPath({ rom: currentRom }));
|
||||
if (!response.ok) throw new Error(`ROM request failed: ${response.status}`);
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
if (!viewAlive || !gameRunning.value) {
|
||||
nextRuntime.dispose();
|
||||
nextRuntime = null;
|
||||
return;
|
||||
}
|
||||
nextRuntime.loadCart(bytes);
|
||||
runtime = nextRuntime;
|
||||
nextRuntime = null;
|
||||
|
||||
try {
|
||||
audioContext = new AudioContext({
|
||||
sampleRate: runtime.audioSampleRate,
|
||||
});
|
||||
} catch {
|
||||
try {
|
||||
audioContext = new AudioContext();
|
||||
} catch {
|
||||
audioContext = null;
|
||||
}
|
||||
}
|
||||
if (audioContext) {
|
||||
audioGain = audioContext.createGain();
|
||||
audioGain.gain.value = 0.75;
|
||||
audioGain.connect(audioContext.destination);
|
||||
void audioContext.resume().catch(() => {});
|
||||
}
|
||||
|
||||
loading.value = false;
|
||||
playSession.start(currentRom);
|
||||
if (fullscreenOnPlay.value && stage.value?.requestFullscreen) {
|
||||
void stage.value.requestFullscreen().catch(() => {});
|
||||
}
|
||||
startLoop();
|
||||
} catch (error) {
|
||||
nextRuntime?.dispose();
|
||||
if (!viewAlive || !gameRunning.value) return;
|
||||
showPlayError(error);
|
||||
}
|
||||
}
|
||||
|
||||
function onlyQuit() {
|
||||
releaseGame();
|
||||
window.history.back();
|
||||
}
|
||||
|
||||
useEventListener(window, "keydown", onKeyDown);
|
||||
useEventListener(window, "keyup", onKeyUp);
|
||||
useEventListener(window, "blur", () => {
|
||||
keyboardMask = 0;
|
||||
mouseButtons = 0;
|
||||
touchMask.value = 0;
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
const romResponse = await romApi.getRom({ romId });
|
||||
if (!viewAlive) return;
|
||||
rom.value = romResponse.data;
|
||||
if (modality.value === "pad" || modality.value === "key") {
|
||||
await nextTick();
|
||||
if (!viewAlive) return;
|
||||
focusPlayButton();
|
||||
}
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
viewAlive = false;
|
||||
releaseGame();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<PlayerShell
|
||||
:hero-rom="heroRom"
|
||||
:title="title"
|
||||
:platform-label="platformLabel"
|
||||
:rom-id="romId"
|
||||
:ready="!!rom"
|
||||
:running="gameRunning"
|
||||
@play="onPlay"
|
||||
@quit="onlyQuit"
|
||||
>
|
||||
<template #settings>
|
||||
<RSwitch v-model="fullscreenOnPlay" :label="t('play.full-screen')" />
|
||||
</template>
|
||||
|
||||
<template #brand>
|
||||
<div class="r-v2-pico8__brand">
|
||||
<span>{{ t("play.powered-by") }}</span>
|
||||
<strong>PICO-8</strong>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #stage>
|
||||
<div ref="stage" class="r-v2-pico8__stage">
|
||||
<div class="r-v2-pico8__screen">
|
||||
<canvas
|
||||
ref="canvas"
|
||||
class="r-v2-pico8__canvas"
|
||||
width="128"
|
||||
height="128"
|
||||
aria-label="PICO-8 game"
|
||||
@pointermove="onCanvasPointerMove"
|
||||
@pointerdown="onCanvasPointerDown"
|
||||
@pointerup="onCanvasPointerUp"
|
||||
@pointercancel="onCanvasPointerCancel"
|
||||
@contextmenu.prevent
|
||||
/>
|
||||
<div v-if="loading" class="r-v2-pico8__loading">
|
||||
<RSpinner :size="32" :aria-label="t('common.loading')" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="r-v2-pico8__controls"
|
||||
role="group"
|
||||
aria-label="PICO-8 controls"
|
||||
>
|
||||
<div class="r-v2-pico8__dpad">
|
||||
<RBtn
|
||||
v-for="control in directionControls"
|
||||
:key="control.label"
|
||||
:icon="control.icon"
|
||||
variant="translucent"
|
||||
size="small"
|
||||
:class="[
|
||||
'r-v2-pico8__control',
|
||||
control.className,
|
||||
{
|
||||
'r-v2-pico8__control--held': touchMask & control.bit,
|
||||
},
|
||||
]"
|
||||
:aria-label="`PICO-8 ${control.label}`"
|
||||
:title="`PICO-8 ${control.label}`"
|
||||
@pointerdown.stop.prevent="
|
||||
onControlPointerDown(control.bit, $event)
|
||||
"
|
||||
@pointerup.stop="onControlPointerUp(control.bit, $event)"
|
||||
@pointercancel.stop="onControlPointerUp(control.bit, $event)"
|
||||
@lostpointercapture="onControlPointerUp(control.bit, $event)"
|
||||
@keydown.stop="onControlKeyDown(control.bit, $event)"
|
||||
@keyup.stop="onControlKeyUp(control.bit)"
|
||||
@blur.stop="onControlKeyUp(control.bit)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="r-v2-pico8__face-buttons">
|
||||
<RBtn
|
||||
v-for="control in faceControls"
|
||||
:key="control.label"
|
||||
size="large"
|
||||
:color="control.color"
|
||||
variant="translucent"
|
||||
class="r-v2-pico8__control"
|
||||
:class="{
|
||||
'r-v2-pico8__control--held': touchMask & control.bit,
|
||||
}"
|
||||
:aria-label="`PICO-8 ${control.label}`"
|
||||
:title="`PICO-8 ${control.label}`"
|
||||
@pointerdown.stop.prevent="
|
||||
onControlPointerDown(control.bit, $event)
|
||||
"
|
||||
@pointerup.stop="onControlPointerUp(control.bit, $event)"
|
||||
@pointercancel.stop="onControlPointerUp(control.bit, $event)"
|
||||
@lostpointercapture="onControlPointerUp(control.bit, $event)"
|
||||
@keydown.stop="onControlKeyDown(control.bit, $event)"
|
||||
@keyup.stop="onControlKeyUp(control.bit)"
|
||||
@blur.stop="onControlKeyUp(control.bit)"
|
||||
>
|
||||
{{ control.label }}
|
||||
</RBtn>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</PlayerShell>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.r-v2-pico8__stage {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
align-content: center;
|
||||
gap: 20px;
|
||||
overflow: auto;
|
||||
padding: 24px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.r-v2-pico8__stage:fullscreen {
|
||||
background: var(--r-color-canvas-bg);
|
||||
}
|
||||
|
||||
.r-v2-pico8__screen {
|
||||
position: relative;
|
||||
width: min(78vmin, 640px);
|
||||
aspect-ratio: 1;
|
||||
flex: 0 0 auto;
|
||||
background: #000;
|
||||
box-shadow: 0 18px 48px color-mix(in srgb, black 55%, transparent);
|
||||
}
|
||||
|
||||
.r-v2-pico8__canvas {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
image-rendering: pixelated;
|
||||
image-rendering: crisp-edges;
|
||||
touch-action: none;
|
||||
}
|
||||
|
||||
.r-v2-pico8__loading {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: color-mix(in srgb, black 45%, transparent);
|
||||
}
|
||||
|
||||
.r-v2-pico8__controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 32px;
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.r-v2-pico8__dpad {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 42px);
|
||||
grid-template-rows: repeat(3, 42px);
|
||||
align-items: center;
|
||||
justify-items: center;
|
||||
}
|
||||
|
||||
.r-v2-pico8__control {
|
||||
min-width: 42px;
|
||||
touch-action: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.r-v2-pico8__control--up {
|
||||
grid-column: 2;
|
||||
grid-row: 1;
|
||||
}
|
||||
|
||||
.r-v2-pico8__control--left {
|
||||
grid-column: 1;
|
||||
grid-row: 2;
|
||||
}
|
||||
|
||||
.r-v2-pico8__control--right {
|
||||
grid-column: 3;
|
||||
grid-row: 2;
|
||||
}
|
||||
|
||||
.r-v2-pico8__control--down {
|
||||
grid-column: 2;
|
||||
grid-row: 3;
|
||||
}
|
||||
|
||||
.r-v2-pico8__control--held {
|
||||
filter: brightness(1.35);
|
||||
}
|
||||
|
||||
.r-v2-pico8__face-buttons {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.r-v2-pico8__brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
color: var(--r-color-fg-faint);
|
||||
font-size: var(--r-font-size-xs);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.r-v2-pico8__brand strong {
|
||||
color: var(--r-color-fg-muted);
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
html[data-bp~="xs"] .r-v2-pico8__stage {
|
||||
gap: 12px;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
html[data-bp~="xs"] .r-v2-pico8__screen {
|
||||
width: min(78vmin, 420px);
|
||||
}
|
||||
|
||||
html[data-bp~="xs"] .r-v2-pico8__controls {
|
||||
gap: 16px;
|
||||
transform: scale(0.9);
|
||||
}
|
||||
</style>
|
||||
91
frontend/src/v2/views/Player/pico8Runtime.test.ts
Normal file
91
frontend/src/v2/views/Player/pico8Runtime.test.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createPico8Runtime, PICO8_HEIGHT, PICO8_WIDTH } from "./pico8Runtime";
|
||||
|
||||
const heap = new Uint8Array(new ArrayBuffer(64 * 1024));
|
||||
const context = {
|
||||
createImageData: vi.fn(() => ({
|
||||
data: new Uint8ClampedArray(PICO8_WIDTH * PICO8_HEIGHT * 4),
|
||||
})),
|
||||
imageSmoothingEnabled: true,
|
||||
putImageData: vi.fn(),
|
||||
};
|
||||
const fakeModule = {
|
||||
HEAPU8: heap,
|
||||
_f08_init: vi.fn(),
|
||||
_f08_load_cart_data: vi.fn(() => 0),
|
||||
_f08_step_frame: vi.fn(),
|
||||
_f08_get_framebuffer_ptr: vi.fn(() => 100),
|
||||
_f08_get_palette_rgba: vi.fn((pointer: number) => {
|
||||
heap[pointer + 4] = 1;
|
||||
heap[pointer + 5] = 2;
|
||||
heap[pointer + 6] = 3;
|
||||
heap[pointer + 8] = 4;
|
||||
heap[pointer + 9] = 5;
|
||||
heap[pointer + 10] = 6;
|
||||
}),
|
||||
_f08_get_target_fps: vi.fn(() => 30),
|
||||
_f08_get_last_error: vi.fn(() => 0),
|
||||
_f08_set_inputs: vi.fn(),
|
||||
_f08_fill_audio_buffer: vi.fn((pointer: number) => {
|
||||
new Int16Array(heap.buffer, pointer, 2).set([1000, -1000]);
|
||||
return 2;
|
||||
}),
|
||||
_f08_get_audio_sample_rate: vi.fn(() => 22050),
|
||||
_malloc: vi.fn(() => 200),
|
||||
_free: vi.fn(),
|
||||
UTF8ToString: vi.fn(() => ""),
|
||||
};
|
||||
|
||||
vi.mock("./scriptLoader", () => ({
|
||||
loadScript: vi.fn(async () => {
|
||||
window.Fake08Module = vi.fn(async () => fakeModule);
|
||||
}),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
heap[100] = 0x21;
|
||||
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(
|
||||
context as unknown as CanvasRenderingContext2D,
|
||||
);
|
||||
});
|
||||
|
||||
describe("createPico8Runtime", () => {
|
||||
it("loads cartridges, maps frames to pixels, and exposes audio", async () => {
|
||||
const runtime = await createPico8Runtime(document.createElement("canvas"));
|
||||
|
||||
runtime.loadCart(new Uint8Array([1, 2, 3]));
|
||||
runtime.step({
|
||||
keyDown: 0x10,
|
||||
keyHeld: 0x30,
|
||||
mouseX: 12,
|
||||
mouseY: 34,
|
||||
mouseButtons: 1,
|
||||
});
|
||||
|
||||
expect(fakeModule._f08_load_cart_data).toHaveBeenCalledWith(200, 3);
|
||||
expect(fakeModule._f08_set_inputs).toHaveBeenCalledWith(
|
||||
0x10,
|
||||
0x30,
|
||||
12,
|
||||
34,
|
||||
1,
|
||||
);
|
||||
expect(context.putImageData).toHaveBeenCalled();
|
||||
const image = context.putImageData.mock.calls[0][0] as ImageData;
|
||||
expect([...image.data.slice(0, 8)]).toEqual([1, 2, 3, 255, 4, 5, 6, 255]);
|
||||
expect([...runtime.getAudioSamples()]).toEqual([1000, -1000]);
|
||||
expect(runtime.frameRate).toBe(30);
|
||||
expect(runtime.audioSampleRate).toBe(22050);
|
||||
|
||||
runtime.dispose();
|
||||
runtime.step({
|
||||
keyDown: 0,
|
||||
keyHeld: 0,
|
||||
mouseX: 0,
|
||||
mouseY: 0,
|
||||
mouseButtons: 0,
|
||||
});
|
||||
expect(fakeModule._f08_step_frame).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
207
frontend/src/v2/views/Player/pico8Runtime.ts
Normal file
207
frontend/src/v2/views/Player/pico8Runtime.ts
Normal file
@@ -0,0 +1,207 @@
|
||||
import { loadScript } from "./scriptLoader";
|
||||
|
||||
export const PICO8_WIDTH = 128;
|
||||
export const PICO8_HEIGHT = 128;
|
||||
export const PICO8_FRAME_RATE = 30;
|
||||
|
||||
export const PICO8_INPUT_BITS = {
|
||||
left: 0x01,
|
||||
right: 0x02,
|
||||
up: 0x04,
|
||||
down: 0x08,
|
||||
a: 0x10,
|
||||
b: 0x20,
|
||||
} as const;
|
||||
|
||||
const PICO8_WASM_PATH = "/assets/pico8/fake08.wasm";
|
||||
const PICO8_SCRIPT_PATH = "/assets/pico8/fake08.js";
|
||||
const FRAMEBUFFER_BYTES = (PICO8_WIDTH * PICO8_HEIGHT) / 2;
|
||||
const PALETTE_BYTES = 16 * 4;
|
||||
|
||||
interface Fake08Module {
|
||||
HEAPU8: Uint8Array;
|
||||
_f08_init: () => void;
|
||||
_f08_load_cart_data: (pointer: number, length: number) => number;
|
||||
_f08_step_frame: () => void;
|
||||
_f08_get_framebuffer_ptr: () => number;
|
||||
_f08_get_palette_rgba: (pointer: number) => void;
|
||||
_f08_get_target_fps: () => number;
|
||||
_f08_get_last_error: () => number;
|
||||
_f08_set_inputs: (
|
||||
keyDown: number,
|
||||
keyHeld: number,
|
||||
mouseX: number,
|
||||
mouseY: number,
|
||||
mouseButtons: number,
|
||||
) => void;
|
||||
_f08_fill_audio_buffer: (pointer: number, maxSamples: number) => number;
|
||||
_f08_get_audio_sample_rate: () => number;
|
||||
_malloc: (size: number) => number;
|
||||
_free: (pointer: number) => void;
|
||||
UTF8ToString: (pointer: number) => string;
|
||||
}
|
||||
|
||||
type Fake08Factory = (options: {
|
||||
locateFile: (path: string) => string;
|
||||
}) => Promise<Fake08Module>;
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
Fake08Module?: Fake08Factory;
|
||||
}
|
||||
}
|
||||
|
||||
let scriptPromise: Promise<void> | null = null;
|
||||
|
||||
function loadPico8Script(): Promise<void> {
|
||||
if (window.Fake08Module) return Promise.resolve();
|
||||
scriptPromise ??= loadScript(PICO8_SCRIPT_PATH).catch((error) => {
|
||||
scriptPromise = null;
|
||||
throw error;
|
||||
});
|
||||
return scriptPromise;
|
||||
}
|
||||
|
||||
function lastRuntimeError(module: Fake08Module): string | null {
|
||||
const pointer = module._f08_get_last_error();
|
||||
if (!pointer) return null;
|
||||
const message = module.UTF8ToString(pointer);
|
||||
module._free(pointer);
|
||||
return message || null;
|
||||
}
|
||||
|
||||
export interface Pico8Input {
|
||||
keyDown: number;
|
||||
keyHeld: number;
|
||||
mouseX: number;
|
||||
mouseY: number;
|
||||
mouseButtons: number;
|
||||
}
|
||||
|
||||
export interface Pico8Runtime {
|
||||
readonly frameRate: number;
|
||||
readonly audioSampleRate: number;
|
||||
loadCart: (bytes: Uint8Array) => void;
|
||||
step: (input: Pico8Input) => void;
|
||||
getAudioSamples: () => Int16Array;
|
||||
dispose: () => void;
|
||||
}
|
||||
|
||||
export async function createPico8Runtime(
|
||||
canvas: HTMLCanvasElement,
|
||||
): Promise<Pico8Runtime> {
|
||||
await loadPico8Script();
|
||||
const factory = window.Fake08Module;
|
||||
if (!factory) throw new Error("PICO-8 runtime is unavailable");
|
||||
|
||||
const module = await factory({
|
||||
locateFile: (path) => (path.endsWith(".wasm") ? PICO8_WASM_PATH : path),
|
||||
});
|
||||
const context = canvas.getContext("2d", { alpha: false });
|
||||
if (!context) throw new Error("PICO-8 needs a 2D canvas");
|
||||
const renderContext = context;
|
||||
|
||||
canvas.width = PICO8_WIDTH;
|
||||
canvas.height = PICO8_HEIGHT;
|
||||
renderContext.imageSmoothingEnabled = false;
|
||||
module._f08_init();
|
||||
|
||||
const framebufferPointer = module._f08_get_framebuffer_ptr();
|
||||
if (!framebufferPointer) throw new Error("PICO-8 framebuffer is unavailable");
|
||||
|
||||
const palettePointer = module._malloc(PALETTE_BYTES);
|
||||
const samplesPerFrame = Math.ceil(
|
||||
module._f08_get_audio_sample_rate() / PICO8_FRAME_RATE,
|
||||
);
|
||||
const audioPointer = module._malloc(samplesPerFrame * 2);
|
||||
const imageData = renderContext.createImageData(PICO8_WIDTH, PICO8_HEIGHT);
|
||||
let disposed = false;
|
||||
|
||||
function render() {
|
||||
module._f08_get_palette_rgba(palettePointer);
|
||||
const palette = new Uint8Array(
|
||||
module.HEAPU8.buffer,
|
||||
palettePointer,
|
||||
PALETTE_BYTES,
|
||||
);
|
||||
const framebuffer = new Uint8Array(
|
||||
module.HEAPU8.buffer,
|
||||
framebufferPointer,
|
||||
FRAMEBUFFER_BYTES,
|
||||
);
|
||||
|
||||
for (let index = 0; index < FRAMEBUFFER_BYTES; index += 1) {
|
||||
const packed = framebuffer[index];
|
||||
const firstPixel = index * 2;
|
||||
const secondPixel = firstPixel + 1;
|
||||
const firstColor = (packed & 0x0f) * 4;
|
||||
const secondColor = (packed >> 4) * 4;
|
||||
const firstTarget = firstPixel * 4;
|
||||
const secondTarget = secondPixel * 4;
|
||||
imageData.data[firstTarget] = palette[firstColor];
|
||||
imageData.data[firstTarget + 1] = palette[firstColor + 1];
|
||||
imageData.data[firstTarget + 2] = palette[firstColor + 2];
|
||||
imageData.data[firstTarget + 3] = 255;
|
||||
imageData.data[secondTarget] = palette[secondColor];
|
||||
imageData.data[secondTarget + 1] = palette[secondColor + 1];
|
||||
imageData.data[secondTarget + 2] = palette[secondColor + 2];
|
||||
imageData.data[secondTarget + 3] = 255;
|
||||
}
|
||||
renderContext.putImageData(imageData, 0, 0);
|
||||
}
|
||||
|
||||
function loadCart(bytes: Uint8Array) {
|
||||
const pointer = module._malloc(bytes.byteLength);
|
||||
try {
|
||||
module.HEAPU8.set(bytes, pointer);
|
||||
const result = module._f08_load_cart_data(pointer, bytes.byteLength);
|
||||
if (result !== 0) {
|
||||
throw new Error(
|
||||
lastRuntimeError(module) ??
|
||||
"The PICO-8 cartridge could not be loaded",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
module._free(pointer);
|
||||
}
|
||||
}
|
||||
|
||||
function step(input: Pico8Input) {
|
||||
if (disposed) return;
|
||||
module._f08_set_inputs(
|
||||
input.keyDown,
|
||||
input.keyHeld,
|
||||
input.mouseX,
|
||||
input.mouseY,
|
||||
input.mouseButtons,
|
||||
);
|
||||
module._f08_step_frame();
|
||||
render();
|
||||
}
|
||||
|
||||
function getAudioSamples() {
|
||||
if (disposed) return new Int16Array();
|
||||
const written = module._f08_fill_audio_buffer(
|
||||
audioPointer,
|
||||
samplesPerFrame,
|
||||
);
|
||||
if (written <= 0) return new Int16Array();
|
||||
return new Int16Array(module.HEAPU8.buffer, audioPointer, written).slice();
|
||||
}
|
||||
|
||||
function dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
module._free(palettePointer);
|
||||
module._free(audioPointer);
|
||||
}
|
||||
|
||||
return {
|
||||
frameRate: module._f08_get_target_fps() || PICO8_FRAME_RATE,
|
||||
audioSampleRate: module._f08_get_audio_sample_rate(),
|
||||
loadCart,
|
||||
step,
|
||||
getAudioSamples,
|
||||
dispose,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user