From 6b73bad8f067274b9c34534ad7744de376319664 Mon Sep 17 00:00:00 2001
From: S-Coding23 <>
Date: Fri, 2 Jan 2026 08:44:02 -0700
Subject: [PATCH] Fix netplay audio and video shift in emulator.js
---
data/src/emulator.js | 7697 ++++++++++++++++++++++++++++++------------
1 file changed, 5468 insertions(+), 2229 deletions(-)
diff --git a/data/src/emulator.js b/data/src/emulator.js
index 9ff2ab2..d29886a 100644
--- a/data/src/emulator.js
+++ b/data/src/emulator.js
@@ -1,42 +1,52 @@
class EmulatorJS {
getCores() {
let rv = {
- "atari5200": ["a5200"],
- "vb": ["beetle_vb"],
- "nds": ["melonds", "desmume", "desmume2015"],
- "arcade": ["fbneo", "fbalpha2012_cps1", "fbalpha2012_cps2", "same_cdi"],
- "nes": ["fceumm", "nestopia"],
- "gb": ["gambatte"],
- "coleco": ["gearcoleco"],
- "segaMS": ["smsplus", "genesis_plus_gx", "genesis_plus_gx_wide", "picodrive"],
- "segaMD": ["genesis_plus_gx", "genesis_plus_gx_wide", "picodrive"],
- "segaGG": ["genesis_plus_gx", "genesis_plus_gx_wide"],
- "segaCD": ["genesis_plus_gx", "genesis_plus_gx_wide", "picodrive"],
- "sega32x": ["picodrive"],
- "sega": ["genesis_plus_gx", "genesis_plus_gx_wide", "picodrive"],
- "lynx": ["handy"],
- "mame": ["mame2003_plus", "mame2003"],
- "ngp": ["mednafen_ngp"],
- "pce": ["mednafen_pce"],
- "pcfx": ["mednafen_pcfx"],
- "psx": ["pcsx_rearmed", "mednafen_psx_hw"],
- "ws": ["mednafen_wswan"],
- "gba": ["mgba"],
- "n64": ["mupen64plus_next", "parallel_n64"],
+ atari5200: ["a5200"],
+ vb: ["beetle_vb"],
+ nds: ["melonds", "desmume", "desmume2015"],
+ arcade: [
+ "fbneo",
+ "fbalpha2012_cps1",
+ "fbalpha2012_cps2",
+ "same_cdi",
+ ],
+ nes: ["fceumm", "nestopia"],
+ gb: ["gambatte"],
+ coleco: ["gearcoleco"],
+ segaMS: [
+ "smsplus",
+ "genesis_plus_gx",
+ "genesis_plus_gx_wide",
+ "picodrive",
+ ],
+ segaMD: ["genesis_plus_gx", "genesis_plus_gx_wide", "picodrive"],
+ segaGG: ["genesis_plus_gx", "genesis_plus_gx_wide"],
+ segaCD: ["genesis_plus_gx", "genesis_plus_gx_wide", "picodrive"],
+ sega32x: ["picodrive"],
+ sega: ["genesis_plus_gx", "genesis_plus_gx_wide", "picodrive"],
+ lynx: ["handy"],
+ mame: ["mame2003_plus", "mame2003"],
+ ngp: ["mednafen_ngp"],
+ pce: ["mednafen_pce"],
+ pcfx: ["mednafen_pcfx"],
+ psx: ["pcsx_rearmed", "mednafen_psx_hw"],
+ ws: ["mednafen_wswan"],
+ gba: ["mgba"],
+ n64: ["parallel_n64", "mupen64plus_next"],
"3do": ["opera"],
- "psp": ["ppsspp"],
- "atari7800": ["prosystem"],
- "snes": ["snes9x", "bsnes"],
- "atari2600": ["stella2014"],
- "jaguar": ["virtualjaguar"],
- "segaSaturn": ["yabause"],
- "amiga": ["puae"],
- "c64": ["vice_x64sc"],
- "c128": ["vice_x128"],
- "pet": ["vice_xpet"],
- "plus4": ["vice_xplus4"],
- "vic20": ["vice_xvic"],
- "dos": ["dosbox_pure"]
+ psp: ["ppsspp"],
+ atari7800: ["prosystem"],
+ snes: ["snes9x", "bsnes"],
+ atari2600: ["stella2014"],
+ jaguar: ["virtualjaguar"],
+ segaSaturn: ["yabause"],
+ amiga: ["puae"],
+ c64: ["vice_x64sc"],
+ c128: ["vice_x128"],
+ pet: ["vice_xpet"],
+ plus4: ["vice_xplus4"],
+ vic20: ["vice_xvic"],
+ dos: ["dosbox_pure"],
};
if (this.isSafari && this.isMobile) {
rv.n64 = rv.n64.reverse();
@@ -63,7 +73,10 @@ class EmulatorJS {
return core;
}
const gen = this.getCore(true);
- if (cores[gen] && cores[gen].includes(this.preGetSetting("retroarch_core"))) {
+ if (
+ cores[gen] &&
+ cores[gen].includes(this.preGetSetting("retroarch_core"))
+ ) {
return this.preGetSetting("retroarch_core");
}
if (cores[core]) {
@@ -79,7 +92,11 @@ class EmulatorJS {
let rv = [];
for (let i = 0; i < listeners.length; i++) {
element.addEventListener(listeners[i], callback);
- const data = { cb: callback, elem: element, listener: listeners[i] };
+ const data = {
+ cb: callback,
+ elem: element,
+ listener: listeners[i],
+ };
rv.push(data);
}
return rv;
@@ -90,7 +107,7 @@ class EmulatorJS {
}
}
downloadFile(path, progressCB, notWithPath, opts) {
- return new Promise(async cb => {
+ return new Promise(async (cb) => {
const data = this.toData(path); //check other data types
if (data) {
data.then((game) => {
@@ -99,16 +116,22 @@ class EmulatorJS {
} else {
cb({ headers: {}, data: game });
}
- })
+ });
return;
}
const basePath = notWithPath ? "" : this.config.dataPath;
path = basePath + path;
- if (!notWithPath && this.config.filePaths && typeof this.config.filePaths[path.split("/").pop()] === "string") {
+ if (
+ !notWithPath &&
+ this.config.filePaths &&
+ typeof this.config.filePaths[path.split("/").pop()] === "string"
+ ) {
path = this.config.filePaths[path.split("/").pop()];
}
let url;
- try { url = new URL(path) } catch(e) {};
+ try {
+ url = new URL(path);
+ } catch (e) {}
if (url && !["http:", "https:"].includes(url.protocol)) {
//Most commonly blob: urls. Not sure what else it could be
if (opts.method === "HEAD") {
@@ -116,16 +139,22 @@ class EmulatorJS {
return;
}
try {
- let res = await fetch(path)
- if ((opts.type && opts.type.toLowerCase() === "arraybuffer") || !opts.type) {
+ let res = await fetch(path);
+ if (
+ (opts.type &&
+ opts.type.toLowerCase() === "arraybuffer") ||
+ !opts.type
+ ) {
res = await res.arrayBuffer();
} else {
res = await res.text();
- try { res = JSON.parse(res) } catch(e) {}
+ try {
+ res = JSON.parse(res);
+ } catch (e) {}
}
if (path.startsWith("blob:")) URL.revokeObjectURL(path);
cb({ data: res, headers: {} });
- } catch(e) {
+ } catch (e) {
cb(-1);
}
return;
@@ -133,34 +162,49 @@ class EmulatorJS {
const xhr = new XMLHttpRequest();
if (progressCB instanceof Function) {
xhr.addEventListener("progress", (e) => {
- const progress = e.total ? " " + Math.floor(e.loaded / e.total * 100).toString() + "%" : " " + (e.loaded / 1048576).toFixed(2) + "MB";
+ const progress = e.total
+ ? " " +
+ Math.floor((e.loaded / e.total) * 100).toString() +
+ "%"
+ : " " + (e.loaded / 1048576).toFixed(2) + "MB";
progressCB(progress);
});
}
- xhr.onload = function() {
+ xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
let data = xhr.response;
- if (xhr.status.toString().startsWith("4") || xhr.status.toString().startsWith("5")) {
+ if (
+ xhr.status.toString().startsWith("4") ||
+ xhr.status.toString().startsWith("5")
+ ) {
cb(-1);
return;
}
- try { data = JSON.parse(data) } catch(e) {}
+ try {
+ data = JSON.parse(data);
+ } catch (e) {}
cb({
data: data,
headers: {
- "content-length": xhr.getResponseHeader("content-length")
- }
+ "content-length":
+ xhr.getResponseHeader("content-length"),
+ },
});
}
- }
+ };
if (opts.responseType) xhr.responseType = opts.responseType;
xhr.onerror = () => cb(-1);
xhr.open(opts.method, path, true);
xhr.send();
- })
+ });
}
toData(data, rv) {
- if (!(data instanceof ArrayBuffer) && !(data instanceof Uint8Array) && !(data instanceof Blob)) return null;
+ if (
+ !(data instanceof ArrayBuffer) &&
+ !(data instanceof Uint8Array) &&
+ !(data instanceof Blob)
+ )
+ return null;
if (rv) return true;
return new Promise(async (resolve) => {
if (data instanceof ArrayBuffer) {
@@ -171,23 +215,32 @@ class EmulatorJS {
resolve(new Uint8Array(await data.arrayBuffer()));
}
resolve();
- })
+ });
}
checkForUpdates() {
if (this.ejs_version.endsWith("-beta")) {
- console.warn("Using EmulatorJS beta. Not checking for updates. This instance may be out of date. Using stable is highly recommended unless you build and ship your own cores.");
+ console.warn(
+ "Using EmulatorJS beta. Not checking for updates. This instance may be out of date. Using stable is highly recommended unless you build and ship your own cores."
+ );
return;
}
- fetch("https://cdn.emulatorjs.org/stable/data/version.json").then(response => {
- if (response.ok) {
- response.text().then(body => {
- let version = JSON.parse(body);
- if (this.versionAsInt(this.ejs_version) < this.versionAsInt(version.version)) {
- console.log(`Using EmulatorJS version ${this.ejs_version} but the newest version is ${version.current_version}\nopen https://github.com/EmulatorJS/EmulatorJS to update`);
- }
- })
+ fetch("https://cdn.emulatorjs.org/stable/data/version.json").then(
+ (response) => {
+ if (response.ok) {
+ response.text().then((body) => {
+ let version = JSON.parse(body);
+ if (
+ this.versionAsInt(this.ejs_version) <
+ this.versionAsInt(version.version)
+ ) {
+ console.log(
+ `Using EmulatorJS version ${this.ejs_version} but the newest version is ${version.current_version}\nopen https://github.com/EmulatorJS/EmulatorJS to update`
+ );
+ }
+ });
+ }
}
- })
+ );
}
versionAsInt(ver) {
if (ver.endsWith("-beta")) {
@@ -204,25 +257,35 @@ class EmulatorJS {
this.extensions = [];
this.allSettings = {};
this.initControlVars();
- this.debug = (window.EJS_DEBUG_XX === true);
- if (this.debug || (window.location && ["localhost", "127.0.0.1"].includes(location.hostname))) {
+ this.debug = window.EJS_DEBUG_XX === true;
+ if (
+ this.debug ||
+ (window.location &&
+ ["localhost", "127.0.0.1"].includes(location.hostname))
+ ) {
this.checkForUpdates();
}
this.netplayEnabled = true;
this.config = config;
- this.config.buttonOpts = this.buildButtonOptions(this.config.buttonOpts);
+ this.config.buttonOpts = this.buildButtonOptions(
+ this.config.buttonOpts
+ );
this.config.settingsLanguage = window.EJS_settingsLanguage || false;
switch (this.config.browserMode) {
case 1: // Force mobile
case "1":
case "mobile":
- if (this.debug) { console.log("Force mobile mode is enabled"); }
+ if (this.debug) {
+ console.log("Force mobile mode is enabled");
+ }
this.config.browserMode = 1;
break;
case 2: // Force desktop
case "2":
case "desktop":
- if (this.debug) { console.log("Force desktop mode is enabled"); }
+ if (this.debug) {
+ console.log("Force desktop mode is enabled");
+ }
this.config.browserMode = 2;
break;
default: // Auto detect
@@ -236,18 +299,32 @@ class EmulatorJS {
this.touch = false;
this.cheats = [];
this.started = false;
- this.volume = (typeof this.config.volume === "number") ? this.config.volume : 0.5;
- if (this.config.defaultControllers) this.defaultControllers = this.config.defaultControllers;
+ this.volume =
+ typeof this.config.volume === "number" ? this.config.volume : 0.5;
+ if (this.config.defaultControllers)
+ this.defaultControllers = this.config.defaultControllers;
this.muted = false;
this.paused = true;
this.missingLang = [];
this.setElements(element);
this.setColor(this.config.color || "");
- this.config.alignStartButton = (typeof this.config.alignStartButton === "string") ? this.config.alignStartButton : "bottom";
- this.config.backgroundColor = (typeof this.config.backgroundColor === "string") ? this.config.backgroundColor : "rgb(51, 51, 51)";
+ this.config.alignStartButton =
+ typeof this.config.alignStartButton === "string"
+ ? this.config.alignStartButton
+ : "bottom";
+ this.config.backgroundColor =
+ typeof this.config.backgroundColor === "string"
+ ? this.config.backgroundColor
+ : "rgb(51, 51, 51)";
if (this.config.adUrl) {
- this.config.adSize = (Array.isArray(this.config.adSize)) ? this.config.adSize : ["300px", "250px"];
- this.setupAds(this.config.adUrl, this.config.adSize[0], this.config.adSize[1]);
+ this.config.adSize = Array.isArray(this.config.adSize)
+ ? this.config.adSize
+ : ["300px", "250px"];
+ this.setupAds(
+ this.config.adUrl,
+ this.config.adSize[0],
+ this.config.adSize[1]
+ );
}
this.isMobile = (() => {
// browserMode can be either a 1 (force mobile), 2 (force desktop) or undefined (auto detect)
@@ -259,18 +336,31 @@ class EmulatorJS {
}
let check = false;
- (function (a) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true; })(navigator.userAgent || navigator.vendor || window.opera);
+ (function (a) {
+ if (
+ /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(
+ a
+ ) ||
+ /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(
+ a.substr(0, 4)
+ )
+ )
+ check = true;
+ })(navigator.userAgent || navigator.vendor || window.opera);
return check;
})();
- this.hasTouchScreen = (function() {
- if (window.PointerEvent && ("maxTouchPoints" in navigator)) {
+ this.hasTouchScreen = (function () {
+ if (window.PointerEvent && "maxTouchPoints" in navigator) {
if (navigator.maxTouchPoints > 0) {
return true;
}
} else {
- if (window.matchMedia && window.matchMedia("(any-pointer:coarse)").matches) {
+ if (
+ window.matchMedia &&
+ window.matchMedia("(any-pointer:coarse)").matches
+ ) {
return true;
- } else if (window.TouchEvent || ("ontouchstart" in window)) {
+ } else if (window.TouchEvent || "ontouchstart" in window) {
return true;
}
}
@@ -278,34 +368,69 @@ class EmulatorJS {
})();
this.canvas = this.createElement("canvas");
this.canvas.classList.add("ejs_canvas");
- this.videoRotation = ([0, 1, 2, 3].includes(this.config.videoRotation)) ? this.config.videoRotation : this.preGetSetting("videoRotation") || 0;
+ this.videoRotation = [0, 1, 2, 3].includes(this.config.videoRotation)
+ ? this.config.videoRotation
+ : this.preGetSetting("videoRotation") || 0;
this.videoRotationChanged = false;
this.capture = this.capture || {};
this.capture.photo = this.capture.photo || {};
- this.capture.photo.source = ["canvas", "retroarch"].includes(this.capture.photo.source) ? this.capture.photo.source : "canvas";
- this.capture.photo.format = (typeof this.capture.photo.format === "string") ? this.capture.photo.format : "png";
- this.capture.photo.upscale = (typeof this.capture.photo.upscale === "number") ? this.capture.photo.upscale : 1;
+ this.capture.photo.source = ["canvas", "retroarch"].includes(
+ this.capture.photo.source
+ )
+ ? this.capture.photo.source
+ : "canvas";
+ this.capture.photo.format =
+ typeof this.capture.photo.format === "string"
+ ? this.capture.photo.format
+ : "png";
+ this.capture.photo.upscale =
+ typeof this.capture.photo.upscale === "number"
+ ? this.capture.photo.upscale
+ : 1;
this.capture.video = this.capture.video || {};
- this.capture.video.format = (typeof this.capture.video.format === "string") ? this.capture.video.format : "detect";
- this.capture.video.upscale = (typeof this.capture.video.upscale === "number") ? this.capture.video.upscale : 1;
- this.capture.video.fps = (typeof this.capture.video.fps === "number") ? this.capture.video.fps : 30;
- this.capture.video.videoBitrate = (typeof this.capture.video.videoBitrate === "number") ? this.capture.video.videoBitrate : 2.5 * 1024 * 1024;
- this.capture.video.audioBitrate = (typeof this.capture.video.audioBitrate === "number") ? this.capture.video.audioBitrate : 192 * 1024;
+ this.capture.video.format =
+ typeof this.capture.video.format === "string"
+ ? this.capture.video.format
+ : "detect";
+ this.capture.video.upscale =
+ typeof this.capture.video.upscale === "number"
+ ? this.capture.video.upscale
+ : 1;
+ this.capture.video.fps =
+ typeof this.capture.video.fps === "number"
+ ? this.capture.video.fps
+ : 30;
+ this.capture.video.videoBitrate =
+ typeof this.capture.video.videoBitrate === "number"
+ ? this.capture.video.videoBitrate
+ : 2.5 * 1024 * 1024;
+ this.capture.video.audioBitrate =
+ typeof this.capture.video.audioBitrate === "number"
+ ? this.capture.video.audioBitrate
+ : 192 * 1024;
this.bindListeners();
// Additions for Netplay
- this.netplayCanvas = null;
+ this.netplayCanvas = null;
this.netplayShowTurnWarning = false;
this.netplayWarningShown = false;
if (this.netplayEnabled) {
- const iceServers = this.config.netplayICEServers || window.EJS_netplayICEServers || [];
- const hasTurnServer = iceServers.some(server =>
- server && typeof server.urls === 'string' && server.urls.startsWith('turn:')
+ const iceServers =
+ this.config.netplayICEServers ||
+ window.EJS_netplayICEServers ||
+ [];
+ const hasTurnServer = iceServers.some(
+ (server) =>
+ server &&
+ typeof server.urls === "string" &&
+ server.urls.startsWith("turn:")
);
if (!hasTurnServer) {
this.netplayShowTurnWarning = true;
}
if (this.netplayShowTurnWarning && this.debug) {
- console.warn("WARNING: No TURN addresses are configured! Many clients may fail to connect!");
+ console.warn(
+ "WARNING: No TURN addresses are configured! Many clients may fail to connect!"
+ );
}
}
@@ -316,7 +441,9 @@ class EmulatorJS {
this.fullscreen = false;
this.enableMouseLock = false;
- this.supportsWebgl2 = !!document.createElement("canvas").getContext("webgl2") && (this.config.forceLegacyCores !== true);
+ this.supportsWebgl2 =
+ !!document.createElement("canvas").getContext("webgl2") &&
+ this.config.forceLegacyCores !== true;
this.webgl2Enabled = (() => {
let setting = this.preGetSetting("webgl2Enabled");
if (setting === "disabled" || !this.supportsWebgl2) {
@@ -326,34 +453,47 @@ class EmulatorJS {
}
return null;
})();
- this.isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
+ this.isSafari = /^((?!chrome|android).)*safari/i.test(
+ navigator.userAgent
+ );
if (this.config.disableDatabases) {
this.storage = {
rom: new window.EJS_DUMMYSTORAGE(),
bios: new window.EJS_DUMMYSTORAGE(),
- core: new window.EJS_DUMMYSTORAGE()
- }
+ core: new window.EJS_DUMMYSTORAGE(),
+ };
} else {
this.storage = {
rom: new window.EJS_STORAGE("EmulatorJS-roms", "rom"),
bios: new window.EJS_STORAGE("EmulatorJS-bios", "bios"),
- core: new window.EJS_STORAGE("EmulatorJS-core", "core")
- }
+ core: new window.EJS_STORAGE("EmulatorJS-core", "core"),
+ };
}
// This is not cache. This is save data
- this.storage.states = new window.EJS_STORAGE("EmulatorJS-states", "states");
+ this.storage.states = new window.EJS_STORAGE(
+ "EmulatorJS-states",
+ "states"
+ );
this.game.classList.add("ejs_game");
if (typeof this.config.backgroundImg === "string") {
this.game.classList.add("ejs_game_background");
- if (this.config.backgroundBlur) this.game.classList.add("ejs_game_background_blur");
- this.game.setAttribute("style", `--ejs-background-image: url("${this.config.backgroundImg}"); --ejs-background-color: ${this.config.backgroundColor};`);
+ if (this.config.backgroundBlur)
+ this.game.classList.add("ejs_game_background_blur");
+ this.game.setAttribute(
+ "style",
+ `--ejs-background-image: url("${this.config.backgroundImg}"); --ejs-background-color: ${this.config.backgroundColor};`
+ );
this.on("start", () => {
this.game.classList.remove("ejs_game_background");
- if (this.config.backgroundBlur) this.game.classList.remove("ejs_game_background_blur");
- })
+ if (this.config.backgroundBlur)
+ this.game.classList.remove("ejs_game_background_blur");
+ });
} else {
- this.game.setAttribute("style", "--ejs-background-color: " + this.config.backgroundColor + ";");
+ this.game.setAttribute(
+ "style",
+ "--ejs-background-color: " + this.config.backgroundColor + ";"
+ );
}
if (Array.isArray(this.config.cheats)) {
@@ -364,8 +504,8 @@ class EmulatorJS {
desc: cheat[0],
checked: false,
code: cheat[1],
- is_permanent: true
- })
+ is_permanent: true,
+ });
}
}
}
@@ -394,7 +534,7 @@ class EmulatorJS {
setColor(color) {
if (typeof color !== "string") color = "";
- let getColor = function(color) {
+ let getColor = function (color) {
color = color.toLowerCase();
if (color && /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(color)) {
if (color.length === 4) {
@@ -411,16 +551,27 @@ class EmulatorJS {
return rv.join(", ");
}
return null;
- }
+ };
if (!color || getColor(color) === null) {
- this.elements.parent.setAttribute("style", "--ejs-primary-color: 26,175,255;");
+ this.elements.parent.setAttribute(
+ "style",
+ "--ejs-primary-color: 26,175,255;"
+ );
return;
}
- this.elements.parent.setAttribute("style", "--ejs-primary-color:" + getColor(color) + ";");
+ this.elements.parent.setAttribute(
+ "style",
+ "--ejs-primary-color:" + getColor(color) + ";"
+ );
}
setupAds(ads, width, height) {
const div = this.createElement("div");
- const time = (typeof this.config.adMode === "number" && this.config.adMode > -1 && this.config.adMode < 3) ? this.config.adMode : 2;
+ const time =
+ typeof this.config.adMode === "number" &&
+ this.config.adMode > -1 &&
+ this.config.adMode < 3
+ ? this.config.adMode
+ : 2;
div.classList.add("ejs_ad_iframe");
const frame = this.createElement("iframe");
frame.src = ads;
@@ -440,25 +591,28 @@ class EmulatorJS {
}
this.addEventListener(closeButton, "click", () => {
div.remove();
- })
+ });
this.on("start-clicked", () => {
if (this.config.adMode === 0) div.remove();
if (this.config.adMode === 1) {
this.elements.parent.appendChild(div);
}
- })
+ });
this.on("start", () => {
closeParent.removeAttribute("hidden");
- const time = (typeof this.config.adTimer === "number" && this.config.adTimer > 0) ? this.config.adTimer : 10000;
+ const time =
+ typeof this.config.adTimer === "number" &&
+ this.config.adTimer > 0
+ ? this.config.adTimer
+ : 10000;
if (this.config.adTimer === -1) div.remove();
if (this.config.adTimer === 0) return;
setTimeout(() => {
div.remove();
}, time);
- })
-
+ });
}
adBlocked(url, del) {
if (del) {
@@ -466,9 +620,13 @@ class EmulatorJS {
} else {
try {
document.querySelector('div[class="ejs_ad_iframe"]').remove();
- } catch(e) {}
+ } catch (e) {}
this.config.adUrl = url;
- this.setupAds(this.config.adUrl, this.config.adSize[0], this.config.adSize[1]);
+ this.setupAds(
+ this.config.adUrl,
+ this.config.adSize[0],
+ this.config.adSize[1]
+ );
}
}
on(event, func) {
@@ -479,7 +637,7 @@ class EmulatorJS {
callEvent(event, data) {
if (!this.functions) this.functions = {};
if (!Array.isArray(this.functions[event])) return 0;
- this.functions[event].forEach(e => e(data));
+ this.functions[event].forEach((e) => e(data));
return this.functions[event].length;
}
setElements(element) {
@@ -491,8 +649,8 @@ class EmulatorJS {
this.elements = {
main: this.game,
- parent: elem
- }
+ parent: elem,
+ };
this.elements.parent.classList.add("ejs_parent");
this.elements.parent.setAttribute("tabindex", -1);
}
@@ -505,7 +663,10 @@ class EmulatorJS {
button.classList.add("ejs_start_button_border");
border = 1;
}
- button.innerText = (typeof this.config.startBtnName === "string") ? this.config.startBtnName : this.localization("Start Game");
+ button.innerText =
+ typeof this.config.startBtnName === "string"
+ ? this.config.startBtnName
+ : this.localization("Start Game");
if (this.config.alignStartButton == "top") {
button.style.bottom = "calc(100% - 20px)";
} else if (this.config.alignStartButton == "center") {
@@ -514,8 +675,12 @@ class EmulatorJS {
this.elements.parent.appendChild(button);
this.addEventListener(button, "touchstart", () => {
this.touch = true;
- })
- this.addEventListener(button, "click", this.startButtonClicked.bind(this));
+ });
+ this.addEventListener(
+ button,
+ "click",
+ this.startButtonClicked.bind(this)
+ );
if (this.config.startOnLoad === true) {
this.startButtonClicked(button);
}
@@ -541,7 +706,8 @@ class EmulatorJS {
createText() {
this.textElem = this.createElement("div");
this.textElem.classList.add("ejs_loading_text");
- if (typeof this.config.backgroundImg === "string") this.textElem.classList.add("ejs_loading_text_glow");
+ if (typeof this.config.backgroundImg === "string")
+ this.textElem.classList.add("ejs_loading_text_glow");
this.textElem.innerText = this.localization("Loading...");
this.elements.parent.appendChild(this.textElem);
}
@@ -552,8 +718,12 @@ class EmulatorJS {
if (this.config.langJson) {
if (typeof log === "undefined") log = true;
if (!this.config.langJson[text] && log) {
- if (!this.missingLang.includes(text)) this.missingLang.push(text);
- if (this.debug) console.log(`Translation not found for '${text}'. Language set to '${this.config.language}'`);
+ if (!this.missingLang.includes(text))
+ this.missingLang.push(text);
+ if (this.debug)
+ console.log(
+ `Translation not found for '${text}'. Language set to '${this.config.language}'`
+ );
}
return this.config.langJson[text] || text;
}
@@ -566,14 +736,26 @@ class EmulatorJS {
if (msg) {
this.textElem.innerText = msg;
}
- return this.compression.decompress(data, (m, appendMsg) => {
- this.textElem.innerText = appendMsg ? (msg + m) : m;
- }, fileCbFunc);
+ return this.compression.decompress(
+ data,
+ (m, appendMsg) => {
+ this.textElem.innerText = appendMsg ? msg + m : m;
+ },
+ fileCbFunc
+ );
}
checkCoreCompatibility(version) {
- if (this.versionAsInt(version.minimumEJSVersion) > this.versionAsInt(this.ejs_version)) {
- this.startGameError(this.localization("Outdated EmulatorJS version"));
- throw new Error("Core requires minimum EmulatorJS version of " + version.minimumEJSVersion);
+ if (
+ this.versionAsInt(version.minimumEJSVersion) >
+ this.versionAsInt(this.ejs_version)
+ ) {
+ this.startGameError(
+ this.localization("Outdated EmulatorJS version")
+ );
+ throw new Error(
+ "Core requires minimum EmulatorJS version of " +
+ version.minimumEJSVersion
+ );
}
}
startGameError(message) {
@@ -591,22 +773,40 @@ class EmulatorJS {
downloadGameCore() {
this.textElem.innerText = this.localization("Download Game Core");
if (!this.config.threads && this.requiresThreads(this.getCore())) {
- this.startGameError(this.localization("Error for site owner") + "\n" + this.localization("Check console"));
- console.warn("This core requires threads, but EJS_threads is not set!");
+ this.startGameError(
+ this.localization("Error for site owner") +
+ "\n" +
+ this.localization("Check console")
+ );
+ console.warn(
+ "This core requires threads, but EJS_threads is not set!"
+ );
return;
}
if (!this.supportsWebgl2 && this.requiresWebGL2(this.getCore())) {
this.startGameError(this.localization("Outdated graphics driver"));
return;
}
- if (this.config.threads && typeof window.SharedArrayBuffer !== "function") {
- this.startGameError(this.localization("Error for site owner") + "\n" + this.localization("Check console"));
- console.warn("Threads is set to true, but the SharedArrayBuffer function is not exposed. Threads requires 2 headers to be set when sending you html page. See https://stackoverflow.com/a/68630724");
+ if (
+ this.config.threads &&
+ typeof window.SharedArrayBuffer !== "function"
+ ) {
+ this.startGameError(
+ this.localization("Error for site owner") +
+ "\n" +
+ this.localization("Check console")
+ );
+ console.warn(
+ "Threads is set to true, but the SharedArrayBuffer function is not exposed. Threads requires 2 headers to be set when sending you html page. See https://stackoverflow.com/a/68630724"
+ );
return;
}
const gotCore = (data) => {
this.defaultCoreOpts = {};
- this.checkCompression(new Uint8Array(data), this.localization("Decompress Game Core")).then((data) => {
+ this.checkCompression(
+ new Uint8Array(data),
+ this.localization("Decompress Game Core")
+ ).then((data) => {
let js, thread, wasm;
for (let k in data) {
if (k.endsWith(".wasm")) {
@@ -616,9 +816,13 @@ class EmulatorJS {
} else if (k.endsWith(".js")) {
js = data[k];
} else if (k === "build.json") {
- this.checkCoreCompatibility(JSON.parse(new TextDecoder().decode(data[k])));
+ this.checkCoreCompatibility(
+ JSON.parse(new TextDecoder().decode(data[k]))
+ );
} else if (k === "core.json") {
- let core = JSON.parse(new TextDecoder().decode(data[k]));
+ let core = JSON.parse(
+ new TextDecoder().decode(data[k])
+ );
this.extensions = core.extensions;
this.coreName = core.name;
this.repository = core.repo;
@@ -632,26 +836,39 @@ class EmulatorJS {
}
if (this.saveFileExt === false) {
- this.elements.bottomBar.saveSavFiles[0].style.display = "none";
- this.elements.bottomBar.loadSavFiles[0].style.display = "none";
+ this.elements.bottomBar.saveSavFiles[0].style.display =
+ "none";
+ this.elements.bottomBar.loadSavFiles[0].style.display =
+ "none";
}
this.initGameCore(js, wasm, thread);
});
- }
+ };
const report = "cores/reports/" + this.getCore() + ".json";
- this.downloadFile(report, null, false, { responseType: "text", method: "GET" }).then(async rep => {
- if (rep === -1 || typeof rep === "string" || typeof rep.data === "string") {
+ this.downloadFile(report, null, false, {
+ responseType: "text",
+ method: "GET",
+ }).then(async (rep) => {
+ if (
+ rep === -1 ||
+ typeof rep === "string" ||
+ typeof rep.data === "string"
+ ) {
rep = {};
} else {
rep = rep.data;
}
if (!rep.buildStart) {
- console.warn("Could not fetch core report JSON! Core caching will be disabled!");
+ console.warn(
+ "Could not fetch core report JSON! Core caching will be disabled!"
+ );
rep.buildStart = Math.random() * 100;
}
if (this.webgl2Enabled === null) {
- this.webgl2Enabled = rep.options ? rep.options.defaultWebGL2 : false;
+ this.webgl2Enabled = rep.options
+ ? rep.options.defaultWebGL2
+ : false;
}
if (this.requiresWebGL2(this.getCore())) {
this.webgl2Enabled = true;
@@ -660,14 +877,19 @@ class EmulatorJS {
if (typeof window.SharedArrayBuffer === "function") {
const opt = this.preGetSetting("ejs_threads");
if (opt) {
- threads = (opt === "enabled");
+ threads = opt === "enabled";
} else {
threads = this.config.threads;
}
}
- let legacy = (this.supportsWebgl2 && this.webgl2Enabled ? "" : "-legacy");
- let filename = this.getCore() + (threads ? "-thread" : "") + legacy + "-wasm.data";
+ let legacy =
+ this.supportsWebgl2 && this.webgl2Enabled ? "" : "-legacy";
+ let filename =
+ this.getCore() +
+ (threads ? "-thread" : "") +
+ legacy +
+ "-wasm.data";
if (!this.debug) {
const result = await this.storage.core.get(filename);
if (result && result.version === rep.buildStart) {
@@ -676,36 +898,65 @@ class EmulatorJS {
}
}
const corePath = "cores/" + filename;
- let res = await this.downloadFile(corePath, (progress) => {
- this.textElem.innerText = this.localization("Download Game Core") + progress;
- }, false, { responseType: "arraybuffer", method: "GET" });
+ let res = await this.downloadFile(
+ corePath,
+ (progress) => {
+ this.textElem.innerText =
+ this.localization("Download Game Core") + progress;
+ },
+ false,
+ { responseType: "arraybuffer", method: "GET" }
+ );
if (res === -1) {
- console.log("File not found, attemping to fetch from emulatorjs cdn.");
- console.error("**THIS METHOD IS A FAILSAFE, AND NOT OFFICIALLY SUPPORTED. USE AT YOUR OWN RISK**");
- let version = this.ejs_version.endsWith("-beta") ? "nightly" : this.ejs_version;
- res = await this.downloadFile(`https://cdn.emulatorjs.org/${version}/data/${corePath}`, (progress) => {
- this.textElem.innerText = this.localization("Download Game Core") + progress;
- }, true, { responseType: "arraybuffer", method: "GET" });
+ console.log(
+ "File not found, attemping to fetch from emulatorjs cdn."
+ );
+ console.error(
+ "**THIS METHOD IS A FAILSAFE, AND NOT OFFICIALLY SUPPORTED. USE AT YOUR OWN RISK**"
+ );
+ let version = this.ejs_version.endsWith("-beta")
+ ? "nightly"
+ : this.ejs_version;
+ res = await this.downloadFile(
+ `https://cdn.emulatorjs.org/${version}/data/${corePath}`,
+ (progress) => {
+ this.textElem.innerText =
+ this.localization("Download Game Core") + progress;
+ },
+ true,
+ { responseType: "arraybuffer", method: "GET" }
+ );
if (res === -1) {
if (!this.supportsWebgl2) {
- this.startGameError(this.localization("Outdated graphics driver"));
+ this.startGameError(
+ this.localization("Outdated graphics driver")
+ );
} else {
- this.startGameError(this.localization("Error downloading core") + " (" + filename + ")");
+ this.startGameError(
+ this.localization("Error downloading core") +
+ " (" +
+ filename +
+ ")"
+ );
}
return;
}
- console.warn("File was not found locally, but was found on the emulatorjs cdn.\nIt is recommended to download the stable release from here: https://cdn.emulatorjs.org/releases/");
+ console.warn(
+ "File was not found locally, but was found on the emulatorjs cdn.\nIt is recommended to download the stable release from here: https://cdn.emulatorjs.org/releases/"
+ );
}
gotCore(res.data);
this.storage.core.put(filename, {
version: rep.buildStart,
- data: res.data
+ data: res.data,
});
});
}
initGameCore(js, wasm, thread) {
let script = this.createElement("script");
- script.src = URL.createObjectURL(new Blob([js], { type: "application/javascript" }));
+ script.src = URL.createObjectURL(
+ new Blob([js], { type: "application/javascript" })
+ );
script.addEventListener("load", () => {
this.initModule(wasm, thread);
});
@@ -714,12 +965,22 @@ class EmulatorJS {
getBaseFileName(force) {
//Only once game and core is loaded
if (!this.started && !force) return null;
- if (force && this.config.gameUrl !== "game" && !this.config.gameUrl.startsWith("blob:")) {
- return this.config.gameUrl.split("/").pop().split("#")[0].split("?")[0];
+ if (
+ force &&
+ this.config.gameUrl !== "game" &&
+ !this.config.gameUrl.startsWith("blob:")
+ ) {
+ return this.config.gameUrl
+ .split("/")
+ .pop()
+ .split("#")[0]
+ .split("?")[0];
}
if (typeof this.config.gameName === "string") {
- const invalidCharacters = /[#<$+%>!`&*'|{}/\\?"=@:^\r\n]/ig;
- const name = this.config.gameName.replace(invalidCharacters, "").trim();
+ const invalidCharacters = /[#<$+%>!`&*'|{}/\\?"=@:^\r\n]/gi;
+ const name = this.config.gameName
+ .replace(invalidCharacters, "")
+ .trim();
if (name) return name;
}
if (!this.fileName) return "game";
@@ -728,7 +989,11 @@ class EmulatorJS {
return parts.join(".");
}
saveInBrowserSupported() {
- return !!window.indexedDB && (typeof this.config.gameName === "string" || !this.config.gameUrl.startsWith("blob:"));
+ return (
+ !!window.indexedDB &&
+ (typeof this.config.gameName === "string" ||
+ !this.config.gameUrl.startsWith("blob:"))
+ );
}
displayMessage(message, time) {
if (!this.msgElem) {
@@ -738,70 +1003,126 @@ class EmulatorJS {
this.elements.parent.appendChild(this.msgElem);
}
clearTimeout(this.msgTimeout);
- this.msgTimeout = setTimeout(() => {
- this.msgElem.innerText = "";
- }, (typeof time === "number" && time > 0) ? time : 3000)
+ this.msgTimeout = setTimeout(
+ () => {
+ this.msgElem.innerText = "";
+ },
+ typeof time === "number" && time > 0 ? time : 3000
+ );
this.msgElem.innerText = message;
}
downloadStartState() {
return new Promise((resolve, reject) => {
- if (typeof this.config.loadState !== "string" && !this.toData(this.config.loadState, true)) {
+ if (
+ typeof this.config.loadState !== "string" &&
+ !this.toData(this.config.loadState, true)
+ ) {
resolve();
return;
}
this.textElem.innerText = this.localization("Download Game State");
- this.downloadFile(this.config.loadState, (progress) => {
- this.textElem.innerText = this.localization("Download Game State") + progress;
- }, true, { responseType: "arraybuffer", method: "GET" }).then((res) => {
+ this.downloadFile(
+ this.config.loadState,
+ (progress) => {
+ this.textElem.innerText =
+ this.localization("Download Game State") + progress;
+ },
+ true,
+ { responseType: "arraybuffer", method: "GET" }
+ ).then((res) => {
if (res === -1) {
- this.startGameError(this.localization("Error downloading game state"));
+ this.startGameError(
+ this.localization("Error downloading game state")
+ );
return;
}
this.on("start", () => {
setTimeout(() => {
this.gameManager.loadState(new Uint8Array(res.data));
}, 10);
- })
+ });
resolve();
});
- })
+ });
}
- downloadGameFile(assetUrl, type, progressMessage, decompressProgressMessage) {
+ downloadGameFile(
+ assetUrl,
+ type,
+ progressMessage,
+ decompressProgressMessage
+ ) {
return new Promise(async (resolve, reject) => {
- if ((typeof assetUrl !== "string" || !assetUrl.trim()) && !this.toData(assetUrl, true)) {
+ if (
+ (typeof assetUrl !== "string" || !assetUrl.trim()) &&
+ !this.toData(assetUrl, true)
+ ) {
return resolve(assetUrl);
}
const gotData = async (input) => {
const coreFilename = "/" + this.fileName;
- const coreFilePath = coreFilename.substring(0, coreFilename.length - coreFilename.split("/").pop().length);
+ const coreFilePath = coreFilename.substring(
+ 0,
+ coreFilename.length - coreFilename.split("/").pop().length
+ );
if (this.config.dontExtractBIOS === true) {
- this.gameManager.FS.writeFile(coreFilePath + assetUrl.split("/").pop(), new Uint8Array(input));
+ this.gameManager.FS.writeFile(
+ coreFilePath + assetUrl.split("/").pop(),
+ new Uint8Array(input)
+ );
return resolve(assetUrl);
}
- const data = await this.checkCompression(new Uint8Array(input), decompressProgressMessage);
+ const data = await this.checkCompression(
+ new Uint8Array(input),
+ decompressProgressMessage
+ );
for (const k in data) {
if (k === "!!notCompressedData") {
- this.gameManager.FS.writeFile(coreFilePath + assetUrl.split("/").pop().split("#")[0].split("?")[0], data[k]);
+ this.gameManager.FS.writeFile(
+ coreFilePath +
+ assetUrl
+ .split("/")
+ .pop()
+ .split("#")[0]
+ .split("?")[0],
+ data[k]
+ );
break;
}
if (k.endsWith("/")) continue;
- this.gameManager.FS.writeFile(coreFilePath + k.split("/").pop(), data[k]);
+ this.gameManager.FS.writeFile(
+ coreFilePath + k.split("/").pop(),
+ data[k]
+ );
}
- }
+ };
this.textElem.innerText = progressMessage;
if (!this.debug) {
- const res = await this.downloadFile(assetUrl, null, true, { method: "HEAD" });
- const result = await this.storage.rom.get(assetUrl.split("/").pop());
- if (result && result["content-length"] === res.headers["content-length"] && result.type === type) {
+ const res = await this.downloadFile(assetUrl, null, true, {
+ method: "HEAD",
+ });
+ const result = await this.storage.rom.get(
+ assetUrl.split("/").pop()
+ );
+ if (
+ result &&
+ result["content-length"] ===
+ res.headers["content-length"] &&
+ result.type === type
+ ) {
await gotData(result.data);
return resolve(assetUrl);
}
}
- const res = await this.downloadFile(assetUrl, (progress) => {
- this.textElem.innerText = progressMessage + progress;
- }, true, { responseType: "arraybuffer", method: "GET" });
+ const res = await this.downloadFile(
+ assetUrl,
+ (progress) => {
+ this.textElem.innerText = progressMessage + progress;
+ },
+ true,
+ { responseType: "arraybuffer", method: "GET" }
+ );
if (res === -1) {
this.startGameError(this.localization("Network Error"));
reject();
@@ -814,31 +1135,53 @@ class EmulatorJS {
}
await gotData(res.data);
resolve(assetUrl);
- const limit = (typeof this.config.cacheLimit === "number") ? this.config.cacheLimit : 1073741824;
- if (parseFloat(res.headers["content-length"]) < limit && this.saveInBrowserSupported() && assetUrl !== "game") {
+ const limit =
+ typeof this.config.cacheLimit === "number"
+ ? this.config.cacheLimit
+ : 1073741824;
+ if (
+ parseFloat(res.headers["content-length"]) < limit &&
+ this.saveInBrowserSupported() &&
+ assetUrl !== "game"
+ ) {
this.storage.rom.put(assetUrl.split("/").pop(), {
"content-length": res.headers["content-length"],
data: res.data,
- type: type
- })
+ type: type,
+ });
}
});
}
downloadGamePatch() {
return new Promise(async (resolve) => {
- this.config.gamePatchUrl = await this.downloadGameFile(this.config.gamePatchUrl, "patch", this.localization("Download Game Patch"), this.localization("Decompress Game Patch"));
+ this.config.gamePatchUrl = await this.downloadGameFile(
+ this.config.gamePatchUrl,
+ "patch",
+ this.localization("Download Game Patch"),
+ this.localization("Decompress Game Patch")
+ );
resolve();
});
}
downloadGameParent() {
return new Promise(async (resolve) => {
- this.config.gameParentUrl = await this.downloadGameFile(this.config.gameParentUrl, "parent", this.localization("Download Game Parent"), this.localization("Decompress Game Parent"));
+ this.config.gameParentUrl = await this.downloadGameFile(
+ this.config.gameParentUrl,
+ "parent",
+ this.localization("Download Game Parent"),
+ this.localization("Decompress Game Parent")
+ );
resolve();
});
}
downloadBios() {
return new Promise(async (resolve) => {
- this.config.biosUrl = await this.downloadGameFile(this.config.biosUrl, "bios", this.localization("Download Game BIOS"), this.localization("Decompress Game BIOS"));
+ this.config.biosUrl = await this.downloadGameFile(
+ this.config.biosUrl,
+ "bios",
+ this.localization("Download Game BIOS"),
+ this.localization("Decompress Game BIOS")
+ );
resolve();
});
}
@@ -849,18 +1192,24 @@ class EmulatorJS {
return this.extensions.includes(ext);
};
- return new Promise(resolve => {
+ return new Promise((resolve) => {
this.textElem.innerText = this.localization("Download Game Data");
const gotGameData = (data) => {
const coreName = this.getCore(true);
const altName = this.getBaseFileName(true);
- if (["arcade", "mame"].includes(coreName) || this.config.dontExtractRom === true) {
+ if (
+ ["arcade", "mame"].includes(coreName) ||
+ this.config.dontExtractRom === true
+ ) {
this.fileName = altName;
- this.gameManager.FS.writeFile(this.fileName, new Uint8Array(data));
+ this.gameManager.FS.writeFile(
+ this.fileName,
+ new Uint8Array(data)
+ );
resolve();
return;
- }
+ }
// List of cores to generate a CUE file for, if it doesn't exist.
const cueGeneration = ["mednafen_psx_hw"];
@@ -872,43 +1221,58 @@ class EmulatorJS {
}
let fileNames = [];
- this.checkCompression(new Uint8Array(data), this.localization("Decompress Game Data"), (fileName, fileData) => {
- if (fileName.includes("/")) {
- const paths = fileName.split("/");
- let cp = "";
- for (let i = 0; i < paths.length - 1; i++) {
- if (paths[i] === "") continue;
- cp += `/${paths[i]}`;
- if (!this.gameManager.FS.analyzePath(cp).exists) {
- this.gameManager.FS.mkdir(cp);
+ this.checkCompression(
+ new Uint8Array(data),
+ this.localization("Decompress Game Data"),
+ (fileName, fileData) => {
+ if (fileName.includes("/")) {
+ const paths = fileName.split("/");
+ let cp = "";
+ for (let i = 0; i < paths.length - 1; i++) {
+ if (paths[i] === "") continue;
+ cp += `/${paths[i]}`;
+ if (
+ !this.gameManager.FS.analyzePath(cp).exists
+ ) {
+ this.gameManager.FS.mkdir(cp);
+ }
}
}
+ if (fileName.endsWith("/")) {
+ this.gameManager.FS.mkdir(fileName);
+ return;
+ }
+ if (fileName === "!!notCompressedData") {
+ this.gameManager.FS.writeFile(altName, fileData);
+ fileNames.push(altName);
+ } else {
+ this.gameManager.FS.writeFile(
+ `/${fileName}`,
+ fileData
+ );
+ fileNames.push(fileName);
+ }
}
- if (fileName.endsWith("/")) {
- this.gameManager.FS.mkdir(fileName);
- return;
- }
- if (fileName === "!!notCompressedData") {
- this.gameManager.FS.writeFile(altName, fileData);
- fileNames.push(altName);
- } else {
- this.gameManager.FS.writeFile(`/${fileName}`, fileData);
- fileNames.push(fileName);
- }
- }).then(() => {
+ ).then(() => {
let isoFile = null;
let supportedFile = null;
let cueFile = null;
- fileNames.forEach(fileName => {
+ fileNames.forEach((fileName) => {
const ext = fileName.split(".").pop().toLowerCase();
if (supportedFile === null && supportsExt(ext)) {
supportedFile = fileName;
}
- if (isoFile === null && ["iso", "cso", "chd", "elf"].includes(ext)) {
+ if (
+ isoFile === null &&
+ ["iso", "cso", "chd", "elf"].includes(ext)
+ ) {
isoFile = fileName;
}
if (prioritizeExtensions.includes(ext)) {
- const currentCueExt = (cueFile === null) ? null : cueFile.split(".").pop().toLowerCase();
+ const currentCueExt =
+ cueFile === null
+ ? null
+ : cueFile.split(".").pop().toLowerCase();
if (coreName === "psx") {
// Always prefer m3u files for psx cores
if (currentCueExt !== "m3u") {
@@ -917,10 +1281,13 @@ class EmulatorJS {
}
}
} else {
- const priority = ["cue", "ccd"]
+ const priority = ["cue", "ccd"];
// Prefer cue or ccd files over toc or m3u
if (!priority.includes(currentCueExt)) {
- if (cueFile === null || priority.includes(ext)) {
+ if (
+ cueFile === null ||
+ priority.includes(ext)
+ ) {
cueFile = fileName;
}
}
@@ -932,24 +1299,44 @@ class EmulatorJS {
} else {
this.fileName = fileNames[0];
}
- if (isoFile !== null && supportsExt(isoFile.split(".").pop().toLowerCase())) {
+ if (
+ isoFile !== null &&
+ supportsExt(isoFile.split(".").pop().toLowerCase())
+ ) {
this.fileName = isoFile;
}
- if (cueFile !== null && supportsExt(cueFile.split(".").pop().toLowerCase())) {
+ if (
+ cueFile !== null &&
+ supportsExt(cueFile.split(".").pop().toLowerCase())
+ ) {
this.fileName = cueFile;
- } else if (createCueFile && supportsExt("m3u") && supportsExt("cue")) {
- this.fileName = this.gameManager.createCueFile(fileNames);
+ } else if (
+ createCueFile &&
+ supportsExt("m3u") &&
+ supportsExt("cue")
+ ) {
+ this.fileName =
+ this.gameManager.createCueFile(fileNames);
}
- if (this.getCore(true) === "dos" && !this.config.disableBatchBootup) {
+ if (
+ this.getCore(true) === "dos" &&
+ !this.config.disableBatchBootup
+ ) {
this.fileName = this.gameManager.writeBootupBatchFile();
}
resolve();
});
- }
+ };
const downloadFile = async () => {
- const res = await this.downloadFile(this.config.gameUrl, (progress) => {
- this.textElem.innerText = this.localization("Download Game Data") + progress;
- }, true, { responseType: "arraybuffer", method: "GET" });
+ const res = await this.downloadFile(
+ this.config.gameUrl,
+ (progress) => {
+ this.textElem.innerText =
+ this.localization("Download Game Data") + progress;
+ },
+ true,
+ { responseType: "arraybuffer", method: "GET" }
+ );
if (res === -1) {
this.startGameError(this.localization("Network Error"));
return;
@@ -960,29 +1347,46 @@ class EmulatorJS {
this.config.gameUrl = "game";
}
gotGameData(res.data);
- const limit = (typeof this.config.cacheLimit === "number") ? this.config.cacheLimit : 1073741824;
- if (parseFloat(res.headers["content-length"]) < limit && this.saveInBrowserSupported() && this.config.gameUrl !== "game") {
+ const limit =
+ typeof this.config.cacheLimit === "number"
+ ? this.config.cacheLimit
+ : 1073741824;
+ if (
+ parseFloat(res.headers["content-length"]) < limit &&
+ this.saveInBrowserSupported() &&
+ this.config.gameUrl !== "game"
+ ) {
this.storage.rom.put(this.config.gameUrl.split("/").pop(), {
"content-length": res.headers["content-length"],
- data: res.data
- })
+ data: res.data,
+ });
}
- }
+ };
if (!this.debug) {
- this.downloadFile(this.config.gameUrl, null, true, { method: "HEAD" }).then(async (res) => {
- const name = (typeof this.config.gameUrl === "string") ? this.config.gameUrl.split("/").pop() : "game";
+ this.downloadFile(this.config.gameUrl, null, true, {
+ method: "HEAD",
+ }).then(async (res) => {
+ const name =
+ typeof this.config.gameUrl === "string"
+ ? this.config.gameUrl.split("/").pop()
+ : "game";
const result = await this.storage.rom.get(name);
- if (result && result["content-length"] === res.headers["content-length"] && name !== "game") {
+ if (
+ result &&
+ result["content-length"] ===
+ res.headers["content-length"] &&
+ name !== "game"
+ ) {
gotGameData(result.data);
return;
}
downloadFile();
- })
+ });
} else {
downloadFile();
}
- })
+ });
}
downloadFiles() {
(async () => {
@@ -1004,50 +1408,61 @@ class EmulatorJS {
initModule(wasmData, threadData) {
if (typeof window.EJS_Runtime !== "function") {
console.warn("EJS_Runtime is not defined!");
- this.startGameError(this.localization("Error loading EmulatorJS runtime"));
+ this.startGameError(
+ this.localization("Error loading EmulatorJS runtime")
+ );
throw new Error("EJS_Runtime is not defined!");
}
- window.EJS_Runtime({
- noInitialRun: true,
- onRuntimeInitialized: null,
- arguments: [],
- preRun: [],
- postRun: [],
- canvas: this.canvas,
- callbacks: {},
- parent: this.elements.parent,
- print: (msg) => {
- if (this.debug) {
- console.log(msg);
- }
- },
- printErr: (msg) => {
- if (this.debug) {
- console.log(msg);
- }
- },
- totalDependencies: 0,
- locateFile: function (fileName) {
- if (this.debug) console.log(fileName);
- if (fileName.endsWith(".wasm")) {
- return URL.createObjectURL(new Blob([wasmData], { type: "application/wasm" }));
- } else if (fileName.endsWith(".worker.js")) {
- return URL.createObjectURL(new Blob([threadData], { type: "application/javascript" }));
- }
- },
- getSavExt: () => {
- if (this.saveFileExt) {
- return "." + this.saveFileExt;
- }
- return ".srm";
- }
- }).then(module => {
- this.Module = module;
- this.downloadFiles();
- }).catch(e => {
- console.warn(e);
- this.startGameError(this.localization("Failed to start game"));
- });
+ window
+ .EJS_Runtime({
+ noInitialRun: true,
+ onRuntimeInitialized: null,
+ arguments: [],
+ preRun: [],
+ postRun: [],
+ canvas: this.canvas,
+ callbacks: {},
+ parent: this.elements.parent,
+ print: (msg) => {
+ if (this.debug) {
+ console.log(msg);
+ }
+ },
+ printErr: (msg) => {
+ if (this.debug) {
+ console.log(msg);
+ }
+ },
+ totalDependencies: 0,
+ locateFile: function (fileName) {
+ if (this.debug) console.log(fileName);
+ if (fileName.endsWith(".wasm")) {
+ return URL.createObjectURL(
+ new Blob([wasmData], { type: "application/wasm" })
+ );
+ } else if (fileName.endsWith(".worker.js")) {
+ return URL.createObjectURL(
+ new Blob([threadData], {
+ type: "application/javascript",
+ })
+ );
+ }
+ },
+ getSavExt: () => {
+ if (this.saveFileExt) {
+ return "." + this.saveFileExt;
+ }
+ return ".srm";
+ },
+ })
+ .then((module) => {
+ this.Module = module;
+ this.downloadFiles();
+ })
+ .catch((e) => {
+ console.warn(e);
+ this.startGameError(this.localization("Failed to start game"));
+ });
}
startGame() {
try {
@@ -1056,7 +1471,10 @@ class EmulatorJS {
args.push("/" + this.fileName);
if (this.debug) console.log(args);
this.Module.callMain(args);
- if (typeof this.config.softLoad === "number" && this.config.softLoad > 0) {
+ if (
+ typeof this.config.softLoad === "number" &&
+ this.config.softLoad > 0
+ ) {
this.resetTimeout = setTimeout(() => {
this.gameManager.restart();
}, this.config.softLoad * 1000);
@@ -1089,8 +1507,9 @@ class EmulatorJS {
if (this.config.fullscreenOnLoad) {
try {
this.toggleFullscreen(true);
- } catch(e) {
- if (this.debug) console.warn("Could not fullscreen on load");
+ } catch (e) {
+ if (this.debug)
+ console.warn("Could not fullscreen on load");
}
}
this.menu.open();
@@ -1098,7 +1517,7 @@ class EmulatorJS {
//Safari is --- funny
this.checkStarted();
}
- } catch(e) {
+ } catch (e) {
console.warn("Failed to start game", e);
this.startGameError(this.localization("Failed to start game"));
this.callEvent("exit");
@@ -1108,19 +1527,21 @@ class EmulatorJS {
}
checkStarted() {
(async () => {
- let sleep = (ms) => new Promise(r => setTimeout(r, ms));
+ let sleep = (ms) => new Promise((r) => setTimeout(r, ms));
let state = "suspended";
let popup;
while (state === "suspended") {
if (!this.Module.AL) return;
- this.Module.AL.currentCtx.sources.forEach(ctx => {
+ this.Module.AL.currentCtx.sources.forEach((ctx) => {
state = ctx.gain.context.state;
});
if (state !== "suspended") break;
if (!popup) {
popup = this.createPopup("", {});
const button = this.createElement("button");
- button.innerText = this.localization("Click to resume Emulator");
+ button.innerText = this.localization(
+ "Click to resume Emulator"
+ );
button.classList.add("ejs_menu_button");
button.style.width = "25%";
button.style.height = "25%";
@@ -1137,35 +1558,54 @@ class EmulatorJS {
this.createContextMenu();
this.createBottomMenuBar();
this.createControlSettingMenu();
- this.createCheatsMenu()
+ this.createCheatsMenu();
this.createNetplayMenu();
this.setVirtualGamepad();
- this.addEventListener(this.elements.parent, "keydown keyup", this.keyChange.bind(this));
- this.addEventListener(this.elements.parent, "mousedown touchstart", (e) => {
- if (document.activeElement !== this.elements.parent && this.config.noAutoFocus !== true) this.elements.parent.focus();
- })
+ this.addEventListener(
+ this.elements.parent,
+ "keydown keyup",
+ this.keyChange.bind(this)
+ );
+ this.addEventListener(
+ this.elements.parent,
+ "mousedown touchstart",
+ (e) => {
+ if (
+ document.activeElement !== this.elements.parent &&
+ this.config.noAutoFocus !== true
+ )
+ this.elements.parent.focus();
+ }
+ );
this.addEventListener(window, "resize", this.handleResize.bind(this));
//this.addEventListener(window, "blur", e => console.log(e), true); //TODO - add "click to make keyboard keys work" message?
let counter = 0;
this.elements.statePopupPanel = this.createPopup("", {}, true);
- this.elements.statePopupPanel.innerText = this.localization("Drop save state here to load");
+ this.elements.statePopupPanel.innerText = this.localization(
+ "Drop save state here to load"
+ );
this.elements.statePopupPanel.style["text-align"] = "center";
this.elements.statePopupPanel.style["font-size"] = "28px";
//to fix a funny apple bug
- this.addEventListener(window, "webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange", () => {
- setTimeout(() => {
- this.handleResize.bind(this);
- if (this.config.noAutoFocus !== true) this.elements.parent.focus();
- }, 0);
- });
+ this.addEventListener(
+ window,
+ "webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange",
+ () => {
+ setTimeout(() => {
+ this.handleResize.bind(this);
+ if (this.config.noAutoFocus !== true)
+ this.elements.parent.focus();
+ }, 0);
+ }
+ );
this.addEventListener(window, "beforeunload", (e) => {
if (this.config.disableAutoUnload) {
e.preventDefault();
e.returnValue = "";
- return
- }
+ return;
+ }
if (!this.started) return;
this.callEvent("exit");
});
@@ -1183,7 +1623,8 @@ class EmulatorJS {
if (!this.started) return;
counter--;
if (counter === 0) {
- this.elements.statePopupPanel.parentElement.style.display = "none";
+ this.elements.statePopupPanel.parentElement.style.display =
+ "none";
}
});
this.addEventListener(this.elements.parent, "dragend", (e) => {
@@ -1207,9 +1648,9 @@ class EmulatorJS {
}
if (!file) return;
const fileHandle = file.getAsFile();
- fileHandle.arrayBuffer().then(data => {
+ fileHandle.arrayBuffer().then((data) => {
this.gameManager.loadState(new Uint8Array(data));
- })
+ });
});
this.gamepad = new GamepadHandler(); //https://github.com/ethanaobrien/Gamepad
@@ -1217,22 +1658,30 @@ class EmulatorJS {
if (!this.gamepadLabels) return;
for (let i = 0; i < this.gamepadSelection.length; i++) {
if (this.gamepadSelection[i] === "") {
- this.gamepadSelection[i] = this.gamepad.gamepads[e.gamepadIndex].id + "_" + this.gamepad.gamepads[e.gamepadIndex].index;
+ this.gamepadSelection[i] =
+ this.gamepad.gamepads[e.gamepadIndex].id +
+ "_" +
+ this.gamepad.gamepads[e.gamepadIndex].index;
break;
}
}
this.updateGamepadLabels();
- })
+ });
this.gamepad.on("disconnected", (e) => {
- const gamepadIndex = this.gamepad.gamepads.indexOf(this.gamepad.gamepads.find(f => f.index == e.gamepadIndex));
- const gamepadSelection = this.gamepad.gamepads[gamepadIndex].id + "_" + this.gamepad.gamepads[gamepadIndex].index;
+ const gamepadIndex = this.gamepad.gamepads.indexOf(
+ this.gamepad.gamepads.find((f) => f.index == e.gamepadIndex)
+ );
+ const gamepadSelection =
+ this.gamepad.gamepads[gamepadIndex].id +
+ "_" +
+ this.gamepad.gamepads[gamepadIndex].index;
for (let i = 0; i < this.gamepadSelection.length; i++) {
if (this.gamepadSelection[i] === gamepadSelection) {
this.gamepadSelection[i] = "";
}
}
setTimeout(this.updateGamepadLabels.bind(this), 10);
- })
+ });
this.gamepad.on("axischanged", this.gamepadEvent.bind(this));
this.gamepad.on("buttondown", this.gamepadEvent.bind(this));
this.gamepad.on("buttonup", this.gamepadEvent.bind(this));
@@ -1245,24 +1694,37 @@ class EmulatorJS {
this.elements.contextMenu.save.style.display = "none";
this.elements.contextMenu.load.style.display = "none";
}
- if (typeof this.config.gameId !== "number" || !this.config.netplayUrl || this.netplayEnabled === false) {
+ if (
+ typeof this.config.gameId !== "number" ||
+ !this.config.netplayUrl ||
+ this.netplayEnabled === false
+ ) {
this.elements.bottomBar.netplay[0].style.display = "none";
}
}
updateGamepadLabels() {
for (let i = 0; i < this.gamepadLabels.length; i++) {
- this.gamepadLabels[i].innerHTML = ""
+ this.gamepadLabels[i].innerHTML = "";
const def = this.createElement("option");
def.setAttribute("value", "notconnected");
def.innerText = "Not Connected";
this.gamepadLabels[i].appendChild(def);
for (let j = 0; j < this.gamepad.gamepads.length; j++) {
const opt = this.createElement("option");
- opt.setAttribute("value", this.gamepad.gamepads[j].id + "_" + this.gamepad.gamepads[j].index);
- opt.innerText = this.gamepad.gamepads[j].id + "_" + this.gamepad.gamepads[j].index;
+ opt.setAttribute(
+ "value",
+ this.gamepad.gamepads[j].id +
+ "_" +
+ this.gamepad.gamepads[j].index
+ );
+ opt.innerText =
+ this.gamepad.gamepads[j].id +
+ "_" +
+ this.gamepad.gamepads[j].index;
this.gamepadLabels[i].appendChild(opt);
}
- this.gamepadLabels[i].value = this.gamepadSelection[i] || "notconnected";
+ this.gamepadLabels[i].value =
+ this.gamepadSelection[i] || "notconnected";
}
}
createLink(elem, link, text, useP) {
@@ -1282,126 +1744,126 @@ class EmulatorJS {
playPause: {
visible: true,
icon: "play",
- displayName: "Play/Pause"
+ displayName: "Play/Pause",
},
play: {
visible: true,
icon: '',
- displayName: "Play"
+ displayName: "Play",
},
pause: {
visible: true,
icon: '',
- displayName: "Pause"
+ displayName: "Pause",
},
restart: {
visible: true,
icon: '',
- displayName: "Restart"
+ displayName: "Restart",
},
mute: {
visible: true,
icon: '',
- displayName: "Mute"
+ displayName: "Mute",
},
unmute: {
visible: true,
icon: '',
- displayName: "Unmute"
+ displayName: "Unmute",
},
settings: {
visible: true,
icon: '',
- displayName: "Settings"
+ displayName: "Settings",
},
fullscreen: {
visible: true,
icon: "fullscreen",
- displayName: "Fullscreen"
+ displayName: "Fullscreen",
},
enterFullscreen: {
visible: true,
icon: '',
- displayName: "Enter Fullscreen"
+ displayName: "Enter Fullscreen",
},
exitFullscreen: {
visible: true,
icon: '',
- displayName: "Exit Fullscreen"
+ displayName: "Exit Fullscreen",
},
saveState: {
visible: true,
icon: '',
- displayName: "Save State"
+ displayName: "Save State",
},
loadState: {
visible: true,
icon: '',
- displayName: "Load State"
+ displayName: "Load State",
},
screenRecord: {
- visible: true
+ visible: true,
},
gamepad: {
visible: true,
icon: '',
- displayName: "Control Settings"
+ displayName: "Control Settings",
},
cheat: {
visible: true,
icon: '',
- displayName: "Cheats"
+ displayName: "Cheats",
},
volumeSlider: {
- visible: true
+ visible: true,
},
saveSavFiles: {
visible: true,
icon: '',
- displayName: "Export Save File"
+ displayName: "Export Save File",
},
loadSavFiles: {
visible: true,
icon: '',
- displayName: "Import Save File"
+ displayName: "Import Save File",
},
quickSave: {
- visible: true
+ visible: true,
},
quickLoad: {
- visible: true
+ visible: true,
},
screenshot: {
- visible: true
+ visible: true,
},
cacheManager: {
visible: true,
icon: '',
- displayName: "Cache Manager"
+ displayName: "Cache Manager",
},
exitEmulation: {
visible: true,
icon: '',
- displayName: "Exit Emulation"
+ displayName: "Exit Emulation",
},
netplay: {
visible: true,
icon: '',
- displayName: "Netplay"
+ displayName: "Netplay",
},
diskButton: {
visible: true,
icon: '',
- displayName: "Disks"
+ displayName: "Disks",
},
contextMenu: {
visible: true,
icon: '',
- displayName: "Context Menu"
- }
+ displayName: "Context Menu",
+ },
};
defaultButtonAliases = {
- volume: "volumeSlider"
+ volume: "volumeSlider",
};
buildButtonOptions(buttonUserOpts) {
let mergedButtonOptions = this.defaultButtonOptions;
@@ -1422,67 +1884,94 @@ class EmulatorJS {
if (!mergedButtonOptions[searchKey]) {
// If the button does not exist in the default buttons, create a custom button
// Custom buttons must have a displayName, icon, and callback property
- if (!buttonUserOpts[searchKey] || !buttonUserOpts[searchKey].displayName || !buttonUserOpts[searchKey].icon || !buttonUserOpts[searchKey].callback) {
- if (this.debug) console.warn(`Custom button "${searchKey}" is missing required properties`);
+ if (
+ !buttonUserOpts[searchKey] ||
+ !buttonUserOpts[searchKey].displayName ||
+ !buttonUserOpts[searchKey].icon ||
+ !buttonUserOpts[searchKey].callback
+ ) {
+ if (this.debug)
+ console.warn(
+ `Custom button "${searchKey}" is missing required properties`
+ );
continue;
}
mergedButtonOptions[searchKey] = {
visible: true,
- displayName: buttonUserOpts[searchKey].displayName || searchKey,
+ displayName:
+ buttonUserOpts[searchKey].displayName || searchKey,
icon: buttonUserOpts[searchKey].icon || "",
- callback: buttonUserOpts[searchKey].callback || (() => { }),
- custom: true
+ callback:
+ buttonUserOpts[searchKey].callback || (() => {}),
+ custom: true,
};
}
// if the value is a boolean, set the visible property to the value
if (typeof buttonUserOpts[searchKey] === "boolean") {
- mergedButtonOptions[searchKey].visible = buttonUserOpts[searchKey];
+ mergedButtonOptions[searchKey].visible =
+ buttonUserOpts[searchKey];
} else if (typeof buttonUserOpts[searchKey] === "object") {
// If the value is an object, merge it with the default button properties
-
+
// if the button is the contextMenu, only allow the visible property to be set
if (searchKey === "contextMenu") {
- mergedButtonOptions[searchKey].visible = buttonUserOpts[searchKey].visible !== undefined ? buttonUserOpts[searchKey].visible : true;
+ mergedButtonOptions[searchKey].visible =
+ buttonUserOpts[searchKey].visible !== undefined
+ ? buttonUserOpts[searchKey].visible
+ : true;
} else if (this.defaultButtonOptions[searchKey]) {
// copy properties from the button definition if they aren't null
for (const prop in buttonUserOpts[searchKey]) {
if (buttonUserOpts[searchKey][prop] !== null) {
- mergedButtonOptions[searchKey][prop] = buttonUserOpts[searchKey][prop];
+ mergedButtonOptions[searchKey][prop] =
+ buttonUserOpts[searchKey][prop];
}
}
} else {
// button was not in the default buttons list and is therefore a custom button
// verify that the value has a displayName, icon, and callback property
- if (buttonUserOpts[searchKey].displayName && buttonUserOpts[searchKey].icon && buttonUserOpts[searchKey].callback) {
+ if (
+ buttonUserOpts[searchKey].displayName &&
+ buttonUserOpts[searchKey].icon &&
+ buttonUserOpts[searchKey].callback
+ ) {
mergedButtonOptions[searchKey] = {
visible: true,
- displayName: buttonUserOpts[searchKey].displayName,
+ displayName:
+ buttonUserOpts[searchKey].displayName,
icon: buttonUserOpts[searchKey].icon,
callback: buttonUserOpts[searchKey].callback,
- custom: true
+ custom: true,
};
} else if (this.debug) {
- console.warn(`Custom button "${searchKey}" is missing required properties`);
+ console.warn(
+ `Custom button "${searchKey}" is missing required properties`
+ );
}
}
}
-
+
// behaviour exceptions
switch (searchKey) {
case "playPause":
- mergedButtonOptions.play.visible = mergedButtonOptions.playPause.visible;
- mergedButtonOptions.pause.visible = mergedButtonOptions.playPause.visible;
+ mergedButtonOptions.play.visible =
+ mergedButtonOptions.playPause.visible;
+ mergedButtonOptions.pause.visible =
+ mergedButtonOptions.playPause.visible;
break;
-
+
case "mute":
- mergedButtonOptions.unmute.visible = mergedButtonOptions.mute.visible;
+ mergedButtonOptions.unmute.visible =
+ mergedButtonOptions.mute.visible;
break;
-
+
case "fullscreen":
- mergedButtonOptions.enterFullscreen.visible = mergedButtonOptions.fullscreen.visible;
- mergedButtonOptions.exitFullscreen.visible = mergedButtonOptions.fullscreen.visible;
+ mergedButtonOptions.enterFullscreen.visible =
+ mergedButtonOptions.fullscreen.visible;
+ mergedButtonOptions.exitFullscreen.visible =
+ mergedButtonOptions.fullscreen.visible;
break;
}
}
@@ -1495,20 +1984,31 @@ class EmulatorJS {
this.elements.contextmenu.classList.add("ejs_context_menu");
this.addEventListener(this.game, "contextmenu", (e) => {
e.preventDefault();
- if ((this.config.buttonOpts && this.config.buttonOpts.rightClick === false) || !this.started) return;
+ if (
+ (this.config.buttonOpts &&
+ this.config.buttonOpts.rightClick === false) ||
+ !this.started
+ )
+ return;
const parentRect = this.elements.parent.getBoundingClientRect();
this.elements.contextmenu.style.display = "block";
const rect = this.elements.contextmenu.getBoundingClientRect();
const up = e.offsetY + rect.height > parentRect.height - 25;
const left = e.offsetX + rect.width > parentRect.width - 5;
- this.elements.contextmenu.style.left = (e.offsetX - (left ? rect.width : 0)) + "px";
- this.elements.contextmenu.style.top = (e.offsetY - (up ? rect.height : 0)) + "px";
- })
+ this.elements.contextmenu.style.left =
+ e.offsetX - (left ? rect.width : 0) + "px";
+ this.elements.contextmenu.style.top =
+ e.offsetY - (up ? rect.height : 0) + "px";
+ });
const hideMenu = () => {
this.elements.contextmenu.style.display = "none";
- }
- this.addEventListener(this.elements.contextmenu, "contextmenu", (e) => e.preventDefault());
- this.addEventListener(this.elements.parent, "contextmenu", (e) => e.preventDefault());
+ };
+ this.addEventListener(this.elements.contextmenu, "contextmenu", (e) =>
+ e.preventDefault()
+ );
+ this.addEventListener(this.elements.parent, "contextmenu", (e) =>
+ e.preventDefault()
+ );
this.addEventListener(this.game, "mousedown touchend", hideMenu);
const parent = this.createElement("ul");
const addButton = (title, hidden, functi0n) => {
@@ -1529,12 +2029,19 @@ class EmulatorJS {
parent.appendChild(li);
hideMenu();
return li;
- }
+ };
let screenshotUrl;
const screenshot = addButton("Take Screenshot", false, () => {
if (screenshotUrl) URL.revokeObjectURL(screenshotUrl);
const date = new Date();
- const fileName = this.getBaseFileName() + "-" + date.getMonth() + "-" + date.getDate() + "-" + date.getFullYear();
+ const fileName =
+ this.getBaseFileName() +
+ "-" +
+ date.getMonth() +
+ "-" +
+ date.getDate() +
+ "-" +
+ date.getFullYear();
this.screenshot((blob, format) => {
screenshotUrl = URL.createObjectURL(blob);
const a = this.createElement("a");
@@ -1546,38 +2053,54 @@ class EmulatorJS {
});
let screenMediaRecorder = null;
- const startScreenRecording = addButton("Start Screen Recording", false, () => {
- if (screenMediaRecorder !== null) {
- screenMediaRecorder.stop();
+ const startScreenRecording = addButton(
+ "Start Screen Recording",
+ false,
+ () => {
+ if (screenMediaRecorder !== null) {
+ screenMediaRecorder.stop();
+ }
+ screenMediaRecorder = this.screenRecord();
+ startScreenRecording.setAttribute("hidden", "hidden");
+ stopScreenRecording.removeAttribute("hidden");
+ hideMenu();
}
- screenMediaRecorder = this.screenRecord();
- startScreenRecording.setAttribute("hidden", "hidden");
- stopScreenRecording.removeAttribute("hidden");
- hideMenu();
- });
- const stopScreenRecording = addButton("Stop Screen Recording", true, () => {
- if (screenMediaRecorder !== null) {
- screenMediaRecorder.stop();
- screenMediaRecorder = null;
+ );
+ const stopScreenRecording = addButton(
+ "Stop Screen Recording",
+ true,
+ () => {
+ if (screenMediaRecorder !== null) {
+ screenMediaRecorder.stop();
+ screenMediaRecorder = null;
+ }
+ startScreenRecording.removeAttribute("hidden");
+ stopScreenRecording.setAttribute("hidden", "hidden");
+ hideMenu();
}
- startScreenRecording.removeAttribute("hidden");
- stopScreenRecording.setAttribute("hidden", "hidden");
- hideMenu();
- });
+ );
const qSave = addButton("Quick Save", false, () => {
- const slot = this.getSettingValue("save-state-slot") ? this.getSettingValue("save-state-slot") : "1";
+ const slot = this.getSettingValue("save-state-slot")
+ ? this.getSettingValue("save-state-slot")
+ : "1";
if (this.gameManager.quickSave(slot)) {
- this.displayMessage(this.localization("SAVED STATE TO SLOT") + " " + slot);
+ this.displayMessage(
+ this.localization("SAVED STATE TO SLOT") + " " + slot
+ );
} else {
this.displayMessage(this.localization("FAILED TO SAVE STATE"));
}
hideMenu();
});
const qLoad = addButton("Quick Load", false, () => {
- const slot = this.getSettingValue("save-state-slot") ? this.getSettingValue("save-state-slot") : "1";
+ const slot = this.getSettingValue("save-state-slot")
+ ? this.getSettingValue("save-state-slot")
+ : "1";
this.gameManager.quickLoad(slot);
- this.displayMessage(this.localization("LOADED STATE FROM SLOT") + " " + slot);
+ this.displayMessage(
+ this.localization("LOADED STATE FROM SLOT") + " " + slot
+ );
hideMenu();
});
this.elements.contextMenu = {
@@ -1585,14 +2108,14 @@ class EmulatorJS {
startScreenRecording: startScreenRecording,
stopScreenRecording: stopScreenRecording,
save: qSave,
- load: qLoad
- }
+ load: qLoad,
+ };
addButton("EmulatorJS v" + this.ejs_version, false, () => {
hideMenu();
const body = this.createPopup("EmulatorJS", {
- "Close": () => {
+ Close: () => {
this.closePopup();
- }
+ },
});
body.style.display = "flex";
@@ -1618,7 +2141,7 @@ class EmulatorJS {
parent.appendChild(li);
hideMenu();
return li;
- }
+ };
//body.style["padding-left"] = "20%";
const home = this.createElement("div");
const license = this.createElement("div");
@@ -1641,16 +2164,30 @@ class EmulatorJS {
retroarch.classList.add("ejs_context_menu_tab");
coreLicense.classList.add("ejs_context_menu_tab");
- this.createLink(home, "https://github.com/EmulatorJS/EmulatorJS", "View on GitHub", true);
+ this.createLink(
+ home,
+ "https://github.com/EmulatorJS/EmulatorJS",
+ "View on GitHub",
+ true
+ );
- this.createLink(home, "https://discord.gg/6akryGkETU", "Join the discord", true);
+ this.createLink(
+ home,
+ "https://discord.gg/6akryGkETU",
+ "Join the discord",
+ true
+ );
const info = this.createElement("div");
this.createLink(info, "https://emulatorjs.org", "EmulatorJS");
// I do not like using innerHTML, though this should be "safe"
info.innerHTML += " is powered by ";
- this.createLink(info, "https://github.com/libretro/RetroArch/", "RetroArch");
+ this.createLink(
+ info,
+ "https://github.com/libretro/RetroArch/",
+ "RetroArch"
+ );
if (this.repository && this.coreName) {
info.innerHTML += ". This core is powered by ";
this.createLink(info, this.repository, this.coreName);
@@ -1660,7 +2197,6 @@ class EmulatorJS {
}
home.appendChild(info);
-
home.appendChild(this.createElement("br"));
menu.appendChild(parent);
let current = home;
@@ -1669,14 +2205,16 @@ class EmulatorJS {
if (current) {
current.style.display = "none";
}
- let activeLi = li.parentElement.querySelector(".ejs_active_list_element");
+ let activeLi = li.parentElement.querySelector(
+ ".ejs_active_list_element"
+ );
if (activeLi) {
activeLi.classList.remove("ejs_active_list_element");
}
li.classList.add("ejs_active_list_element");
current = element;
element.style.display = "";
- }
+ };
addButton("Home", false, (li) => {
setElem(home, li);
}).classList.add("ejs_active_list_element");
@@ -1689,12 +2227,13 @@ class EmulatorJS {
if (this.coreName && this.license) {
addButton(this.coreName + " License", false, (li) => {
setElem(coreLicense, li);
- })
+ });
coreLicense.innerText = this.license;
}
//Todo - Contributors.
- retroarch.innerText = this.localization("This project is powered by") + " ";
+ retroarch.innerText =
+ this.localization("This project is powered by") + " ";
const a = this.createElement("a");
a.href = "https://github.com/libretro/RetroArch";
a.target = "_blank";
@@ -1702,19 +2241,27 @@ class EmulatorJS {
retroarch.appendChild(a);
const licenseLink = this.createElement("a");
licenseLink.target = "_blank";
- licenseLink.href = "https://github.com/libretro/RetroArch/blob/master/COPYING";
- licenseLink.innerText = this.localization("View the RetroArch license here");
+ licenseLink.href =
+ "https://github.com/libretro/RetroArch/blob/master/COPYING";
+ licenseLink.innerText = this.localization(
+ "View the RetroArch license here"
+ );
a.appendChild(this.createElement("br"));
a.appendChild(licenseLink);
- license.innerText = ' GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. \n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n Preamble\n\n The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users. We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors. You can apply it to\nyour programs, too.\n\n When we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights. Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received. You must make sure that they, too, receive\nor can get the source code. And you must show them these terms so they\nknow their rights.\n\n Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n For the developers\' and authors\' protection, the GPL clearly explains\nthat there is no warranty for this free software. For both users\' and\nauthors\' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so. This is fundamentally incompatible with the aim of\nprotecting users\' freedom to change the software. The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable. Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts. If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary. To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n The precise terms and conditions for copying, distribution and\nmodification follow.\n\n TERMS AND CONDITIONS\n\n 0. Definitions.\n\n "This License" refers to version 3 of the GNU General Public License.\n\n "Copyright" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n "The Program" refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as "you". "Licensees" and\n"recipients" may be individuals or organizations.\n\n To "modify" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy. The resulting work is called a "modified version" of the\nearlier work or a work "based on" the earlier work.\n\n A "covered work" means either the unmodified Program or a work based\non the Program.\n\n To "propagate" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n To "convey" a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n An interactive user interface displays "Appropriate Legal Notices"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n 1. Source Code.\n\n The "source code" for a work means the preferred form of the work\nfor making modifications to it. "Object code" means any non-source\nform of a work.\n\n A "Standard Interface" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n The "System Libraries" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n"Major Component", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n The "Corresponding Source" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work\'s\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n The Corresponding Source for a work in source code form is that\nsame work.\n\n 2. Basic Permissions.\n\n All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force. You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright. Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n Conveying under any other circumstances is permitted solely under\nthe conditions stated below. Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n 3. Protecting Users\' Legal Rights From Anti-Circumvention Law.\n\n No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work\'s\nusers, your or third parties\' legal rights to forbid circumvention of\ntechnological measures.\n\n 4. Conveying Verbatim Copies.\n\n You may convey verbatim copies of the Program\'s source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n 5. Conveying Modified Source Versions.\n\n You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n a) The work must carry prominent notices stating that you modified\n it, and giving a relevant date.\n\n b) The work must carry prominent notices stating that it is\n released under this License and any conditions added under section\n 7. This requirement modifies the requirement in section 4 to\n "keep intact all notices".\n\n c) You must license the entire work, as a whole, under this\n License to anyone who comes into possession of a copy. This\n License will therefore apply, along with any applicable section 7\n additional terms, to the whole of the work, and all its parts,\n regardless of how they are packaged. This License gives no\n permission to license the work in any other way, but it does not\n invalidate such permission if you have separately received it.\n\n d) If the work has interactive user interfaces, each must display\n Appropriate Legal Notices; however, if the Program has interactive\n interfaces that do not display Appropriate Legal Notices, your\n work need not make them do so.\n\n A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n"aggregate" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation\'s users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n 6. Conveying Non-Source Forms.\n\n You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n a) Convey the object code in, or embodied in, a physical product\n (including a physical distribution medium), accompanied by the\n Corresponding Source fixed on a durable physical medium\n customarily used for software interchange.\n\n b) Convey the object code in, or embodied in, a physical product\n (including a physical distribution medium), accompanied by a\n written offer, valid for at least three years and valid for as\n long as you offer spare parts or customer support for that product\n model, to give anyone who possesses the object code either (1) a\n copy of the Corresponding Source for all the software in the\n product that is covered by this License, on a durable physical\n medium customarily used for software interchange, for a price no\n more than your reasonable cost of physically performing this\n conveying of source, or (2) access to copy the\n Corresponding Source from a network server at no charge.\n\n c) Convey individual copies of the object code with a copy of the\n written offer to provide the Corresponding Source. This\n alternative is allowed only occasionally and noncommercially, and\n only if you received the object code with such an offer, in accord\n with subsection 6b.\n\n d) Convey the object code by offering access from a designated\n place (gratis or for a charge), and offer equivalent access to the\n Corresponding Source in the same way through the same place at no\n further charge. You need not require recipients to copy the\n Corresponding Source along with the object code. If the place to\n copy the object code is a network server, the Corresponding Source\n may be on a different server (operated by you or a third party)\n that supports equivalent copying facilities, provided you maintain\n clear directions next to the object code saying where to find the\n Corresponding Source. Regardless of what server hosts the\n Corresponding Source, you remain obligated to ensure that it is\n available for as long as needed to satisfy these requirements.\n\n e) Convey the object code using peer-to-peer transmission, provided\n you inform other peers where the object code and Corresponding\n Source of the work are being offered to the general public at no\n charge under subsection 6d.\n\n A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n A "User Product" is either (1) a "consumer product", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling. In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage. For a particular\nproduct received by a particular user, "normally used" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product. A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n "Installation Information" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source. The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed. Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n 7. Additional Terms.\n\n "Additional permissions" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n a) Disclaiming warranty or limiting liability differently from the\n terms of sections 15 and 16 of this License; or\n\n b) Requiring preservation of specified reasonable legal notices or\n author attributions in that material or in the Appropriate Legal\n Notices displayed by works containing it; or\n\n c) Prohibiting misrepresentation of the origin of that material, or\n requiring that modified versions of such material be marked in\n reasonable ways as different from the original version; or\n\n d) Limiting the use for publicity purposes of names of licensors or\n authors of the material; or\n\n e) Declining to grant rights under trademark law for use of some\n trade names, trademarks, or service marks; or\n\n f) Requiring indemnification of licensors and authors of that\n material by anyone who conveys the material (or modified versions of\n it) with contractual assumptions of liability to the recipient, for\n any liability that these contractual assumptions directly impose on\n those licensors and authors.\n\n All other non-permissive additional terms are considered "further\nrestrictions" within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n 8. Termination.\n\n You may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n 9. Acceptance Not Required for Having Copies.\n\n You are not required to accept this License in order to receive or\nrun a copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n 10. Automatic Licensing of Downstream Recipients.\n\n Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\n An "entity transaction" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party\'s predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n 11. Patents.\n\n A "contributor" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor\'s "contributor version".\n\n A contributor\'s "essential patent claims" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, "control" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor\'s essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n In the following three paragraphs, a "patent license" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To "grant" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. "Knowingly relying" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient\'s use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n A patent license is "discriminatory" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License. You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n 12. No Surrender of Others\' Freedom.\n\n If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all. For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n 13. Use with the GNU Affero General Public License.\n\n Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n 14. Revised Versions of this License.\n\n The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time. Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n Each version is given a distinguishing version number. If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License "or any later version" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation. If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy\'s\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n Later license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n 15. Disclaimer of Warranty.\n\n THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n 16. Limitation of Liability.\n\n IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n 17. Interpretation of Sections 15 and 16.\n\n If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n END OF TERMS AND CONDITIONS\n\n How to Apply These Terms to Your New Programs\n\n If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n To do so, attach the following notices to the program. It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe "copyright" line and a pointer to where the full notice is found.\n\n EmulatorJS: RetroArch on the web\n Copyright (C) 2022-2024 Ethan O\'Brien\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n\nAlso add information on how to contact you by electronic and paper mail.\n\n If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n EmulatorJS Copyright (C) 2023-2025 Ethan O\'Brien\n This program comes with ABSOLUTELY NO WARRANTY; for details type `show w\'.\n This is free software, and you are welcome to redistribute it\n under certain conditions; type `show c\' for details.\n\nThe hypothetical commands `show w\' and `show c\' should show the appropriate\nparts of the General Public License. Of course, your program\'s commands\nmight be different; for a GUI interface, you would use an "about box".\n\n You should also get your employer (if you work as a programmer) or school,\nif any, to sign a "copyright disclaimer" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n.\n\n The GNU General Public License does not permit incorporating your program\ninto proprietary programs. If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library. If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License. But first, please read\n.\n';
+ license.innerText =
+ ' GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. \n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n Preamble\n\n The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works. By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users. We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors. You can apply it to\nyour programs, too.\n\n When we speak of free software, we are referring to freedom, not\nprice. Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights. Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received. You must make sure that they, too, receive\nor can get the source code. And you must show them these terms so they\nknow their rights.\n\n Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n For the developers\' and authors\' protection, the GPL clearly explains\nthat there is no warranty for this free software. For both users\' and\nauthors\' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so. This is fundamentally incompatible with the aim of\nprotecting users\' freedom to change the software. The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable. Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts. If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary. To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n The precise terms and conditions for copying, distribution and\nmodification follow.\n\n TERMS AND CONDITIONS\n\n 0. Definitions.\n\n "This License" refers to version 3 of the GNU General Public License.\n\n "Copyright" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n "The Program" refers to any copyrightable work licensed under this\nLicense. Each licensee is addressed as "you". "Licensees" and\n"recipients" may be individuals or organizations.\n\n To "modify" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy. The resulting work is called a "modified version" of the\nearlier work or a work "based on" the earlier work.\n\n A "covered work" means either the unmodified Program or a work based\non the Program.\n\n To "propagate" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy. Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n To "convey" a work means any kind of propagation that enables other\nparties to make or receive copies. Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n An interactive user interface displays "Appropriate Legal Notices"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License. If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n 1. Source Code.\n\n The "source code" for a work means the preferred form of the work\nfor making modifications to it. "Object code" means any non-source\nform of a work.\n\n A "Standard Interface" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n The "System Libraries" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form. A\n"Major Component", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n The "Corresponding Source" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities. However, it does not include the work\'s\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work. For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n The Corresponding Source for a work in source code form is that\nsame work.\n\n 2. Basic Permissions.\n\n All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met. This License explicitly affirms your unlimited\npermission to run the unmodified Program. The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work. This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force. You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright. Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n Conveying under any other circumstances is permitted solely under\nthe conditions stated below. Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n 3. Protecting Users\' Legal Rights From Anti-Circumvention Law.\n\n No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work\'s\nusers, your or third parties\' legal rights to forbid circumvention of\ntechnological measures.\n\n 4. Conveying Verbatim Copies.\n\n You may convey verbatim copies of the Program\'s source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n 5. Conveying Modified Source Versions.\n\n You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n a) The work must carry prominent notices stating that you modified\n it, and giving a relevant date.\n\n b) The work must carry prominent notices stating that it is\n released under this License and any conditions added under section\n 7. This requirement modifies the requirement in section 4 to\n "keep intact all notices".\n\n c) You must license the entire work, as a whole, under this\n License to anyone who comes into possession of a copy. This\n License will therefore apply, along with any applicable section 7\n additional terms, to the whole of the work, and all its parts,\n regardless of how they are packaged. This License gives no\n permission to license the work in any other way, but it does not\n invalidate such permission if you have separately received it.\n\n d) If the work has interactive user interfaces, each must display\n Appropriate Legal Notices; however, if the Program has interactive\n interfaces that do not display Appropriate Legal Notices, your\n work need not make them do so.\n\n A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n"aggregate" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation\'s users\nbeyond what the individual works permit. Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n 6. Conveying Non-Source Forms.\n\n You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n a) Convey the object code in, or embodied in, a physical product\n (including a physical distribution medium), accompanied by the\n Corresponding Source fixed on a durable physical medium\n customarily used for software interchange.\n\n b) Convey the object code in, or embodied in, a physical product\n (including a physical distribution medium), accompanied by a\n written offer, valid for at least three years and valid for as\n long as you offer spare parts or customer support for that product\n model, to give anyone who possesses the object code either (1) a\n copy of the Corresponding Source for all the software in the\n product that is covered by this License, on a durable physical\n medium customarily used for software interchange, for a price no\n more than your reasonable cost of physically performing this\n conveying of source, or (2) access to copy the\n Corresponding Source from a network server at no charge.\n\n c) Convey individual copies of the object code with a copy of the\n written offer to provide the Corresponding Source. This\n alternative is allowed only occasionally and noncommercially, and\n only if you received the object code with such an offer, in accord\n with subsection 6b.\n\n d) Convey the object code by offering access from a designated\n place (gratis or for a charge), and offer equivalent access to the\n Corresponding Source in the same way through the same place at no\n further charge. You need not require recipients to copy the\n Corresponding Source along with the object code. If the place to\n copy the object code is a network server, the Corresponding Source\n may be on a different server (operated by you or a third party)\n that supports equivalent copying facilities, provided you maintain\n clear directions next to the object code saying where to find the\n Corresponding Source. Regardless of what server hosts the\n Corresponding Source, you remain obligated to ensure that it is\n available for as long as needed to satisfy these requirements.\n\n e) Convey the object code using peer-to-peer transmission, provided\n you inform other peers where the object code and Corresponding\n Source of the work are being offered to the general public at no\n charge under subsection 6d.\n\n A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n A "User Product" is either (1) a "consumer product", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling. In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage. For a particular\nproduct received by a particular user, "normally used" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product. A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n "Installation Information" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source. The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information. But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed. Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n 7. Additional Terms.\n\n "Additional permissions" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law. If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit. (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.) You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n a) Disclaiming warranty or limiting liability differently from the\n terms of sections 15 and 16 of this License; or\n\n b) Requiring preservation of specified reasonable legal notices or\n author attributions in that material or in the Appropriate Legal\n Notices displayed by works containing it; or\n\n c) Prohibiting misrepresentation of the origin of that material, or\n requiring that modified versions of such material be marked in\n reasonable ways as different from the original version; or\n\n d) Limiting the use for publicity purposes of names of licensors or\n authors of the material; or\n\n e) Declining to grant rights under trademark law for use of some\n trade names, trademarks, or service marks; or\n\n f) Requiring indemnification of licensors and authors of that\n material by anyone who conveys the material (or modified versions of\n it) with contractual assumptions of liability to the recipient, for\n any liability that these contractual assumptions directly impose on\n those licensors and authors.\n\n All other non-permissive additional terms are considered "further\nrestrictions" within the meaning of section 10. If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term. If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n 8. Termination.\n\n You may not propagate or modify a covered work except as expressly\nprovided under this License. Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License. If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n 9. Acceptance Not Required for Having Copies.\n\n You are not required to accept this License in order to receive or\nrun a copy of the Program. Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance. However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work. These actions infringe copyright if you do\nnot accept this License. Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n 10. Automatic Licensing of Downstream Recipients.\n\n Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License. You are not responsible\nfor enforcing compliance by third parties with this License.\n\n An "entity transaction" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations. If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party\'s predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License. For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n 11. Patents.\n\n A "contributor" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based. The\nwork thus licensed is called the contributor\'s "contributor version".\n\n A contributor\'s "essential patent claims" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version. For\npurposes of this definition, "control" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor\'s essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n In the following three paragraphs, a "patent license" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement). To "grant" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients. "Knowingly relying" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient\'s use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n A patent license is "discriminatory" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License. You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n 12. No Surrender of Others\' Freedom.\n\n If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License. If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all. For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n 13. Use with the GNU Affero General Public License.\n\n Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work. The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n 14. Revised Versions of this License.\n\n The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time. Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n Each version is given a distinguishing version number. If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License "or any later version" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation. If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy\'s\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n Later license versions may give you additional or different\npermissions. However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n 15. Disclaimer of Warranty.\n\n THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n 16. Limitation of Liability.\n\n IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n 17. Interpretation of Sections 15 and 16.\n\n If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n END OF TERMS AND CONDITIONS\n\n How to Apply These Terms to Your New Programs\n\n If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n To do so, attach the following notices to the program. It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe "copyright" line and a pointer to where the full notice is found.\n\n EmulatorJS: RetroArch on the web\n Copyright (C) 2022-2024 Ethan O\'Brien\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n\nAlso add information on how to contact you by electronic and paper mail.\n\n If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n EmulatorJS Copyright (C) 2023-2025 Ethan O\'Brien\n This program comes with ABSOLUTELY NO WARRANTY; for details type `show w\'.\n This is free software, and you are welcome to redistribute it\n under certain conditions; type `show c\' for details.\n\nThe hypothetical commands `show w\' and `show c\' should show the appropriate\nparts of the General Public License. Of course, your program\'s commands\nmight be different; for a GUI interface, you would use an "about box".\n\n You should also get your employer (if you work as a programmer) or school,\nif any, to sign a "copyright disclaimer" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n.\n\n The GNU General Public License does not permit incorporating your program\ninto proprietary programs. If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library. If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License. But first, please read\n.\n';
});
if (this.config.buttonOpts) {
- if (this.config.buttonOpts.screenshot.visible === false) screenshot.setAttribute("hidden", "");
- if (this.config.buttonOpts.screenRecord.visible === false) startScreenRecording.setAttribute("hidden", "");
- if (this.config.buttonOpts.quickSave.visible === false) qSave.setAttribute("hidden", "");
- if (this.config.buttonOpts.quickLoad.visible === false) qLoad.setAttribute("hidden", "");
+ if (this.config.buttonOpts.screenshot.visible === false)
+ screenshot.setAttribute("hidden", "");
+ if (this.config.buttonOpts.screenRecord.visible === false)
+ startScreenRecording.setAttribute("hidden", "");
+ if (this.config.buttonOpts.quickSave.visible === false)
+ qSave.setAttribute("hidden", "");
+ if (this.config.buttonOpts.quickLoad.visible === false)
+ qLoad.setAttribute("hidden", "");
}
this.elements.contextmenu.appendChild(parent);
@@ -1725,7 +2272,7 @@ class EmulatorJS {
if (this.currentPopup !== null) {
try {
this.currentPopup.remove();
- } catch(e) {}
+ } catch (e) {}
this.currentPopup = null;
}
}
@@ -1773,12 +2320,17 @@ class EmulatorJS {
file.type = "file";
this.addEventListener(file, "change", (e) => {
resolve(e.target.files[0]);
- })
+ });
file.click();
- })
+ });
}
isPopupOpen() {
- return this.cheatMenu.style.display !== "none" || this.netplayMenu.style.display !== "none" || this.controlMenu.style.display !== "none" || this.currentPopup !== null;
+ return (
+ this.cheatMenu.style.display !== "none" ||
+ this.netplayMenu.style.display !== "none" ||
+ this.controlMenu.style.display !== "none" ||
+ this.currentPopup !== null
+ );
}
isChild(first, second) {
if (!first || !second) return false;
@@ -1790,7 +2342,10 @@ class EmulatorJS {
return adown.contains(second);
}
- return first.compareDocumentPosition && first.compareDocumentPosition(second) & 16;
+ return (
+ first.compareDocumentPosition &&
+ first.compareDocumentPosition(second) & 16
+ );
}
createBottomMenuBar() {
this.elements.menu = this.createElement("div");
@@ -1799,22 +2354,23 @@ class EmulatorJS {
this.elements.menu.style.opacity = 0;
this.on("start", (e) => {
this.elements.menu.style.opacity = "";
- })
+ });
this.elements.menu.classList.add("ejs_menu_bar");
this.elements.menu.classList.add("ejs_menu_bar_hidden");
let timeout = null;
let ignoreEvents = false;
const hide = () => {
- if (this.paused || this.settingsMenuOpen || this.disksMenuOpen) return;
+ if (this.paused || this.settingsMenuOpen || this.disksMenuOpen)
+ return;
this.elements.menu.classList.add("ejs_menu_bar_hidden");
- }
+ };
const show = () => {
clearTimeout(timeout);
timeout = setTimeout(hide, 3000);
this.elements.menu.classList.remove("ejs_menu_bar_hidden");
- }
+ };
this.menu = {
close: () => {
@@ -1830,22 +2386,34 @@ class EmulatorJS {
toggle: () => {
if (!this.started) return;
clearTimeout(timeout);
- if (this.elements.menu.classList.contains("ejs_menu_bar_hidden")) {
+ if (
+ this.elements.menu.classList.contains("ejs_menu_bar_hidden")
+ ) {
timeout = setTimeout(hide, 3000);
}
this.elements.menu.classList.toggle("ejs_menu_bar_hidden");
- }
- }
+ },
+ };
this.createBottomMenuBarListeners = () => {
const clickListener = (e) => {
if (e.pointerType === "touch") return;
- if (!this.started || ignoreEvents || document.pointerLockElement === this.canvas) return;
+ if (
+ !this.started ||
+ ignoreEvents ||
+ document.pointerLockElement === this.canvas
+ )
+ return;
if (this.isPopupOpen()) return;
show();
- }
+ };
const mouseListener = (e) => {
- if (!this.started || ignoreEvents || document.pointerLockElement === this.canvas) return;
+ if (
+ !this.started ||
+ ignoreEvents ||
+ document.pointerLockElement === this.canvas
+ )
+ return;
if (this.isPopupOpen()) return;
const deltaX = e.movementX;
const deltaY = e.movementY;
@@ -1860,41 +2428,72 @@ class EmulatorJS {
if (angle < 0) angle += 360;
if (angle < 85 || angle > 95) return;
show();
- }
- if (this.menu.mousemoveListener) this.removeEventListener(this.menu.mousemoveListener);
-
- if ((this.preGetSetting("menubarBehavior") || "downward") === "downward") {
- this.menu.mousemoveListener = this.addEventListener(this.elements.parent, "mousemove", mouseListener);
+ };
+ if (this.menu.mousemoveListener)
+ this.removeEventListener(this.menu.mousemoveListener);
+
+ if (
+ (this.preGetSetting("menubarBehavior") || "downward") ===
+ "downward"
+ ) {
+ this.menu.mousemoveListener = this.addEventListener(
+ this.elements.parent,
+ "mousemove",
+ mouseListener
+ );
} else {
- this.menu.mousemoveListener = this.addEventListener(this.elements.parent, "mousemove", clickListener);
+ this.menu.mousemoveListener = this.addEventListener(
+ this.elements.parent,
+ "mousemove",
+ clickListener
+ );
}
this.addEventListener(this.elements.parent, "click", clickListener);
- }
+ };
this.createBottomMenuBarListeners();
this.elements.parent.appendChild(this.elements.menu);
let tmout;
- this.addEventListener(this.elements.parent, "mousedown touchstart", (e) => {
- if (this.isChild(this.elements.menu, e.target) || this.isChild(this.elements.menuToggle, e.target)) return;
- if (!this.started || this.elements.menu.classList.contains("ejs_menu_bar_hidden") || this.isPopupOpen()) return;
- const width = this.elements.parent.getBoundingClientRect().width;
- if (width > 575) return;
- clearTimeout(tmout);
- tmout = setTimeout(() => {
- ignoreEvents = false;
- }, 2000)
- ignoreEvents = true;
- this.menu.close();
- })
+ this.addEventListener(
+ this.elements.parent,
+ "mousedown touchstart",
+ (e) => {
+ if (
+ this.isChild(this.elements.menu, e.target) ||
+ this.isChild(this.elements.menuToggle, e.target)
+ )
+ return;
+ if (
+ !this.started ||
+ this.elements.menu.classList.contains(
+ "ejs_menu_bar_hidden"
+ ) ||
+ this.isPopupOpen()
+ )
+ return;
+ const width =
+ this.elements.parent.getBoundingClientRect().width;
+ if (width > 575) return;
+ clearTimeout(tmout);
+ tmout = setTimeout(() => {
+ ignoreEvents = false;
+ }, 2000);
+ ignoreEvents = true;
+ this.menu.close();
+ }
+ );
let paddingSet = false;
//Now add buttons
const addButton = (buttonConfig, callback, element, both) => {
const button = this.createElement("button");
button.type = "button";
- const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
+ const svg = document.createElementNS(
+ "http://www.w3.org/2000/svg",
+ "svg"
+ );
svg.setAttribute("role", "presentation");
svg.setAttribute("focusable", "false");
svg.innerHTML = buttonConfig.icon;
@@ -1919,8 +2518,8 @@ class EmulatorJS {
this.addEventListener(button, "click", buttonConfig.callback);
}
return both ? [button, svg, text] : button;
- }
-
+ };
+
const restartButton = addButton(this.config.buttonOpts.restart, () => {
if (this.isNetplay && this.netplay.owner) {
this.gameManager.restart();
@@ -1970,57 +2569,84 @@ class EmulatorJS {
this.canvas.mozExitPointerLock();
}
}
- }
+ };
this.play = (dontUpdate) => {
if (this.paused) this.togglePlaying(dontUpdate);
- }
+ };
this.pause = (dontUpdate) => {
if (!this.paused) this.togglePlaying(dontUpdate);
- }
+ };
let stateUrl;
- const saveState = addButton(this.config.buttonOpts.saveState, async () => {
- let state;
- try {
- state = this.gameManager.getState();
- } catch(e) {
- this.displayMessage(this.localization("FAILED TO SAVE STATE"));
- return;
+ const saveState = addButton(
+ this.config.buttonOpts.saveState,
+ async () => {
+ let state;
+ try {
+ state = this.gameManager.getState();
+ } catch (e) {
+ this.displayMessage(
+ this.localization("FAILED TO SAVE STATE")
+ );
+ return;
+ }
+ const { screenshot, format } = await this.takeScreenshot(
+ this.capture.photo.source,
+ this.capture.photo.format,
+ this.capture.photo.upscale
+ );
+ const called = this.callEvent("saveState", {
+ screenshot: screenshot,
+ format: format,
+ state: state,
+ });
+ if (called > 0) return;
+ if (stateUrl) URL.revokeObjectURL(stateUrl);
+ if (
+ this.getSettingValue("save-state-location") === "browser" &&
+ this.saveInBrowserSupported()
+ ) {
+ this.storage.states.put(
+ this.getBaseFileName() + ".state",
+ state
+ );
+ this.displayMessage(
+ this.localization("SAVED STATE TO BROWSER")
+ );
+ } else {
+ const blob = new Blob([state]);
+ stateUrl = URL.createObjectURL(blob);
+ const a = this.createElement("a");
+ a.href = stateUrl;
+ a.download = this.getBaseFileName() + ".state";
+ a.click();
+ }
}
- const { screenshot, format } = await this.takeScreenshot(this.capture.photo.source, this.capture.photo.format, this.capture.photo.upscale);
- const called = this.callEvent("saveState", {
- screenshot: screenshot,
- format: format,
- state: state
- });
- if (called > 0) return;
- if (stateUrl) URL.revokeObjectURL(stateUrl);
- if (this.getSettingValue("save-state-location") === "browser" && this.saveInBrowserSupported()) {
- this.storage.states.put(this.getBaseFileName() + ".state", state);
- this.displayMessage(this.localization("SAVED STATE TO BROWSER"));
- } else {
- const blob = new Blob([state]);
- stateUrl = URL.createObjectURL(blob);
- const a = this.createElement("a");
- a.href = stateUrl;
- a.download = this.getBaseFileName() + ".state";
- a.click();
+ );
+ const loadState = addButton(
+ this.config.buttonOpts.loadState,
+ async () => {
+ const called = this.callEvent("loadState");
+ if (called > 0) return;
+ if (
+ this.getSettingValue("save-state-location") === "browser" &&
+ this.saveInBrowserSupported()
+ ) {
+ this.storage.states
+ .get(this.getBaseFileName() + ".state")
+ .then((e) => {
+ this.gameManager.loadState(e);
+ this.displayMessage(
+ this.localization("LOADED STATE FROM BROWSER")
+ );
+ });
+ } else {
+ const file = await this.selectFile();
+ const state = new Uint8Array(await file.arrayBuffer());
+ this.gameManager.loadState(state);
+ }
}
- });
- const loadState = addButton(this.config.buttonOpts.loadState, async () => {
- const called = this.callEvent("loadState");
- if (called > 0) return;
- if (this.getSettingValue("save-state-location") === "browser" && this.saveInBrowserSupported()) {
- this.storage.states.get(this.getBaseFileName() + ".state").then(e => {
- this.gameManager.loadState(e);
- this.displayMessage(this.localization("LOADED STATE FROM BROWSER"));
- })
- } else {
- const file = await this.selectFile();
- const state = new Uint8Array(await file.arrayBuffer());
- this.gameManager.loadState(state);
- }
- });
+ );
const controlMenu = addButton(this.config.buttonOpts.gamepad, () => {
this.controlMenu.style.display = "";
});
@@ -2036,43 +2662,58 @@ class EmulatorJS {
let savUrl;
- const saveSavFiles = addButton(this.config.buttonOpts.saveSavFiles, async () => {
- const file = await this.gameManager.getSaveFile();
- const { screenshot, format } = await this.takeScreenshot(this.capture.photo.source, this.capture.photo.format, this.capture.photo.upscale);
- const called = this.callEvent("saveSave", {
- screenshot: screenshot,
- format: format,
- save: file
- });
- if (called > 0) return;
- const blob = new Blob([file]);
- savUrl = URL.createObjectURL(blob);
- const a = this.createElement("a");
- a.href = savUrl;
- a.download = this.gameManager.getSaveFilePath().split("/").pop();
- a.click();
- });
- const loadSavFiles = addButton(this.config.buttonOpts.loadSavFiles, async () => {
- const called = this.callEvent("loadSave");
- if (called > 0) return;
- const file = await this.selectFile();
- const sav = new Uint8Array(await file.arrayBuffer());
- const path = this.gameManager.getSaveFilePath();
- const paths = path.split("/");
- let cp = "";
- for (let i = 0; i < paths.length - 1; i++) {
- if (paths[i] === "") continue;
- cp += "/" + paths[i];
- if (!this.gameManager.FS.analyzePath(cp).exists) this.gameManager.FS.mkdir(cp);
+ const saveSavFiles = addButton(
+ this.config.buttonOpts.saveSavFiles,
+ async () => {
+ const file = await this.gameManager.getSaveFile();
+ const { screenshot, format } = await this.takeScreenshot(
+ this.capture.photo.source,
+ this.capture.photo.format,
+ this.capture.photo.upscale
+ );
+ const called = this.callEvent("saveSave", {
+ screenshot: screenshot,
+ format: format,
+ save: file,
+ });
+ if (called > 0) return;
+ const blob = new Blob([file]);
+ savUrl = URL.createObjectURL(blob);
+ const a = this.createElement("a");
+ a.href = savUrl;
+ a.download = this.gameManager
+ .getSaveFilePath()
+ .split("/")
+ .pop();
+ a.click();
}
- if (this.gameManager.FS.analyzePath(path).exists) this.gameManager.FS.unlink(path);
- this.gameManager.FS.writeFile(path, sav);
- this.gameManager.loadSaveFiles();
- });
+ );
+ const loadSavFiles = addButton(
+ this.config.buttonOpts.loadSavFiles,
+ async () => {
+ const called = this.callEvent("loadSave");
+ if (called > 0) return;
+ const file = await this.selectFile();
+ const sav = new Uint8Array(await file.arrayBuffer());
+ const path = this.gameManager.getSaveFilePath();
+ const paths = path.split("/");
+ let cp = "";
+ for (let i = 0; i < paths.length - 1; i++) {
+ if (paths[i] === "") continue;
+ cp += "/" + paths[i];
+ if (!this.gameManager.FS.analyzePath(cp).exists)
+ this.gameManager.FS.mkdir(cp);
+ }
+ if (this.gameManager.FS.analyzePath(path).exists)
+ this.gameManager.FS.unlink(path);
+ this.gameManager.FS.writeFile(path, sav);
+ this.gameManager.loadSaveFiles();
+ }
+ );
const netplay = addButton(this.config.buttonOpts.netplay, async () => {
this.openNetplayMenu();
});
-
+
// add custom buttons
// get all elements from this.config.buttonOpts with custom: true
if (this.config.buttonOpts) {
@@ -2090,19 +2731,27 @@ class EmulatorJS {
const volumeSettings = this.createElement("div");
volumeSettings.classList.add("ejs_volume_parent");
- const muteButton = addButton(this.config.buttonOpts.mute, () => {
- muteButton.style.display = "none";
- unmuteButton.style.display = "";
- this.muted = true;
- this.setVolume(0);
- }, volumeSettings);
- const unmuteButton = addButton(this.config.buttonOpts.unmute, () => {
- if (this.volume === 0) this.volume = 0.5;
- muteButton.style.display = "";
- unmuteButton.style.display = "none";
- this.muted = false;
- this.setVolume(this.volume);
- }, volumeSettings);
+ const muteButton = addButton(
+ this.config.buttonOpts.mute,
+ () => {
+ muteButton.style.display = "none";
+ unmuteButton.style.display = "";
+ this.muted = true;
+ this.setVolume(0);
+ },
+ volumeSettings
+ );
+ const unmuteButton = addButton(
+ this.config.buttonOpts.unmute,
+ () => {
+ if (this.volume === 0) this.volume = 0.5;
+ muteButton.style.display = "";
+ unmuteButton.style.display = "none";
+ this.muted = false;
+ this.setVolume(this.volume);
+ },
+ volumeSettings
+ );
unmuteButton.style.display = "none";
const volumeSlider = this.createElement("input");
@@ -2119,94 +2768,186 @@ class EmulatorJS {
this.setVolume = (volume) => {
this.saveSettings();
- this.muted = (volume === 0);
+ this.muted = volume === 0;
volumeSlider.value = volume;
volumeSlider.setAttribute("aria-valuenow", volume * 100);
- volumeSlider.setAttribute("aria-valuetext", (volume * 100).toFixed(1) + "%");
- volumeSlider.setAttribute("style", "--value: " + volume * 100 + "%;margin-left: 5px;position: relative;z-index: 2;");
- if (this.Module.AL && this.Module.AL.currentCtx && this.Module.AL.currentCtx.sources) {
- this.Module.AL.currentCtx.sources.forEach(e => {
+ volumeSlider.setAttribute(
+ "aria-valuetext",
+ (volume * 100).toFixed(1) + "%"
+ );
+ volumeSlider.setAttribute(
+ "style",
+ "--value: " +
+ volume * 100 +
+ "%;margin-left: 5px;position: relative;z-index: 2;"
+ );
+ if (
+ this.Module.AL &&
+ this.Module.AL.currentCtx &&
+ this.Module.AL.currentCtx.sources
+ ) {
+ this.Module.AL.currentCtx.sources.forEach((e) => {
e.gain.gain.value = volume;
- })
+ });
}
- if (!this.config.buttonOpts || this.config.buttonOpts.mute !== false) {
- unmuteButton.style.display = (volume === 0) ? "" : "none";
- muteButton.style.display = (volume === 0) ? "none" : "";
+ if (
+ !this.config.buttonOpts ||
+ this.config.buttonOpts.mute !== false
+ ) {
+ unmuteButton.style.display = volume === 0 ? "" : "none";
+ muteButton.style.display = volume === 0 ? "none" : "";
}
- }
+ };
- this.addEventListener(volumeSlider, "change mousemove touchmove mousedown touchstart mouseup", (e) => {
- setTimeout(() => {
- const newVal = parseFloat(volumeSlider.value);
- if (newVal === 0 && this.muted) return;
- this.volume = newVal;
- this.setVolume(this.volume);
- }, 5);
- })
+ this.addEventListener(
+ volumeSlider,
+ "change mousemove touchmove mousedown touchstart mouseup",
+ (e) => {
+ setTimeout(() => {
+ const newVal = parseFloat(volumeSlider.value);
+ if (newVal === 0 && this.muted) return;
+ this.volume = newVal;
+ this.setVolume(this.volume);
+ }, 5);
+ }
+ );
- if (!this.config.buttonOpts || this.config.buttonOpts.volume !== false) {
+ if (
+ !this.config.buttonOpts ||
+ this.config.buttonOpts.volume !== false
+ ) {
volumeSettings.appendChild(volumeSlider);
}
this.elements.menu.appendChild(volumeSettings);
- const contextMenuButton = addButton(this.config.buttonOpts.contextMenu, () => {
- if (this.elements.contextmenu.style.display === "none") {
- this.elements.contextmenu.style.display = "block";
- this.elements.contextmenu.style.left = (getComputedStyle(this.elements.parent).width.split("px")[0] / 2 - getComputedStyle(this.elements.contextmenu).width.split("px")[0] / 2) + "px";
- this.elements.contextmenu.style.top = (getComputedStyle(this.elements.parent).height.split("px")[0] / 2 - getComputedStyle(this.elements.contextmenu).height.split("px")[0] / 2) + "px";
- setTimeout(this.menu.close.bind(this), 20);
- } else {
- this.elements.contextmenu.style.display = "none";
+ const contextMenuButton = addButton(
+ this.config.buttonOpts.contextMenu,
+ () => {
+ if (this.elements.contextmenu.style.display === "none") {
+ this.elements.contextmenu.style.display = "block";
+ this.elements.contextmenu.style.left =
+ getComputedStyle(this.elements.parent).width.split(
+ "px"
+ )[0] /
+ 2 -
+ getComputedStyle(this.elements.contextmenu).width.split(
+ "px"
+ )[0] /
+ 2 +
+ "px";
+ this.elements.contextmenu.style.top =
+ getComputedStyle(this.elements.parent).height.split(
+ "px"
+ )[0] /
+ 2 -
+ getComputedStyle(
+ this.elements.contextmenu
+ ).height.split("px")[0] /
+ 2 +
+ "px";
+ setTimeout(this.menu.close.bind(this), 20);
+ } else {
+ this.elements.contextmenu.style.display = "none";
+ }
}
- });
+ );
this.diskParent = this.createElement("div");
this.diskParent.id = "ejs_disksMenu";
this.disksMenuOpen = false;
- const diskButton = addButton(this.config.buttonOpts.diskButton, () => {
- this.disksMenuOpen = !this.disksMenuOpen;
- diskButton[1].classList.toggle("ejs_svg_rotate", this.disksMenuOpen);
- this.disksMenu.style.display = this.disksMenuOpen ? "" : "none";
- diskButton[2].classList.toggle("ejs_disks_text", this.disksMenuOpen);
- }, this.diskParent, true);
+ const diskButton = addButton(
+ this.config.buttonOpts.diskButton,
+ () => {
+ this.disksMenuOpen = !this.disksMenuOpen;
+ diskButton[1].classList.toggle(
+ "ejs_svg_rotate",
+ this.disksMenuOpen
+ );
+ this.disksMenu.style.display = this.disksMenuOpen ? "" : "none";
+ diskButton[2].classList.toggle(
+ "ejs_disks_text",
+ this.disksMenuOpen
+ );
+ },
+ this.diskParent,
+ true
+ );
this.elements.menu.appendChild(this.diskParent);
this.closeDisksMenu = () => {
if (!this.disksMenu) return;
this.disksMenuOpen = false;
- diskButton[1].classList.toggle("ejs_svg_rotate", this.disksMenuOpen);
- diskButton[2].classList.toggle("ejs_disks_text", this.disksMenuOpen);
+ diskButton[1].classList.toggle(
+ "ejs_svg_rotate",
+ this.disksMenuOpen
+ );
+ diskButton[2].classList.toggle(
+ "ejs_disks_text",
+ this.disksMenuOpen
+ );
this.disksMenu.style.display = "none";
- }
- this.addEventListener(this.elements.parent, "mousedown touchstart", (e) => {
- if (this.isChild(this.disksMenu, e.target)) return;
- if (e.pointerType === "touch") return;
- if (e.target === diskButton[0] || e.target === diskButton[2]) return;
- this.closeDisksMenu();
- })
+ };
+ this.addEventListener(
+ this.elements.parent,
+ "mousedown touchstart",
+ (e) => {
+ if (this.isChild(this.disksMenu, e.target)) return;
+ if (e.pointerType === "touch") return;
+ if (e.target === diskButton[0] || e.target === diskButton[2])
+ return;
+ this.closeDisksMenu();
+ }
+ );
this.settingParent = this.createElement("div");
this.settingsMenuOpen = false;
- const settingButton = addButton(this.config.buttonOpts.settings, () => {
- this.settingsMenuOpen = !this.settingsMenuOpen;
- settingButton[1].classList.toggle("ejs_svg_rotate", this.settingsMenuOpen);
- this.settingsMenu.style.display = this.settingsMenuOpen ? "" : "none";
- settingButton[2].classList.toggle("ejs_settings_text", this.settingsMenuOpen);
- }, this.settingParent, true);
+ const settingButton = addButton(
+ this.config.buttonOpts.settings,
+ () => {
+ this.settingsMenuOpen = !this.settingsMenuOpen;
+ settingButton[1].classList.toggle(
+ "ejs_svg_rotate",
+ this.settingsMenuOpen
+ );
+ this.settingsMenu.style.display = this.settingsMenuOpen
+ ? ""
+ : "none";
+ settingButton[2].classList.toggle(
+ "ejs_settings_text",
+ this.settingsMenuOpen
+ );
+ },
+ this.settingParent,
+ true
+ );
this.elements.menu.appendChild(this.settingParent);
this.closeSettingsMenu = () => {
if (!this.settingsMenu) return;
this.settingsMenuOpen = false;
- settingButton[1].classList.toggle("ejs_svg_rotate", this.settingsMenuOpen);
- settingButton[2].classList.toggle("ejs_settings_text", this.settingsMenuOpen);
+ settingButton[1].classList.toggle(
+ "ejs_svg_rotate",
+ this.settingsMenuOpen
+ );
+ settingButton[2].classList.toggle(
+ "ejs_settings_text",
+ this.settingsMenuOpen
+ );
this.settingsMenu.style.display = "none";
- }
- this.addEventListener(this.elements.parent, "mousedown touchstart", (e) => {
- if (this.isChild(this.settingsMenu, e.target)) return;
- if (e.pointerType === "touch") return;
- if (e.target === settingButton[0] || e.target === settingButton[2]) return;
- this.closeSettingsMenu();
- })
+ };
+ this.addEventListener(
+ this.elements.parent,
+ "mousedown touchstart",
+ (e) => {
+ if (this.isChild(this.settingsMenu, e.target)) return;
+ if (e.pointerType === "touch") return;
+ if (
+ e.target === settingButton[0] ||
+ e.target === settingButton[2]
+ )
+ return;
+ this.closeSettingsMenu();
+ }
+ );
this.addEventListener(this.canvas, "click", (e) => {
if (e.pointerType === "touch") return;
@@ -2218,7 +2959,7 @@ class EmulatorJS {
}
this.menu.close();
}
- })
+ });
const enter = addButton(this.config.buttonOpts.enterFullscreen, () => {
this.toggleFullscreen(true);
@@ -2243,8 +2984,14 @@ class EmulatorJS {
enter.style.display = "none";
if (this.isMobile) {
try {
- screen.orientation.lock(this.getCore(true) === "nds" ? "portrait" : "landscape").catch(e => {});
- } catch(e) {}
+ screen.orientation
+ .lock(
+ this.getCore(true) === "nds"
+ ? "portrait"
+ : "landscape"
+ )
+ .catch((e) => {});
+ } catch (e) {}
}
} else {
if (document.exitFullscreen) {
@@ -2261,79 +3008,94 @@ class EmulatorJS {
if (this.isMobile) {
try {
screen.orientation.unlock();
- } catch(e) {}
+ } catch (e) {}
}
}
- }
+ };
let exitMenuIsOpen = false;
- const exitEmulation = addButton(this.config.buttonOpts.exitEmulation, async () => {
- if (exitMenuIsOpen) return;
- exitMenuIsOpen = true;
- const popups = this.createSubPopup();
- this.game.appendChild(popups[0]);
- popups[1].classList.add("ejs_cheat_parent");
- popups[1].style.width = "100%";
- const popup = popups[1];
- const header = this.createElement("div");
- header.classList.add("ejs_cheat_header");
- const title = this.createElement("h2");
- title.innerText = this.localization("Are you sure you want to exit?");
- title.classList.add("ejs_cheat_heading");
- const close = this.createElement("button");
- close.classList.add("ejs_cheat_close");
- header.appendChild(title);
- header.appendChild(close);
- popup.appendChild(header);
- this.addEventListener(close, "click", (e) => {
- exitMenuIsOpen = false
- popups[0].remove();
- })
- popup.appendChild(this.createElement("br"));
+ const exitEmulation = addButton(
+ this.config.buttonOpts.exitEmulation,
+ async () => {
+ if (exitMenuIsOpen) return;
+ exitMenuIsOpen = true;
+ const popups = this.createSubPopup();
+ this.game.appendChild(popups[0]);
+ popups[1].classList.add("ejs_cheat_parent");
+ popups[1].style.width = "100%";
+ const popup = popups[1];
+ const header = this.createElement("div");
+ header.classList.add("ejs_cheat_header");
+ const title = this.createElement("h2");
+ title.innerText = this.localization(
+ "Are you sure you want to exit?"
+ );
+ title.classList.add("ejs_cheat_heading");
+ const close = this.createElement("button");
+ close.classList.add("ejs_cheat_close");
+ header.appendChild(title);
+ header.appendChild(close);
+ popup.appendChild(header);
+ this.addEventListener(close, "click", (e) => {
+ exitMenuIsOpen = false;
+ popups[0].remove();
+ });
+ popup.appendChild(this.createElement("br"));
- const footer = this.createElement("footer");
- const submit = this.createElement("button");
- const closeButton = this.createElement("button");
- submit.innerText = this.localization("Exit");
- closeButton.innerText = this.localization("Cancel");
- submit.classList.add("ejs_button_button");
- closeButton.classList.add("ejs_button_button");
- submit.classList.add("ejs_popup_submit");
- closeButton.classList.add("ejs_popup_submit");
- submit.style["background-color"] = "rgba(var(--ejs-primary-color),1)";
- footer.appendChild(submit);
- const span = this.createElement("span");
- span.innerText = " ";
- footer.appendChild(span);
- footer.appendChild(closeButton);
- popup.appendChild(footer);
+ const footer = this.createElement("footer");
+ const submit = this.createElement("button");
+ const closeButton = this.createElement("button");
+ submit.innerText = this.localization("Exit");
+ closeButton.innerText = this.localization("Cancel");
+ submit.classList.add("ejs_button_button");
+ closeButton.classList.add("ejs_button_button");
+ submit.classList.add("ejs_popup_submit");
+ closeButton.classList.add("ejs_popup_submit");
+ submit.style["background-color"] =
+ "rgba(var(--ejs-primary-color),1)";
+ footer.appendChild(submit);
+ const span = this.createElement("span");
+ span.innerText = " ";
+ footer.appendChild(span);
+ footer.appendChild(closeButton);
+ popup.appendChild(footer);
- this.addEventListener(closeButton, "click", (e) => {
- popups[0].remove();
- exitMenuIsOpen = false
- })
+ this.addEventListener(closeButton, "click", (e) => {
+ popups[0].remove();
+ exitMenuIsOpen = false;
+ });
- this.addEventListener(submit, "click", (e) => {
- popups[0].remove();
- const body = this.createPopup("EmulatorJS has exited", {});
- this.callEvent("exit");
- })
- setTimeout(this.menu.close.bind(this), 20);
- });
-
- this.addEventListener(document, "webkitfullscreenchange mozfullscreenchange fullscreenchange", (e) => {
- if (e.target !== this.elements.parent) return;
- if (document.fullscreenElement === null) {
- exit.style.display = "none";
- enter.style.display = "";
- } else {
- //not sure if this is possible, lets put it here anyways
- exit.style.display = "";
- enter.style.display = "none";
+ this.addEventListener(submit, "click", (e) => {
+ popups[0].remove();
+ const body = this.createPopup("EmulatorJS has exited", {});
+ this.callEvent("exit");
+ });
+ setTimeout(this.menu.close.bind(this), 20);
}
- })
+ );
- const hasFullscreen = !!(this.elements.parent.requestFullscreen || this.elements.parent.mozRequestFullScreen || this.elements.parent.webkitRequestFullscreen || this.elements.parent.msRequestFullscreen);
+ this.addEventListener(
+ document,
+ "webkitfullscreenchange mozfullscreenchange fullscreenchange",
+ (e) => {
+ if (e.target !== this.elements.parent) return;
+ if (document.fullscreenElement === null) {
+ exit.style.display = "none";
+ enter.style.display = "";
+ } else {
+ //not sure if this is possible, lets put it here anyways
+ exit.style.display = "";
+ enter.style.display = "none";
+ }
+ }
+ );
+
+ const hasFullscreen = !!(
+ this.elements.parent.requestFullscreen ||
+ this.elements.parent.mozRequestFullScreen ||
+ this.elements.parent.webkitRequestFullscreen ||
+ this.elements.parent.msRequestFullscreen
+ );
if (!hasFullscreen) {
exit.style.display = "none";
@@ -2354,8 +3116,8 @@ class EmulatorJS {
saveSavFiles: [saveSavFiles],
loadSavFiles: [loadSavFiles],
netplay: [netplay],
- exit: [exitEmulation]
- }
+ exit: [exitEmulation],
+ };
if (this.config.buttonOpts) {
if (this.debug) console.log(this.config.buttonOpts);
@@ -2363,9 +3125,16 @@ class EmulatorJS {
pauseButton.style.display = "none";
playButton.style.display = "none";
}
- if (this.config.buttonOpts.contextMenu.visible === false && this.config.buttonOpts.rightClick !== false && this.isMobile === false) contextMenuButton.style.display = "none"
- if (this.config.buttonOpts.restart.visible === false) restartButton.style.display = "none"
- if (this.config.buttonOpts.settings.visible === false) settingButton[0].style.display = "none"
+ if (
+ this.config.buttonOpts.contextMenu.visible === false &&
+ this.config.buttonOpts.rightClick !== false &&
+ this.isMobile === false
+ )
+ contextMenuButton.style.display = "none";
+ if (this.config.buttonOpts.restart.visible === false)
+ restartButton.style.display = "none";
+ if (this.config.buttonOpts.settings.visible === false)
+ settingButton[0].style.display = "none";
if (this.config.buttonOpts.fullscreen.visible === false) {
enter.style.display = "none";
exit.style.display = "none";
@@ -2374,17 +3143,28 @@ class EmulatorJS {
muteButton.style.display = "none";
unmuteButton.style.display = "none";
}
- if (this.config.buttonOpts.saveState.visible === false) saveState.style.display = "none";
- if (this.config.buttonOpts.loadState.visible === false) loadState.style.display = "none";
- if (this.config.buttonOpts.saveSavFiles.visible === false) saveSavFiles.style.display = "none";
- if (this.config.buttonOpts.loadSavFiles.visible === false) loadSavFiles.style.display = "none";
- if (this.config.buttonOpts.gamepad.visible === false) controlMenu.style.display = "none";
- if (this.config.buttonOpts.cheat.visible === false) cheatMenu.style.display = "none";
- if (this.config.buttonOpts.cacheManager.visible === false) cache.style.display = "none";
- if (this.config.buttonOpts.netplay.visible === false) netplay.style.display = "none";
- if (this.config.buttonOpts.diskButton.visible === false) diskButton[0].style.display = "none";
- if (this.config.buttonOpts.volumeSlider.visible === false) volumeSlider.style.display = "none";
- if (this.config.buttonOpts.exitEmulation.visible === false) exitEmulation.style.display = "none";
+ if (this.config.buttonOpts.saveState.visible === false)
+ saveState.style.display = "none";
+ if (this.config.buttonOpts.loadState.visible === false)
+ loadState.style.display = "none";
+ if (this.config.buttonOpts.saveSavFiles.visible === false)
+ saveSavFiles.style.display = "none";
+ if (this.config.buttonOpts.loadSavFiles.visible === false)
+ loadSavFiles.style.display = "none";
+ if (this.config.buttonOpts.gamepad.visible === false)
+ controlMenu.style.display = "none";
+ if (this.config.buttonOpts.cheat.visible === false)
+ cheatMenu.style.display = "none";
+ if (this.config.buttonOpts.cacheManager.visible === false)
+ cache.style.display = "none";
+ if (this.config.buttonOpts.netplay.visible === false)
+ netplay.style.display = "none";
+ if (this.config.buttonOpts.diskButton.visible === false)
+ diskButton[0].style.display = "none";
+ if (this.config.buttonOpts.volumeSlider.visible === false)
+ volumeSlider.style.display = "none";
+ if (this.config.buttonOpts.exitEmulation.visible === false)
+ exitEmulation.style.display = "none";
}
this.menu.failedToStart = () => {
@@ -2419,7 +3199,7 @@ class EmulatorJS {
this.virtualGamepad.style.display = "none";
settingButton[0].classList.add("shadow");
this.menu.open(true);
- }
+ };
}
openCacheMenu() {
(async () => {
@@ -2433,9 +3213,9 @@ class EmulatorJS {
}
tbody.innerHTML = "";
},
- "Close": () => {
+ Close: () => {
this.closePopup();
- }
+ },
});
const roms = await this.storage.rom.getSizes();
list.style.width = "100%";
@@ -2446,10 +3226,13 @@ class EmulatorJS {
const getSize = function (size) {
let i = -1;
do {
- size /= 1024, i++;
+ (size /= 1024), i++;
} while (size > 1024);
- return Math.max(size, 0.1).toFixed(1) + [" kB", " MB", " GB", " TB", "PB", "EB", "ZB", "YB"][i];
- }
+ return (
+ Math.max(size, 0.1).toFixed(1) +
+ [" kB", " MB", " GB", " TB", "PB", "EB", "ZB", "YB"][i]
+ );
+ };
for (const k in roms) {
const line = this.createElement("tr");
const name = this.createElement("td");
@@ -2464,7 +3247,7 @@ class EmulatorJS {
this.addEventListener(remove, "click", () => {
this.storage.rom.remove(k);
line.remove();
- })
+ });
remove.appendChild(a);
line.appendChild(name);
@@ -2475,7 +3258,10 @@ class EmulatorJS {
})();
}
getControlScheme() {
- if (this.config.controlScheme && typeof this.config.controlScheme === "string") {
+ if (
+ this.config.controlScheme &&
+ typeof this.config.controlScheme === "string"
+ ) {
return this.config.controlScheme;
} else {
return this.getCore(true);
@@ -2483,27 +3269,34 @@ class EmulatorJS {
}
createControlSettingMenu() {
let buttonListeners = [];
- this.checkGamepadInputs = () => buttonListeners.forEach(elem => elem());
+ this.checkGamepadInputs = () =>
+ buttonListeners.forEach((elem) => elem());
this.gamepadLabels = [];
this.gamepadSelection = [];
this.controls = JSON.parse(JSON.stringify(this.defaultControllers));
- const body = this.createPopup("Control Settings", {
- "Reset": () => {
- this.controls = JSON.parse(JSON.stringify(this.defaultControllers));
- this.setupKeys();
- this.checkGamepadInputs();
- this.saveSettings();
+ const body = this.createPopup(
+ "Control Settings",
+ {
+ Reset: () => {
+ this.controls = JSON.parse(
+ JSON.stringify(this.defaultControllers)
+ );
+ this.setupKeys();
+ this.checkGamepadInputs();
+ this.saveSettings();
+ },
+ Clear: () => {
+ this.controls = { 0: {}, 1: {}, 2: {}, 3: {} };
+ this.setupKeys();
+ this.checkGamepadInputs();
+ this.saveSettings();
+ },
+ Close: () => {
+ this.controlMenu.style.display = "none";
+ },
},
- "Clear": () => {
- this.controls = { 0: {}, 1: {}, 2: {}, 3: {} };
- this.setupKeys();
- this.checkGamepadInputs();
- this.saveSettings();
- },
- "Close": () => {
- this.controlMenu.style.display = "none";
- }
- }, true);
+ true
+ );
this.setupKeys();
this.controlMenu = body.parentElement;
body.classList.add("ejs_control_body");
@@ -2532,10 +3325,19 @@ class EmulatorJS {
{ id: 7, label: this.localization("RIGHT") },
];
if (this.getCore() === "nestopia") {
- buttons.push({ id: 10, label: this.localization("SWAP DISKS") });
+ buttons.push({
+ id: 10,
+ label: this.localization("SWAP DISKS"),
+ });
} else {
- buttons.push({ id: 10, label: this.localization("SWAP DISKS") });
- buttons.push({ id: 11, label: this.localization("EJECT/INSERT DISK") });
+ buttons.push({
+ id: 10,
+ label: this.localization("SWAP DISKS"),
+ });
+ buttons.push({
+ id: 11,
+ label: this.localization("EJECT/INSERT DISK"),
+ });
}
} else if ("snes" === this.getControlScheme()) {
buttons = [
@@ -2935,12 +3737,14 @@ class EmulatorJS {
player.id = "controls-" + (i - 1) + "-label";
this.addEventListener(player, "click", (e) => {
e.preventDefault();
- players[selectedPlayer].classList.remove("ejs_control_selected");
+ players[selectedPlayer].classList.remove(
+ "ejs_control_selected"
+ );
playerDivs[selectedPlayer].setAttribute("hidden", "");
selectedPlayer = i - 1;
players[i - 1].classList.add("ejs_control_selected");
playerDivs[i - 1].removeAttribute("hidden");
- })
+ });
playerContainer.appendChild(player);
playerSelect.appendChild(playerContainer);
players.push(playerContainer);
@@ -2954,7 +3758,8 @@ class EmulatorJS {
const playerTitle = this.createElement("div");
const gamepadTitle = this.createElement("div");
- gamepadTitle.innerText = this.localization("Connected Gamepad") + ": ";
+ gamepadTitle.innerText =
+ this.localization("Connected Gamepad") + ": ";
const gamepadName = this.createElement("select");
gamepadName.classList.add("ejs_gamepad_dropdown");
@@ -2962,7 +3767,7 @@ class EmulatorJS {
gamepadName.setAttribute("index", i);
this.gamepadLabels.push(gamepadName);
this.gamepadSelection.push("");
- this.addEventListener(gamepadName, "change", e => {
+ this.addEventListener(gamepadName, "change", (e) => {
const controller = e.target.value;
const player = parseInt(e.target.getAttribute("index"));
if (controller === "notconnected") {
@@ -3009,7 +3814,8 @@ class EmulatorJS {
if ((this.touch || this.hasTouchScreen) && i === 0) {
const vgp = this.createElement("div");
- vgp.style = "width:25%;float:right;clear:none;padding:0;font-size: 11px;padding-left: 2.25rem;";
+ vgp.style =
+ "width:25%;float:right;clear:none;padding:0;font-size: 11px;padding-left: 2.25rem;";
vgp.classList.add("ejs_control_row");
vgp.classList.add("ejs_cheat_row");
const input = this.createElement("input");
@@ -3024,13 +3830,18 @@ class EmulatorJS {
vgp.appendChild(label);
label.addEventListener("click", (e) => {
input.checked = !input.checked;
- this.changeSettingOption("virtual-gamepad", input.checked ? "enabled" : "disabled");
- })
+ this.changeSettingOption(
+ "virtual-gamepad",
+ input.checked ? "enabled" : "disabled"
+ );
+ });
this.on("start", (e) => {
- if (this.getSettingValue("virtual-gamepad") === "disabled") {
+ if (
+ this.getSettingValue("virtual-gamepad") === "disabled"
+ ) {
input.checked = false;
}
- })
+ });
playerTitle.appendChild(vgp);
}
@@ -3079,24 +3890,37 @@ class EmulatorJS {
buttonListeners.push(() => {
textBox2.value = "";
textBox1.value = "";
- if (this.controls[i][k] && this.controls[i][k].value !== undefined) {
+ if (
+ this.controls[i][k] &&
+ this.controls[i][k].value !== undefined
+ ) {
let value = this.keyMap[this.controls[i][k].value];
value = this.localization(value);
textBox2.value = value;
}
- if (this.controls[i][k] && this.controls[i][k].value2 !== undefined && this.controls[i][k].value2 !== "") {
+ if (
+ this.controls[i][k] &&
+ this.controls[i][k].value2 !== undefined &&
+ this.controls[i][k].value2 !== ""
+ ) {
let value2 = this.controls[i][k].value2.toString();
if (value2.includes(":")) {
value2 = value2.split(":");
- value2 = this.localization(value2[0]) + ":" + this.localization(value2[1])
+ value2 =
+ this.localization(value2[0]) +
+ ":" +
+ this.localization(value2[1]);
} else if (!isNaN(value2)) {
- value2 = this.localization("BUTTON") + " " + this.localization(value2);
+ value2 =
+ this.localization("BUTTON") +
+ " " +
+ this.localization(value2);
} else {
value2 = this.localization(value2);
}
textBox1.value = value2;
}
- })
+ });
if (this.controls[i][k] && this.controls[i][k].value) {
let value = this.keyMap[this.controls[i][k].value];
@@ -3107,9 +3931,15 @@ class EmulatorJS {
let value2 = this.controls[i][k].value2.toString();
if (value2.includes(":")) {
value2 = value2.split(":");
- value2 = this.localization(value2[0]) + ":" + this.localization(value2[1])
+ value2 =
+ this.localization(value2[0]) +
+ ":" +
+ this.localization(value2[1]);
} else if (!isNaN(value2)) {
- value2 = this.localization("BUTTON") + " " + this.localization(value2);
+ value2 =
+ this.localization("BUTTON") +
+ " " +
+ this.localization(value2);
} else {
value2 = this.localization(value2);
}
@@ -3142,11 +3972,17 @@ class EmulatorJS {
this.addEventListener(buttonText, "mousedown", (e) => {
e.preventDefault();
- this.controlPopup.parentElement.parentElement.removeAttribute("hidden");
- this.controlPopup.innerText = "[ " + controlLabel + " ]\n" + this.localization("Press Keyboard");
+ this.controlPopup.parentElement.parentElement.removeAttribute(
+ "hidden"
+ );
+ this.controlPopup.innerText =
+ "[ " +
+ controlLabel +
+ " ]\n" +
+ this.localization("Press Keyboard");
this.controlPopup.setAttribute("button-num", k);
this.controlPopup.setAttribute("player-num", i);
- })
+ });
}
controls.appendChild(player);
player.setAttribute("hidden", "");
@@ -3163,8 +3999,11 @@ class EmulatorJS {
const popupMsg = this.createElement("div");
this.addEventListener(popup, "mousedown click touchstart", (e) => {
if (this.isChild(popupMsg, e.target)) return;
- this.controlPopup.parentElement.parentElement.setAttribute("hidden", "");
- })
+ this.controlPopup.parentElement.parentElement.setAttribute(
+ "hidden",
+ ""
+ );
+ });
const btn = this.createElement("a");
btn.classList.add("ejs_control_set_button");
btn.innerText = this.localization("Clear");
@@ -3176,10 +4015,13 @@ class EmulatorJS {
}
this.controls[player][num].value = 0;
this.controls[player][num].value2 = "";
- this.controlPopup.parentElement.parentElement.setAttribute("hidden", "");
+ this.controlPopup.parentElement.parentElement.setAttribute(
+ "hidden",
+ ""
+ );
this.checkGamepadInputs();
this.saveSettings();
- })
+ });
popupMsg.classList.add("ejs_popup_box");
popupMsg.innerText = "";
popup.setAttribute("hidden", "");
@@ -3195,109 +4037,109 @@ class EmulatorJS {
this.defaultControllers = {
0: {
0: {
- "value": "x",
- "value2": "BUTTON_2"
+ value: "x",
+ value2: "BUTTON_2",
},
1: {
- "value": "s",
- "value2": "BUTTON_4"
+ value: "s",
+ value2: "BUTTON_4",
},
2: {
- "value": "v",
- "value2": "SELECT"
+ value: "v",
+ value2: "SELECT",
},
3: {
- "value": "enter",
- "value2": "START"
+ value: "enter",
+ value2: "START",
},
4: {
- "value": "up arrow",
- "value2": "DPAD_UP"
+ value: "up arrow",
+ value2: "DPAD_UP",
},
5: {
- "value": "down arrow",
- "value2": "DPAD_DOWN"
+ value: "down arrow",
+ value2: "DPAD_DOWN",
},
6: {
- "value": "left arrow",
- "value2": "DPAD_LEFT"
+ value: "left arrow",
+ value2: "DPAD_LEFT",
},
7: {
- "value": "right arrow",
- "value2": "DPAD_RIGHT"
+ value: "right arrow",
+ value2: "DPAD_RIGHT",
},
8: {
- "value": "z",
- "value2": "BUTTON_1"
+ value: "z",
+ value2: "BUTTON_1",
},
9: {
- "value": "a",
- "value2": "BUTTON_3"
+ value: "a",
+ value2: "BUTTON_3",
},
10: {
- "value": "q",
- "value2": "LEFT_TOP_SHOULDER"
+ value: "q",
+ value2: "LEFT_TOP_SHOULDER",
},
11: {
- "value": "e",
- "value2": "RIGHT_TOP_SHOULDER"
+ value: "e",
+ value2: "RIGHT_TOP_SHOULDER",
},
12: {
- "value": "tab",
- "value2": "LEFT_BOTTOM_SHOULDER"
+ value: "tab",
+ value2: "LEFT_BOTTOM_SHOULDER",
},
13: {
- "value": "r",
- "value2": "RIGHT_BOTTOM_SHOULDER"
+ value: "r",
+ value2: "RIGHT_BOTTOM_SHOULDER",
},
14: {
- "value": "",
- "value2": "LEFT_STICK",
+ value: "",
+ value2: "LEFT_STICK",
},
15: {
- "value": "",
- "value2": "RIGHT_STICK",
+ value: "",
+ value2: "RIGHT_STICK",
},
16: {
- "value": "h",
- "value2": "LEFT_STICK_X:+1"
+ value: "h",
+ value2: "LEFT_STICK_X:+1",
},
17: {
- "value": "f",
- "value2": "LEFT_STICK_X:-1"
+ value: "f",
+ value2: "LEFT_STICK_X:-1",
},
18: {
- "value": "g",
- "value2": "LEFT_STICK_Y:+1"
+ value: "g",
+ value2: "LEFT_STICK_Y:+1",
},
19: {
- "value": "t",
- "value2": "LEFT_STICK_Y:-1"
+ value: "t",
+ value2: "LEFT_STICK_Y:-1",
},
20: {
- "value": "l",
- "value2": "RIGHT_STICK_X:+1"
+ value: "l",
+ value2: "RIGHT_STICK_X:+1",
},
21: {
- "value": "j",
- "value2": "RIGHT_STICK_X:-1"
+ value: "j",
+ value2: "RIGHT_STICK_X:-1",
},
22: {
- "value": "k",
- "value2": "RIGHT_STICK_Y:+1"
+ value: "k",
+ value2: "RIGHT_STICK_Y:+1",
},
23: {
- "value": "i",
- "value2": "RIGHT_STICK_Y:-1"
+ value: "i",
+ value2: "RIGHT_STICK_Y:-1",
},
24: {
- "value": "1"
+ value: "1",
},
25: {
- "value": "2"
+ value: "2",
},
26: {
- "value": "3"
+ value: "3",
},
27: {},
28: {},
@@ -3305,8 +4147,8 @@ class EmulatorJS {
},
1: {},
2: {},
- 3: {}
- }
+ 3: {},
+ };
this.keyMap = {
0: "",
8: "backspace",
@@ -3407,17 +4249,22 @@ class EmulatorJS {
219: "open bracket",
220: "back slash",
221: "close braket",
- 222: "single quote"
- }
+ 222: "single quote",
+ };
}
setupKeys() {
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 30; j++) {
if (this.controls[i][j]) {
- this.controls[i][j].value = parseInt(this.keyLookup(this.controls[i][j].value));
+ this.controls[i][j].value = parseInt(
+ this.keyLookup(this.controls[i][j].value)
+ );
if (this.controls[i][j].value === -1 && this.debug) {
delete this.controls[i][j].value;
- if (this.debug) console.warn("Invalid key for control " + j + " player " + i);
+ if (this.debug)
+ console.warn(
+ "Invalid key for control " + j + " player " + i
+ );
}
}
}
@@ -3426,7 +4273,7 @@ class EmulatorJS {
keyLookup(controllerkey) {
if (controllerkey === undefined) return 0;
if (typeof controllerkey === "number") return controllerkey;
- controllerkey = controllerkey.toString().toLowerCase()
+ controllerkey = controllerkey.toString().toLowerCase();
const values = Object.values(this.keyMap);
if (values.includes(controllerkey)) {
const index = values.indexOf(controllerkey);
@@ -3437,106 +4284,204 @@ class EmulatorJS {
keyChange(e) {
if (e.repeat) return;
if (!this.started) return;
- if (this.controlPopup.parentElement.parentElement.getAttribute("hidden") === null) {
+ if (
+ this.controlPopup.parentElement.parentElement.getAttribute(
+ "hidden"
+ ) === null
+ ) {
const num = this.controlPopup.getAttribute("button-num");
const player = this.controlPopup.getAttribute("player-num");
if (!this.controls[player][num]) {
this.controls[player][num] = {};
}
this.controls[player][num].value = e.keyCode;
- this.controlPopup.parentElement.parentElement.setAttribute("hidden", "");
+ this.controlPopup.parentElement.parentElement.setAttribute(
+ "hidden",
+ ""
+ );
this.checkGamepadInputs();
this.saveSettings();
return;
}
- if (this.settingsMenu.style.display !== "none" || this.isPopupOpen() || this.getSettingValue("keyboardInput") === "enabled") return;
+ if (
+ this.settingsMenu.style.display !== "none" ||
+ this.isPopupOpen() ||
+ this.getSettingValue("keyboardInput") === "enabled"
+ )
+ return;
e.preventDefault();
const special = [16, 17, 18, 19, 20, 21, 22, 23];
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 30; j++) {
- if (this.controls[i][j] && this.controls[i][j].value === e.keyCode) {
- this.gameManager.simulateInput(i, j, (e.type === "keyup" ? 0 : (special.includes(j) ? 0x7fff : 1)));
+ if (
+ this.controls[i][j] &&
+ this.controls[i][j].value === e.keyCode
+ ) {
+ this.gameManager.simulateInput(
+ i,
+ j,
+ e.type === "keyup"
+ ? 0
+ : special.includes(j)
+ ? 0x7fff
+ : 1
+ );
}
}
}
}
gamepadEvent(e) {
if (!this.started) return;
- const gamepadIndex = this.gamepadSelection.indexOf(this.gamepad.gamepads[e.gamepadIndex].id + "_" + this.gamepad.gamepads[e.gamepadIndex].index);
+ const gamepadIndex = this.gamepadSelection.indexOf(
+ this.gamepad.gamepads[e.gamepadIndex].id +
+ "_" +
+ this.gamepad.gamepads[e.gamepadIndex].index
+ );
if (gamepadIndex < 0) {
return; // Gamepad not set anywhere
}
- const value = function (value) {
+ const value = (function (value) {
if (value > 0.5 || value < -0.5) {
- return (value > 0) ? 1 : -1;
+ return value > 0 ? 1 : -1;
} else {
return 0;
}
- }(e.value || 0);
- if (this.controlPopup.parentElement.parentElement.getAttribute("hidden") === null) {
- if ("buttonup" === e.type || (e.type === "axischanged" && value === 0)) return;
+ })(e.value || 0);
+ if (
+ this.controlPopup.parentElement.parentElement.getAttribute(
+ "hidden"
+ ) === null
+ ) {
+ if (
+ "buttonup" === e.type ||
+ (e.type === "axischanged" && value === 0)
+ )
+ return;
const num = this.controlPopup.getAttribute("button-num");
- const player = parseInt(this.controlPopup.getAttribute("player-num"));
+ const player = parseInt(
+ this.controlPopup.getAttribute("player-num")
+ );
if (gamepadIndex !== player) return;
if (!this.controls[player][num]) {
this.controls[player][num] = {};
}
this.controls[player][num].value2 = e.label;
- this.controlPopup.parentElement.parentElement.setAttribute("hidden", "");
+ this.controlPopup.parentElement.parentElement.setAttribute(
+ "hidden",
+ ""
+ );
this.checkGamepadInputs();
this.saveSettings();
return;
}
- if (this.settingsMenu.style.display !== "none" || this.isPopupOpen()) return;
+ if (this.settingsMenu.style.display !== "none" || this.isPopupOpen())
+ return;
const special = [16, 17, 18, 19, 20, 21, 22, 23];
for (let i = 0; i < 4; i++) {
if (gamepadIndex !== i) continue;
for (let j = 0; j < 30; j++) {
- if (!this.controls[i][j] || this.controls[i][j].value2 === undefined) {
+ if (
+ !this.controls[i][j] ||
+ this.controls[i][j].value2 === undefined
+ ) {
continue;
}
const controlValue = this.controls[i][j].value2;
- if (["buttonup", "buttondown"].includes(e.type) && (controlValue === e.label || controlValue === e.index)) {
- this.gameManager.simulateInput(i, j, (e.type === "buttonup" ? 0 : (special.includes(j) ? 0x7fff : 1)));
+ if (
+ ["buttonup", "buttondown"].includes(e.type) &&
+ (controlValue === e.label || controlValue === e.index)
+ ) {
+ this.gameManager.simulateInput(
+ i,
+ j,
+ e.type === "buttonup"
+ ? 0
+ : special.includes(j)
+ ? 0x7fff
+ : 1
+ );
} else if (e.type === "axischanged") {
- if (typeof controlValue === "string" && controlValue.split(":")[0] === e.axis) {
+ if (
+ typeof controlValue === "string" &&
+ controlValue.split(":")[0] === e.axis
+ ) {
if (special.includes(j)) {
if (j === 16 || j === 17) {
if (e.value > 0) {
- this.gameManager.simulateInput(i, 16, 0x7fff * e.value);
+ this.gameManager.simulateInput(
+ i,
+ 16,
+ 0x7fff * e.value
+ );
this.gameManager.simulateInput(i, 17, 0);
} else {
- this.gameManager.simulateInput(i, 17, -0x7fff * e.value);
+ this.gameManager.simulateInput(
+ i,
+ 17,
+ -0x7fff * e.value
+ );
this.gameManager.simulateInput(i, 16, 0);
}
} else if (j === 18 || j === 19) {
if (e.value > 0) {
- this.gameManager.simulateInput(i, 18, 0x7fff * e.value);
+ this.gameManager.simulateInput(
+ i,
+ 18,
+ 0x7fff * e.value
+ );
this.gameManager.simulateInput(i, 19, 0);
} else {
- this.gameManager.simulateInput(i, 19, -0x7fff * e.value);
+ this.gameManager.simulateInput(
+ i,
+ 19,
+ -0x7fff * e.value
+ );
this.gameManager.simulateInput(i, 18, 0);
}
} else if (j === 20 || j === 21) {
if (e.value > 0) {
- this.gameManager.simulateInput(i, 20, 0x7fff * e.value);
+ this.gameManager.simulateInput(
+ i,
+ 20,
+ 0x7fff * e.value
+ );
this.gameManager.simulateInput(i, 21, 0);
} else {
- this.gameManager.simulateInput(i, 21, -0x7fff * e.value);
+ this.gameManager.simulateInput(
+ i,
+ 21,
+ -0x7fff * e.value
+ );
this.gameManager.simulateInput(i, 20, 0);
}
} else if (j === 22 || j === 23) {
if (e.value > 0) {
- this.gameManager.simulateInput(i, 22, 0x7fff * e.value);
+ this.gameManager.simulateInput(
+ i,
+ 22,
+ 0x7fff * e.value
+ );
this.gameManager.simulateInput(i, 23, 0);
} else {
- this.gameManager.simulateInput(i, 23, -0x7fff * e.value);
+ this.gameManager.simulateInput(
+ i,
+ 23,
+ -0x7fff * e.value
+ );
this.gameManager.simulateInput(i, 22, 0);
}
}
- } else if (value === 0 || controlValue === e.label || controlValue === `${e.axis}:${value}`) {
- this.gameManager.simulateInput(i, j, ((value === 0) ? 0 : 1));
+ } else if (
+ value === 0 ||
+ controlValue === e.label ||
+ controlValue === `${e.axis}:${value}`
+ ) {
+ this.gameManager.simulateInput(
+ i,
+ j,
+ value === 0 ? 0 : 1
+ );
}
}
}
@@ -3547,292 +4492,1645 @@ class EmulatorJS {
this.virtualGamepad = this.createElement("div");
this.toggleVirtualGamepad = (show) => {
this.virtualGamepad.style.display = show ? "" : "none";
- }
+ };
this.virtualGamepad.classList.add("ejs_virtualGamepad_parent");
this.elements.parent.appendChild(this.virtualGamepad);
const speedControlButtons = [
- { "type": "button", "text": "Fast", "id": "speed_fast", "location": "center", "left": -35, "top": 50, "fontSize": 15, "block": true, "input_value": 27 },
- { "type": "button", "text": "Slow", "id": "speed_slow", "location": "center", "left": 95, "top": 50, "fontSize": 15, "block": true, "input_value": 29 },
+ {
+ type: "button",
+ text: "Fast",
+ id: "speed_fast",
+ location: "center",
+ left: -35,
+ top: 50,
+ fontSize: 15,
+ block: true,
+ input_value: 27,
+ },
+ {
+ type: "button",
+ text: "Slow",
+ id: "speed_slow",
+ location: "center",
+ left: 95,
+ top: 50,
+ fontSize: 15,
+ block: true,
+ input_value: 29,
+ },
];
if (this.rewindEnabled) {
- speedControlButtons.push({ "type": "button", "text": "Rewind", "id": "speed_rewind", "location": "center", "left": 30, "top": 50, "fontSize": 15, "block": true, "input_value": 28 });
+ speedControlButtons.push({
+ type: "button",
+ text: "Rewind",
+ id: "speed_rewind",
+ location: "center",
+ left: 30,
+ top: 50,
+ fontSize: 15,
+ block: true,
+ input_value: 28,
+ });
}
let info;
- if (this.config.VirtualGamepadSettings && function (set) {
- if (!Array.isArray(set)) {
- if (this.debug) console.warn("Virtual gamepad settings is not array! Using default gamepad settings");
- return false;
- }
- if (!set.length) {
- if (this.debug) console.warn("Virtual gamepad settings is empty! Using default gamepad settings");
- return false;
- }
- for (let i = 0; i < set.length; i++) {
- if (!set[i].type) continue;
- try {
- if (set[i].type === "zone" || set[i].type === "dpad") {
- if (!set[i].location) {
- console.warn("Missing location value for " + set[i].type + "! Using default gamepad settings");
- return false;
- } else if (!set[i].inputValues) {
- console.warn("Missing inputValues for " + set[i].type + "! Using default gamepad settings");
- return false;
- }
- continue;
- }
- if (!set[i].location) {
- console.warn("Missing location value for button " + set[i].text + "! Using default gamepad settings");
- return false;
- } else if (!set[i].type) {
- console.warn("Missing type value for button " + set[i].text + "! Using default gamepad settings");
- return false;
- } else if (!set[i].id.toString()) {
- console.warn("Missing id value for button " + set[i].text + "! Using default gamepad settings");
- return false;
- } else if (!set[i].input_value.toString()) {
- console.warn("Missing input_value for button " + set[i].text + "! Using default gamepad settings");
- return false;
- }
- } catch(e) {
- console.warn("Error checking values! Using default gamepad settings");
+ if (
+ this.config.VirtualGamepadSettings &&
+ (function (set) {
+ if (!Array.isArray(set)) {
+ if (this.debug)
+ console.warn(
+ "Virtual gamepad settings is not array! Using default gamepad settings"
+ );
return false;
}
- }
- return true;
- }(this.config.VirtualGamepadSettings)) {
+ if (!set.length) {
+ if (this.debug)
+ console.warn(
+ "Virtual gamepad settings is empty! Using default gamepad settings"
+ );
+ return false;
+ }
+ for (let i = 0; i < set.length; i++) {
+ if (!set[i].type) continue;
+ try {
+ if (set[i].type === "zone" || set[i].type === "dpad") {
+ if (!set[i].location) {
+ console.warn(
+ "Missing location value for " +
+ set[i].type +
+ "! Using default gamepad settings"
+ );
+ return false;
+ } else if (!set[i].inputValues) {
+ console.warn(
+ "Missing inputValues for " +
+ set[i].type +
+ "! Using default gamepad settings"
+ );
+ return false;
+ }
+ continue;
+ }
+ if (!set[i].location) {
+ console.warn(
+ "Missing location value for button " +
+ set[i].text +
+ "! Using default gamepad settings"
+ );
+ return false;
+ } else if (!set[i].type) {
+ console.warn(
+ "Missing type value for button " +
+ set[i].text +
+ "! Using default gamepad settings"
+ );
+ return false;
+ } else if (!set[i].id.toString()) {
+ console.warn(
+ "Missing id value for button " +
+ set[i].text +
+ "! Using default gamepad settings"
+ );
+ return false;
+ } else if (!set[i].input_value.toString()) {
+ console.warn(
+ "Missing input_value for button " +
+ set[i].text +
+ "! Using default gamepad settings"
+ );
+ return false;
+ }
+ } catch (e) {
+ console.warn(
+ "Error checking values! Using default gamepad settings"
+ );
+ return false;
+ }
+ }
+ return true;
+ })(this.config.VirtualGamepadSettings)
+ ) {
info = this.config.VirtualGamepadSettings;
} else if ("gba" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "B", "id": "b", "location": "right", "left": 10, "top": 70, "bold": true, "input_value": 0 },
- { "type": "button", "text": "A", "id": "a", "location": "right", "left": 81, "top": 40, "bold": true, "input_value": 8 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "top": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Start", "id": "start", "location": "center", "left": 60, "fontSize": 15, "block": true, "input_value": 3 },
- { "type": "button", "text": "Select", "id": "select", "location": "center", "left": -5, "fontSize": 15, "block": true, "input_value": 2 },
- { "type": "button", "text": "L", "id": "l", "location": "left", "left": 3, "top": -90, "bold": true, "block": true, "input_value": 10 },
- { "type": "button", "text": "R", "id": "r", "location": "right", "right": 3, "top": -90, "bold": true, "block": true, "input_value": 11 }
+ {
+ type: "button",
+ text: "B",
+ id: "b",
+ location: "right",
+ left: 10,
+ top: 70,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "A",
+ id: "a",
+ location: "right",
+ left: 81,
+ top: 40,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ top: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Start",
+ id: "start",
+ location: "center",
+ left: 60,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
+ {
+ type: "button",
+ text: "Select",
+ id: "select",
+ location: "center",
+ left: -5,
+ fontSize: 15,
+ block: true,
+ input_value: 2,
+ },
+ {
+ type: "button",
+ text: "L",
+ id: "l",
+ location: "left",
+ left: 3,
+ top: -90,
+ bold: true,
+ block: true,
+ input_value: 10,
+ },
+ {
+ type: "button",
+ text: "R",
+ id: "r",
+ location: "right",
+ right: 3,
+ top: -90,
+ bold: true,
+ block: true,
+ input_value: 11,
+ },
];
info.push(...speedControlButtons);
} else if ("gb" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "A", "id": "a", "location": "right", "left": 81, "top": 40, "bold": true, "input_value": 8 },
- { "type": "button", "text": "B", "id": "b", "location": "right", "left": 10, "top": 70, "bold": true, "input_value": 0 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "top": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Start", "id": "start", "location": "center", "left": 60, "fontSize": 15, "block": true, "input_value": 3 },
- { "type": "button", "text": "Select", "id": "select", "location": "center", "left": -5, "fontSize": 15, "block": true, "input_value": 2 }
+ {
+ type: "button",
+ text: "A",
+ id: "a",
+ location: "right",
+ left: 81,
+ top: 40,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "button",
+ text: "B",
+ id: "b",
+ location: "right",
+ left: 10,
+ top: 70,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ top: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Start",
+ id: "start",
+ location: "center",
+ left: 60,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
+ {
+ type: "button",
+ text: "Select",
+ id: "select",
+ location: "center",
+ left: -5,
+ fontSize: 15,
+ block: true,
+ input_value: 2,
+ },
];
info.push(...speedControlButtons);
} else if ("nes" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "B", "id": "b", "location": "right", "right": 75, "top": 70, "bold": true, "input_value": 0 },
- { "type": "button", "text": "A", "id": "a", "location": "right", "right": 5, "top": 70, "bold": true, "input_value": 8 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Start", "id": "start", "location": "center", "left": 60, "fontSize": 15, "block": true, "input_value": 3 },
- { "type": "button", "text": "Select", "id": "select", "location": "center", "left": -5, "fontSize": 15, "block": true, "input_value": 2 }
+ {
+ type: "button",
+ text: "B",
+ id: "b",
+ location: "right",
+ right: 75,
+ top: 70,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "A",
+ id: "a",
+ location: "right",
+ right: 5,
+ top: 70,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Start",
+ id: "start",
+ location: "center",
+ left: 60,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
+ {
+ type: "button",
+ text: "Select",
+ id: "select",
+ location: "center",
+ left: -5,
+ fontSize: 15,
+ block: true,
+ input_value: 2,
+ },
];
info.push(...speedControlButtons);
} else if ("n64" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "B", "id": "b", "location": "right", "left": -10, "top": 95, "input_value": 1, "bold": true },
- { "type": "button", "text": "A", "id": "a", "location": "right", "left": 40, "top": 150, "input_value": 0, "bold": true },
- { "type": "zone", "id": "stick", "location": "left", "left": "50%", "top": "100%", "joystickInput": true, "inputValues": [16, 17, 18, 19] },
- { "type": "zone", "id": "dpad", "location": "left", "left": "50%", "top": "0%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Start", "id": "start", "location": "center", "left": 30, "top": -10, "fontSize": 15, "block": true, "input_value": 3 },
- { "type": "button", "text": "L", "id": "l", "block": true, "location": "top", "left": 10, "top": -40, "bold": true, "input_value": 10 },
- { "type": "button", "text": "R", "id": "r", "block": true, "location": "top", "right": 10, "top": -40, "bold": true, "input_value": 11 },
- { "type": "button", "text": "Z", "id": "z", "block": true, "location": "top", "left": 10, "bold": true, "input_value": 12 },
- { "fontSize": 20, "type": "button", "text": "CU", "id": "cu", "joystickInput": true, "location": "right", "left": 25, "top": -65, "input_value": 23 },
- { "fontSize": 20, "type": "button", "text": "CD", "id": "cd", "joystickInput": true, "location": "right", "left": 25, "top": 15, "input_value": 22 },
- { "fontSize": 20, "type": "button", "text": "CL", "id": "cl", "joystickInput": true, "location": "right", "left": -15, "top": -25, "input_value": 21 },
- { "fontSize": 20, "type": "button", "text": "CR", "id": "cr", "joystickInput": true, "location": "right", "left": 65, "top": -25, "input_value": 20 }
+ {
+ type: "button",
+ text: "B",
+ id: "b",
+ location: "right",
+ left: -10,
+ top: 95,
+ input_value: 1,
+ bold: true,
+ },
+ {
+ type: "button",
+ text: "A",
+ id: "a",
+ location: "right",
+ left: 40,
+ top: 150,
+ input_value: 0,
+ bold: true,
+ },
+ {
+ type: "zone",
+ id: "stick",
+ location: "left",
+ left: "50%",
+ top: "100%",
+ joystickInput: true,
+ inputValues: [16, 17, 18, 19],
+ },
+ {
+ type: "zone",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ top: "0%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Start",
+ id: "start",
+ location: "center",
+ left: 30,
+ top: -10,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
+ {
+ type: "button",
+ text: "L",
+ id: "l",
+ block: true,
+ location: "top",
+ left: 10,
+ top: -40,
+ bold: true,
+ input_value: 10,
+ },
+ {
+ type: "button",
+ text: "R",
+ id: "r",
+ block: true,
+ location: "top",
+ right: 10,
+ top: -40,
+ bold: true,
+ input_value: 11,
+ },
+ {
+ type: "button",
+ text: "Z",
+ id: "z",
+ block: true,
+ location: "top",
+ left: 10,
+ bold: true,
+ input_value: 12,
+ },
+ {
+ fontSize: 20,
+ type: "button",
+ text: "CU",
+ id: "cu",
+ joystickInput: true,
+ location: "right",
+ left: 25,
+ top: -65,
+ input_value: 23,
+ },
+ {
+ fontSize: 20,
+ type: "button",
+ text: "CD",
+ id: "cd",
+ joystickInput: true,
+ location: "right",
+ left: 25,
+ top: 15,
+ input_value: 22,
+ },
+ {
+ fontSize: 20,
+ type: "button",
+ text: "CL",
+ id: "cl",
+ joystickInput: true,
+ location: "right",
+ left: -15,
+ top: -25,
+ input_value: 21,
+ },
+ {
+ fontSize: 20,
+ type: "button",
+ text: "CR",
+ id: "cr",
+ joystickInput: true,
+ location: "right",
+ left: 65,
+ top: -25,
+ input_value: 20,
+ },
];
info.push(...speedControlButtons);
} else if ("nds" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "X", "id": "x", "location": "right", "left": 40, "bold": true, "input_value": 9 },
- { "type": "button", "text": "Y", "id": "y", "location": "right", "top": 40, "bold": true, "input_value": 1 },
- { "type": "button", "text": "A", "id": "a", "location": "right", "left": 81, "top": 40, "bold": true, "input_value": 8 },
- { "type": "button", "text": "B", "id": "b", "location": "right", "left": 40, "top": 80, "bold": true, "input_value": 0 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "top": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Start", "id": "start", "location": "center", "left": 60, "fontSize": 15, "block": true, "input_value": 3 },
- { "type": "button", "text": "Select", "id": "select", "location": "center", "left": -5, "fontSize": 15, "block": true, "input_value": 2 },
- { "type": "button", "text": "L", "id": "l", "location": "left", "left": 3, "top": -100, "bold": true, "block": true, "input_value": 10 },
- { "type": "button", "text": "R", "id": "r", "location": "right", "right": 3, "top": -100, "bold": true, "block": true, "input_value": 11 }
+ {
+ type: "button",
+ text: "X",
+ id: "x",
+ location: "right",
+ left: 40,
+ bold: true,
+ input_value: 9,
+ },
+ {
+ type: "button",
+ text: "Y",
+ id: "y",
+ location: "right",
+ top: 40,
+ bold: true,
+ input_value: 1,
+ },
+ {
+ type: "button",
+ text: "A",
+ id: "a",
+ location: "right",
+ left: 81,
+ top: 40,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "button",
+ text: "B",
+ id: "b",
+ location: "right",
+ left: 40,
+ top: 80,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ top: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Start",
+ id: "start",
+ location: "center",
+ left: 60,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
+ {
+ type: "button",
+ text: "Select",
+ id: "select",
+ location: "center",
+ left: -5,
+ fontSize: 15,
+ block: true,
+ input_value: 2,
+ },
+ {
+ type: "button",
+ text: "L",
+ id: "l",
+ location: "left",
+ left: 3,
+ top: -100,
+ bold: true,
+ block: true,
+ input_value: 10,
+ },
+ {
+ type: "button",
+ text: "R",
+ id: "r",
+ location: "right",
+ right: 3,
+ top: -100,
+ bold: true,
+ block: true,
+ input_value: 11,
+ },
];
info.push(...speedControlButtons);
} else if ("snes" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "X", "id": "x", "location": "right", "left": 40, "bold": true, "input_value": 9 },
- { "type": "button", "text": "Y", "id": "y", "location": "right", "top": 40, "bold": true, "input_value": 1 },
- { "type": "button", "text": "A", "id": "a", "location": "right", "left": 81, "top": 40, "bold": true, "input_value": 8 },
- { "type": "button", "text": "B", "id": "b", "location": "right", "left": 40, "top": 80, "bold": true, "input_value": 0 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "top": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Start", "id": "start", "location": "center", "left": 60, "fontSize": 15, "block": true, "input_value": 3 },
- { "type": "button", "text": "Select", "id": "select", "location": "center", "left": -5, "fontSize": 15, "block": true, "input_value": 2 },
- { "type": "button", "text": "L", "id": "l", "location": "left", "left": 3, "top": -100, "bold": true, "block": true, "input_value": 10 },
- { "type": "button", "text": "R", "id": "r", "location": "right", "right": 3, "top": -100, "bold": true, "block": true, "input_value": 11 }
+ {
+ type: "button",
+ text: "X",
+ id: "x",
+ location: "right",
+ left: 40,
+ bold: true,
+ input_value: 9,
+ },
+ {
+ type: "button",
+ text: "Y",
+ id: "y",
+ location: "right",
+ top: 40,
+ bold: true,
+ input_value: 1,
+ },
+ {
+ type: "button",
+ text: "A",
+ id: "a",
+ location: "right",
+ left: 81,
+ top: 40,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "button",
+ text: "B",
+ id: "b",
+ location: "right",
+ left: 40,
+ top: 80,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ top: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Start",
+ id: "start",
+ location: "center",
+ left: 60,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
+ {
+ type: "button",
+ text: "Select",
+ id: "select",
+ location: "center",
+ left: -5,
+ fontSize: 15,
+ block: true,
+ input_value: 2,
+ },
+ {
+ type: "button",
+ text: "L",
+ id: "l",
+ location: "left",
+ left: 3,
+ top: -100,
+ bold: true,
+ block: true,
+ input_value: 10,
+ },
+ {
+ type: "button",
+ text: "R",
+ id: "r",
+ location: "right",
+ right: 3,
+ top: -100,
+ bold: true,
+ block: true,
+ input_value: 11,
+ },
];
info.push(...speedControlButtons);
- } else if (["segaMD", "segaCD", "sega32x"].includes(this.getControlScheme())) {
+ } else if (
+ ["segaMD", "segaCD", "sega32x"].includes(this.getControlScheme())
+ ) {
info = [
- { "type": "button", "text": "A", "id": "a", "location": "right", "right": 145, "top": 70, "bold": true, "input_value": 1 },
- { "type": "button", "text": "B", "id": "b", "location": "right", "right": 75, "top": 70, "bold": true, "input_value": 0 },
- { "type": "button", "text": "C", "id": "c", "location": "right", "right": 5, "top": 70, "bold": true, "input_value": 8 },
- { "type": "button", "text": "X", "id": "x", "location": "right", "right": 145, "top": 0, "bold": true, "input_value": 10 },
- { "type": "button", "text": "Y", "id": "y", "location": "right", "right": 75, "top": 0, "bold": true, "input_value": 9 },
- { "type": "button", "text": "Z", "id": "z", "location": "right", "right": 5, "top": 0, "bold": true, "input_value": 11 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Mode", "id": "mode", "location": "center", "left": -5, "fontSize": 15, "block": true, "input_value": 2 },
- { "type": "button", "text": "Start", "id": "start", "location": "center", "left": 60, "fontSize": 15, "block": true, "input_value": 3 }
+ {
+ type: "button",
+ text: "A",
+ id: "a",
+ location: "right",
+ right: 145,
+ top: 70,
+ bold: true,
+ input_value: 1,
+ },
+ {
+ type: "button",
+ text: "B",
+ id: "b",
+ location: "right",
+ right: 75,
+ top: 70,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "C",
+ id: "c",
+ location: "right",
+ right: 5,
+ top: 70,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "button",
+ text: "X",
+ id: "x",
+ location: "right",
+ right: 145,
+ top: 0,
+ bold: true,
+ input_value: 10,
+ },
+ {
+ type: "button",
+ text: "Y",
+ id: "y",
+ location: "right",
+ right: 75,
+ top: 0,
+ bold: true,
+ input_value: 9,
+ },
+ {
+ type: "button",
+ text: "Z",
+ id: "z",
+ location: "right",
+ right: 5,
+ top: 0,
+ bold: true,
+ input_value: 11,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Mode",
+ id: "mode",
+ location: "center",
+ left: -5,
+ fontSize: 15,
+ block: true,
+ input_value: 2,
+ },
+ {
+ type: "button",
+ text: "Start",
+ id: "start",
+ location: "center",
+ left: 60,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
];
info.push(...speedControlButtons);
} else if ("segaMS" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "1", "id": "button_1", "location": "right", "left": 10, "top": 40, "bold": true, "input_value": 0 },
- { "type": "button", "text": "2", "id": "button_2", "location": "right", "left": 81, "top": 40, "bold": true, "input_value": 8 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] }
+ {
+ type: "button",
+ text: "1",
+ id: "button_1",
+ location: "right",
+ left: 10,
+ top: 40,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "2",
+ id: "button_2",
+ location: "right",
+ left: 81,
+ top: 40,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
];
info.push(...speedControlButtons);
} else if ("segaGG" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "1", "id": "button_1", "location": "right", "left": 10, "top": 70, "bold": true, "input_value": 0 },
- { "type": "button", "text": "2", "id": "button_2", "location": "right", "left": 81, "top": 40, "bold": true, "input_value": 8 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "top": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Start", "id": "start", "location": "center", "left": 30, "fontSize": 15, "block": true, "input_value": 3 }
+ {
+ type: "button",
+ text: "1",
+ id: "button_1",
+ location: "right",
+ left: 10,
+ top: 70,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "2",
+ id: "button_2",
+ location: "right",
+ left: 81,
+ top: 40,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ top: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Start",
+ id: "start",
+ location: "center",
+ left: 30,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
];
info.push(...speedControlButtons);
} else if ("segaSaturn" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "A", "id": "a", "location": "right", "right": 145, "top": 70, "bold": true, "input_value": 1 },
- { "type": "button", "text": "B", "id": "b", "location": "right", "right": 75, "top": 70, "bold": true, "input_value": 0 },
- { "type": "button", "text": "C", "id": "c", "location": "right", "right": 5, "top": 70, "bold": true, "input_value": 8 },
- { "type": "button", "text": "X", "id": "x", "location": "right", "right": 145, "top": 0, "bold": true, "input_value": 9 },
- { "type": "button", "text": "Y", "id": "y", "location": "right", "right": 75, "top": 0, "bold": true, "input_value": 10 },
- { "type": "button", "text": "Z", "id": "z", "location": "right", "right": 5, "top": 0, "bold": true, "input_value": 11 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "L", "id": "l", "location": "left", "left": 3, "top": -90, "bold": true, "block": true, "input_value": 12 },
- { "type": "button", "text": "R", "id": "r", "location": "right", "right": 3, "top": -90, "bold": true, "block": true, "input_value": 13 },
- { "type": "button", "text": "Start", "id": "start", "location": "center", "left": 30, "fontSize": 15, "block": true, "input_value": 3 }
+ {
+ type: "button",
+ text: "A",
+ id: "a",
+ location: "right",
+ right: 145,
+ top: 70,
+ bold: true,
+ input_value: 1,
+ },
+ {
+ type: "button",
+ text: "B",
+ id: "b",
+ location: "right",
+ right: 75,
+ top: 70,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "C",
+ id: "c",
+ location: "right",
+ right: 5,
+ top: 70,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "button",
+ text: "X",
+ id: "x",
+ location: "right",
+ right: 145,
+ top: 0,
+ bold: true,
+ input_value: 9,
+ },
+ {
+ type: "button",
+ text: "Y",
+ id: "y",
+ location: "right",
+ right: 75,
+ top: 0,
+ bold: true,
+ input_value: 10,
+ },
+ {
+ type: "button",
+ text: "Z",
+ id: "z",
+ location: "right",
+ right: 5,
+ top: 0,
+ bold: true,
+ input_value: 11,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "L",
+ id: "l",
+ location: "left",
+ left: 3,
+ top: -90,
+ bold: true,
+ block: true,
+ input_value: 12,
+ },
+ {
+ type: "button",
+ text: "R",
+ id: "r",
+ location: "right",
+ right: 3,
+ top: -90,
+ bold: true,
+ block: true,
+ input_value: 13,
+ },
+ {
+ type: "button",
+ text: "Start",
+ id: "start",
+ location: "center",
+ left: 30,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
];
info.push(...speedControlButtons);
} else if ("atari2600" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "", "id": "button_1", "location": "right", "right": 10, "top": 70, "bold": true, "input_value": 0 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Reset", "id": "reset", "location": "center", "left": 60, "fontSize": 15, "block": true, "input_value": 3 },
- { "type": "button", "text": "Select", "id": "select", "location": "center", "left": -5, "fontSize": 15, "block": true, "input_value": 2 }
+ {
+ type: "button",
+ text: "",
+ id: "button_1",
+ location: "right",
+ right: 10,
+ top: 70,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Reset",
+ id: "reset",
+ location: "center",
+ left: 60,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
+ {
+ type: "button",
+ text: "Select",
+ id: "select",
+ location: "center",
+ left: -5,
+ fontSize: 15,
+ block: true,
+ input_value: 2,
+ },
];
info.push(...speedControlButtons);
} else if ("atari7800" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "1", "id": "button_1", "location": "right", "right": 75, "top": 70, "bold": true, "input_value": 0 },
- { "type": "button", "text": "2", "id": "button_2", "location": "right", "right": 5, "top": 70, "bold": true, "input_value": 8 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Reset", "id": "reset", "location": "center", "left": -35, "fontSize": 15, "block": true, "input_value": 9 },
- { "type": "button", "text": "Pause", "id": "pause", "location": "center", "left": 95, "fontSize": 15, "block": true, "input_value": 3 },
- { "type": "button", "text": "Select", "id": "select", "location": "center", "left": 30, "fontSize": 15, "block": true, "input_value": 2 },
+ {
+ type: "button",
+ text: "1",
+ id: "button_1",
+ location: "right",
+ right: 75,
+ top: 70,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "2",
+ id: "button_2",
+ location: "right",
+ right: 5,
+ top: 70,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Reset",
+ id: "reset",
+ location: "center",
+ left: -35,
+ fontSize: 15,
+ block: true,
+ input_value: 9,
+ },
+ {
+ type: "button",
+ text: "Pause",
+ id: "pause",
+ location: "center",
+ left: 95,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
+ {
+ type: "button",
+ text: "Select",
+ id: "select",
+ location: "center",
+ left: 30,
+ fontSize: 15,
+ block: true,
+ input_value: 2,
+ },
];
info.push(...speedControlButtons);
} else if ("lynx" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "B", "id": "button_1", "location": "right", "right": 75, "top": 70, "bold": true, "input_value": 0 },
- { "type": "button", "text": "A", "id": "button_2", "location": "right", "right": 5, "top": 70, "bold": true, "input_value": 8 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Opt 1", "id": "option_1", "location": "center", "left": -35, "fontSize": 15, "block": true, "input_value": 10 },
- { "type": "button", "text": "Opt 2", "id": "option_2", "location": "center", "left": 95, "fontSize": 15, "block": true, "input_value": 11 },
- { "type": "button", "text": "Start", "id": "start", "location": "center", "left": 30, "fontSize": 15, "block": true, "input_value": 3 }
+ {
+ type: "button",
+ text: "B",
+ id: "button_1",
+ location: "right",
+ right: 75,
+ top: 70,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "A",
+ id: "button_2",
+ location: "right",
+ right: 5,
+ top: 70,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Opt 1",
+ id: "option_1",
+ location: "center",
+ left: -35,
+ fontSize: 15,
+ block: true,
+ input_value: 10,
+ },
+ {
+ type: "button",
+ text: "Opt 2",
+ id: "option_2",
+ location: "center",
+ left: 95,
+ fontSize: 15,
+ block: true,
+ input_value: 11,
+ },
+ {
+ type: "button",
+ text: "Start",
+ id: "start",
+ location: "center",
+ left: 30,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
];
info.push(...speedControlButtons);
} else if ("jaguar" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "A", "id": "a", "location": "right", "right": 145, "top": 70, "bold": true, "input_value": 8 },
- { "type": "button", "text": "B", "id": "b", "location": "right", "right": 75, "top": 70, "bold": true, "input_value": 0 },
- { "type": "button", "text": "C", "id": "c", "location": "right", "right": 5, "top": 70, "bold": true, "input_value": 1 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Option", "id": "option", "location": "center", "left": 60, "fontSize": 15, "block": true, "input_value": 3 },
- { "type": "button", "text": "Pause", "id": "pause", "location": "center", "left": -5, "fontSize": 15, "block": true, "input_value": 2 }
+ {
+ type: "button",
+ text: "A",
+ id: "a",
+ location: "right",
+ right: 145,
+ top: 70,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "button",
+ text: "B",
+ id: "b",
+ location: "right",
+ right: 75,
+ top: 70,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "C",
+ id: "c",
+ location: "right",
+ right: 5,
+ top: 70,
+ bold: true,
+ input_value: 1,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Option",
+ id: "option",
+ location: "center",
+ left: 60,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
+ {
+ type: "button",
+ text: "Pause",
+ id: "pause",
+ location: "center",
+ left: -5,
+ fontSize: 15,
+ block: true,
+ input_value: 2,
+ },
];
info.push(...speedControlButtons);
} else if ("vb" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "B", "id": "b", "location": "right", "right": 75, "top": 150, "bold": true, "input_value": 0 },
- { "type": "button", "text": "A", "id": "a", "location": "right", "right": 5, "top": 150, "bold": true, "input_value": 8 },
- { "type": "dpad", "id": "left_dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "dpad", "id": "right_dpad", "location": "right", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [19, 18, 17, 16] },
- { "type": "button", "text": "L", "id": "l", "location": "left", "left": 3, "top": -90, "bold": true, "block": true, "input_value": 10 },
- { "type": "button", "text": "R", "id": "r", "location": "right", "right": 3, "top": -90, "bold": true, "block": true, "input_value": 11 },
- { "type": "button", "text": "Start", "id": "start", "location": "center", "left": 60, "fontSize": 15, "block": true, "input_value": 3 },
- { "type": "button", "text": "Select", "id": "select", "location": "center", "left": -5, "fontSize": 15, "block": true, "input_value": 2 }
+ {
+ type: "button",
+ text: "B",
+ id: "b",
+ location: "right",
+ right: 75,
+ top: 150,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "A",
+ id: "a",
+ location: "right",
+ right: 5,
+ top: 150,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "dpad",
+ id: "left_dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "dpad",
+ id: "right_dpad",
+ location: "right",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [19, 18, 17, 16],
+ },
+ {
+ type: "button",
+ text: "L",
+ id: "l",
+ location: "left",
+ left: 3,
+ top: -90,
+ bold: true,
+ block: true,
+ input_value: 10,
+ },
+ {
+ type: "button",
+ text: "R",
+ id: "r",
+ location: "right",
+ right: 3,
+ top: -90,
+ bold: true,
+ block: true,
+ input_value: 11,
+ },
+ {
+ type: "button",
+ text: "Start",
+ id: "start",
+ location: "center",
+ left: 60,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
+ {
+ type: "button",
+ text: "Select",
+ id: "select",
+ location: "center",
+ left: -5,
+ fontSize: 15,
+ block: true,
+ input_value: 2,
+ },
];
info.push(...speedControlButtons);
} else if ("3do" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "A", "id": "a", "location": "right", "right": 145, "top": 70, "bold": true, "input_value": 1 },
- { "type": "button", "text": "B", "id": "b", "location": "right", "right": 75, "top": 70, "bold": true, "input_value": 0 },
- { "type": "button", "text": "C", "id": "c", "location": "right", "right": 5, "top": 70, "bold": true, "input_value": 8 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "L", "id": "l", "location": "left", "left": 3, "top": -90, "bold": true, "block": true, "input_value": 10 },
- { "type": "button", "text": "R", "id": "r", "location": "right", "right": 3, "top": -90, "bold": true, "block": true, "input_value": 11 },
- { "type": "button", "text": "X", "id": "x", "location": "center", "left": -5, "fontSize": 15, "block": true, "bold": true, "input_value": 2 },
- { "type": "button", "text": "P", "id": "p", "location": "center", "left": 60, "fontSize": 15, "block": true, "bold": true, "input_value": 3 }
+ {
+ type: "button",
+ text: "A",
+ id: "a",
+ location: "right",
+ right: 145,
+ top: 70,
+ bold: true,
+ input_value: 1,
+ },
+ {
+ type: "button",
+ text: "B",
+ id: "b",
+ location: "right",
+ right: 75,
+ top: 70,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "C",
+ id: "c",
+ location: "right",
+ right: 5,
+ top: 70,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "L",
+ id: "l",
+ location: "left",
+ left: 3,
+ top: -90,
+ bold: true,
+ block: true,
+ input_value: 10,
+ },
+ {
+ type: "button",
+ text: "R",
+ id: "r",
+ location: "right",
+ right: 3,
+ top: -90,
+ bold: true,
+ block: true,
+ input_value: 11,
+ },
+ {
+ type: "button",
+ text: "X",
+ id: "x",
+ location: "center",
+ left: -5,
+ fontSize: 15,
+ block: true,
+ bold: true,
+ input_value: 2,
+ },
+ {
+ type: "button",
+ text: "P",
+ id: "p",
+ location: "center",
+ left: 60,
+ fontSize: 15,
+ block: true,
+ bold: true,
+ input_value: 3,
+ },
];
info.push(...speedControlButtons);
} else if ("pce" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "II", "id": "ii", "location": "right", "right": 75, "top": 70, "bold": true, "input_value": 0 },
- { "type": "button", "text": "I", "id": "i", "location": "right", "right": 5, "top": 70, "bold": true, "input_value": 8 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Run", "id": "run", "location": "center", "left": 60, "fontSize": 15, "block": true, "input_value": 3 },
- { "type": "button", "text": "Select", "id": "select", "location": "center", "left": -5, "fontSize": 15, "block": true, "input_value": 2 }
+ {
+ type: "button",
+ text: "II",
+ id: "ii",
+ location: "right",
+ right: 75,
+ top: 70,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "I",
+ id: "i",
+ location: "right",
+ right: 5,
+ top: 70,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Run",
+ id: "run",
+ location: "center",
+ left: 60,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
+ {
+ type: "button",
+ text: "Select",
+ id: "select",
+ location: "center",
+ left: -5,
+ fontSize: 15,
+ block: true,
+ input_value: 2,
+ },
];
info.push(...speedControlButtons);
} else if ("ngp" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "A", "id": "a", "location": "right", "right": 75, "top": 70, "bold": true, "input_value": 0 },
- { "type": "button", "text": "B", "id": "b", "location": "right", "right": 5, "top": 50, "bold": true, "input_value": 8 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Option", "id": "option", "location": "center", "left": 30, "fontSize": 15, "block": true, "input_value": 3 }
+ {
+ type: "button",
+ text: "A",
+ id: "a",
+ location: "right",
+ right: 75,
+ top: 70,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "B",
+ id: "b",
+ location: "right",
+ right: 5,
+ top: 50,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Option",
+ id: "option",
+ location: "center",
+ left: 30,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
];
info.push(...speedControlButtons);
} else if ("ws" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "B", "id": "b", "location": "right", "right": 75, "top": 150, "bold": true, "input_value": 0 },
- { "type": "button", "text": "A", "id": "a", "location": "right", "right": 5, "top": 150, "bold": true, "input_value": 8 },
- { "type": "dpad", "id": "x_dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "dpad", "id": "y_dpad", "location": "right", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [13, 12, 10, 11] },
- { "type": "button", "text": "Start", "id": "start", "location": "center", "left": 30, "fontSize": 15, "block": true, "input_value": 3 },
+ {
+ type: "button",
+ text: "B",
+ id: "b",
+ location: "right",
+ right: 75,
+ top: 150,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "A",
+ id: "a",
+ location: "right",
+ right: 5,
+ top: 150,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "dpad",
+ id: "x_dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "dpad",
+ id: "y_dpad",
+ location: "right",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [13, 12, 10, 11],
+ },
+ {
+ type: "button",
+ text: "Start",
+ id: "start",
+ location: "center",
+ left: 30,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
];
info.push(...speedControlButtons);
} else if ("coleco" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "L", "id": "l", "location": "right", "left": 10, "top": 40, "bold": true, "input_value": 8 },
- { "type": "button", "text": "R", "id": "r", "location": "right", "left": 81, "top": 40, "bold": true, "input_value": 0 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] }
+ {
+ type: "button",
+ text: "L",
+ id: "l",
+ location: "right",
+ left: 10,
+ top: 40,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "button",
+ text: "R",
+ id: "r",
+ location: "right",
+ left: 81,
+ top: 40,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
];
info.push(...speedControlButtons);
} else if ("pcfx" === this.getControlScheme()) {
info = [
- { "type": "button", "text": "I", "id": "i", "location": "right", "right": 5, "top": 70, "bold": true, "input_value": 8 },
- { "type": "button", "text": "II", "id": "ii", "location": "right", "right": 75, "top": 70, "bold": true, "input_value": 0 },
- { "type": "button", "text": "III", "id": "iii", "location": "right", "right": 145, "top": 70, "bold": true, "input_value": 9 },
- { "type": "button", "text": "IV", "id": "iv", "location": "right", "right": 5, "top": 0, "bold": true, "input_value": 1 },
- { "type": "button", "text": "V", "id": "v", "location": "right", "right": 75, "top": 0, "bold": true, "input_value": 10 },
- { "type": "button", "text": "VI", "id": "vi", "location": "right", "right": 145, "top": 0, "bold": true, "input_value": 11 },
- { "type": "dpad", "id": "dpad", "location": "left", "left": "50%", "right": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Select", "id": "select", "location": "center", "left": -5, "fontSize": 15, "block": true, "input_value": 2 },
- { "type": "button", "text": "Run", "id": "run", "location": "center", "left": 60, "fontSize": 15, "block": true, "input_value": 3 }
+ {
+ type: "button",
+ text: "I",
+ id: "i",
+ location: "right",
+ right: 5,
+ top: 70,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "button",
+ text: "II",
+ id: "ii",
+ location: "right",
+ right: 75,
+ top: 70,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "button",
+ text: "III",
+ id: "iii",
+ location: "right",
+ right: 145,
+ top: 70,
+ bold: true,
+ input_value: 9,
+ },
+ {
+ type: "button",
+ text: "IV",
+ id: "iv",
+ location: "right",
+ right: 5,
+ top: 0,
+ bold: true,
+ input_value: 1,
+ },
+ {
+ type: "button",
+ text: "V",
+ id: "v",
+ location: "right",
+ right: 75,
+ top: 0,
+ bold: true,
+ input_value: 10,
+ },
+ {
+ type: "button",
+ text: "VI",
+ id: "vi",
+ location: "right",
+ right: 145,
+ top: 0,
+ bold: true,
+ input_value: 11,
+ },
+ {
+ type: "dpad",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ right: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Select",
+ id: "select",
+ location: "center",
+ left: -5,
+ fontSize: 15,
+ block: true,
+ input_value: 2,
+ },
+ {
+ type: "button",
+ text: "Run",
+ id: "run",
+ location: "center",
+ left: 60,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
];
info.push(...speedControlButtons);
} else {
info = [
- { "type": "button", "text": "Y", "id": "y", "location": "right", "left": 40, "bold": true, "input_value": 9 },
- { "type": "button", "text": "X", "id": "x", "location": "right", "top": 40, "bold": true, "input_value": 1 },
- { "type": "button", "text": "B", "id": "b", "location": "right", "left": 81, "top": 40, "bold": true, "input_value": 8 },
- { "type": "button", "text": "A", "id": "a", "location": "right", "left": 40, "top": 80, "bold": true, "input_value": 0 },
- { "type": "zone", "id": "dpad", "location": "left", "left": "50%", "top": "50%", "joystickInput": false, "inputValues": [4, 5, 6, 7] },
- { "type": "button", "text": "Start", "id": "start", "location": "center", "left": 60, "fontSize": 15, "block": true, "input_value": 3 },
- { "type": "button", "text": "Select", "id": "select", "location": "center", "left": -5, "fontSize": 15, "block": true, "input_value": 2 }
+ {
+ type: "button",
+ text: "Y",
+ id: "y",
+ location: "right",
+ left: 40,
+ bold: true,
+ input_value: 9,
+ },
+ {
+ type: "button",
+ text: "X",
+ id: "x",
+ location: "right",
+ top: 40,
+ bold: true,
+ input_value: 1,
+ },
+ {
+ type: "button",
+ text: "B",
+ id: "b",
+ location: "right",
+ left: 81,
+ top: 40,
+ bold: true,
+ input_value: 8,
+ },
+ {
+ type: "button",
+ text: "A",
+ id: "a",
+ location: "right",
+ left: 40,
+ top: 80,
+ bold: true,
+ input_value: 0,
+ },
+ {
+ type: "zone",
+ id: "dpad",
+ location: "left",
+ left: "50%",
+ top: "50%",
+ joystickInput: false,
+ inputValues: [4, 5, 6, 7],
+ },
+ {
+ type: "button",
+ text: "Start",
+ id: "start",
+ location: "center",
+ left: 60,
+ fontSize: 15,
+ block: true,
+ input_value: 3,
+ },
+ {
+ type: "button",
+ text: "Select",
+ id: "select",
+ location: "center",
+ left: -5,
+ fontSize: 15,
+ block: true,
+ input_value: 2,
+ },
];
info.push(...speedControlButtons);
}
@@ -3863,16 +6161,23 @@ class EmulatorJS {
right.classList.toggle("ejs_virtualGamepad_right", !enabled);
left.classList.toggle("ejs_virtualGamepad_right", enabled);
right.classList.toggle("ejs_virtualGamepad_left", enabled);
- }
+ };
const leftHandedMode = false;
- const blockCSS = "height:31px;text-align:center;border:1px solid #ccc;border-radius:5px;line-height:31px;";
- const controlSchemeCls = `cs_${this.getControlScheme()}`.split(/\s/g).join("_");
+ const blockCSS =
+ "height:31px;text-align:center;border:1px solid #ccc;border-radius:5px;line-height:31px;";
+ const controlSchemeCls = `cs_${this.getControlScheme()}`
+ .split(/\s/g)
+ .join("_");
for (let i = 0; i < info.length; i++) {
if (info[i].type !== "button") continue;
- if (leftHandedMode && ["left", "right"].includes(info[i].location)) {
- info[i].location = (info[i].location === "left") ? "right" : "left";
+ if (
+ leftHandedMode &&
+ ["left", "right"].includes(info[i].location)
+ ) {
+ info[i].location =
+ info[i].location === "left" ? "right" : "left";
const amnt = JSON.parse(JSON.stringify(info[i]));
if (amnt.left) {
info[i].right = amnt.left;
@@ -3883,13 +6188,25 @@ class EmulatorJS {
}
let style = "";
if (info[i].left) {
- style += "left:" + info[i].left + (typeof info[i].left === "number" ? "px" : "") + ";";
+ style +=
+ "left:" +
+ info[i].left +
+ (typeof info[i].left === "number" ? "px" : "") +
+ ";";
}
if (info[i].right) {
- style += "right:" + info[i].right + (typeof info[i].right === "number" ? "px" : "") + ";";
+ style +=
+ "right:" +
+ info[i].right +
+ (typeof info[i].right === "number" ? "px" : "") +
+ ";";
}
if (info[i].top) {
- style += "top:" + info[i].top + (typeof info[i].top === "number" ? "px" : "") + ";";
+ style +=
+ "top:" +
+ info[i].top +
+ (typeof info[i].top === "number" ? "px" : "") +
+ ";";
}
if (!info[i].bold) {
style += "font-weight:normal;";
@@ -3905,25 +6222,36 @@ class EmulatorJS {
const button = this.createElement("div");
button.style = style;
button.innerText = info[i].text;
- button.classList.add("ejs_virtualGamepad_button", controlSchemeCls);
+ button.classList.add(
+ "ejs_virtualGamepad_button",
+ controlSchemeCls
+ );
if (info[i].id) {
button.classList.add(`b_${info[i].id}`);
}
elems[info[i].location].appendChild(button);
const value = info[i].input_new_cores || info[i].input_value;
let downValue = info[i].joystickInput === true ? 0x7fff : 1;
- this.addEventListener(button, "touchstart touchend touchcancel", (e) => {
- e.preventDefault();
- if (e.type === "touchend" || e.type === "touchcancel") {
- e.target.classList.remove("ejs_virtualGamepad_button_down");
- window.setTimeout(() => {
- this.gameManager.simulateInput(0, value, 0);
- })
- } else {
- e.target.classList.add("ejs_virtualGamepad_button_down");
- this.gameManager.simulateInput(0, value, downValue);
+ this.addEventListener(
+ button,
+ "touchstart touchend touchcancel",
+ (e) => {
+ e.preventDefault();
+ if (e.type === "touchend" || e.type === "touchcancel") {
+ e.target.classList.remove(
+ "ejs_virtualGamepad_button_down"
+ );
+ window.setTimeout(() => {
+ this.gameManager.simulateInput(0, value, 0);
+ });
+ } else {
+ e.target.classList.add(
+ "ejs_virtualGamepad_button_down"
+ );
+ this.gameManager.simulateInput(0, value, downValue);
+ }
}
- })
+ );
}
}
@@ -3969,21 +6297,27 @@ class EmulatorJS {
if (x >= 10) {
right = 1;
left = 0;
- if (angle < 0 && angle >= -35 || angle > 0 && angle <= 35) {
+ if (
+ (angle < 0 && angle >= -35) ||
+ (angle > 0 && angle <= 35)
+ ) {
right = 0;
}
- up = (angle < 0 && angle >= -55 ? 1 : 0);
- down = (angle > 0 && angle <= 55 ? 1 : 0);
+ up = angle < 0 && angle >= -55 ? 1 : 0;
+ down = angle > 0 && angle <= 55 ? 1 : 0;
}
if (x <= -10) {
right = 0;
left = 1;
- if (angle < 0 && angle >= -35 || angle > 0 && angle <= 35) {
+ if (
+ (angle < 0 && angle >= -35) ||
+ (angle > 0 && angle <= 35)
+ ) {
left = 0;
}
- up = (angle > 0 && angle <= 55 ? 1 : 0);
- down = (angle < 0 && angle >= -55 ? 1 : 0);
+ up = angle > 0 && angle <= 55 ? 1 : 0;
+ down = angle < 0 && angle >= -55 ? 1 : 0;
}
dpadMain.classList.toggle("ejs_dpad_up_pressed", up);
@@ -3992,7 +6326,7 @@ class EmulatorJS {
dpadMain.classList.toggle("ejs_dpad_left_pressed", left);
callback(up, down, left, right);
- }
+ };
const cancelCb = (e) => {
e.preventDefault();
dpadMain.classList.remove("ejs_dpad_up_pressed");
@@ -4001,19 +6335,18 @@ class EmulatorJS {
dpadMain.classList.remove("ejs_dpad_left_pressed");
callback(0, 0, 0, 0);
- }
+ };
this.addEventListener(dpadMain, "touchstart touchmove", updateCb);
this.addEventListener(dpadMain, "touchend touchcancel", cancelCb);
-
container.appendChild(dpadMain);
- }
+ };
info.forEach((dpad, index) => {
if (dpad.type !== "dpad") return;
if (leftHandedMode && ["left", "right"].includes(dpad.location)) {
- dpad.location = (dpad.location === "left") ? "right" : "left";
+ dpad.location = dpad.location === "left" ? "right" : "left";
const amnt = JSON.parse(JSON.stringify(dpad));
if (amnt.left) {
dpad.right = amnt.left;
@@ -4049,17 +6382,29 @@ class EmulatorJS {
if (right === 1) right = 0x7fff;
}
this.gameManager.simulateInput(0, dpad.inputValues[0], up);
- this.gameManager.simulateInput(0, dpad.inputValues[1], down);
- this.gameManager.simulateInput(0, dpad.inputValues[2], left);
- this.gameManager.simulateInput(0, dpad.inputValues[3], right);
- }
+ this.gameManager.simulateInput(
+ 0,
+ dpad.inputValues[1],
+ down
+ );
+ this.gameManager.simulateInput(
+ 0,
+ dpad.inputValues[2],
+ left
+ );
+ this.gameManager.simulateInput(
+ 0,
+ dpad.inputValues[3],
+ right
+ );
+ },
});
- })
+ });
info.forEach((zone, index) => {
if (zone.type !== "zone") return;
if (leftHandedMode && ["left", "right"].includes(zone.location)) {
- zone.location = (zone.location === "left") ? "right" : "left";
+ zone.location = zone.location === "left" ? "right" : "left";
const amnt = JSON.parse(JSON.stringify(zone));
if (amnt.left) {
zone.right = amnt.left;
@@ -4069,22 +6414,26 @@ class EmulatorJS {
}
}
const elem = this.createElement("div");
- this.addEventListener(elem, "touchstart touchmove touchend touchcancel", (e) => {
- e.preventDefault();
- });
+ this.addEventListener(
+ elem,
+ "touchstart touchmove touchend touchcancel",
+ (e) => {
+ e.preventDefault();
+ }
+ );
elem.classList.add(controlSchemeCls);
if (zone.id) {
elem.classList.add(`b_${zone.id}`);
}
elems[zone.location].appendChild(elem);
const zoneObj = nipplejs.create({
- "zone": elem,
- "mode": "static",
- "position": {
- "left": zone.left,
- "top": zone.top
+ zone: elem,
+ mode: "static",
+ position: {
+ left: zone.left,
+ top: zone.top,
},
- "color": zone.color || "red"
+ color: zone.color || "red",
});
zoneObj.on("end", () => {
this.gameManager.simulateInput(0, zone.inputValues[0], 0);
@@ -4096,112 +6445,206 @@ class EmulatorJS {
const degree = info.angle.degree;
const distance = info.distance;
if (zone.joystickInput === true) {
- let x = 0, y = 0;
+ let x = 0,
+ y = 0;
if (degree > 0 && degree <= 45) {
x = distance / 50;
- y = -0.022222222222222223 * degree * distance / 50;
+ y = (-0.022222222222222223 * degree * distance) / 50;
}
if (degree > 45 && degree <= 90) {
- x = 0.022222222222222223 * (90 - degree) * distance / 50;
+ x =
+ (0.022222222222222223 * (90 - degree) * distance) /
+ 50;
y = -distance / 50;
}
if (degree > 90 && degree <= 135) {
- x = 0.022222222222222223 * (90 - degree) * distance / 50;
+ x =
+ (0.022222222222222223 * (90 - degree) * distance) /
+ 50;
y = -distance / 50;
}
if (degree > 135 && degree <= 180) {
x = -distance / 50;
- y = -0.022222222222222223 * (180 - degree) * distance / 50;
+ y =
+ (-0.022222222222222223 *
+ (180 - degree) *
+ distance) /
+ 50;
}
if (degree > 135 && degree <= 225) {
x = -distance / 50;
- y = -0.022222222222222223 * (180 - degree) * distance / 50;
+ y =
+ (-0.022222222222222223 *
+ (180 - degree) *
+ distance) /
+ 50;
}
if (degree > 225 && degree <= 270) {
- x = -0.022222222222222223 * (270 - degree) * distance / 50;
+ x =
+ (-0.022222222222222223 *
+ (270 - degree) *
+ distance) /
+ 50;
y = distance / 50;
}
if (degree > 270 && degree <= 315) {
- x = -0.022222222222222223 * (270 - degree) * distance / 50;
+ x =
+ (-0.022222222222222223 *
+ (270 - degree) *
+ distance) /
+ 50;
y = distance / 50;
}
if (degree > 315 && degree <= 359.9) {
x = distance / 50;
- y = 0.022222222222222223 * (360 - degree) * distance / 50;
+ y =
+ (0.022222222222222223 * (360 - degree) * distance) /
+ 50;
}
if (x > 0) {
- this.gameManager.simulateInput(0, zone.inputValues[0], 0x7fff * x);
- this.gameManager.simulateInput(0, zone.inputValues[1], 0);
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[0],
+ 0x7fff * x
+ );
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[1],
+ 0
+ );
} else {
- this.gameManager.simulateInput(0, zone.inputValues[1], 0x7fff * -x);
- this.gameManager.simulateInput(0, zone.inputValues[0], 0);
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[1],
+ 0x7fff * -x
+ );
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[0],
+ 0
+ );
}
if (y > 0) {
- this.gameManager.simulateInput(0, zone.inputValues[2], 0x7fff * y);
- this.gameManager.simulateInput(0, zone.inputValues[3], 0);
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[2],
+ 0x7fff * y
+ );
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[3],
+ 0
+ );
} else {
- this.gameManager.simulateInput(0, zone.inputValues[3], 0x7fff * -y);
- this.gameManager.simulateInput(0, zone.inputValues[2], 0);
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[3],
+ 0x7fff * -y
+ );
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[2],
+ 0
+ );
}
-
} else {
if (degree >= 30 && degree < 150) {
- this.gameManager.simulateInput(0, zone.inputValues[0], 1);
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[0],
+ 1
+ );
} else {
window.setTimeout(() => {
- this.gameManager.simulateInput(0, zone.inputValues[0], 0);
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[0],
+ 0
+ );
}, 30);
}
if (degree >= 210 && degree < 330) {
- this.gameManager.simulateInput(0, zone.inputValues[1], 1);
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[1],
+ 1
+ );
} else {
window.setTimeout(() => {
- this.gameManager.simulateInput(0, zone.inputValues[1], 0);
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[1],
+ 0
+ );
}, 30);
}
if (degree >= 120 && degree < 240) {
- this.gameManager.simulateInput(0, zone.inputValues[2], 1);
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[2],
+ 1
+ );
} else {
window.setTimeout(() => {
- this.gameManager.simulateInput(0, zone.inputValues[2], 0);
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[2],
+ 0
+ );
}, 30);
}
- if (degree >= 300 || degree >= 0 && degree < 60) {
- this.gameManager.simulateInput(0, zone.inputValues[3], 1);
+ if (degree >= 300 || (degree >= 0 && degree < 60)) {
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[3],
+ 1
+ );
} else {
window.setTimeout(() => {
- this.gameManager.simulateInput(0, zone.inputValues[3], 0);
+ this.gameManager.simulateInput(
+ 0,
+ zone.inputValues[3],
+ 0
+ );
}, 30);
}
}
});
- })
+ });
if (this.touch || this.hasTouchScreen) {
const menuButton = this.createElement("div");
- menuButton.innerHTML = '';
+ menuButton.innerHTML =
+ '';
menuButton.classList.add("ejs_virtualGamepad_open");
menuButton.style.display = "none";
this.on("start", () => {
menuButton.style.display = "";
- if (matchMedia('(pointer:fine)').matches && this.getSettingValue("menu-bar-button") !== "visible") {
+ if (
+ matchMedia("(pointer:fine)").matches &&
+ this.getSettingValue("menu-bar-button") !== "visible"
+ ) {
menuButton.style.opacity = 0;
- this.changeSettingOption('menu-bar-button', 'hidden', true);
+ this.changeSettingOption("menu-bar-button", "hidden", true);
}
});
this.elements.parent.appendChild(menuButton);
let timeout;
let ready = true;
- this.addEventListener(menuButton, "touchstart touchend mousedown mouseup click", (e) => {
- if (!ready) return;
- clearTimeout(timeout);
- timeout = setTimeout(() => {
- ready = true;
- }, 2000)
- ready = false;
- e.preventDefault();
- this.menu.toggle();
- })
+ this.addEventListener(
+ menuButton,
+ "touchstart touchend mousedown mouseup click",
+ (e) => {
+ if (!ready) return;
+ clearTimeout(timeout);
+ timeout = setTimeout(() => {
+ ready = true;
+ }, 2000);
+ ready = false;
+ e.preventDefault();
+ this.menu.toggle();
+ }
+ );
this.elements.menuToggle = menuButton;
}
@@ -4215,13 +6658,19 @@ class EmulatorJS {
setTimeout(() => {
this.virtualGamepad.style.display = "none";
this.virtualGamepad.style.opacity = "";
- }, 250)
+ }, 250);
}
}
const positionInfo = this.elements.parent.getBoundingClientRect();
- this.game.parentElement.classList.toggle("ejs_small_screen", positionInfo.width <= 575);
+ this.game.parentElement.classList.toggle(
+ "ejs_small_screen",
+ positionInfo.width <= 575
+ );
//This wouldnt work using :not()... strange.
- this.game.parentElement.classList.toggle("ejs_big_screen", positionInfo.width > 575);
+ this.game.parentElement.classList.toggle(
+ "ejs_big_screen",
+ positionInfo.width > 575
+ );
if (!this.handleSettingsResize) return;
this.handleSettingsResize();
@@ -4235,35 +6684,48 @@ class EmulatorJS {
const res = elem.getBoundingClientRect();
elem.remove();
return {
- "width": res.width,
- "height": res.height
+ width: res.width,
+ height: res.height,
};
}
saveSettings() {
- if (!window.localStorage || this.config.disableLocalStorage || !this.settingsLoaded) return;
+ if (
+ !window.localStorage ||
+ this.config.disableLocalStorage ||
+ !this.settingsLoaded
+ )
+ return;
if (!this.started && !this.failedToStart) return;
const coreSpecific = {
controlSettings: this.controls,
settings: this.settings,
- cheats: this.cheats
- }
+ cheats: this.cheats,
+ };
const ejs_settings = {
volume: this.volume,
- muted: this.muted
- }
+ muted: this.muted,
+ };
localStorage.setItem("ejs-settings", JSON.stringify(ejs_settings));
- localStorage.setItem(this.getLocalStorageKey(), JSON.stringify(coreSpecific));
+ localStorage.setItem(
+ this.getLocalStorageKey(),
+ JSON.stringify(coreSpecific)
+ );
}
getLocalStorageKey() {
let identifier = (this.config.gameId || 1) + "-" + this.getCore(true);
if (typeof this.config.gameName === "string") {
identifier += "-" + this.config.gameName;
- } else if (typeof this.config.gameUrl === "string" && !this.config.gameUrl.toLowerCase().startsWith("blob:")) {
+ } else if (
+ typeof this.config.gameUrl === "string" &&
+ !this.config.gameUrl.toLowerCase().startsWith("blob:")
+ ) {
identifier += "-" + this.config.gameUrl;
} else if (this.config.gameUrl instanceof File) {
identifier += "-" + this.config.gameUrl.name;
} else if (typeof this.config.gameId !== "number") {
- console.warn("gameId (EJS_gameID) is not set. This may result in settings persisting across games.");
+ console.warn(
+ "gameId (EJS_gameID) is not set. This may result in settings persisting across games."
+ );
}
return "ejs-" + identifier + "-settings";
}
@@ -4275,7 +6737,7 @@ class EmulatorJS {
if (coreSpecific && coreSpecific.settings) {
return coreSpecific.settings[setting];
}
- } catch(e) {
+ } catch (e) {
console.warn("Could not load previous settings", e);
}
}
@@ -4289,30 +6751,37 @@ class EmulatorJS {
if (this.config.defaultOptions) {
let rv = "";
for (const k in this.config.defaultOptions) {
- let value = isNaN(this.config.defaultOptions[k]) ? `"${this.config.defaultOptions[k]}"` : this.config.defaultOptions[k];
+ let value = isNaN(this.config.defaultOptions[k])
+ ? `"${this.config.defaultOptions[k]}"`
+ : this.config.defaultOptions[k];
rv += `${k} = ${value}\n`;
}
return rv;
}
return "";
- };
+ }
let coreSpecific = localStorage.getItem(this.getLocalStorageKey());
if (coreSpecific) {
try {
coreSpecific = JSON.parse(coreSpecific);
- if (!(coreSpecific.settings instanceof Object)) throw new Error("Not a JSON object");
+ if (!(coreSpecific.settings instanceof Object))
+ throw new Error("Not a JSON object");
let rv = "";
for (const k in coreSpecific.settings) {
- let value = isNaN(coreSpecific.settings[k]) ? `"${coreSpecific.settings[k]}"` : coreSpecific.settings[k];
+ let value = isNaN(coreSpecific.settings[k])
+ ? `"${coreSpecific.settings[k]}"`
+ : coreSpecific.settings[k];
rv += `${k} = ${value}\n`;
}
for (const k in this.config.defaultOptions) {
if (rv.includes(k)) continue;
- let value = isNaN(this.config.defaultOptions[k]) ? `"${this.config.defaultOptions[k]}"` : this.config.defaultOptions[k];
+ let value = isNaN(this.config.defaultOptions[k])
+ ? `"${this.config.defaultOptions[k]}"`
+ : this.config.defaultOptions[k];
rv += `${k} = ${value}\n`;
}
return rv;
- } catch(e) {
+ } catch (e) {
console.warn("Could not load previous settings", e);
}
}
@@ -4326,7 +6795,12 @@ class EmulatorJS {
if (coreSpecific) {
try {
coreSpecific = JSON.parse(coreSpecific);
- if (!(coreSpecific.controlSettings instanceof Object) || !(coreSpecific.settings instanceof Object) || !Array.isArray(coreSpecific.cheats)) return;
+ if (
+ !(coreSpecific.controlSettings instanceof Object) ||
+ !(coreSpecific.settings instanceof Object) ||
+ !Array.isArray(coreSpecific.cheats)
+ )
+ return;
this.controls = coreSpecific.controlSettings;
this.checkGamepadInputs();
for (const k in coreSpecific.settings) {
@@ -4336,7 +6810,10 @@ class EmulatorJS {
const cheat = coreSpecific.cheats[i];
let includes = false;
for (let j = 0; j < this.cheats.length; j++) {
- if (this.cheats[j].desc === cheat.desc && this.cheats[j].code === cheat.code) {
+ if (
+ this.cheats[j].desc === cheat.desc &&
+ this.cheats[j].code === cheat.code
+ ) {
this.cheats[j].checked = cheat.checked;
includes = true;
break;
@@ -4345,19 +6822,22 @@ class EmulatorJS {
if (includes) continue;
this.cheats.push(cheat);
}
-
- } catch(e) {
+ } catch (e) {
console.warn("Could not load previous settings", e);
}
}
if (ejs_settings) {
try {
ejs_settings = JSON.parse(ejs_settings);
- if (typeof ejs_settings.volume !== "number" || typeof ejs_settings.muted !== "boolean") return;
+ if (
+ typeof ejs_settings.volume !== "number" ||
+ typeof ejs_settings.muted !== "boolean"
+ )
+ return;
this.volume = ejs_settings.volume;
this.muted = ejs_settings.muted;
this.setVolume(this.muted ? 0 : this.volume);
- } catch(e) {
+ } catch (e) {
console.warn("Could not load previous settings", e);
}
}
@@ -4371,7 +6851,8 @@ class EmulatorJS {
this.toggleVirtualGamepad(value !== "disabled");
} else if (option === "menu-bar-button") {
this.elements.menuToggle.style.display = "";
- this.elements.menuToggle.style.opacity = value === "visible" ? 0.5 : 0;
+ this.elements.menuToggle.style.opacity =
+ value === "visible" ? 0.5 : 0;
} else if (option === "virtual-gamepad-left-handed-mode") {
this.toggleVirtualGamepadLeftHanded(value !== "disabled");
} else if (option === "ff-ratio") {
@@ -4383,7 +6864,7 @@ class EmulatorJS {
}
setTimeout(() => {
if (this.isFastForward) this.gameManager.toggleFastForward(1);
- }, 10)
+ }, 10);
} else if (option === "fastForward") {
if (value === "enabled") {
this.isFastForward = true;
@@ -4421,7 +6902,10 @@ class EmulatorJS {
this.gameManager.setVideoRotation(0);
this.videoRotationChanged = true;
}
- } else if (option === "save-save-interval" && !this.config.fixedSaveInterval) {
+ } else if (
+ option === "save-save-interval" &&
+ !this.config.fixedSaveInterval
+ ) {
value = parseInt(value);
this.startSaveInterval(value * 1000);
} else if (option === "menubarBehavior") {
@@ -4431,7 +6915,7 @@ class EmulatorJS {
} else if (option === "altKeyboardInput") {
this.gameManager.setAltKeyEnabled(value === "enabled");
} else if (option === "lockMouse") {
- this.enableMouseLock = (value === "enabled");
+ this.enableMouseLock = value === "enabled";
}
}
menuOptionChanged(option, value) {
@@ -4461,31 +6945,38 @@ class EmulatorJS {
needChange = true;
}
let height = this.elements.parent.getBoundingClientRect().height;
- let w2 = this.diskParent.parentElement.getBoundingClientRect().width;
+ let w2 =
+ this.diskParent.parentElement.getBoundingClientRect().width;
let disksX = this.diskParent.getBoundingClientRect().x;
- if (w2 > window.innerWidth) disksX += (w2 - window.innerWidth);
+ if (w2 > window.innerWidth) disksX += w2 - window.innerWidth;
const onTheRight = disksX > (w2 - 15) / 2;
if (height > 375) height = 375;
- home.style["max-height"] = (height - 95) + "px";
- nested.style["max-height"] = (height - 95) + "px";
+ home.style["max-height"] = height - 95 + "px";
+ nested.style["max-height"] = height - 95 + "px";
for (let i = 0; i < menus.length; i++) {
- menus[i].style["max-height"] = (height - 95) + "px";
+ menus[i].style["max-height"] = height - 95 + "px";
}
- this.disksMenu.classList.toggle("ejs_settings_center_left", !onTheRight);
- this.disksMenu.classList.toggle("ejs_settings_center_right", onTheRight);
+ this.disksMenu.classList.toggle(
+ "ejs_settings_center_left",
+ !onTheRight
+ );
+ this.disksMenu.classList.toggle(
+ "ejs_settings_center_right",
+ onTheRight
+ );
if (needChange) {
this.disksMenu.style.display = "none";
this.disksMenu.style.opacity = "";
}
- }
+ };
home.classList.add("ejs_setting_menu");
nested.appendChild(home);
let funcs = [];
this.changeDiskOption = (title, newValue) => {
this.disks[title] = newValue;
- funcs.forEach(e => e(title));
- }
+ funcs.forEach((e) => e(title));
+ };
let allOpts = {};
// TODO - Why is this duplicated?
@@ -4505,11 +6996,11 @@ class EmulatorJS {
const button = this.createElement("button");
const goToHome = () => {
const homeSize = this.getElementSize(home);
- nested.style.width = (homeSize.width + 20) + "px";
+ nested.style.width = homeSize.width + 20 + "px";
nested.style.height = homeSize.height + "px";
menu.setAttribute("hidden", "");
home.removeAttribute("hidden");
- }
+ };
this.addEventListener(button, "click", goToHome);
button.type = "button";
@@ -4536,7 +7027,10 @@ class EmulatorJS {
funcs.push((title) => {
if (id !== title) return;
for (let j = 0; j < buttons.length; j++) {
- buttons[j].classList.toggle("ejs_option_row_selected", buttons[j].getAttribute("ejs_value") === this.disks[id]);
+ buttons[j].classList.toggle(
+ "ejs_option_row_selected",
+ buttons[j].getAttribute("ejs_value") === this.disks[id]
+ );
}
this.menuOptionChanged(id, this.disks[id]);
current.innerText = opts[this.disks[id]];
@@ -4560,7 +7054,7 @@ class EmulatorJS {
this.menuOptionChanged(id, opt);
current.innerText = opts[opt];
goToHome();
- })
+ });
if (defaultOption === opt) {
optionButton.classList.add("ejs_option_row_selected");
this.menuOptionChanged(id, opt);
@@ -4577,14 +7071,16 @@ class EmulatorJS {
home.appendChild(optionsMenu);
nested.appendChild(menu);
- }
+ };
if (this.gameManager.getDiskCount() > 1) {
const diskLabels = {};
let isM3U = false;
let disks = {};
if (this.fileName.split(".").pop() === "m3u") {
- disks = this.gameManager.Module.FS.readFile(this.fileName, { encoding: "utf8" }).split("\n");
+ disks = this.gameManager.Module.FS.readFile(this.fileName, {
+ encoding: "utf8",
+ }).split("\n");
isM3U = true;
}
for (let i = 0; i < this.gameManager.getDiskCount(); i++) {
@@ -4597,7 +7093,10 @@ class EmulatorJS {
// get disk name from m3u
const diskLabelValues = disks[i].split("|");
// remove the file extension from the disk file name
- let diskLabel = diskLabelValues[0].replace("." + diskLabelValues[0].split(".").pop(), "");
+ let diskLabel = diskLabelValues[0].replace(
+ "." + diskLabelValues[0].split(".").pop(),
+ ""
+ );
if (diskLabelValues.length >= 2) {
// has a label - use that instead
diskLabel = diskLabelValues[1];
@@ -4605,7 +7104,12 @@ class EmulatorJS {
diskLabels[i.toString()] = diskLabel;
}
}
- addToMenu(this.localization("Disk"), "disk", diskLabels, this.gameManager.getCurrentDisk().toString());
+ addToMenu(
+ this.localization("Disk"),
+ "disk",
+ diskLabels,
+ this.gameManager.getCurrentDisk().toString()
+ );
}
this.disksMenu.appendChild(nested);
@@ -4614,7 +7118,7 @@ class EmulatorJS {
this.diskParent.style.position = "relative";
const homeSize = this.getElementSize(home);
- nested.style.width = (homeSize.width + 20) + "px";
+ nested.style.width = homeSize.width + 20 + "px";
nested.style.height = homeSize.height + "px";
this.disksMenu.style.display = "none";
@@ -4663,19 +7167,19 @@ class EmulatorJS {
const button = this.createElement("button");
const goToHome = () => {
const homeSize = this.getElementSize(parentElement);
- nested.style.width = (homeSize.width + 20) + "px";
+ nested.style.width = homeSize.width + 20 + "px";
nested.style.height = homeSize.height + "px";
menu.setAttribute("hidden", "");
parentElement.removeAttribute("hidden");
- }
+ };
this.addEventListener(menuOption, "click", (e) => {
const targetSize = this.getElementSize(menu);
- nested.style.width = (targetSize.width + 20) + "px";
+ nested.style.width = targetSize.width + 20 + "px";
nested.style.height = targetSize.height + "px";
menu.removeAttribute("hidden");
rv.scrollTo(0, 0);
parentElement.setAttribute("hidden", "");
- })
+ });
const observer = new MutationObserver((list) => {
for (const k of list) {
for (const removed of k.removedNodes) {
@@ -4685,8 +7189,9 @@ class EmulatorJS {
const index = menus.indexOf(menu);
if (index !== -1) menus.splice(index, 1);
this.settingsMenu.style.display = "";
- const homeSize = this.getElementSize(parentElement);
- nested.style.width = (homeSize.width + 20) + "px";
+ const homeSize =
+ this.getElementSize(parentElement);
+ nested.style.width = homeSize.width + 20 + "px";
nested.style.height = homeSize.height + "px";
// This SHOULD always be called before the game started - this SHOULD never be an issue
this.settingsMenu.style.display = "none";
@@ -4703,7 +7208,7 @@ class EmulatorJS {
pageTitle.innerText = title;
pageTitle.classList.add("ejs_menu_text_a");
button.appendChild(pageTitle);
-
+
// const optionsMenu = this.createElement("div");
// optionsMenu.classList.add("ejs_setting_menu");
// menu.appendChild(optionsMenu);
@@ -4718,14 +7223,14 @@ class EmulatorJS {
}
return rv;
- }
+ };
const checkForEmptyMenu = (element) => {
if (element.firstChild === null) {
element.parentElement.remove(); // No point in keeping an empty menu
parentMenuCt--;
}
- }
+ };
const home = createSettingParent();
@@ -4737,23 +7242,30 @@ class EmulatorJS {
needChange = true;
}
let height = this.elements.parent.getBoundingClientRect().height;
- let w2 = this.settingParent.parentElement.getBoundingClientRect().width;
+ let w2 =
+ this.settingParent.parentElement.getBoundingClientRect().width;
let settingsX = this.settingParent.getBoundingClientRect().x;
- if (w2 > window.innerWidth) settingsX += (w2 - window.innerWidth);
+ if (w2 > window.innerWidth) settingsX += w2 - window.innerWidth;
const onTheRight = settingsX > (w2 - 15) / 2;
if (height > 375) height = 375;
- home.style["max-height"] = (height - 95) + "px";
- nested.style["max-height"] = (height - 95) + "px";
+ home.style["max-height"] = height - 95 + "px";
+ nested.style["max-height"] = height - 95 + "px";
for (let i = 0; i < menus.length; i++) {
- menus[i].style["max-height"] = (height - 95) + "px";
+ menus[i].style["max-height"] = height - 95 + "px";
}
- this.settingsMenu.classList.toggle("ejs_settings_center_left", !onTheRight);
- this.settingsMenu.classList.toggle("ejs_settings_center_right", onTheRight);
+ this.settingsMenu.classList.toggle(
+ "ejs_settings_center_left",
+ !onTheRight
+ );
+ this.settingsMenu.classList.toggle(
+ "ejs_settings_center_right",
+ onTheRight
+ );
if (needChange) {
this.settingsMenu.style.display = "none";
this.settingsMenu.style.opacity = "";
}
- }
+ };
nested.appendChild(home);
let funcs = [];
@@ -4764,16 +7276,28 @@ class EmulatorJS {
this.settings[title] = newValue;
}
settings[title] = newValue;
- funcs.forEach(e => e(title));
- }
+ funcs.forEach((e) => e(title));
+ };
let allOpts = {};
- const addToMenu = (title, id, options, defaultOption, parentElement, useParentParent) => {
- if (Array.isArray(this.config.hideSettings) && this.config.hideSettings.includes(id)) {
+ const addToMenu = (
+ title,
+ id,
+ options,
+ defaultOption,
+ parentElement,
+ useParentParent
+ ) => {
+ if (
+ Array.isArray(this.config.hideSettings) &&
+ this.config.hideSettings.includes(id)
+ ) {
return;
}
parentElement = parentElement || home;
- const transitionElement = useParentParent ? parentElement.parentElement.parentElement : parentElement;
+ const transitionElement = useParentParent
+ ? parentElement.parentElement.parentElement
+ : parentElement;
const menuOption = this.createElement("div");
menuOption.classList.add("ejs_settings_main_bar");
const span = this.createElement("span");
@@ -4801,19 +7325,19 @@ class EmulatorJS {
transitionElement.removeAttribute("hidden");
menu.setAttribute("hidden", "");
const homeSize = this.getElementSize(transitionElement);
- nested.style.width = (homeSize.width + 20) + "px";
+ nested.style.width = homeSize.width + 20 + "px";
nested.style.height = homeSize.height + "px";
transitionElement.removeAttribute("hidden");
- }
+ };
this.addEventListener(menuOption, "click", (e) => {
const targetSize = this.getElementSize(menu);
- nested.style.width = (targetSize.width + 20) + "px";
+ nested.style.width = targetSize.width + 20 + "px";
nested.style.height = targetSize.height + "px";
menu.removeAttribute("hidden");
optionsMenu.scrollTo(0, 0);
transitionElement.setAttribute("hidden", "");
transitionElement.setAttribute("hidden", "");
- })
+ });
this.addEventListener(button, "click", goToHome);
button.type = "button";
@@ -4837,7 +7361,10 @@ class EmulatorJS {
funcs.push((title) => {
if (id !== title) return;
for (let j = 0; j < buttons.length; j++) {
- buttons[j].classList.toggle("ejs_option_row_selected", buttons[j].getAttribute("ejs_value") === settings[id]);
+ buttons[j].classList.toggle(
+ "ejs_option_row_selected",
+ buttons[j].getAttribute("ejs_value") === settings[id]
+ );
}
this.menuOptionChanged(id, settings[id]);
current.innerText = opts[settings[id]];
@@ -4861,7 +7388,7 @@ class EmulatorJS {
this.menuOptionChanged(id, opt);
current.innerText = opts[opt];
goToHome();
- })
+ });
if (defaultOption === opt) {
optionButton.classList.add("ejs_option_row_selected");
this.menuOptionChanged(id, opt);
@@ -4879,20 +7406,41 @@ class EmulatorJS {
menu.appendChild(menuChild);
nested.appendChild(menu);
- }
+ };
const cores = this.getCores();
const core = cores[this.getCore(true)];
if (core && core.length > 1) {
- addToMenu(this.localization("Core" + " (" + this.localization("Requires restart") + ")"), "retroarch_core", core, this.getCore(), home);
+ addToMenu(
+ this.localization(
+ "Core" + " (" + this.localization("Requires restart") + ")"
+ ),
+ "retroarch_core",
+ core,
+ this.getCore(),
+ home
+ );
}
- if (typeof window.SharedArrayBuffer === "function" && !this.requiresThreads(this.getCore())) {
- addToMenu(this.localization("Threads"), "ejs_threads", {
- "enabled": this.localization("Enabled"),
- "disabled": this.localization("Disabled")
- }, this.config.threads ? "enabled" : "disabled", home);
+ if (
+ typeof window.SharedArrayBuffer === "function" &&
+ !this.requiresThreads(this.getCore())
+ ) {
+ addToMenu(
+ this.localization("Threads"),
+ "ejs_threads",
+ {
+ enabled: this.localization("Enabled"),
+ disabled: this.localization("Disabled"),
+ },
+ this.config.threads ? "enabled" : "disabled",
+ home
+ );
}
- const graphicsOptions = createSettingParent(true, "Graphics Settings", home);
+ const graphicsOptions = createSettingParent(
+ true,
+ "Graphics Settings",
+ home
+ );
if (this.config.shaders) {
const builtinShaders = {
@@ -4907,12 +7455,12 @@ class EmulatorJS {
"crt-mattias.glslp": this.localization("CRT mattias"),
"crt-yeetron": this.localization("CRT yeetron"),
"crt-zfast": this.localization("CRT zfast"),
- "sabr": this.localization("SABR"),
- "bicubic": this.localization("Bicubic"),
+ sabr: this.localization("SABR"),
+ bicubic: this.localization("Bicubic"),
"mix-frames": this.localization("Mix frames"),
};
let shaderMenu = {
- "disabled": this.localization("Disabled"),
+ disabled: this.localization("Disabled"),
};
for (const shaderName in this.config.shaders) {
if (builtinShaders[shaderName]) {
@@ -4921,79 +7469,149 @@ class EmulatorJS {
shaderMenu[shaderName] = shaderName;
}
}
- addToMenu(this.localization("Shaders"), "shader", shaderMenu, "disabled", graphicsOptions, true);
+ addToMenu(
+ this.localization("Shaders"),
+ "shader",
+ shaderMenu,
+ "disabled",
+ graphicsOptions,
+ true
+ );
}
if (this.supportsWebgl2 && !this.requiresWebGL2(this.getCore())) {
- addToMenu(this.localization("WebGL2") + " (" + this.localization("Requires restart") + ")", "webgl2Enabled", {
- "enabled": this.localization("Enabled"),
- "disabled": this.localization("Disabled")
- }, this.webgl2Enabled ? "enabled" : "disabled", graphicsOptions, true);
+ addToMenu(
+ this.localization("WebGL2") +
+ " (" +
+ this.localization("Requires restart") +
+ ")",
+ "webgl2Enabled",
+ {
+ enabled: this.localization("Enabled"),
+ disabled: this.localization("Disabled"),
+ },
+ this.webgl2Enabled ? "enabled" : "disabled",
+ graphicsOptions,
+ true
+ );
}
- addToMenu(this.localization("FPS"), "fps", {
- "show": this.localization("show"),
- "hide": this.localization("hide")
- }, "hide", graphicsOptions, true);
+ addToMenu(
+ this.localization("FPS"),
+ "fps",
+ {
+ show: this.localization("show"),
+ hide: this.localization("hide"),
+ },
+ "hide",
+ graphicsOptions,
+ true
+ );
- addToMenu(this.localization("VSync"), "vsync", {
- "enabled": this.localization("Enabled"),
- "disabled": this.localization("Disabled")
- }, "enabled", graphicsOptions, true);
+ addToMenu(
+ this.localization("VSync"),
+ "vsync",
+ {
+ enabled: this.localization("Enabled"),
+ disabled: this.localization("Disabled"),
+ },
+ "enabled",
+ graphicsOptions,
+ true
+ );
- addToMenu(this.localization("Video Rotation"), "videoRotation", {
- "0": "0 deg",
- "1": "90 deg",
- "2": "180 deg",
- "3": "270 deg"
- }, this.videoRotation.toString(), graphicsOptions, true);
+ addToMenu(
+ this.localization("Video Rotation"),
+ "videoRotation",
+ {
+ 0: "0 deg",
+ 1: "90 deg",
+ 2: "180 deg",
+ 3: "270 deg",
+ },
+ this.videoRotation.toString(),
+ graphicsOptions,
+ true
+ );
- const screenCaptureOptions = createSettingParent(true, "Screen Capture", home);
+ const screenCaptureOptions = createSettingParent(
+ true,
+ "Screen Capture",
+ home
+ );
- addToMenu(this.localization("Screenshot Source"), "screenshotSource", {
- "canvas": "canvas",
- "retroarch": "retroarch"
- }, this.capture.photo.source, screenCaptureOptions, true);
+ addToMenu(
+ this.localization("Screenshot Source"),
+ "screenshotSource",
+ {
+ canvas: "canvas",
+ retroarch: "retroarch",
+ },
+ this.capture.photo.source,
+ screenCaptureOptions,
+ true
+ );
let screenshotFormats = {
- "png": "png",
- "jpeg": "jpeg",
- "webp": "webp"
- }
- if (this.isSafari) {
- delete screenshotFormats["webp"];
+ png: "png",
+ jpeg: "jpeg",
+ webp: "webp",
+ };
+ if (this.isSafari) {
+ delete screenshotFormats["webp"];
}
if (!(this.capture.photo.format in screenshotFormats)) {
this.capture.photo.format = "png";
}
- addToMenu(this.localization("Screenshot Format"), "screenshotFormat", screenshotFormats, this.capture.photo.format, screenCaptureOptions, true);
+ addToMenu(
+ this.localization("Screenshot Format"),
+ "screenshotFormat",
+ screenshotFormats,
+ this.capture.photo.format,
+ screenCaptureOptions,
+ true
+ );
const screenshotUpscale = this.capture.photo.upscale.toString();
let screenshotUpscales = {
- "0": "native",
- "1": "1x",
- "2": "2x",
- "3": "3x"
- }
+ 0: "native",
+ 1: "1x",
+ 2: "2x",
+ 3: "3x",
+ };
if (!(screenshotUpscale in screenshotUpscales)) {
screenshotUpscales[screenshotUpscale] = screenshotUpscale + "x";
}
- addToMenu(this.localization("Screenshot Upscale"), "screenshotUpscale", screenshotUpscales, screenshotUpscale, screenCaptureOptions, true);
+ addToMenu(
+ this.localization("Screenshot Upscale"),
+ "screenshotUpscale",
+ screenshotUpscales,
+ screenshotUpscale,
+ screenCaptureOptions,
+ true
+ );
const screenRecordFPS = this.capture.video.fps.toString();
let screenRecordFPSs = {
- "30": "30",
- "60": "60"
- }
+ 30: "30",
+ 60: "60",
+ };
if (!(screenRecordFPS in screenRecordFPSs)) {
screenRecordFPSs[screenRecordFPS] = screenRecordFPS;
}
- addToMenu(this.localization("Screen Recording FPS"), "screenRecordFPS", screenRecordFPSs, screenRecordFPS, screenCaptureOptions, true);
+ addToMenu(
+ this.localization("Screen Recording FPS"),
+ "screenRecordFPS",
+ screenRecordFPSs,
+ screenRecordFPS,
+ screenCaptureOptions,
+ true
+ );
let screenRecordFormats = {
- "mp4": "mp4",
- "webm": "webm"
- }
+ mp4: "mp4",
+ webm: "webm",
+ };
for (const format in screenRecordFormats) {
if (!MediaRecorder.isTypeSupported("video/" + format)) {
delete screenRecordFormats[format];
@@ -5002,164 +7620,372 @@ class EmulatorJS {
if (!(this.capture.video.format in screenRecordFormats)) {
this.capture.video.format = Object.keys(screenRecordFormats)[0];
}
- addToMenu(this.localization("Screen Recording Format"), "screenRecordFormat", screenRecordFormats, this.capture.video.format, screenCaptureOptions, true);
+ addToMenu(
+ this.localization("Screen Recording Format"),
+ "screenRecordFormat",
+ screenRecordFormats,
+ this.capture.video.format,
+ screenCaptureOptions,
+ true
+ );
const screenRecordUpscale = this.capture.video.upscale.toString();
let screenRecordUpscales = {
- "1": "1x",
- "2": "2x",
- "3": "3x",
- "4": "4x"
- }
+ 1: "1x",
+ 2: "2x",
+ 3: "3x",
+ 4: "4x",
+ };
if (!(screenRecordUpscale in screenRecordUpscales)) {
- screenRecordUpscales[screenRecordUpscale] = screenRecordUpscale + "x";
+ screenRecordUpscales[screenRecordUpscale] =
+ screenRecordUpscale + "x";
}
- addToMenu(this.localization("Screen Recording Upscale"), "screenRecordUpscale", screenRecordUpscales, screenRecordUpscale, screenCaptureOptions, true);
+ addToMenu(
+ this.localization("Screen Recording Upscale"),
+ "screenRecordUpscale",
+ screenRecordUpscales,
+ screenRecordUpscale,
+ screenCaptureOptions,
+ true
+ );
- const screenRecordVideoBitrate = this.capture.video.videoBitrate.toString();
+ const screenRecordVideoBitrate =
+ this.capture.video.videoBitrate.toString();
let screenRecordVideoBitrates = {
- "1048576": "1 Mbit/sec",
- "2097152": "2 Mbit/sec",
- "2621440": "2.5 Mbit/sec",
- "3145728": "3 Mbit/sec",
- "4194304": "4 Mbit/sec"
- }
+ 1048576: "1 Mbit/sec",
+ 2097152: "2 Mbit/sec",
+ 2621440: "2.5 Mbit/sec",
+ 3145728: "3 Mbit/sec",
+ 4194304: "4 Mbit/sec",
+ };
if (!(screenRecordVideoBitrate in screenRecordVideoBitrates)) {
- screenRecordVideoBitrates[screenRecordVideoBitrate] = screenRecordVideoBitrate + " Bits/sec";
+ screenRecordVideoBitrates[screenRecordVideoBitrate] =
+ screenRecordVideoBitrate + " Bits/sec";
}
- addToMenu(this.localization("Screen Recording Video Bitrate"), "screenRecordVideoBitrate", screenRecordVideoBitrates, screenRecordVideoBitrate, screenCaptureOptions, true);
+ addToMenu(
+ this.localization("Screen Recording Video Bitrate"),
+ "screenRecordVideoBitrate",
+ screenRecordVideoBitrates,
+ screenRecordVideoBitrate,
+ screenCaptureOptions,
+ true
+ );
- const screenRecordAudioBitrate = this.capture.video.audioBitrate.toString();
+ const screenRecordAudioBitrate =
+ this.capture.video.audioBitrate.toString();
let screenRecordAudioBitrates = {
- "65536": "64 Kbit/sec",
- "131072": "128 Kbit/sec",
- "196608": "192 Kbit/sec",
- "262144": "256 Kbit/sec",
- "327680": "320 Kbit/sec"
- }
+ 65536: "64 Kbit/sec",
+ 131072: "128 Kbit/sec",
+ 196608: "192 Kbit/sec",
+ 262144: "256 Kbit/sec",
+ 327680: "320 Kbit/sec",
+ };
if (!(screenRecordAudioBitrate in screenRecordAudioBitrates)) {
- screenRecordAudioBitrates[screenRecordAudioBitrate] = screenRecordAudioBitrate + " Bits/sec";
+ screenRecordAudioBitrates[screenRecordAudioBitrate] =
+ screenRecordAudioBitrate + " Bits/sec";
}
- addToMenu(this.localization("Screen Recording Audio Bitrate"), "screenRecordAudioBitrate", screenRecordAudioBitrates, screenRecordAudioBitrate, screenCaptureOptions, true);
+ addToMenu(
+ this.localization("Screen Recording Audio Bitrate"),
+ "screenRecordAudioBitrate",
+ screenRecordAudioBitrates,
+ screenRecordAudioBitrate,
+ screenCaptureOptions,
+ true
+ );
checkForEmptyMenu(screenCaptureOptions);
const speedOptions = createSettingParent(true, "Speed Options", home);
- addToMenu(this.localization("Fast Forward"), "fastForward", {
- "enabled": this.localization("Enabled"),
- "disabled": this.localization("Disabled")
- }, "disabled", speedOptions, true);
+ addToMenu(
+ this.localization("Fast Forward"),
+ "fastForward",
+ {
+ enabled: this.localization("Enabled"),
+ disabled: this.localization("Disabled"),
+ },
+ "disabled",
+ speedOptions,
+ true
+ );
- addToMenu(this.localization("Fast Forward Ratio"), "ff-ratio", [
- "1.5", "2.0", "2.5", "3.0", "3.5", "4.0", "4.5", "5.0", "5.5", "6.0", "6.5", "7.0", "7.5", "8.0", "8.5", "9.0", "9.5", "10.0", "unlimited"
- ], "3.0", speedOptions, true);
+ addToMenu(
+ this.localization("Fast Forward Ratio"),
+ "ff-ratio",
+ [
+ "1.5",
+ "2.0",
+ "2.5",
+ "3.0",
+ "3.5",
+ "4.0",
+ "4.5",
+ "5.0",
+ "5.5",
+ "6.0",
+ "6.5",
+ "7.0",
+ "7.5",
+ "8.0",
+ "8.5",
+ "9.0",
+ "9.5",
+ "10.0",
+ "unlimited",
+ ],
+ "3.0",
+ speedOptions,
+ true
+ );
- addToMenu(this.localization("Slow Motion"), "slowMotion", {
- "enabled": this.localization("Enabled"),
- "disabled": this.localization("Disabled")
- }, "disabled", speedOptions, true);
+ addToMenu(
+ this.localization("Slow Motion"),
+ "slowMotion",
+ {
+ enabled: this.localization("Enabled"),
+ disabled: this.localization("Disabled"),
+ },
+ "disabled",
+ speedOptions,
+ true
+ );
- addToMenu(this.localization("Slow Motion Ratio"), "sm-ratio", [
- "1.5", "2.0", "2.5", "3.0", "3.5", "4.0", "4.5", "5.0", "5.5", "6.0", "6.5", "7.0", "7.5", "8.0", "8.5", "9.0", "9.5", "10.0"
- ], "3.0", speedOptions, true);
+ addToMenu(
+ this.localization("Slow Motion Ratio"),
+ "sm-ratio",
+ [
+ "1.5",
+ "2.0",
+ "2.5",
+ "3.0",
+ "3.5",
+ "4.0",
+ "4.5",
+ "5.0",
+ "5.5",
+ "6.0",
+ "6.5",
+ "7.0",
+ "7.5",
+ "8.0",
+ "8.5",
+ "9.0",
+ "9.5",
+ "10.0",
+ ],
+ "3.0",
+ speedOptions,
+ true
+ );
- addToMenu(this.localization("Rewind Enabled" + " (" + this.localization("Requires restart") + ")"), "rewindEnabled", {
- "enabled": this.localization("Enabled"),
- "disabled": this.localization("Disabled")
- }, "disabled", speedOptions, true);
+ addToMenu(
+ this.localization(
+ "Rewind Enabled" +
+ " (" +
+ this.localization("Requires restart") +
+ ")"
+ ),
+ "rewindEnabled",
+ {
+ enabled: this.localization("Enabled"),
+ disabled: this.localization("Disabled"),
+ },
+ "disabled",
+ speedOptions,
+ true
+ );
if (this.rewindEnabled) {
- addToMenu(this.localization("Rewind Granularity"), "rewind-granularity", [
- "1", "3", "6", "12", "25", "50", "100"
- ], "6", speedOptions, true);
+ addToMenu(
+ this.localization("Rewind Granularity"),
+ "rewind-granularity",
+ ["1", "3", "6", "12", "25", "50", "100"],
+ "6",
+ speedOptions,
+ true
+ );
}
const inputOptions = createSettingParent(true, "Input Options", home);
- addToMenu(this.localization("Menubar Mouse Trigger"), "menubarBehavior", {
- "downward": this.localization("Downward Movement"),
- "anywhere": this.localization("Movement Anywhere"),
- }, "downward", inputOptions, true);
+ addToMenu(
+ this.localization("Menubar Mouse Trigger"),
+ "menubarBehavior",
+ {
+ downward: this.localization("Downward Movement"),
+ anywhere: this.localization("Movement Anywhere"),
+ },
+ "downward",
+ inputOptions,
+ true
+ );
- addToMenu(this.localization("Direct Keyboard Input"), "keyboardInput", {
- "disabled": this.localization("Disabled"),
- "enabled": this.localization("Enabled"),
- }, ((this.defaultCoreOpts && this.defaultCoreOpts.useKeyboard === true) ? "enabled" : "disabled"), inputOptions, true);
+ addToMenu(
+ this.localization("Direct Keyboard Input"),
+ "keyboardInput",
+ {
+ disabled: this.localization("Disabled"),
+ enabled: this.localization("Enabled"),
+ },
+ this.defaultCoreOpts && this.defaultCoreOpts.useKeyboard === true
+ ? "enabled"
+ : "disabled",
+ inputOptions,
+ true
+ );
- addToMenu(this.localization("Forward Alt key"), "altKeyboardInput", {
- "disabled": this.localization("Disabled"),
- "enabled": this.localization("Enabled"),
- }, "disabled", inputOptions, true);
+ addToMenu(
+ this.localization("Forward Alt key"),
+ "altKeyboardInput",
+ {
+ disabled: this.localization("Disabled"),
+ enabled: this.localization("Enabled"),
+ },
+ "disabled",
+ inputOptions,
+ true
+ );
- addToMenu(this.localization("Lock Mouse"), "lockMouse", {
- "disabled": this.localization("Disabled"),
- "enabled": this.localization("Enabled"),
- }, (this.enableMouseLock === true ? "enabled" : "disabled"), inputOptions, true);
+ addToMenu(
+ this.localization("Lock Mouse"),
+ "lockMouse",
+ {
+ disabled: this.localization("Disabled"),
+ enabled: this.localization("Enabled"),
+ },
+ this.enableMouseLock === true ? "enabled" : "disabled",
+ inputOptions,
+ true
+ );
checkForEmptyMenu(inputOptions);
if (this.saveInBrowserSupported()) {
- const saveStateOpts = createSettingParent(true, "Save States", home);
- addToMenu(this.localization("Save State Slot"), "save-state-slot", ["1", "2", "3", "4", "5", "6", "7", "8", "9"], "1", saveStateOpts, true);
- addToMenu(this.localization("Save State Location"), "save-state-location", {
- "download": this.localization("Download"),
- "browser": this.localization("Keep in Browser")
- }, "download", saveStateOpts, true);
+ const saveStateOpts = createSettingParent(
+ true,
+ "Save States",
+ home
+ );
+ addToMenu(
+ this.localization("Save State Slot"),
+ "save-state-slot",
+ ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
+ "1",
+ saveStateOpts,
+ true
+ );
+ addToMenu(
+ this.localization("Save State Location"),
+ "save-state-location",
+ {
+ download: this.localization("Download"),
+ browser: this.localization("Keep in Browser"),
+ },
+ "download",
+ saveStateOpts,
+ true
+ );
if (!this.config.fixedSaveInterval) {
- addToMenu(this.localization("System Save interval"), "save-save-interval", {
- "0": "Disabled",
- "30": "30 seconds",
- "60": "1 minute",
- "300": "5 minutes",
- "600": "10 minutes",
- "900": "15 minutes",
- "1800": "30 minutes"
- }, "300", saveStateOpts, true);
+ addToMenu(
+ this.localization("System Save interval"),
+ "save-save-interval",
+ {
+ 0: "Disabled",
+ 30: "30 seconds",
+ 60: "1 minute",
+ 300: "5 minutes",
+ 600: "10 minutes",
+ 900: "15 minutes",
+ 1800: "30 minutes",
+ },
+ "300",
+ saveStateOpts,
+ true
+ );
}
checkForEmptyMenu(saveStateOpts);
}
if (this.touch || this.hasTouchScreen) {
- const virtualGamepad = createSettingParent(true, "Virtual Gamepad", home);
- addToMenu(this.localization("Virtual Gamepad"), "virtual-gamepad", {
- "enabled": this.localization("Enabled"),
- "disabled": this.localization("Disabled")
- }, this.isMobile ? "enabled" : "disabled", virtualGamepad, true);
- addToMenu(this.localization("Menu Bar Button"), "menu-bar-button", {
- "visible": this.localization("visible"),
- "hidden": this.localization("hidden")
- }, "visible", virtualGamepad, true);
- addToMenu(this.localization("Left Handed Mode"), "virtual-gamepad-left-handed-mode", {
- "enabled": this.localization("Enabled"),
- "disabled": this.localization("Disabled")
- }, "disabled", virtualGamepad, true);
+ const virtualGamepad = createSettingParent(
+ true,
+ "Virtual Gamepad",
+ home
+ );
+ addToMenu(
+ this.localization("Virtual Gamepad"),
+ "virtual-gamepad",
+ {
+ enabled: this.localization("Enabled"),
+ disabled: this.localization("Disabled"),
+ },
+ this.isMobile ? "enabled" : "disabled",
+ virtualGamepad,
+ true
+ );
+ addToMenu(
+ this.localization("Menu Bar Button"),
+ "menu-bar-button",
+ {
+ visible: this.localization("visible"),
+ hidden: this.localization("hidden"),
+ },
+ "visible",
+ virtualGamepad,
+ true
+ );
+ addToMenu(
+ this.localization("Left Handed Mode"),
+ "virtual-gamepad-left-handed-mode",
+ {
+ enabled: this.localization("Enabled"),
+ disabled: this.localization("Disabled"),
+ },
+ "disabled",
+ virtualGamepad,
+ true
+ );
checkForEmptyMenu(virtualGamepad);
}
let coreOpts;
try {
coreOpts = this.gameManager.getCoreOptions();
- } catch(e) {}
+ } catch (e) {}
if (coreOpts) {
- const coreOptions = createSettingParent(true, "Backend Core Options", home);
+ const coreOptions = createSettingParent(
+ true,
+ "Backend Core Options",
+ home
+ );
coreOpts.split("\n").forEach((line, index) => {
let option = line.split("; ");
let name = option[0];
let options = option[1].split("|"),
- optionName = name.split("|")[0].replace(/_/g, " ").replace(/.+\-(.+)/, "$1");
+ optionName = name
+ .split("|")[0]
+ .replace(/_/g, " ")
+ .replace(/.+\-(.+)/, "$1");
options.slice(1, -1);
if (options.length === 1) return;
let availableOptions = {};
for (let i = 0; i < options.length; i++) {
- availableOptions[options[i]] = this.localization(options[i], this.config.settingsLanguage);
+ availableOptions[options[i]] = this.localization(
+ options[i],
+ this.config.settingsLanguage
+ );
}
- addToMenu(this.localization(optionName, this.config.settingsLanguage),
- name.split("|")[0], availableOptions,
- (name.split("|").length > 1) ? name.split("|")[1] : options[0].replace("(Default) ", ""),
+ addToMenu(
+ this.localization(optionName, this.config.settingsLanguage),
+ name.split("|")[0],
+ availableOptions,
+ name.split("|").length > 1
+ ? name.split("|")[1]
+ : options[0].replace("(Default) ", ""),
coreOptions,
- true);
- })
+ true
+ );
+ });
checkForEmptyMenu(coreOptions);
}
@@ -5177,15 +8003,27 @@ class EmulatorJS {
];*/
if (this.retroarchOpts && Array.isArray(this.retroarchOpts)) {
- const retroarchOptsMenu = createSettingParent(true, "RetroArch Options" + " (" + this.localization("Requires restart") + ")", home);
- this.retroarchOpts.forEach(option => {
- addToMenu(this.localization(option.title, this.config.settingsLanguage),
+ const retroarchOptsMenu = createSettingParent(
+ true,
+ "RetroArch Options" +
+ " (" +
+ this.localization("Requires restart") +
+ ")",
+ home
+ );
+ this.retroarchOpts.forEach((option) => {
+ addToMenu(
+ this.localization(
+ option.title,
+ this.config.settingsLanguage
+ ),
option.name,
option.options,
option.default,
retroarchOptsMenu,
- true);
- })
+ true
+ );
+ });
checkForEmptyMenu(retroarchOptsMenu);
}
@@ -5199,7 +8037,7 @@ class EmulatorJS {
this.settingsMenu.style.display = "";
const homeSize = this.getElementSize(home);
- nested.style.width = (homeSize.width + 20) + "px";
+ nested.style.width = homeSize.width + 20 + "px";
nested.style.height = homeSize.height + "px";
this.settingsMenu.style.display = "none";
@@ -5210,7 +8048,11 @@ class EmulatorJS {
if (this.config.defaultOptions) {
for (const k in this.config.defaultOptions) {
- this.changeSettingOption(k, this.config.defaultOptions[k], true);
+ this.changeSettingOption(
+ k,
+ this.config.defaultOptions[k],
+ true
+ );
}
}
@@ -5247,41 +8089,49 @@ class EmulatorJS {
...(bar.loadSavFiles || []),
...(bar.exit || []),
...(bar.contextMenu || []),
- ...(bar.cacheManager || [])
+ ...(bar.cacheManager || []),
];
-
+
// Add the parent containers to the same logic
- if (bar.settings && bar.settings.length > 0 && bar.settings[0].parentElement) {
+ if (
+ bar.settings &&
+ bar.settings.length > 0 &&
+ bar.settings[0].parentElement
+ ) {
elementsToToggle.push(bar.settings[0].parentElement);
}
if (this.diskParent) {
elementsToToggle.push(this.diskParent);
}
- elementsToToggle.forEach(el => {
+ elementsToToggle.forEach((el) => {
if (el) {
- el.classList.toggle('netplay-hidden', shouldHideButtons);
+ el.classList.toggle("netplay-hidden", shouldHideButtons);
}
});
}
createNetplayMenu() {
- const body = this.createPopup("Netplay", {
- "Create a Room": () => {
- if (typeof this.netplay.updateList !== "function")
- this.defineNetplayFunctions();
- if (this.isNetplay) {
- this.netplay.leaveRoom();
- } else {
- this.netplay.showOpenRoomDialog();
- }
+ const body = this.createPopup(
+ "Netplay",
+ {
+ "Create a Room": () => {
+ if (typeof this.netplay.updateList !== "function")
+ this.defineNetplayFunctions();
+ if (this.isNetplay) {
+ this.netplay.leaveRoom();
+ } else {
+ this.netplay.showOpenRoomDialog();
+ }
+ },
+ Close: () => {
+ this.netplayMenu.style.display = "none";
+ if (this.netplay.updateList) {
+ this.netplay.updateList.stop();
+ }
+ },
},
- "Close": () => {
- this.netplayMenu.style.display = "none";
- if (this.netplay.updateList) {
- this.netplay.updateList.stop();
- }
- }
- }, true);
+ true
+ );
this.netplayMenu = body.parentElement;
const createButton = this.netplayMenu.getElementsByTagName("a")[0];
const rooms = this.createElement("div");
@@ -5348,8 +8198,10 @@ class EmulatorJS {
if (this.netplayShowTurnWarning && !this.netplayWarningShown) {
const warningDiv = this.createElement("div");
warningDiv.className = "ejs_netplay_warning";
- warningDiv.innerText = "Warning: No TURN server configured. Netplay connections may fail.";
- const menuBody = this.netplayMenu.querySelector(".ejs_popup_body");
+ warningDiv.innerText =
+ "Warning: No TURN server configured. Netplay connections may fail.";
+ const menuBody =
+ this.netplayMenu.querySelector(".ejs_popup_body");
if (menuBody) {
menuBody.prepend(warningDiv);
this.netplayWarningShown = true;
@@ -5364,7 +8216,7 @@ class EmulatorJS {
roomNameElem: title2,
createButton: createButton,
tabs: [rooms, joined],
- ...this.netplay
+ ...this.netplay,
};
const popups = this.createSubPopup();
this.netplayMenu.appendChild(popups[0]);
@@ -5395,12 +8247,12 @@ class EmulatorJS {
const submit = this.createElement("button");
submit.classList.add("ejs_button_button");
submit.classList.add("ejs_popup_submit");
- submit.style["background-color"] = "rgba(var(--ejs-primary-color),1)";
+ submit.style["background-color"] =
+ "rgba(var(--ejs-primary-color),1)";
submit.innerText = this.localization("Submit");
popup.appendChild(submit);
this.addEventListener(submit, "click", (e) => {
- if (!input.value.trim())
- return;
+ if (!input.value.trim()) return;
this.netplay.name = input.value.trim();
popups[0].remove();
});
@@ -5417,33 +8269,44 @@ class EmulatorJS {
function guidGenerator() {
const S4 = function () {
- return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
+ return (((1 + Math.random()) * 0x10000) | 0)
+ .toString(16)
+ .substring(1);
};
- return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
+ return (
+ S4() +
+ S4() +
+ "-" +
+ S4() +
+ "-" +
+ S4() +
+ "-" +
+ S4() +
+ "-" +
+ S4() +
+ S4() +
+ S4()
+ );
}
this.getNativeResolution = function () {
if (this.Module && this.Module.getNativeResolution) {
try {
const res = this.Module.getNativeResolution();
- console.log("Native resolution from Module:", res);
return res;
} catch (error) {
console.error("Failed to get native resolution:", error);
- return {
- width: 640,
- height: 480
- };
+ return { width: 640, height: 480 };
}
}
- return {
- width: 640,
- height: 480
- };
+ return { width: 640, height: 480 };
};
this.netplayGetUserIndex = function () {
- if (!this.isNetplay || !this.netplay.players || !this.netplay.playerID) {
- console.warn("netplayGetUserIndex: Netplay not active or players/playerID undefined");
+ if (
+ !this.isNetplay ||
+ !this.netplay.players ||
+ !this.netplay.playerID
+ ) {
return 0;
}
const playerIds = Object.keys(this.netplay.players);
@@ -5452,14 +8315,12 @@ class EmulatorJS {
};
this.netplay.simulateInput = (player, index, value) => {
- console.log("netplay.simulateInput called:", {
- player,
- index,
- value,
- playerIndex: this.netplayGetUserIndex()
- });
- if (!this.isNetplay || !this.gameManager || !this.gameManager.functions || !this.gameManager.functions.simulateInput) {
- console.error("Cannot simulate input: Netplay not active or gameManager.functions.simulateInput undefined");
+ if (
+ !this.isNetplay ||
+ !this.gameManager ||
+ !this.gameManager.functions ||
+ !this.gameManager.functions.simulateInput
+ ) {
return;
}
const playerIndex = this.netplayGetUserIndex();
@@ -5469,30 +8330,34 @@ class EmulatorJS {
this.netplay.inputsData[frame] = [];
this.netplay.inputsData[frame].push({
frame: frame,
- connected_input: [playerIndex, index, value]
+ connected_input: [playerIndex, index, value],
});
- this.gameManager.functions.simulateInput(playerIndex, index, value);
+ this.gameManager.functions.simulateInput(
+ playerIndex,
+ index,
+ value
+ );
} else {
- this.gameManager.functions.simulateInput(playerIndex, index, value);
+ this.gameManager.functions.simulateInput(
+ playerIndex,
+ index,
+ value
+ );
if (this.netplaySendMessage) {
this.netplaySendMessage({
- "sync-control": [{
+ "sync-control": [
+ {
frame: frame + 20,
- connected_input: [playerIndex, index, value]
- }
- ]
+ connected_input: [playerIndex, index, value],
+ },
+ ],
});
- } else {
- console.error("netplaySendMessage is undefined");
}
}
};
this.netplayUpdateTableList = async () => {
- if (!this.netplay || !this.netplay.table) {
- console.error("netplay or netplay.table is undefined");
- return;
- }
+ if (!this.netplay || !this.netplay.table) return;
const addToTable = (id, name, current, max, hasPassword) => {
const row = this.createElement("tr");
@@ -5513,17 +8378,27 @@ class EmulatorJS {
if (current < max) {
const join = this.createElement("button");
- join.classList.add("ejs_netplay_join_button", "ejs_button_button");
- join.style["background-color"] = "rgba(var(--ejs-primary-color),1)";
+ join.classList.add(
+ "ejs_netplay_join_button",
+ "ejs_button_button"
+ );
+ join.style["background-color"] =
+ "rgba(var(--ejs-primary-color),1)";
join.innerText = this.localization("Join");
parent.appendChild(join);
this.addEventListener(join, "click", () => {
if (hasPassword) {
- let password = prompt("Please enter the room password:");
+ let password = prompt(
+ "Please enter the room password:"
+ );
if (password !== null) {
- password = password.trim();
- this.netplayJoinRoom(id, name, max, password);
+ this.netplayJoinRoom(
+ id,
+ name,
+ max,
+ password.trim()
+ );
}
} else {
this.netplayJoinRoom(id, name, max, null);
@@ -5536,7 +8411,13 @@ class EmulatorJS {
const open = await this.netplayGetOpenRooms();
this.netplay.table.innerHTML = "";
for (const k in open) {
- addToTable(k, open[k].room_name, open[k].current, open[k].max, open[k].hasPassword);
+ addToTable(
+ k,
+ open[k].room_name,
+ open[k].current,
+ open[k].max,
+ open[k].hasPassword
+ );
}
} catch (e) {
console.error("Could not update room list:", e);
@@ -5544,27 +8425,28 @@ class EmulatorJS {
};
this.netplayGetOpenRooms = async () => {
- if (!this.netplay.url) {
- console.error("netplay.url is undefined");
- return {};
- }
+ if (!this.netplay.url) return {};
try {
- const response = await fetch(this.netplay.url + "/list?domain=" + window.location.host + "&game_id=" + this.config.gameId);
+ const response = await fetch(
+ this.netplay.url +
+ "/list?domain=" +
+ window.location.host +
+ "&game_id=" +
+ this.config.gameId
+ );
const data = await response.text();
- console.log("Fetched open rooms:", data);
return JSON.parse(data);
} catch (error) {
- console.error("Error fetching open rooms:", error);
return {};
}
};
this.netplayUpdateListStart = () => {
- if (!this.netplayUpdateTableList) {
- console.error("netplayUpdateTableList is undefined");
- return;
- }
- this.netplay.updateListInterval = setInterval(this.netplayUpdateTableList.bind(this), 1000);
+ if (this.netplayUpdateTableList)
+ this.netplay.updateListInterval = setInterval(
+ this.netplayUpdateTableList.bind(this),
+ 1000
+ );
};
this.netplayUpdateListStop = () => {
@@ -5572,10 +8454,7 @@ class EmulatorJS {
};
this.netplayShowOpenRoomDialog = () => {
- if (!this.createSubPopup || !this.createElement || !this.localization || !this.addEventListener) {
- console.error("Required methods for netplayShowOpenRoomDialog are undefined");
- return;
- }
+ if (!this.createSubPopup) return;
this.originalControls = JSON.parse(JSON.stringify(this.controls));
const popups = this.createSubPopup();
this.netplayMenu.appendChild(popups[0]);
@@ -5600,8 +8479,7 @@ class EmulatorJS {
const maxhead = this.createElement("strong");
maxhead.innerText = this.localization("Max Players");
const maxinput = this.createElement("select");
- const playerCounts = ["2", "3", "4"];
- playerCounts.forEach(count => {
+ ["2", "3", "4"].forEach((count) => {
const option = this.createElement("option");
option.value = count;
option.innerText = count;
@@ -5629,25 +8507,18 @@ class EmulatorJS {
popup.appendChild(this.createElement("br"));
const submit = this.createElement("button");
submit.classList.add("ejs_button_button", "ejs_popup_submit");
- submit.style["background-color"] = "rgba(var(--ejs-primary-color),1)";
+ submit.style["background-color"] =
+ "rgba(var(--ejs-primary-color),1)";
submit.style.margin = "0 10px";
submit.innerText = this.localization("Submit");
popup.appendChild(submit);
this.addEventListener(submit, "click", () => {
- console.log("Submit button clicked");
- if (!rninput.value.trim()) {
- console.log("Room name is empty, aborting");
- return;
- }
- const roomName = rninput.value.trim();
- const maxPlayers = parseInt(maxinput.value);
- const password = pwinput.value.trim();
- console.log("Creating room with:", {
- roomName,
- maxPlayers,
- password
- });
- this.netplayOpenRoom(roomName, maxPlayers, password);
+ if (!rninput.value.trim()) return;
+ this.netplayOpenRoom(
+ rninput.value.trim(),
+ parseInt(maxinput.value),
+ pwinput.value.trim()
+ );
popups[0].remove();
});
const close = this.createElement("button");
@@ -5659,67 +8530,102 @@ class EmulatorJS {
};
this.netplayInitWebRTCStream = async () => {
- if (this.netplay.localStream)
- return;
- console.log("Initializing WebRTC stream for owner...");
- const { width: nativeWidth, height: nativeHeight } = this.getNativeResolution();
+ if (this.netplay.localStream) return;
+ const { width: nativeWidth, height: nativeHeight } =
+ this.getNativeResolution();
if (this.canvas) {
this.canvas.width = nativeWidth;
this.canvas.height = nativeHeight;
}
- if (this.netplay.owner && this.Module && this.Module.setCanvasSize) {
+ if (
+ this.netplay.owner &&
+ this.Module &&
+ this.Module.setCanvasSize
+ ) {
this.Module.setCanvasSize(nativeWidth, nativeHeight);
- console.log("Set emulator canvas size to native:", {
- width: nativeWidth,
- height: nativeHeight
- });
}
- const stream = this.collectScreenRecordingMediaTracks(this.canvas, 30);
+ const stream = this.collectScreenRecordingMediaTracks(
+ this.canvas,
+ 30
+ );
if (!stream || !stream.getTracks().length) {
- console.error("Failed to capture stream:", stream);
this.displayMessage("Failed to initialize video stream", 5000);
return;
}
+ if (
+ this.gameManager &&
+ this.gameManager.audioContext &&
+ this.gameManager.audioNode
+ ) {
+ try {
+ const ctx = this.gameManager.audioContext;
+ const audioDest = ctx.createMediaStreamDestination();
+ const streamGain = ctx.createGain();
+ this.gameManager.audioNode.connect(streamGain);
+ streamGain.connect(audioDest);
+ this.netplay.volumeInterval = setInterval(() => {
+ let vol =
+ typeof this.volume === "number" ? this.volume : 1;
+ const safeVol = Math.max(vol, 0.001);
+ const targetGain = 1.0 / safeVol;
+
+ try {
+ streamGain.gain.setTargetAtTime(
+ targetGain,
+ ctx.currentTime,
+ 0.1
+ );
+ } catch (e) {
+ streamGain.gain.value = targetGain;
+ }
+ }, 200);
+ audioDest.stream.getAudioTracks().forEach((track) => {
+ stream.addTrack(track);
+ if (this.netplay.peerConnections) {
+ Object.values(this.netplay.peerConnections).forEach(
+ (pcData) => {
+ if (
+ pcData.pc &&
+ pcData.pc.connectionState ===
+ "connected"
+ ) {
+ try {
+ pcData.pc.addTrack(track, stream);
+ } catch (e) {}
+ }
+ }
+ );
+ }
+ });
+ } catch (e) {
+ console.error("Error setting up Netplay audio:", e);
+ }
+ }
+
const videoTrack = stream.getVideoTracks()[0];
if (videoTrack) {
- videoTrack.applyConstraints({
- width: {
- ideal: nativeWidth
- },
- height: {
- ideal: nativeHeight
- },
- frameRate: {
- ideal: 30,
- max: 30
- }
- }).catch(err => console.error("Constraint error:", err));
- console.log("Track settings:", videoTrack.getSettings());
+ videoTrack
+ .applyConstraints({
+ width: { ideal: nativeWidth },
+ height: { ideal: nativeHeight },
+ frameRate: { ideal: 30, max: 30 },
+ })
+ .catch((err) => console.error("Constraint error:", err));
}
- stream.getTracks().forEach(track => {
- console.log("Track:", {
- kind: track.kind,
- enabled: track.enabled,
- muted: track.muted
- });
- track.onmute = () => console.warn("Track muted:", track.id);
- track.onended = () => console.warn("Track ended:", track.id);
- });
this.netplay.localStream = stream;
};
this.netplayCreatePeerConnection = (peerId) => {
const pc = new RTCPeerConnection({
iceServers: this.config.netplayICEServers,
- iceCandidatePoolSize: 10
+ iceCandidatePoolSize: 10,
});
let dataChannel;
if (this.netplay.owner) {
- dataChannel = pc.createDataChannel('inputs');
- dataChannel.onopen = () => console.log(`Data channel opened for peer ${peerId}`);
+ dataChannel = pc.createDataChannel("inputs");
dataChannel.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === "host-left") {
@@ -5729,71 +8635,86 @@ class EmulatorJS {
}
const playerIndex = data.player;
const frame = this.netplay.currentFrame || 0;
-
- if (!this.netplay.inputsData[frame]) {
+ if (!this.netplay.inputsData[frame])
this.netplay.inputsData[frame] = [];
- }
this.netplay.inputsData[frame].push({
frame: frame,
- connected_input: [playerIndex, data.index, data.value]
+ connected_input: [playerIndex, data.index, data.value],
});
- if (this.gameManager && this.gameManager.functions && this.gameManager.functions.simulateInput) {
- this.gameManager.functions.simulateInput(playerIndex, data.index, data.value);
- } else {
- console.error("Cannot process input: gameManager.functions.simulateInput is undefined");
+ if (
+ this.gameManager &&
+ this.gameManager.functions &&
+ this.gameManager.functions.simulateInput
+ ) {
+ this.gameManager.functions.simulateInput(
+ playerIndex,
+ data.index,
+ data.value
+ );
}
};
} else {
pc.ondatachannel = (event) => {
dataChannel = event.channel;
- dataChannel.onopen = () => console.log(`Data channel opened for peer ${peerId}`);
dataChannel.onmessage = (event) => {
const data = JSON.parse(event.data);
if (data.type === "host-left") {
- this.displayMessage("Host left. Restarting...", 3000);
+ this.displayMessage(
+ "Host left. Restarting...",
+ 3000
+ );
this.netplayLeaveRoom();
return;
}
- console.log(`Received input from host ${peerId}:`, data);
- if (this.gameManager && this.gameManager.functions && this.gameManager.functions.simulateInput) {
- this.gameManager.functions.simulateInput(data.player, data.index, data.value);
- } else {
- console.error("Cannot process input: gameManager.functions.simulateInput is undefined");
+ if (
+ this.gameManager &&
+ this.gameManager.functions &&
+ this.gameManager.functions.simulateInput
+ ) {
+ this.gameManager.functions.simulateInput(
+ data.player,
+ data.index,
+ data.value
+ );
}
};
};
}
if (this.netplay.owner && this.netplay.localStream) {
- this.netplay.localStream.getTracks().forEach(track => {
+ this.netplay.localStream.getTracks().forEach((track) => {
pc.addTrack(track, this.netplay.localStream);
});
-
- const codecs = RTCRtpSender.getCapabilities('video').codecs;
- const preferredCodecs = codecs.filter(codec => ['video/H264', 'video/VP8'].includes(codec.mimeType));
- const transceiver = pc.getTransceivers().find(t => t.sender && t.sender.track && t.sender.track.kind === 'video');
+ const codecs = RTCRtpSender.getCapabilities("video").codecs;
+ const preferredCodecs = codecs.filter((codec) =>
+ ["video/H264", "video/VP8"].includes(codec.mimeType)
+ );
+ const transceiver = pc
+ .getTransceivers()
+ .find(
+ (t) =>
+ t.sender &&
+ t.sender.track &&
+ t.sender.track.kind === "video"
+ );
if (transceiver && preferredCodecs.length) {
try {
transceiver.setCodecPreferences(preferredCodecs);
- } catch (error) {
- console.error("Failed to set codec preferences:", error);
- }
+ } catch (e) {}
}
} else {
- pc.addTransceiver('video', {
- direction: 'recvonly'
- });
+ pc.addTransceiver("video", { direction: "recvonly" });
}
- this.netplay.peerConnections[peerId] = {
- pc,
- dataChannel
- };
+ this.netplay.peerConnections[peerId] = { pc, dataChannel };
let streamReceived = false;
const streamTimeout = setTimeout(() => {
if (!streamReceived && !this.netplay.owner) {
- this.displayMessage("Failed to receive video stream. Check your network and try again.", 5000);
+ this.displayMessage(
+ "Failed to receive video stream. Check your network.",
+ 5000
+ );
this.netplayLeaveRoom();
}
}, 10000);
@@ -5802,42 +8723,81 @@ class EmulatorJS {
if (event.candidate) {
this.netplay.socket.emit("webrtc-signal", {
target: peerId,
- candidate: event.candidate
+ candidate: event.candidate,
});
}
};
- pc.onicecandidateerror = (event) => {
- console.error("ICE candidate error for peer", peerId, ":", event);
- };
-
pc.onconnectionstatechange = () => {
if (pc.connectionState === "connected") {
this.netplay.webRtcReady = true;
- } else if (pc.connectionState === "failed" || pc.connectionState === "disconnected") {
- this.displayMessage("Connection with player lost. Attempting to reconnect...", 3000);
+ } else if (
+ pc.connectionState === "failed" ||
+ pc.connectionState === "disconnected"
+ ) {
+ this.displayMessage(
+ "Connection lost. Reconnecting...",
+ 3000
+ );
clearTimeout(streamTimeout);
pc.close();
delete this.netplay.peerConnections[peerId];
- setTimeout(() => this.netplayCreatePeerConnection(peerId), 2000);
+ setTimeout(
+ () => this.netplayCreatePeerConnection(peerId),
+ 2000
+ );
}
};
pc.ontrack = (event) => {
if (!this.netplay.owner) {
+ if (event.track.kind === "audio") {
+ const audioStream = new MediaStream([event.track]);
+ const remoteAudio = document.createElement("audio");
+ remoteAudio.id = "ejs-remote-audio-" + peerId;
+ remoteAudio.style.display = "none";
+ remoteAudio.srcObject = audioStream;
+ document.body.appendChild(remoteAudio);
+ const attemptPlay = () => {
+ remoteAudio.play().catch(() => {
+ const listener = () => {
+ remoteAudio.play();
+ document.removeEventListener(
+ "click",
+ listener
+ );
+ document.removeEventListener(
+ "touchstart",
+ listener
+ );
+ document.removeEventListener(
+ "keydown",
+ listener
+ );
+ };
+ document.addEventListener("click", listener);
+ document.addEventListener(
+ "touchstart",
+ listener
+ );
+ document.addEventListener("keydown", listener);
+ });
+ };
+ attemptPlay();
+ return;
+ }
streamReceived = true;
clearTimeout(streamTimeout);
const stream = event.streams[0];
if (!this.netplay.video) {
- this.netplay.video = document.createElement('video');
+ this.netplay.video = document.createElement("video");
this.netplay.video.muted = true;
this.netplay.video.playsInline = true;
}
this.netplay.video.srcObject = stream;
this.netplay.video.play().catch(() => {
- if (this.isMobile) {
+ if (this.isMobile)
this.promptUserInteraction(this.netplay.video);
- }
});
this.drawVideoToCanvas();
}
@@ -5845,150 +8805,75 @@ class EmulatorJS {
if (this.netplay.owner && this.netplay.localStream) {
pc.createOffer()
- .then(offer => {
- offer.sdp = offer.sdp.replace(/profile-level-id=[0-9a-fA-F]+/, 'profile-level-id=42e01f');
- return pc.setLocalDescription(offer);
- })
- .then(() => {
- this.netplay.socket.emit("webrtc-signal", {
- target: peerId,
- offer: pc.localDescription
- });
- })
- .catch(error => console.error("Error creating offer:", error));
+ .then((offer) => {
+ offer.sdp = offer.sdp.replace(
+ /profile-level-id=[0-9a-fA-F]+/,
+ "profile-level-id=42e01f"
+ );
+ return pc.setLocalDescription(offer);
+ })
+ .then(() => {
+ this.netplay.socket.emit("webrtc-signal", {
+ target: peerId,
+ offer: pc.localDescription,
+ });
+ })
+ .catch((error) =>
+ console.error("Error creating offer:", error)
+ );
}
-
return pc;
};
this.showVideoOverlay = () => {
- const videoElement = this.netplay.video;
- if (!videoElement) {
- console.error("showVideoOverlay: videoElement is not initialized");
- return;
- }
- console.log("showVideoOverlay called, videoElement exists:", videoElement);
-
- if (videoElement.parentElement) {
- console.log("Removing video element from current parent:", videoElement.parentElement);
- videoElement.parentElement.removeChild(videoElement);
- }
-
- videoElement.style.position = "absolute";
- if (this.isMobile) {
- videoElement.style.top = "0";
- videoElement.style.left = "0";
- videoElement.style.width = "100vw";
- videoElement.style.height = "100vh";
- videoElement.style.maxHeight = "100vh";
- } else {
- videoElement.style.top = "0";
- videoElement.style.left = "0";
- videoElement.style.width = "100%";
- videoElement.style.height = "100%";
- }
- videoElement.style.border = "1px solid white";
- videoElement.style.zIndex = "1";
- videoElement.style.display = "";
- videoElement.style.objectFit = "contain";
- document.body.appendChild(videoElement);
- console.log("Video overlay added to DOM, styles:", videoElement.style.cssText);
-
- const playVideo = async() => {
- console.log("Attempting to play video, readyState:", videoElement.readyState, "Paused:", videoElement.paused, "Ended:", videoElement.ended, "Muted:", videoElement.muted);
- try {
- await videoElement.play();
- console.log("Video playback started successfully, currentTime:", videoElement.currentTime);
- } catch (error) {
- console.error("Video play error:", error);
- if (this.isMobile) {
- this.promptUserInteraction(videoElement);
- } else {
- console.log("Autoplay failed on desktop, but user interaction not required for muted video");
- }
- }
- if (videoElement.videoWidth === 0 || videoElement.videoHeight === 0) {
- console.warn("Video element has zero dimensions, likely no valid frame:", {
- videoWidth: videoElement.videoWidth,
- videoHeight: videoElement.videoHeight
- });
- } else {
- console.log("Video dimensions:", {
- videoWidth: videoElement.videoWidth,
- videoHeight: videoElement.videoHeight
- });
- }
- };
- playVideo();
+ /* Not used in this logic flow, kept empty/minimal if needed */
};
this.drawVideoToCanvas = () => {
const videoElement = this.netplay.video;
const canvas = this.netplayCanvas;
- if (!canvas) {
- console.error("drawVideoToCanvas: Missing canvas!");
- }
- const ctx = canvas.getContext('2d', {
- alpha: false,
- willReadFrequently: true
- });
+ const ctx = canvas
+ ? canvas.getContext("2d", {
+ alpha: false,
+ willReadFrequently: true,
+ })
+ : null;
- if (!videoElement || !ctx) {
- console.error("drawVideoToCanvas: Missing video, or context!");
- return;
- }
+ if (!videoElement || !ctx) return;
- const { width: nativeWidth, height: nativeHeight } = this.getNativeResolution() || {
- width: 720,
- height: 700
- };
+ const { width: nativeWidth, height: nativeHeight } =
+ this.getNativeResolution() || { width: 720, height: 700 };
canvas.width = nativeWidth;
canvas.height = nativeHeight;
- const ensureVideoPlaying = async() => {
- let retries = 0;
- const maxRetries = 5;
- while (retries < maxRetries) {
- if (videoElement.paused || videoElement.ended) {
- try {
- await videoElement.play();
- } catch (error) {
- if (this.isMobile)
- this.promptUserInteraction(videoElement);
- }
- }
- if (videoElement.videoWidth > 0 && videoElement.videoHeight > 0) {
- if (!this.netplay.lockedAspectRatio) {
- this.netplay.lockedAspectRatio = videoElement.videoWidth / videoElement.videoHeight;
- console.log("Locked aspect ratio:", this.netplay.lockedAspectRatio);
- }
- break;
- }
- retries++;
- await new Promise(resolve => setTimeout(resolve, 1000));
+ const ensureVideoPlaying = async () => {
+ if (videoElement.paused || videoElement.ended) {
+ try {
+ await videoElement.play();
+ } catch (e) {}
}
-
- if (retries >= maxRetries) {
- this.displayMessage("Failed to initialize video stream", 5000);
- this.netplayLeaveRoom();
+ if (
+ !this.netplay.lockedAspectRatio &&
+ videoElement.videoWidth
+ ) {
+ this.netplay.lockedAspectRatio =
+ videoElement.videoWidth / videoElement.videoHeight;
}
};
const drawFrame = () => {
- if (!this.isNetplay || this.netplay.owner)
- return;
-
- const aspect = this.netplay.lockedAspectRatio || (videoElement.videoWidth / videoElement.videoHeight) || (nativeWidth / nativeHeight);
-
- if (videoElement.readyState >= videoElement.HAVE_CURRENT_DATA && videoElement.videoWidth > 0) {
+ if (!this.isNetplay || this.netplay.owner) return;
+ const aspect =
+ this.netplay.lockedAspectRatio ||
+ videoElement.videoWidth / videoElement.videoHeight ||
+ nativeWidth / nativeHeight;
+ if (
+ videoElement.readyState >= videoElement.HAVE_CURRENT_DATA &&
+ videoElement.videoWidth > 0
+ ) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
-
const canvasAspect = nativeWidth / nativeHeight;
- let drawWidth,
- drawHeight,
- offsetX,
- offsetY;
-
+ let drawWidth, drawHeight, offsetX, offsetY;
if (aspect > canvasAspect) {
drawWidth = nativeWidth;
drawHeight = nativeWidth / aspect;
@@ -6000,225 +8885,199 @@ class EmulatorJS {
offsetX = (nativeWidth - drawWidth) / 2;
offsetY = 0;
}
-
- ctx.drawImage(videoElement, 0, 0, videoElement.videoWidth, videoElement.videoHeight, offsetX, offsetY, drawWidth, drawHeight);
+ ctx.drawImage(
+ videoElement,
+ 0,
+ 0,
+ videoElement.videoWidth,
+ videoElement.videoHeight,
+ offsetX,
+ offsetY,
+ drawWidth,
+ drawHeight
+ );
}
-
requestAnimationFrame(drawFrame);
};
- videoElement.addEventListener('loadeddata', () => {
- ensureVideoPlaying().then(drawFrame);
- }, {
- once: true
- });
-
+ videoElement.addEventListener(
+ "loadeddata",
+ () => {
+ ensureVideoPlaying().then(drawFrame);
+ },
+ { once: true }
+ );
ensureVideoPlaying();
};
this.netplayStartSocketIO = (callback) => {
- if (!this.netplay.previousPlayers) {
+ if (!this.netplay.previousPlayers)
this.netplay.previousPlayers = {};
- }
-
if (typeof io === "undefined") {
- console.error("Socket.IO client library not loaded. Please include ");
this.displayMessage("Socket.IO not available", 5000);
return;
}
if (this.netplay.socket && this.netplay.socket.connected) {
- console.log("Socket already connected, reusing:", this.netplay.socket.id);
callback();
return;
}
if (!this.netplay.url) {
- console.error("Cannot initialize Socket.IO: netplay.url is undefined");
this.displayMessage("Network configuration error", 5000);
return;
}
- console.log("Initializing new Socket.IO connection to:", this.netplay.url);
this.netplay.socket = io(this.netplay.url);
- this.netplay.socket.on("connect", () => {
- console.log("Socket.IO connected:", this.netplay.socket.id);
- callback();
- });
+ this.netplay.socket.on("connect", callback);
this.netplay.socket.on("connect_error", (error) => {
- console.error("Socket.IO connection error:", error.message);
- this.displayMessage("Failed to connect to server: " + error.message, 5000);
+ this.displayMessage(
+ "Failed to connect: " + error.message,
+ 5000
+ );
});
this.netplay.socket.on("users-updated", (users) => {
const currentPlayers = users || {};
- const previousPlayerIds = Object.keys(this.netplay.previousPlayers);
+ const previousPlayerIds = Object.keys(
+ this.netplay.previousPlayers
+ );
const currentPlayerIds = Object.keys(currentPlayers);
-
- // Find who joined
- currentPlayerIds.forEach(id => {
- if (!previousPlayerIds.includes(id) && id !== this.netplay.playerID) {
- const playerName = currentPlayers[id].player_name || 'A player';
- this.displayMessage(`${playerName} has joined the room.`);
+ currentPlayerIds.forEach((id) => {
+ if (
+ !previousPlayerIds.includes(id) &&
+ id !== this.netplay.playerID
+ ) {
+ this.displayMessage(
+ `${
+ currentPlayers[id].player_name || "A player"
+ } joined.`
+ );
}
});
-
- // Find who left
- previousPlayerIds.forEach(id => {
+ previousPlayerIds.forEach((id) => {
if (!currentPlayerIds.includes(id)) {
- const playerName = this.netplay.previousPlayers[id].player_name || 'A player';
- this.displayMessage(`${playerName} has left the room.`);
+ this.displayMessage(
+ `${
+ this.netplay.previousPlayers[id].player_name ||
+ "A player"
+ } left.`
+ );
}
});
-
this.netplay.previousPlayers = currentPlayers;
-
- console.log("Users updated:", users);
this.netplay.players = users;
this.netplayUpdatePlayersTable();
if (this.netplay.owner) {
- console.log("Owner setting up WebRTC for updated users...");
- this.netplayInitWebRTCStream().then(() => {
- Object.keys(users).forEach(playerId => {
- if (playerId !== this.netplay.playerID) {
- const socketId = this.netplay.players[playerId].socketId;
- if (!socketId) {
- console.error("No socketId for player", playerId, "- WebRTC may fail");
- return;
+ this.netplayInitWebRTCStream()
+ .then(() => {
+ Object.keys(users).forEach((playerId) => {
+ if (playerId !== this.netplay.playerID) {
+ const socketId =
+ this.netplay.players[playerId].socketId;
+ if (
+ socketId &&
+ !this.netplay.peerConnections[socketId]
+ ) {
+ this.netplayCreatePeerConnection(
+ socketId
+ );
+ }
}
- const peerId = socketId;
- if (!this.netplay.peerConnections[peerId]) {
- console.log("Creating peer connection for", peerId);
- this.netplayCreatePeerConnection(peerId);
- }
- }
- });
- }).catch(error => console.error("Failed to initialize WebRTC stream in users-updated:", error));
+ });
+ })
+ .catch((e) => console.error(e));
}
});
this.netplay.socket.on("disconnect", () => this.netplayLeaveRoom());
- this.netplay.socket.on("data-message", (data) => this.netplayDataMessage(data));
- this.netplay.socket.on("webrtc-signal", async(data) => {
- const { sender, offer, candidate, answer, requestRenegotiate } = data;
- console.log(`Received WebRTC signal from ${sender}:`, {
- offer: !!offer,
- answer: !!answer,
- candidate: !!candidate,
- requestRenegotiate
- });
- if (!sender && !requestRenegotiate) {
- console.warn("Ignoring signal with no sender and no renegotiation request", data);
- return;
- }
- if (requestRenegotiate && !sender) {
- console.warn("Ignoring renegotiation request with undefined sender", data);
- this.netplay.socket.emit("webrtc-signal-error", {
- error: "Renegotiation request missing sender",
- data
- });
- return;
- }
- let pcData = sender ? this.netplay.peerConnections[sender] : null;
-
- if (pcData && !pcData.iceCandidateQueue) {
+ this.netplay.socket.on("data-message", (data) =>
+ this.netplayDataMessage(data)
+ );
+ this.netplay.socket.on("webrtc-signal", async (data) => {
+ const { sender, offer, candidate, answer, requestRenegotiate } =
+ data;
+ if (!sender && !requestRenegotiate) return;
+ let pcData = sender
+ ? this.netplay.peerConnections[sender]
+ : null;
+ if (pcData && !pcData.iceCandidateQueue)
pcData.iceCandidateQueue = [];
- }
-
if (!pcData && sender) {
- console.log("No existing peer connection for", sender, "- creating new one");
pcData = {
pc: this.netplayCreatePeerConnection(sender),
dataChannel: null,
- iceCandidateQueue: []
- };
+ iceCandidateQueue: [],
+ };
this.netplay.peerConnections[sender] = pcData;
}
const pc = pcData.pc;
try {
if (offer) {
- console.log("Processing offer from", sender);
- await pc.setRemoteDescription(new RTCSessionDescription(offer));
-
+ await pc.setRemoteDescription(
+ new RTCSessionDescription(offer)
+ );
if (pcData.iceCandidateQueue.length > 0) {
- console.log(`Processing ${pcData.iceCandidateQueue.length} queued ICE candidates.`);
- for (const queuedCandidate of pcData.iceCandidateQueue) {
- await pc.addIceCandidate(new RTCIceCandidate(queuedCandidate));
- }
- pcData.iceCandidateQueue = [];
+ for (const c of pcData.iceCandidateQueue)
+ await pc.addIceCandidate(
+ new RTCIceCandidate(c)
+ );
+ pcData.iceCandidateQueue = [];
}
-
- const answer = await pc.createAnswer();
- await pc.setLocalDescription(answer);
- console.log("Sending answer to", sender);
+ const ans = await pc.createAnswer();
+ await pc.setLocalDescription(ans);
this.netplay.socket.emit("webrtc-signal", {
target: sender,
- answer: pc.localDescription
+ answer: pc.localDescription,
});
} else if (answer) {
- console.log("Processing answer from", sender);
- await pc.setRemoteDescription(new RTCSessionDescription(answer));
-
+ await pc.setRemoteDescription(
+ new RTCSessionDescription(answer)
+ );
if (pcData.iceCandidateQueue.length > 0) {
- console.log(`Processing ${pcData.iceCandidateQueue.length} queued ICE candidates.`);
- for (const queuedCandidate of pcData.iceCandidateQueue) {
- await pc.addIceCandidate(new RTCIceCandidate(queuedCandidate));
- }
- pcData.iceCandidateQueue = [];
+ for (const c of pcData.iceCandidateQueue)
+ await pc.addIceCandidate(
+ new RTCIceCandidate(c)
+ );
+ pcData.iceCandidateQueue = [];
}
-
} else if (candidate) {
- if (pc.remoteDescription) {
- console.log("Adding ICE candidate from", sender);
- await pc.addIceCandidate(new RTCIceCandidate(candidate));
- } else {
- console.log("Remote description not set. Queueing ICE candidate from", sender);
- pcData.iceCandidateQueue.push(candidate);
- }
+ if (pc.remoteDescription)
+ await pc.addIceCandidate(
+ new RTCIceCandidate(candidate)
+ );
+ else pcData.iceCandidateQueue.push(candidate);
} else if (requestRenegotiate && this.netplay.owner) {
- console.log("Owner handling renegotiation request...");
- Object.keys(this.netplay.peerConnections).forEach(peerId => {
- if (peerId && this.netplay.peerConnections[peerId]) {
- const peerConn = this.netplay.peerConnections[peerId].pc;
- console.log("Closing and recreating peer connection for", peerId);
- peerConn.close();
- delete this.netplay.peerConnections[peerId];
- this.netplayCreatePeerConnection(peerId);
+ Object.keys(this.netplay.peerConnections).forEach(
+ (pid) => {
+ if (this.netplay.peerConnections[pid]) {
+ this.netplay.peerConnections[
+ pid
+ ].pc.close();
+ delete this.netplay.peerConnections[pid];
+ this.netplayCreatePeerConnection(pid);
+ }
}
- });
+ );
}
- } catch (error) {
- console.error("WebRTC signaling error:", error);
+ } catch (e) {
+ console.error(e);
}
});
};
this.netplayUpdatePlayersTable = () => {
- if (!this.netplay.playerTable) {
- console.error("netplay.playerTable is undefined");
- return;
- }
- const table = this.netplay.playerTable;
- table.innerHTML = "";
-
+ if (!this.netplay.playerTable) return;
+ this.netplay.playerTable.innerHTML = "";
const playerCount = Object.keys(this.netplay.players).length;
const maxPlayers = this.netplay.maxPlayers || "?";
-
- const addToTable = (playerNumber, playerName, statusText) => {
- const row = this.createElement("tr");
- const addCell = (text) => {
- const item = this.createElement("td");
- item.innerText = text;
- row.appendChild(item);
- return item;
- };
- addCell(playerNumber).style.width = "80px";
- addCell(playerName);
- addCell(statusText).style.width = "80px";
- table.appendChild(row);
- };
-
let i = 0;
for (const k in this.netplay.players) {
- const playerNumber = i + 1;
- const playerName = this.netplay.players[k].player_name || "Unknown";
- const statusText = (i === 0) ? `${playerCount}/${maxPlayers}` : "";
- addToTable(playerNumber, playerName, statusText);
+ const row = this.createElement("tr");
+ const addCell = (text) => {
+ const td = this.createElement("td");
+ td.innerText = text;
+ row.appendChild(td);
+ };
+ addCell(i + 1);
+ addCell(this.netplay.players[k].player_name || "Unknown");
+ addCell(i === 0 ? `${playerCount}/${maxPlayers}` : "");
+ this.netplay.playerTable.appendChild(row);
i++;
}
};
@@ -6234,23 +9093,30 @@ class EmulatorJS {
room_name: roomName,
player_name: this.netplay.name,
userid: this.netplay.playerID,
- sessionid: sessionid
+ sessionid: sessionid,
};
this.netplay.players[this.netplay.playerID] = this.netplay.extra;
this.netplay.owner = true;
this.netplayStartSocketIO(() => {
- this.netplay.socket.emit("open-room", {
- extra: this.netplay.extra,
- maxPlayers: maxPlayers,
- password: password
- }, (error) => {
- if (error) {
- console.error("Error opening room:", error);
- this.displayMessage("Failed to create room: " + error, 5000);
- return;
+ this.netplay.socket.emit(
+ "open-room",
+ { extra: this.netplay.extra, maxPlayers, password },
+ (error) => {
+ if (error) {
+ this.displayMessage(
+ "Failed to create room: " + error,
+ 5000
+ );
+ return;
+ }
+ this.netplayRoomJoined(
+ true,
+ roomName,
+ password,
+ sessionid
+ );
}
- this.netplayRoomJoined(true, roomName, password, sessionid);
- });
+ );
});
};
@@ -6264,40 +9130,34 @@ class EmulatorJS {
room_name: roomName,
player_name: this.netplay.name,
userid: this.netplay.playerID,
- sessionid: sessionid
+ sessionid: sessionid,
};
this.netplay.players[this.netplay.playerID] = this.netplay.extra;
this.netplay.owner = false;
this.netplayStartSocketIO(() => {
- this.netplay.socket.emit("join-room", {
- extra: this.netplay.extra,
- password: password
- }, (error, users) => {
- if (error) {
- console.error("Error joining room:", error);
- alert("Error joining room: " + error);
- return;
+ this.netplay.socket.emit(
+ "join-room",
+ { extra: this.netplay.extra, password },
+ (error, users) => {
+ if (error) {
+ alert("Error joining room: " + error);
+ return;
+ }
+ this.netplay.players = users;
+ this.netplayRoomJoined(
+ false,
+ roomName,
+ password,
+ sessionid
+ );
}
- this.netplay.players = users;
- this.netplayRoomJoined(false, roomName, password, sessionid);
- });
+ );
});
};
this.netplayRoomJoined = (isOwner, roomName, password, roomId) => {
EJS_INSTANCE.updateNetplayUI(true);
- if (!this.netplay || !this.canvas || !this.elements || !this.elements.parent) {
- console.error("netplayRoomJoined: Required objects are undefined", {
- netplay: !!this.netplay,
- canvas: !!this.canvas,
- elements: !!this.elements,
- parent: !!(this.elements && this.elements.parent)
- });
- this.displayMessage("Failed to initialize netplay room", 5000);
- return;
- }
-
if (!this.netplayCanvas) {
this.netplayCanvas = this.createElement("canvas");
this.netplayCanvas.classList.add("ejs_canvas");
@@ -6309,178 +9169,212 @@ class EmulatorJS {
this.netplayCanvas.style.objectFit = "contain";
this.netplayCanvas.style.width = "100%";
this.netplayCanvas.style.height = "100%";
- this.netplayCanvas.style.objectPosition = "top";
}
this.isNetplay = true;
this.netplay.inputs = {};
this.netplay.owner = isOwner;
- console.log("Room joined with extra:", this.netplay.extra);
- if (this.netplay.roomNameElem) {
+ if (this.netplay.roomNameElem)
this.netplay.roomNameElem.innerText = roomName;
- }
- if (this.netplay.tabs && this.netplay.tabs[0] && this.netplay.tabs[1]) {
+ if (this.netplay.tabs && this.netplay.tabs[0]) {
this.netplay.tabs[0].style.display = "none";
this.netplay.tabs[1].style.display = "";
}
if (this.netplay.passwordElem) {
- if (password) {
- this.netplay.passwordElem.style.display = "";
- this.netplay.passwordElem.innerText = this.localization("Password") + ": " + password;
- } else {
- this.netplay.passwordElem.style.display = "none";
- }
- }
- if (this.netplay.createButton) {
- this.netplay.createButton.innerText = this.localization("Leave Room");
+ this.netplay.passwordElem.style.display = password
+ ? ""
+ : "none";
+ this.netplay.passwordElem.innerText = password
+ ? this.localization("Password") + ": " + password
+ : "";
}
+ if (this.netplay.createButton)
+ this.netplay.createButton.innerText =
+ this.localization("Leave Room");
this.netplayUpdatePlayersTable();
- this.elements.parent.style.width = "100vw";
- this.elements.parent.style.height = "100vh";
this.elements.parent.style.position = "relative";
-
- const { width: nativeWidth, height: nativeHeight } = this.getNativeResolution() || {
- width: 700,
- height: 720
- };
+ const { width: nativeWidth, height: nativeHeight } =
+ this.getNativeResolution() || { width: 700, height: 720 };
if (!this.netplay.owner) {
+ if (this.gameManager) {
+ this.gameManager.toggleMainLoop(0);
+ }
+ if (this.gameManager && this.gameManager.audioNode) {
+ try {
+ this.gameManager.audioNode.disconnect();
+ } catch (e) {}
+ }
+ if (this.volume === 0) {
+ this.setVolume(1);
+ }
+ this.netplay.guestVolInterval = setInterval(() => {
+ const currentVol =
+ typeof this.volume === "number" ? this.volume : 1.0;
+ document
+ .querySelectorAll('audio[id^="ejs-remote-audio-"]')
+ .forEach((el) => {
+ el.muted = false;
+ el.volume = currentVol;
+ });
+ }, 200);
+
this.canvas.style.display = "none";
if (!this.netplayCanvas.parentElement) {
this.elements.parent.appendChild(this.netplayCanvas);
- console.log("Appended netplayCanvas to this.elements.parent:", this.elements.parent);
}
this.netplayCanvas.width = nativeWidth;
this.netplayCanvas.height = nativeHeight;
Object.assign(this.netplayCanvas.style, {
- position: 'absolute',
- top: '0',
- left: '0',
- width: '100%',
- height: 'auto',
- maxHeight: '100%',
- zIndex: '5',
- display: 'block',
- pointerEvents: 'none'
+ position: "absolute",
+ top: "0",
+ left: "0",
+ width: "100%",
+ height: "100%",
+ zIndex: "5",
+ display: "block",
+ pointerEvents: "none",
});
- const parentStyles = window.getComputedStyle(this.elements.parent);
- console.log("Parent container styles:", {
- display: parentStyles.display,
- visibility: parentStyles.visibility,
- opacity: parentStyles.opacity,
- position: parentStyles.position,
- zIndex: parentStyles.zIndex
- });
-
- if (this.elements.bottomBar && this.elements.bottomBar.cheat && this.elements.bottomBar.cheat[0]) {
- this.netplay.oldStyles = [this.elements.bottomBar.cheat[0].style.display];
+ if (
+ this.elements.bottomBar &&
+ this.elements.bottomBar.cheat &&
+ this.elements.bottomBar.cheat[0]
+ ) {
+ this.netplay.oldStyles = [
+ this.elements.bottomBar.cheat[0].style.display,
+ ];
this.elements.bottomBar.cheat[0].style.display = "none";
}
- if (this.gameManager && this.gameManager.resetCheat) {
+ if (this.gameManager && this.gameManager.resetCheat)
this.gameManager.resetCheat();
- }
- console.log("Player 2 joined, awaiting WebRTC stream...");
+
this.elements.parent.focus();
- if (this.gameManager && this.gameManager.functions && this.gameManager.functions.simulateInput) {
- const originalSimulateInput = this.gameManager.functions.simulateInput;
- this.gameManager.functions.simulateInput = (player, index, value) => {
+ if (
+ this.gameManager &&
+ this.gameManager.functions &&
+ this.gameManager.functions.simulateInput
+ ) {
+ const originalSimulateInput =
+ this.gameManager.functions.simulateInput;
+ this.gameManager.functions.simulateInput = (
+ player,
+ index,
+ value
+ ) => {
const playerIndex = this.netplayGetUserIndex();
- console.log("Player 2 input:", {
- player,
- index,
- value,
- playerIndex
- });
- Object.values(this.netplay.peerConnections).forEach((pcData) => {
- if (
- pcData.pc &&
- pcData.pc.connectionState === "connected" &&
- pcData.dataChannel &&
- pcData.dataChannel.readyState === "open"
- ) {
- pcData.dataChannel.send(
- JSON.stringify({
- player: playerIndex,
- index,
- value,
- }));
+ Object.values(this.netplay.peerConnections).forEach(
+ (pcData) => {
+ if (
+ pcData.pc &&
+ pcData.pc.connectionState === "connected" &&
+ pcData.dataChannel &&
+ pcData.dataChannel.readyState === "open"
+ ) {
+ pcData.dataChannel.send(
+ JSON.stringify({
+ player: playerIndex,
+ index,
+ value,
+ })
+ );
+ }
}
- });
+ );
};
- this.netplayLeaveRoom = (originalLeaveRoom => {
+
+ this.netplayLeaveRoom = ((originalLeaveRoom) => {
return function () {
originalLeaveRoom.call(this);
- this.gameManager.functions.simulateInput = originalSimulateInput;
- if (this.netplay.video && this.netplay.video.parentElement) {
- this.netplay.video.parentElement.removeChild(this.netplay.video);
+ this.gameManager.functions.simulateInput =
+ originalSimulateInput;
+ if (
+ this.netplay.video &&
+ this.netplay.video.parentElement
+ ) {
+ this.netplay.video.parentElement.removeChild(
+ this.netplay.video
+ );
}
};
})(this.netplayLeaveRoom);
- } else {
- console.error("Cannot override simulateInput: gameManager.functions.simulateInput is undefined");
}
if (this.isMobile && this.gamepadElement) {
const newGamepad = this.gamepadElement.cloneNode(true);
- this.gamepadElement.parentNode.replaceChild(newGamepad, this.gamepadElement);
+ this.gamepadElement.parentNode.replaceChild(
+ newGamepad,
+ this.gamepadElement
+ );
this.gamepadElement = newGamepad;
Object.assign(this.gamepadElement.style, {
zIndex: "1000",
position: "absolute",
- pointerEvents: "auto"
+ pointerEvents: "auto",
});
-
- this.gamepadElement.addEventListener("touchstart", (e) => {
- e.preventDefault();
- const button = e.target.closest('[data-button]');
- if (button && this.gameManager && this.gameManager.functions && this.gameManager.functions.simulateInput) {
- this.gameManager.functions.simulateInput(0, button.dataset.button, 1);
- }
- }, {
- passive: false
- });
-
- this.gamepadElement.addEventListener("touchend", (e) => {
- e.preventDefault();
- const button = e.target.closest('[data-button]');
- if (button && this.gameManager && this.gameManager.functions && this.gameManager.functions.simulateInput) {
- this.gameManager.functions.simulateInput(0, button.dataset.button, 0);
- }
- }, {
- passive: false
- });
-
- this.gamepadElement.focus();
+ this.gamepadElement.addEventListener(
+ "touchstart",
+ (e) => {
+ e.preventDefault();
+ const button = e.target.closest("[data-button]");
+ if (
+ button &&
+ this.gameManager.functions.simulateInput
+ )
+ this.gameManager.functions.simulateInput(
+ 0,
+ button.dataset.button,
+ 1
+ );
+ },
+ { passive: false }
+ );
+ this.gamepadElement.addEventListener(
+ "touchend",
+ (e) => {
+ e.preventDefault();
+ const button = e.target.closest("[data-button]");
+ if (
+ button &&
+ this.gameManager.functions.simulateInput
+ )
+ this.gameManager.functions.simulateInput(
+ 0,
+ button.dataset.button,
+ 0
+ );
+ },
+ { passive: false }
+ );
}
+
const updateGamepadStyles = () => {
if (this.isMobile && this.gamepadElement) {
Object.assign(this.gamepadElement.style, {
zIndex: "1000",
position: "absolute",
- pointerEvents: "auto"
+ pointerEvents: "auto",
});
this.netplayCanvas.style.pointerEvents = "none";
- this.netplayCanvas.width = nativeWidth;
- this.netplayCanvas.height = nativeHeight;
- this.netplayCanvas.style.width = "100%";
- this.netplayCanvas.style.height = "100%";
}
};
- document.addEventListener("fullscreenchange", updateGamepadStyles);
- document.addEventListener("webkitfullscreenchange", updateGamepadStyles);
-
+ document.addEventListener(
+ "fullscreenchange",
+ updateGamepadStyles
+ );
+ document.addEventListener(
+ "webkitfullscreenchange",
+ updateGamepadStyles
+ );
setTimeout(() => {
if (!this.netplay.webRtcReady) {
- console.error("WebRTC connection not established after timeout");
- this.displayMessage("Failed to connect to Player 1. Please check your network and try again.", 5000);
- if (this.interactionOverlay) {
- this.interactionOverlay.remove();
- this.interactionOverlay = null;
- }
+ this.displayMessage(
+ "Failed to connect. Check network.",
+ 5000
+ );
this.netplayLeaveRoom();
}
}, 10000);
@@ -6491,28 +9385,23 @@ class EmulatorJS {
this.canvas.style.display = "block";
this.canvas.style.objectFit = "contain";
}
- if (this.netplayCanvas) {
+ if (this.netplayCanvas)
this.netplayCanvas.style.display = "none";
- }
- if (this.netplay.videoContainer) {
- this.netplay.videoContainer.style.display = "none";
- }
- if (this.elements.bottomBar && this.elements.bottomBar.cheat && this.elements.bottomBar.cheat[0]) {
- this.netplay.oldStyles = [this.elements.bottomBar.cheat[0].style.display];
- }
-
- if (this.netplay.owner && this.Module && this.Module.setCanvasSize) {
+ if (
+ this.netplay.owner &&
+ this.Module &&
+ this.Module.setCanvasSize
+ ) {
this.Module.setCanvasSize(nativeWidth, nativeHeight);
}
-
+ if (this.gameManager) this.gameManager.toggleMainLoop(1);
this.netplay.lockedAspectRatio = nativeWidth / nativeHeight;
const resizeCanvasWithAspect = () => {
const aspect = this.netplay.lockedAspectRatio;
- const vw = window.innerWidth;
- const vh = window.innerHeight;
- let newWidth,
- newHeight;
-
+ const parent = this.elements.parent;
+ const vw = parent.clientWidth || window.innerWidth;
+ const vh = parent.clientHeight || window.innerHeight;
+ let newWidth, newHeight;
if (vw / vh > aspect) {
newHeight = vh;
newWidth = vh * aspect;
@@ -6526,81 +9415,95 @@ class EmulatorJS {
width: `${newWidth}px`,
height: `${newHeight}px`,
display: "block",
- objectFit: "contain"
+ objectFit: "contain",
});
-
- const isFullscreen = document.fullscreenElement || document.webkitFullscreenElement;
-
+ const isFullscreen =
+ document.fullscreenElement ||
+ document.webkitFullscreenElement;
if (isFullscreen) {
Object.assign(this.canvas.style, {
position: "absolute",
top: "0",
left: "50%",
- transform: "translateX(-50%)"
+ transform: "translateX(-50%)",
});
} else {
Object.assign(this.canvas.style, {
position: "",
left: "",
top: "",
- transform: ""
+ transform: "",
});
}
}
};
this._netplayResizeCanvas = resizeCanvasWithAspect;
window.addEventListener("resize", resizeCanvasWithAspect);
- document.addEventListener("fullscreenchange", resizeCanvasWithAspect);
- document.addEventListener("webkitfullscreenchange", resizeCanvasWithAspect);
+ document.addEventListener(
+ "fullscreenchange",
+ resizeCanvasWithAspect
+ );
+ document.addEventListener(
+ "webkitfullscreenchange",
+ resizeCanvasWithAspect
+ );
resizeCanvasWithAspect();
- window.dispatchEvent(new Event('resize'));
+ window.dispatchEvent(new Event("resize"));
}
};
this.netplayLeaveRoom = () => {
EJS_INSTANCE.updateNetplayUI(false);
-
- console.log("Leaving netplay room...");
-
- if (this.netplay.owner && this.netplaySendMessage) {
- this.netplaySendMessage({
- type: "host-left"
- });
- }
-
- if (this.netplay.socket && this.netplay.socket.connected) {
- this.netplay.socket.emit('leave-room');
- }
-
+ if (this.netplay.owner && this.netplaySendMessage)
+ this.netplaySendMessage({ type: "host-left" });
if (this.netplay.socket) {
+ if (this.netplay.socket.connected)
+ this.netplay.socket.emit("leave-room");
this.netplay.socket.disconnect();
this.netplay.socket = null;
}
-
if (this.netplay.localStream) {
- this.netplay.localStream.getTracks().forEach(track => track.stop());
+ this.netplay.localStream
+ .getTracks()
+ .forEach((track) => track.stop());
this.netplay.localStream = null;
}
-
if (this.netplay.peerConnections) {
- Object.values(this.netplay.peerConnections).forEach(pcData => {
- if (pcData.pc)
- pcData.pc.close();
- });
+ Object.values(this.netplay.peerConnections).forEach(
+ (pcData) => {
+ if (pcData.pc) pcData.pc.close();
+ }
+ );
this.netplay.peerConnections = {};
}
-
if (this.netplayCanvas && this.netplayCanvas.parentElement) {
- this.netplayCanvas.parentElement.removeChild(this.netplayCanvas);
+ this.netplayCanvas.parentElement.removeChild(
+ this.netplayCanvas
+ );
this.netplayCanvas.style.display = "none";
}
if (this.netplay.video && this.netplay.video.parentElement) {
- this.netplay.video.parentElement.removeChild(this.netplay.video);
- this.netplay.video.srcObject = null;
+ this.netplay.video.parentElement.removeChild(
+ this.netplay.video
+ );
this.netplay.video = null;
}
- if (this.netplay.videoContainer) {
- this.netplay.videoContainer.style.display = "none";
+ document
+ .querySelectorAll('[id^="ejs-remote-audio-"]')
+ .forEach((el) => el.remove());
+ clearInterval(this.netplay.volumeInterval);
+ clearInterval(this.netplay.guestVolInterval);
+
+ if (
+ this.gameManager &&
+ this.gameManager.audioNode &&
+ this.gameManager.audioContext
+ ) {
+ try {
+ this.gameManager.audioNode.connect(
+ this.gameManager.audioContext.destination
+ );
+ } catch (e) {}
}
if (this.canvas) {
@@ -6612,45 +9515,56 @@ class EmulatorJS {
position: "absolute",
top: "0",
left: "0",
- transform: "none"
+ transform: "none",
});
}
- if (this.netplay.createButton) {
- this.netplay.createButton.innerText = this.localization("Create Room");
- }
+ if (this.netplay.createButton)
+ this.netplay.createButton.innerText =
+ this.localization("Create Room");
if (this.netplay.tabs) {
this.netplay.tabs[0].style.display = "";
this.netplay.tabs[1].style.display = "none";
}
- if (this.netplay.roomNameElem) {
+ if (this.netplay.roomNameElem)
this.netplay.roomNameElem.innerText = "";
- }
if (this.netplay.passwordElem) {
this.netplay.passwordElem.style.display = "none";
this.netplay.passwordElem.innerText = "";
}
- if (this.netplay.playerTable) {
+ if (this.netplay.playerTable)
this.netplay.playerTable.innerHTML = "";
- }
-
- if (this.netplay.oldStyles && this.elements.bottomBar && this.elements.bottomBar.cheat && this.elements.bottomBar.cheat[0]) {
- this.elements.bottomBar.cheat[0].style.display = this.netplay.oldStyles[0] || "";
+ if (
+ this.netplay.oldStyles &&
+ this.elements.bottomBar &&
+ this.elements.bottomBar.cheat &&
+ this.elements.bottomBar.cheat[0]
+ ) {
+ this.elements.bottomBar.cheat[0].style.display =
+ this.netplay.oldStyles[0] || "";
}
if (this._netplayResizeCanvas) {
window.removeEventListener("resize", this._netplayResizeCanvas);
- document.removeEventListener("fullscreenchange", this._netplayResizeCanvas);
- document.removeEventListener("webkitfullscreenchange", this._netplayResizeCanvas);
+ document.removeEventListener(
+ "fullscreenchange",
+ this._netplayResizeCanvas
+ );
+ document.removeEventListener(
+ "webkitfullscreenchange",
+ this._netplayResizeCanvas
+ );
this._netplayResizeCanvas = null;
}
-
- // Restore the original input function when leaving the room
- if (this.netplay.originalSimulateInput && this.gameManager && this.gameManager.functions) {
- this.gameManager.functions.simulateInput = this.netplay.originalSimulateInput;
+ if (
+ this.netplay.originalSimulateInput &&
+ this.gameManager &&
+ this.gameManager.functions
+ ) {
+ this.gameManager.functions.simulateInput =
+ this.netplay.originalSimulateInput;
this.netplay.originalSimulateInput = null;
}
-
this.isNetplay = false;
this.netplay.owner = false;
this.netplay.players = {};
@@ -6660,26 +9574,24 @@ class EmulatorJS {
this.netplay.webRtcReady = false;
this.netplay.lockedAspectRatio = null;
this.player = 1;
-
if (this.originalControls) {
- this.controls = JSON.parse(JSON.stringify(this.originalControls));
+ this.controls = JSON.parse(
+ JSON.stringify(this.originalControls)
+ );
this.originalControls = null;
}
-
if (this.isMobile && this.gamepadElement) {
Object.assign(this.gamepadElement.style, {
zIndex: "1000",
position: "absolute",
- pointerEvents: "auto"
+ pointerEvents: "auto",
});
}
-
if (this.gameManager && this.gameManager.restart) {
this.gameManager.restart();
} else if (this.startGame) {
this.startGame();
}
-
this.displayMessage("Left the room", 3000);
};
@@ -6689,90 +9601,68 @@ class EmulatorJS {
let inFrame = parseInt(value.frame);
if (!value.connected_input || value.connected_input[0] < 0)
return;
- this.netplay.inputsData[inFrame] = this.netplay.inputsData[inFrame] || [];
+ this.netplay.inputsData[inFrame] =
+ this.netplay.inputsData[inFrame] || [];
this.netplay.inputsData[inFrame].push(value);
- this.netplaySendMessage({
- frameAck: inFrame
- });
- if (this.netplay.owner) {
- console.log("Owner processing input:", value.connected_input);
- if (this.gameManager && this.gameManager.functions && this.gameManager.functions.simulateInput) {
- this.gameManager.functions.simulateInput(
- value.connected_input[0],
- value.connected_input[1],
- value.connected_input[2]);
- } else {
- console.error("Cannot process input: gameManager.functions.simulateInput is undefined");
- }
+ this.netplaySendMessage({ frameAck: inFrame });
+ if (
+ this.netplay.owner &&
+ this.gameManager &&
+ this.gameManager.functions &&
+ this.gameManager.functions.simulateInput
+ ) {
+ this.gameManager.functions.simulateInput(
+ value.connected_input[0],
+ value.connected_input[1],
+ value.connected_input[2]
+ );
}
});
}
- if (data.frameData) {
- console.log("Received frame data on Player 2:", data.frameData);
- if (!this.canvas) {
- console.error("Canvas unavailable for frame data processing");
- return;
- }
- const ctx = this.canvas.getContext('2d');
- if (!ctx) {
- console.error("Canvas context unavailable for frame data processing");
- return;
- }
- if (data.frameData.pixelSample.every(v => v === 0)) {
- console.warn("Frame data indicates black screen, attempting reconstruction");
- if (this.reconstructFrame) {
- this.reconstructFrame(data.frameData.inputs);
- } else {
- console.error("reconstructFrame is undefined");
- }
- } else {
- console.log("Frame data indicates content, relying on WebRTC stream");
- }
- }
};
this.netplaySendMessage = (data) => {
if (this.netplay.socket && this.netplay.socket.connected) {
this.netplay.socket.emit("data-message", data);
- console.log("Sent data message:", data);
- } else {
- console.error("Cannot send message: Socket is not connected");
}
};
this.netplayReset = () => {
- this.netplay.init_frame = this.gameManager ? this.gameManager.getFrameNum() : 0;
+ this.netplay.init_frame = this.gameManager
+ ? this.gameManager.getFrameNum()
+ : 0;
this.netplay.currentFrame = 0;
this.netplay.inputsData = {};
this.netplay.syncing = false;
};
this.netplayInitModulePostMainLoop = () => {
- if (this.isNetplay && !this.netplay.owner) {
- return;
- }
-
- this.netplay.currentFrame = parseInt(this.gameManager ? this.gameManager.getFrameNum() : 0) - (this.netplay.init_frame || 0);
- if (!this.isNetplay)
- return;
-
+ if (this.isNetplay && !this.netplay.owner) return;
+ this.netplay.currentFrame =
+ parseInt(
+ this.gameManager ? this.gameManager.getFrameNum() : 0
+ ) - (this.netplay.init_frame || 0);
+ if (!this.isNetplay) return;
if (this.netplay.owner) {
let to_send = [];
let i = this.netplay.currentFrame;
if (this.netplay.inputsData[i]) {
this.netplay.inputsData[i].forEach((value) => {
- if (this.gameManager && this.gameManager.functions && this.gameManager.functions.simulateInput) {
+ if (
+ this.gameManager &&
+ this.gameManager.functions &&
+ this.gameManager.functions.simulateInput
+ ) {
this.gameManager.functions.simulateInput(
value.connected_input[0],
value.connected_input[1],
- value.connected_input[2]);
+ value.connected_input[2]
+ );
}
value.frame = this.netplay.currentFrame + 20;
to_send.push(value);
});
- this.netplaySendMessage({
- "sync-control": to_send
- });
+ this.netplaySendMessage({ "sync-control": to_send });
delete this.netplay.inputsData[i];
}
}
@@ -6780,7 +9670,7 @@ class EmulatorJS {
this.netplay.updateList = {
start: this.netplayUpdateListStart,
- stop: this.netplayUpdateListStop
+ stop: this.netplayUpdateListStop,
};
this.netplay.showOpenRoomDialog = this.netplayShowOpenRoomDialog;
this.netplay.openRoom = this.netplayOpenRoom;
@@ -6800,115 +9690,362 @@ class EmulatorJS {
this.netplay.ready = 0;
this.netplay.webRtcReady = false;
this.netplay.peerConnections = this.netplay.peerConnections || {};
-
this.netplay.url = this.config.netplayUrl || window.EJS_netplayUrl;
if (!this.netplay.url) {
- if (this.debug) console.error("netplayUrl is not defined. Please set it in EJS_config or as a global EJS_netplayUrl variable.");
- this.displayMessage("Network configuration error: netplay URL is not set.", 5000);
- return;
+ if (this.debug) console.error("netplayUrl is not defined.");
+ this.displayMessage("Network configuration error.", 5000);
+ return;
}
while (this.netplay.url.endsWith("/")) {
- this.netplay.url = this.netplay.url.substring(0, this.netplay.url.length - 1);
+ this.netplay.url = this.netplay.url.substring(
+ 0,
+ this.netplay.url.length - 1
+ );
}
this.netplay.current_frame = 0;
if (this.gameManager && this.gameManager.Module) {
- this.gameManager.Module.postMainLoop = this.netplayInitModulePostMainLoop.bind(this);
+ this.gameManager.Module.postMainLoop =
+ this.netplayInitModulePostMainLoop.bind(this);
} else if (this.Module) {
- this.Module.postMainLoop = this.netplayInitModulePostMainLoop.bind(this);
- } else if (this.debug) {
- console.warn("Module is undefined. postMainLoop will not be set.");
+ this.Module.postMainLoop =
+ this.netplayInitModulePostMainLoop.bind(this);
}
}
createCheatsMenu() {
- const body = this.createPopup("Cheats", {
- "Add Cheat": () => {
- const popups = this.createSubPopup();
- this.cheatMenu.appendChild(popups[0]);
- popups[1].classList.add("ejs_cheat_parent");
- popups[1].style.width = "100%";
- const popup = popups[1];
- const header = this.createElement("div");
- header.classList.add("ejs_cheat_header");
- const title = this.createElement("h2");
- title.innerText = this.localization("Add Cheat Code");
- title.classList.add("ejs_cheat_heading");
- const close = this.createElement("button");
- close.classList.add("ejs_cheat_close");
- header.appendChild(title);
- header.appendChild(close);
- popup.appendChild(header);
- this.addEventListener(close, "click", (e) => {
- popups[0].remove();
- })
-
- const main = this.createElement("div");
- main.classList.add("ejs_cheat_main");
- const header3 = this.createElement("strong");
- header3.innerText = this.localization("Code");
- main.appendChild(header3);
- main.appendChild(this.createElement("br"));
- const mainText = this.createElement("textarea");
- mainText.classList.add("ejs_cheat_code");
- mainText.style.width = "100%";
- mainText.style.height = "80px";
- main.appendChild(mainText);
- main.appendChild(this.createElement("br"));
- const header2 = this.createElement("strong");
- header2.innerText = this.localization("Description");
- main.appendChild(header2);
- main.appendChild(this.createElement("br"));
- const mainText2 = this.createElement("input");
- mainText2.type = "text";
- mainText2.classList.add("ejs_cheat_code");
- main.appendChild(mainText2);
- main.appendChild(this.createElement("br"));
- popup.appendChild(main);
-
- const footer = this.createElement("footer");
- const submit = this.createElement("button");
- const closeButton = this.createElement("button");
- submit.innerText = this.localization("Submit");
- closeButton.innerText = this.localization("Close");
- submit.classList.add("ejs_button_button");
- closeButton.classList.add("ejs_button_button");
- submit.classList.add("ejs_popup_submit");
- closeButton.classList.add("ejs_popup_submit");
- submit.style["background-color"] = "rgba(var(--ejs-primary-color),1)";
- footer.appendChild(submit);
- const span = this.createElement("span");
- span.innerText = " ";
- footer.appendChild(span);
- footer.appendChild(closeButton);
- popup.appendChild(footer);
-
- this.addEventListener(submit, "click", (e) => {
- if (!mainText.value.trim() || !mainText2.value.trim()) return;
- popups[0].remove();
- this.cheats.push({
- code: mainText.value,
- desc: mainText2.value,
- checked: false
+ const body = this.createPopup(
+ "Cheats",
+ {
+ "Add Cheat": () => {
+ const popups = this.createSubPopup();
+ this.cheatMenu.appendChild(popups[0]);
+ popups[1].classList.add("ejs_cheat_parent");
+ popups[1].style.width = "100%";
+ const popup = popups[1];
+ const header = this.createElement("div");
+ header.classList.add("ejs_cheat_header");
+ const title = this.createElement("h2");
+ title.innerText = this.localization("Add Cheat Code");
+ title.classList.add("ejs_cheat_heading");
+ const close = this.createElement("button");
+ close.classList.add("ejs_cheat_close");
+ header.appendChild(title);
+ header.appendChild(close);
+ popup.appendChild(header);
+ this.addEventListener(close, "click", (e) => {
+ popups[0].remove();
});
- this.updateCheatUI();
- this.saveSettings();
- })
- this.addEventListener(closeButton, "click", (e) => {
- popups[0].remove();
- })
+
+ let cheatDB = {};
+ const systemKey = this.getCore(true);
+ const cleanRomTags = (name) => {
+ return name
+ .replace(/\([^)]+\)/g, "")
+ .replace(/\[[^\]]+\]/g, "")
+ .trim();
+ };
+
+ const normalizeAndConvertNumerals = (name) => {
+ let normalized = name.toLowerCase();
+ normalized = normalized.replace(/ iv/g, " 4");
+ normalized = normalized.replace(/ iii/g, " 3");
+ normalized = normalized.replace(/ ii/g, " 2");
+ normalized = normalized.replace(/ v/g, " 5");
+ normalized = normalized.replace(/ i/g, " 1");
+
+ return normalized.replace(/[^a-z0-9]/g, "");
+ };
+
+ const createSelect = (labelText) => {
+ const div = this.createElement("div");
+ const label = this.createElement("strong");
+ label.innerText = this.localization(labelText);
+ div.appendChild(label);
+ div.appendChild(this.createElement("br"));
+ const select = this.createElement("select");
+ select.style.width = "100%";
+ select.classList.add("ejs_cheat_code");
+ div.appendChild(select);
+ return { container: div, select: select };
+ };
+
+ const importDiv = this.createElement("div");
+ importDiv.classList.add("ejs_cheat_main");
+ importDiv.style.borderBottom = "1px solid #555";
+ importDiv.style.paddingBottom = "10px";
+ importDiv.style.display = "none";
+
+ const importTitle = this.createElement("h3");
+ importTitle.innerText =
+ this.localization("Import from Database") +
+ (systemKey ? ` (${systemKey.toUpperCase()})` : "");
+ importTitle.style.marginTop = "0px";
+ importDiv.appendChild(importTitle);
+
+ const gameSelectUI = createSelect("Game");
+ const cheatSelectUI = createSelect("Cheat");
+
+ importDiv.appendChild(gameSelectUI.container);
+ importDiv.appendChild(cheatSelectUI.container);
+
+ popup.appendChild(importDiv);
+
+ const main = this.createElement("div");
+ main.classList.add("ejs_cheat_main");
+ const header3 = this.createElement("strong");
+ header3.innerText = this.localization(
+ "Manual Entry - Code"
+ );
+ main.appendChild(header3);
+ main.appendChild(this.createElement("br"));
+
+ const manualCodeTextarea = this.createElement("textarea");
+ manualCodeTextarea.classList.add("ejs_cheat_code");
+ manualCodeTextarea.style.width = "100%";
+ manualCodeTextarea.style.height = "80px";
+ main.appendChild(manualCodeTextarea);
+ main.appendChild(this.createElement("br"));
+
+ const header2 = this.createElement("strong");
+ header2.innerText = this.localization(
+ "Manual Entry - Description"
+ );
+ main.appendChild(header2);
+ main.appendChild(this.createElement("br"));
+
+ const manualDescriptionInput = this.createElement("input");
+ manualDescriptionInput.type = "text";
+ manualDescriptionInput.classList.add("ejs_cheat_code");
+ manualDescriptionInput.style.width = "100%";
+ main.appendChild(manualDescriptionInput);
+ main.appendChild(this.createElement("br"));
+ popup.appendChild(main);
+
+ const loadCheatList = (gameName) => {
+ cheatSelectUI.select.innerHTML = "";
+
+ const defaultOpt = this.createElement("option");
+ defaultOpt.value = "";
+ defaultOpt.innerText =
+ "--- " +
+ this.localization("Select a Cheat") +
+ " ---";
+ cheatSelectUI.select.appendChild(defaultOpt);
+
+ manualCodeTextarea.value = "";
+ manualDescriptionInput.value = "";
+
+ if (!gameName || !cheatDB[gameName]) return;
+
+ const cheats = cheatDB[gameName];
+ cheats.forEach((cheat) => {
+ const opt = this.createElement("option");
+ opt.value = cheat.desc;
+ opt.innerText = cheat.desc;
+ cheatSelectUI.select.appendChild(opt);
+ });
+
+ if (cheats.length > 0) {
+ cheatSelectUI.select.value = cheats[0].desc;
+ manualCodeTextarea.value = cheats[0].code;
+ manualDescriptionInput.value = cheats[0].desc;
+ }
+ };
+
+ const loadCheatDatabase = async (system) => {
+ gameSelectUI.select.innerHTML = "";
+ cheatSelectUI.select.innerHTML = "";
+
+ const defaultGameOpt = this.createElement("option");
+ defaultGameOpt.value = "";
+ defaultGameOpt.innerText =
+ "--- " +
+ this.localization("Select a Game") +
+ " ---";
+ gameSelectUI.select.appendChild(defaultGameOpt);
+
+ if (!this.config.cheatPath) {
+ if (this.debug)
+ console.error(
+ "Cheat file load error: EJS_cheatPath is not configured."
+ );
+ importDiv.style.display = "none";
+ return;
+ }
+
+ const url = this.config.cheatPath + system + ".json";
+
+ try {
+ const res = await this.downloadFile(
+ url,
+ null,
+ true,
+ { responseType: "text", method: "GET" }
+ );
+
+ let data;
+ if (res === -1) {
+ throw new Error(
+ "Cheat JSON not found. Create a file at: " +
+ url
+ );
+ } else if (typeof res.data === "string") {
+ try {
+ data = JSON.parse(res.data);
+ } catch (e) {
+ throw new Error(
+ "Failed to parse cheat JSON: " +
+ e.message
+ );
+ }
+ } else {
+ data = res.data;
+ }
+
+ cheatDB = data;
+ importDiv.style.display = "";
+
+ const gameNames = Object.keys(cheatDB).sort();
+ gameNames.forEach((name) => {
+ const opt = this.createElement("option");
+ opt.value = name;
+ opt.innerText = name;
+ gameSelectUI.select.appendChild(opt);
+ });
+
+ let currentFileBaseName =
+ this.getBaseFileName(true);
+ currentFileBaseName = currentFileBaseName.replace(
+ /\.[^/.]+$/,
+ ""
+ );
+ const cleanedFileName =
+ cleanRomTags(currentFileBaseName);
+ const normalizedFile =
+ normalizeAndConvertNumerals(cleanedFileName);
+ let matchedGameName = null;
+ if (
+ this.config.gameName &&
+ gameNames.includes(this.config.gameName)
+ ) {
+ matchedGameName = this.config.gameName;
+ }
+
+ if (!matchedGameName) {
+ for (const name of gameNames) {
+ if (
+ normalizeAndConvertNumerals(name) ===
+ normalizedFile
+ ) {
+ matchedGameName = name;
+ break;
+ }
+ }
+ }
+
+ if (matchedGameName) {
+ gameSelectUI.select.value = matchedGameName;
+ }
+
+ loadCheatList(gameSelectUI.select.value);
+ } catch (e) {
+ if (this.debug)
+ console.error(
+ "Cheat file load error:",
+ e.message
+ );
+ importDiv.style.display = "none";
+ cheatDB = {};
+ loadCheatList(null);
+ }
+ };
+
+ gameSelectUI.select.addEventListener("change", () => {
+ loadCheatList(gameSelectUI.select.value);
+ });
+
+ cheatSelectUI.select.addEventListener("change", () => {
+ const game = gameSelectUI.select.value;
+ const cheatDesc = cheatSelectUI.select.value;
+
+ if (!game || !cheatDesc) {
+ manualCodeTextarea.value = "";
+ manualDescriptionInput.value = "";
+ return;
+ }
+
+ const cheat = cheatDB[game].find(
+ (c) => c.desc === cheatDesc
+ );
+ if (cheat) {
+ manualCodeTextarea.value = cheat.code;
+ manualDescriptionInput.value = cheat.desc;
+ }
+ });
+
+ if (systemKey) {
+ loadCheatDatabase(systemKey).catch((e) => {
+ if (this.debug)
+ console.error("Initial cheat load failed:", e);
+ });
+ } else {
+ importDiv.style.display = "none";
+ }
+
+ const footer = this.createElement("footer");
+ const submit = this.createElement("button");
+ const closeButton = this.createElement("button");
+ submit.innerText = this.localization("Submit");
+ closeButton.innerText = this.localization("Close");
+ submit.classList.add("ejs_button_button");
+ closeButton.classList.add("ejs_button_button");
+ submit.classList.add("ejs_popup_submit");
+ closeButton.classList.add("ejs_popup_submit");
+ submit.style["background-color"] =
+ "rgba(var(--ejs-primary-color),1)";
+ footer.appendChild(submit);
+ const span = this.createElement("span");
+ span.innerText = " ";
+ footer.appendChild(span);
+ footer.appendChild(closeButton);
+ popup.appendChild(footer);
+
+ this.addEventListener(submit, "click", (e) => {
+ if (
+ !manualCodeTextarea.value.trim() ||
+ !manualDescriptionInput.value.trim()
+ )
+ return;
+ popups[0].remove();
+ this.cheats.push({
+ code: manualCodeTextarea.value,
+ desc: manualDescriptionInput.value,
+ checked: false,
+ });
+ this.updateCheatUI();
+ this.saveSettings();
+ });
+ this.addEventListener(closeButton, "click", (e) => {
+ popups[0].remove();
+ });
+ },
+ Close: () => {
+ this.cheatMenu.style.display = "none";
+ },
},
- "Close": () => {
- this.cheatMenu.style.display = "none";
- }
- }, true);
+ true
+ );
this.cheatMenu = body.parentElement;
- this.cheatMenu.getElementsByTagName("h4")[0].style["padding-bottom"] = "0px";
+ this.cheatMenu.getElementsByTagName("h4")[0].style["padding-bottom"] =
+ "0px";
const msg = this.createElement("div");
msg.style["padding-top"] = "0px";
msg.style["padding-bottom"] = "15px";
- msg.innerText = this.localization("Note that some cheats require a restart to disable");
+ msg.innerText = this.localization(
+ "Note that some cheats require a restart to disable"
+ );
body.appendChild(msg);
const rows = this.createElement("div");
body.appendChild(rows);
@@ -6937,7 +10074,7 @@ class EmulatorJS {
this.cheats[i].checked = input.checked;
this.cheatChanged(input.checked, code, i);
this.saveSettings();
- })
+ });
if (!is_permanent) {
const close = this.createElement("a");
close.classList.add("ejs_cheat_row_button");
@@ -6948,14 +10085,20 @@ class EmulatorJS {
this.cheats.splice(i, 1);
this.updateCheatUI();
this.saveSettings();
- })
+ });
}
this.elements.cheatRows.appendChild(row);
this.cheatChanged(checked, code, i);
- }
+ };
this.gameManager.resetCheat();
for (let i = 0; i < this.cheats.length; i++) {
- addToMenu(this.cheats[i].desc, this.cheats[i].checked, this.cheats[i].code, this.cheats[i].is_permanent, i);
+ addToMenu(
+ this.cheats[i].desc,
+ this.cheats[i].checked,
+ this.cheats[i].code,
+ this.cheats[i].is_permanent,
+ i
+ );
}
}
cheatChanged(checked, code, index) {
@@ -6967,7 +10110,7 @@ class EmulatorJS {
if (!this.gameManager) return;
try {
this.Module.FS.unlink("/shader/shader.glslp");
- } catch(e) {}
+ } catch (e) {}
if (name === "disabled" || !this.config.shaders[name]) {
this.gameManager.toggleShader(0);
@@ -6977,13 +10120,30 @@ class EmulatorJS {
const shaderConfig = this.config.shaders[name];
if (typeof shaderConfig === "string") {
- this.Module.FS.writeFile("/shader/shader.glslp", shaderConfig, {}, "w+");
+ this.Module.FS.writeFile(
+ "/shader/shader.glslp",
+ shaderConfig,
+ {},
+ "w+"
+ );
} else {
const shader = shaderConfig.shader;
- this.Module.FS.writeFile("/shader/shader.glslp", shader.type === "base64" ? atob(shader.value) : shader.value, {}, "w+");
+ this.Module.FS.writeFile(
+ "/shader/shader.glslp",
+ shader.type === "base64" ? atob(shader.value) : shader.value,
+ {},
+ "w+"
+ );
if (shaderConfig.resources && shaderConfig.resources.length) {
- shaderConfig.resources.forEach(resource => {
- this.Module.FS.writeFile(`/shader/${resource.name}`, resource.type === "base64" ? atob(resource.value) : resource.value, {}, "w+");
+ shaderConfig.resources.forEach((resource) => {
+ this.Module.FS.writeFile(
+ `/shader/${resource.name}`,
+ resource.type === "base64"
+ ? atob(resource.value)
+ : resource.value,
+ {},
+ "w+"
+ );
});
}
}
@@ -6992,27 +10152,41 @@ class EmulatorJS {
}
screenshot(callback, source, format, upscale) {
- const imageFormat = format || this.getSettingValue("screenshotFormat") || this.capture.photo.format;
- const imageUpscale = upscale || parseInt(this.getSettingValue("screenshotUpscale") || this.capture.photo.upscale);
- const screenshotSource = source || this.getSettingValue("screenshotSource") || this.capture.photo.source;
- const videoRotation = parseInt(this.getSettingValue("videoRotation") || 0);
- const aspectRatio = this.gameManager.getVideoDimensions("aspect") || 1.333333;
+ const imageFormat =
+ format ||
+ this.getSettingValue("screenshotFormat") ||
+ this.capture.photo.format;
+ const imageUpscale =
+ upscale ||
+ parseInt(
+ this.getSettingValue("screenshotUpscale") ||
+ this.capture.photo.upscale
+ );
+ const screenshotSource =
+ source ||
+ this.getSettingValue("screenshotSource") ||
+ this.capture.photo.source;
+ const videoRotation = parseInt(
+ this.getSettingValue("videoRotation") || 0
+ );
+ const aspectRatio =
+ this.gameManager.getVideoDimensions("aspect") || 1.333333;
const gameWidth = this.gameManager.getVideoDimensions("width") || 256;
const gameHeight = this.gameManager.getVideoDimensions("height") || 224;
- const videoTurned = (videoRotation === 1 || videoRotation === 3);
+ const videoTurned = videoRotation === 1 || videoRotation === 3;
let width = this.canvas.width;
let height = this.canvas.height;
let scaleHeight = imageUpscale;
let scaleWidth = imageUpscale;
let scale = 1;
-
+
if (screenshotSource === "retroarch") {
if (width >= height) {
width = height * aspectRatio;
} else if (width < height) {
height = width / aspectRatio;
}
- this.gameManager.screenshot().then(screenshot => {
+ this.gameManager.screenshot().then((screenshot) => {
const blob = new Blob([screenshot], { type: "image/png" });
if (imageUpscale === 0) {
callback(blob, "png");
@@ -7029,13 +10203,17 @@ class EmulatorJS {
ctx.imageSmoothingEnabled = false;
ctx.scale(scaleWidth, scaleHeight);
ctx.drawImage(img, 0, 0, width, height);
- canvas.toBlob((blob) => {
- callback(blob, imageFormat);
- img.remove();
- URL.revokeObjectURL(screenshotUrl);
- canvas.remove();
- }, "image/" + imageFormat, 1);
- }
+ canvas.toBlob(
+ (blob) => {
+ callback(blob, imageFormat);
+ img.remove();
+ URL.revokeObjectURL(screenshotUrl);
+ canvas.remove();
+ },
+ "image/" + imageFormat,
+ 1
+ );
+ };
}
});
} else if (screenshotSource === "canvas") {
@@ -7044,9 +10222,9 @@ class EmulatorJS {
} else if (width < height && !videoTurned) {
height = width / aspectRatio;
} else if (width >= height && videoTurned) {
- width = height * (1/aspectRatio);
+ width = height * (1 / aspectRatio);
} else if (width < height && videoTurned) {
- width = height / (1/aspectRatio);
+ width = height / (1 / aspectRatio);
}
if (imageUpscale === 0) {
scale = gameHeight / height;
@@ -7073,11 +10251,21 @@ class EmulatorJS {
offsetY = (this.canvas.height - height) / -2;
}
const drawNextFrame = () => {
- captureCtx.drawImage(this.canvas, offsetX, offsetY, this.canvas.width, this.canvas.height);
- captureCanvas.toBlob((blob) => {
- callback(blob, imageFormat);
- captureCanvas.remove();
- }, "image/" + imageFormat, 1);
+ captureCtx.drawImage(
+ this.canvas,
+ offsetX,
+ offsetY,
+ this.canvas.width,
+ this.canvas.height
+ );
+ captureCanvas.toBlob(
+ (blob) => {
+ callback(blob, imageFormat);
+ captureCanvas.remove();
+ },
+ "image/" + imageFormat,
+ 1
+ );
};
requestAnimationFrame(drawNextFrame);
}
@@ -7085,11 +10273,16 @@ class EmulatorJS {
takeScreenshot(source, format, upscale) {
return new Promise((resolve) => {
- this.screenshot(async (blob, returnFormat) => {
- const arrayBuffer = await blob.arrayBuffer();
- const uint8 = new Uint8Array(arrayBuffer);
- resolve({ screenshot: uint8, format: returnFormat });
- }, source, format, upscale);
+ this.screenshot(
+ async (blob, returnFormat) => {
+ const arrayBuffer = await blob.arrayBuffer();
+ const uint8 = new Uint8Array(arrayBuffer);
+ resolve({ screenshot: uint8, format: returnFormat });
+ },
+ source,
+ format,
+ upscale
+ );
});
}
@@ -7104,7 +10297,11 @@ class EmulatorJS {
}
let audioTrack = null;
- if (this.Module.AL && this.Module.AL.currentCtx && this.Module.AL.currentCtx.audioCtx) {
+ if (
+ this.Module.AL &&
+ this.Module.AL.currentCtx &&
+ this.Module.AL.currentCtx.audioCtx
+ ) {
const alContext = this.Module.AL.currentCtx;
const audioContext = alContext.audioCtx;
@@ -7114,7 +10311,7 @@ class EmulatorJS {
}
const merger = audioContext.createChannelMerger(gainNodes.length);
- gainNodes.forEach(node => node.connect(merger));
+ gainNodes.forEach((node) => node.connect(merger));
const destination = audioContext.createMediaStreamDestination();
merger.connect(destination);
@@ -7136,14 +10333,27 @@ class EmulatorJS {
}
screenRecord() {
- const captureFps = this.getSettingValue("screenRecordingFPS") || this.capture.video.fps;
- const captureFormat = this.getSettingValue("screenRecordFormat") || this.capture.video.format;
- const captureUpscale = this.getSettingValue("screenRecordUpscale") || this.capture.video.upscale;
- const captureVideoBitrate = this.getSettingValue("screenRecordVideoBitrate") || this.capture.video.videoBitrate;
- const captureAudioBitrate = this.getSettingValue("screenRecordAudioBitrate") || this.capture.video.audioBitrate;
- const aspectRatio = this.gameManager.getVideoDimensions("aspect") || 1.333333;
- const videoRotation = parseInt(this.getSettingValue("videoRotation") || 0);
- const videoTurned = (videoRotation === 1 || videoRotation === 3);
+ const captureFps =
+ this.getSettingValue("screenRecordingFPS") ||
+ this.capture.video.fps;
+ const captureFormat =
+ this.getSettingValue("screenRecordFormat") ||
+ this.capture.video.format;
+ const captureUpscale =
+ this.getSettingValue("screenRecordUpscale") ||
+ this.capture.video.upscale;
+ const captureVideoBitrate =
+ this.getSettingValue("screenRecordVideoBitrate") ||
+ this.capture.video.videoBitrate;
+ const captureAudioBitrate =
+ this.getSettingValue("screenRecordAudioBitrate") ||
+ this.capture.video.audioBitrate;
+ const aspectRatio =
+ this.gameManager.getVideoDimensions("aspect") || 1.333333;
+ const videoRotation = parseInt(
+ this.getSettingValue("videoRotation") || 0
+ );
+ const videoTurned = videoRotation === 1 || videoRotation === 3;
let width = 800;
let height = 600;
let frameAspect = this.canvas.width / this.canvas.height;
@@ -7158,15 +10368,15 @@ class EmulatorJS {
const updateSize = () => {
width = this.canvas.width;
height = this.canvas.height;
- frameAspect = width / height
+ frameAspect = width / height;
if (width >= height && !videoTurned) {
width = height * aspectRatio;
} else if (width < height && !videoTurned) {
height = width / aspectRatio;
} else if (width >= height && videoTurned) {
- width = height * (1/aspectRatio);
+ width = height * (1 / aspectRatio);
} else if (width < height && videoTurned) {
- width = height / (1/aspectRatio);
+ width = height / (1 / aspectRatio);
}
canvasAspect = width / height;
captureCanvas.width = width * captureUpscale;
@@ -7177,7 +10387,7 @@ class EmulatorJS {
} else if (frameAspect < canvasAspect) {
offsetY = (this.canvas.height - height) / -2;
}
- }
+ };
updateSize();
this.addEventListener(this.canvas, "resize", () => {
updateSize();
@@ -7186,7 +10396,13 @@ class EmulatorJS {
let animation = true;
const drawNextFrame = () => {
- captureCtx.drawImage(this.canvas, offsetX, offsetY, this.canvas.width, this.canvas.height);
+ captureCtx.drawImage(
+ this.canvas,
+ offsetX,
+ offsetY,
+ this.canvas.width,
+ this.canvas.height
+ );
if (animation) {
requestAnimationFrame(drawNextFrame);
}
@@ -7194,13 +10410,16 @@ class EmulatorJS {
requestAnimationFrame(drawNextFrame);
const chunks = [];
- const tracks = this.collectScreenRecordingMediaTracks(captureCanvas, captureFps);
+ const tracks = this.collectScreenRecordingMediaTracks(
+ captureCanvas,
+ captureFps
+ );
const recorder = new MediaRecorder(tracks, {
videoBitsPerSecond: captureVideoBitrate,
audioBitsPerSecond: captureAudioBitrate,
- mimeType: "video/" + captureFormat
+ mimeType: "video/" + captureFormat,
});
- recorder.addEventListener("dataavailable", e => {
+ recorder.addEventListener("dataavailable", (e) => {
chunks.push(e.data);
});
recorder.addEventListener("stop", () => {
@@ -7209,7 +10428,16 @@ class EmulatorJS {
const date = new Date();
const a = document.createElement("a");
a.href = url;
- a.download = this.getBaseFileName() + "-" + date.getMonth() + "-" + date.getDate() + "-" + date.getFullYear() + "." + captureFormat;
+ a.download =
+ this.getBaseFileName() +
+ "-" +
+ date.getMonth() +
+ "-" +
+ date.getDate() +
+ "-" +
+ date.getFullYear() +
+ "." +
+ captureFormat;
a.click();
animation = false;
@@ -7224,25 +10452,28 @@ class EmulatorJS {
// https://stackoverflow.com/questions/7616461
// Modified to accept a buffer instead of a string and return hex instead of an int
async function cyrb53(charBuffer, seed = 0) {
- let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
- for(let i = 0, ch; i < charBuffer.length; i++) {
+ let h1 = 0xdeadbeef ^ seed,
+ h2 = 0x41c6ce57 ^ seed;
+ for (let i = 0, ch; i < charBuffer.length; i++) {
ch = charBuffer[i];
h1 = Math.imul(h1 ^ ch, 2654435761);
h2 = Math.imul(h2 ^ ch, 1597334677);
}
- h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
- h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
// Cyrb53 is a 53-bit hash; we need 14 hex characters to represent it, and the first char will
// always be 0 or 1 (since it is only 1 bit)
- return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(16).padStart(14, "0");
- };
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0))
+ .toString(16)
+ .padStart(14, "0");
+ }
function withGameSaveHash(saveFile, callback) {
if (saveFile) {
- cyrb53(saveFile).then(digest => callback(digest, saveFile));
+ cyrb53(saveFile).then((digest) => callback(digest, saveFile));
} else {
console.warn("Save file not found when attempting to hash");
callback(null, null);
@@ -7250,23 +10481,31 @@ class EmulatorJS {
}
var recentHash = null;
- if (this.gameManager) { withGameSaveHash(this.gameManager.getSaveFile(false), (hash, _) => { recentHash = hash }) }
+ if (this.gameManager) {
+ withGameSaveHash(this.gameManager.getSaveFile(false), (hash, _) => {
+ recentHash = hash;
+ });
+ }
- this.on("saveSaveFiles", saveFile => {
+ this.on("saveSaveFiles", (saveFile) => {
withGameSaveHash(saveFile, (newHash, fileContents) => {
if (newHash && fileContents && newHash !== recentHash) {
recentHash = newHash;
- this.takeScreenshot(this.capture.photo.source, this.capture.photo.format, this.capture.photo.upscale).then(({ screenshot, format }) => {
+ this.takeScreenshot(
+ this.capture.photo.source,
+ this.capture.photo.format,
+ this.capture.photo.upscale
+ ).then(({ screenshot, format }) => {
this.callEvent("saveUpdate", {
hash: newHash,
save: fileContents,
screenshot: screenshot,
- format: format
+ format: format,
});
- })
+ });
}
- })
- })
+ });
+ });
}
}
-window.EmulatorJS = EmulatorJS;
+window.EmulatorJS = EmulatorJS;
\ No newline at end of file