Skip to content

PS2 games in the browser: static recompilation to WebAssembly with a native runtime

C++
53.3 KB
Raw Blame
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
<title>ps2-web-recomp</title>
<style>
  :root { color-scheme: dark; }
  html, body { margin: 0; height: 100%; overflow: hidden; background: #0b0b0d; color: #d8d8dc; font: 13px system-ui, sans-serif; }
  body { display: flex; flex-direction: column; }
  #stage { flex: 1; display: flex; align-items: center; justify-content: center; min-height: 0; }
  canvas { width: 100%; height: 100%; display: block; background: #000; }
  #remote { display: none; width: 100%; height: 100%; background: #000; object-fit: fill; }
  body.guest #remote { display: block; }
  body.guest.frames #remote { display: none; }
  body.guest.frames #canvas { display: block; }
  body.guest:not(.frames) #canvas, body.guest #bar .host-only, body.guest #menu .host-only { display: none; }
  #bar { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; padding: 6px 12px; background: #141418; border-top: 1px solid #222; }
  #status { flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  #stats { font-variant-numeric: tabular-nums; color: #9ad; }
  select { background: #2a3a55; color: #fff; border: 0; padding: 5px 8px; border-radius: 4px; }
  button { background: #2a3a55; color: #fff; border: 0; padding: 6px 14px; border-radius: 4px; cursor: pointer; }
  #aa-label, #stats-label { display: flex; align-items: center; gap: 6px; color: #9ad; white-space: nowrap; }
  #menu { position: fixed; right: 8px; z-index: 4; display: flex; flex-direction: column; align-items: stretch; gap: 8px; padding: 10px;
    background: #141418; border: 1px solid #2a2a33; border-radius: 8px; max-height: 70vh; overflow-y: auto; }
  #menu[hidden] { display: none; }
  body.touch #menu button, body.touch #menu select { padding: 8px 12px; font-size: 14px; }
  #overlay { position: fixed; inset: 0; display: flex; align-items: center; justify-content: center; background: rgba(0,0,0,.6); padding: 16px; }
  #panel { display: flex; flex-direction: column; align-items: center; gap: 14px; max-width: 520px; text-align: center; }
  #help { margin: 0; line-height: 1.5; color: #e8c37a; }
  .controls { display: none; }
  body.touch { overscroll-behavior: none; touch-action: none; -webkit-user-select: none; user-select: none; }
  body.touch #bar { flex-wrap: nowrap; overflow-x: auto; gap: 8px; padding: 4px 8px calc(4px + env(safe-area-inset-bottom)); touch-action: pan-x; scrollbar-width: none; }
  body.touch #bar::-webkit-scrollbar { display: none; }
  body.touch #bar > button { flex: none; }
  body.touch #status, body.touch #stats { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  body.touch #stats { flex: 0 1 auto; }
  body.touch #bar button, body.touch #bar select { padding: 5px 10px; font-size: 12px; }
  body.touch #stage { flex: none; width: 100%; aspect-ratio: 4 / 3; max-height: 60vh; }
  body.touch.wide #stage { aspect-ratio: 16 / 9; }
  body.touch .controls {
    flex: 1; display: grid; grid-template-columns: 1fr 1fr; grid-template-areas: "mid mid" "left right";
    gap: 10px 8px; align-content: center; padding: 8px 12px calc(8px + env(safe-area-inset-bottom));
    touch-action: none; -webkit-touch-callout: none; -webkit-tap-highlight-color: transparent;
    --ctl: #1d2433; --ctl-on: #4a6aa5; --ctl-line: #34405a; --ctl-text: #dfe6f3;
    --cell: clamp(30px, min(11vw, 5.2vh), 64px);
  }
  .controls { --face: calc(var(--cell) * 1.25); }
  .cluster { display: flex; flex-direction: column; align-items: center; gap: 12px; }
  .cluster.left { grid-area: left; } .cluster.right { grid-area: right; }
  .cluster.mid { grid-area: mid; flex-direction: row; gap: 10px; justify-self: center; }
  .shoulders { display: flex; gap: 8px; width: 100%; max-width: calc(var(--cell) * 4); }
  .ctl {
    display: flex; align-items: center; justify-content: center; color: var(--ctl-text);
    background: var(--ctl); border: 1px solid var(--ctl-line); font-weight: 600;
  }
  .ctl.on, .dpad span.on { background: var(--ctl-on); }
  .shoulder { flex: 1; height: calc(var(--cell) * 0.95); border-radius: 12px 12px 6px 6px; }
  .small { padding: 0 calc(var(--cell) * 0.3); height: calc(var(--cell) * 0.75); border-radius: calc(var(--cell) * 0.375); font-size: calc(var(--cell) * 0.3); font-weight: 500; }
  .face { display: grid; grid-template-columns: repeat(3, var(--face)); grid-template-rows: repeat(3, var(--face)); }
  .face .ctl { border-radius: 50%; font-size: calc(var(--face) * 0.4); }
  .face .tri { grid-area: 1 / 2; } .face .sq { grid-area: 2 / 1; }
  .face .ci { grid-area: 2 / 3; } .face .cr { grid-area: 3 / 2; }
  .dpad { width: calc(var(--cell) * 3); height: calc(var(--cell) * 3); display: grid; grid-template-columns: repeat(3, var(--cell)); grid-template-rows: repeat(3, var(--cell)); }
  .dpad span {
    display: flex; align-items: center; justify-content: center; font-size: calc(var(--cell) * 0.35);
    color: var(--ctl-text); background: var(--ctl); border: 1px solid var(--ctl-line);
  }
  .dpad .up { grid-area: 1 / 2; border-radius: 8px 8px 0 0; } .dpad .down { grid-area: 3 / 2; border-radius: 0 0 8px 8px; }
  .dpad .left { grid-area: 2 / 1; border-radius: 8px 0 0 8px; } .dpad .right { grid-area: 2 / 3; border-radius: 0 8px 8px 0; }
  .dpad .hub { grid-area: 2 / 2; }
  .stick { position: relative; width: calc(var(--cell) * 3); height: calc(var(--cell) * 3); border-radius: 50%; background: var(--ctl); border: 1px solid var(--ctl-line); }
  .knob {
    position: absolute; left: 50%; top: 50%; width: 43%; height: 43%; margin: -21.5% 0 0 -21.5%;
    border-radius: 50%; background: var(--ctl-on); border: 1px solid var(--ctl-line);
  }
  body.touch.hide-controls .controls { display: none; }
  #exit-fullscreen {
    display: none; position: fixed; z-index: 3; top: calc(8px + env(safe-area-inset-top)); right: calc(8px + env(safe-area-inset-right));
    padding: 4px 10px; font-size: 12px; background: rgba(255, 255, 255, 0.15); opacity: 0.4;
  }
  #exit-fullscreen:hover { opacity: 0.9; }
  body.fullscreen { background: #000; }
  body.fullscreen #bar { display: none; }
  body.fullscreen #exit-fullscreen { display: block; }
  @media (orientation: landscape) {
    body.touch #stage { flex: 1; aspect-ratio: auto; max-height: none; }
    body.touch .controls { position: fixed; inset: 0; display: block; padding: 0; pointer-events: none; z-index: 1;
      --ctl: rgba(255, 255, 255, 0.12); --ctl-on: rgba(255, 255, 255, 0.45); --ctl-line: rgba(255, 255, 255, 0.28); --ctl-text: #fff;
      --cell: clamp(26px, min(9vh, 7vw), 60px); }
    body.touch .cluster { position: absolute; top: 8px; bottom: 40px; justify-content: space-between; pointer-events: auto; opacity: 0.75; }
    body.touch .cluster.left { left: calc(10px + env(safe-area-inset-left)); }
    body.touch .cluster.right { right: calc(10px + env(safe-area-inset-right)); }
    body.touch .cluster.mid { top: auto; bottom: 40px; left: 50%; transform: translateX(-50%); }
    body.fullscreen.touch .cluster { bottom: calc(8px + env(safe-area-inset-bottom)); }
    body.fullscreen.touch .cluster.mid { bottom: calc(8px + env(safe-area-inset-bottom)); }
  }
</style>
</head>
<body>
<div id="stage"><canvas id="canvas" tabindex="0"></canvas><video id="remote" playsinline></video></div>
<div id="touch" class="controls" aria-hidden="true">
  <div class="cluster left">
    <div class="shoulders"><div class="ctl shoulder" data-btn="256">L2</div><div class="ctl shoulder" data-btn="1024">L1</div></div>
    <div class="dpad" data-dpad>
      <span class="up" data-dir="16">▲</span><span class="left" data-dir="128">◀</span><span class="hub"></span>
      <span class="right" data-dir="32">▶</span><span class="down" data-dir="64">▼</span>
    </div>
    <div class="stick" data-stick><div class="knob" id="knob"></div></div>
  </div>
  <div class="cluster mid">
    <div class="ctl small" data-btn="1">Select</div>
    <div class="ctl small" data-btn="8">Start</div>
  </div>
  <div class="cluster right">
    <div class="shoulders"><div class="ctl shoulder" data-btn="2048">R1</div><div class="ctl shoulder" data-btn="512">R2</div></div>
    <div class="face">
      <div class="ctl tri" data-btn="4096">△</div>
      <div class="ctl sq" data-btn="32768">□</div>
      <div class="ctl ci" data-btn="8192">○</div>
      <div class="ctl cr" data-btn="16384">✕</div>
    </div>
  </div>
</div>
<div id="bar"><span id="status">Loading…</span><span id="stats"></span>
  <button id="invite" class="host-only" type="button" disabled title="Make a room and copy a link that lets a friend watch and play as player 2">Invite</button>
  <button id="menu-toggle" type="button" aria-expanded="false" aria-controls="menu">Menu ▴</button>
  <button id="fullscreen" type="button" title="Fullscreen (F or double click)">Fullscreen</button></div>
<div id="menu" hidden>
  <select id="scale" class="host-only" aria-label="Resolution" title="Internal resolution, the page reloads to apply it">
    <option value="1">640×512</option>
    <option value="2">1280×1024</option>
    <option value="3">1920×1536</option>
  </select>
  <select id="aspect" class="host-only" aria-label="Aspect ratio" title="Screen shape the game is told about, the page reloads to apply it">
    <option value="4:3">4:3</option>
    <option value="16:9">16:9</option>
  </select>
  <select id="pad" aria-label="Player 1 gamepad" title="Gamepad for player 1, the next connected one is player 2 (press a button on a pad if it is missing)">
    <option value="">Pad: auto</option>
  </select>
  <button id="save-state" class="host-only" type="button" disabled title="Save the game to this device">Save state</button>
  <button id="load-state" class="host-only" type="button" disabled title="Load the quick save from this device">Load state</button>
  <button id="export-state" class="host-only" type="button" title="Download the quick save as a .state file">Export state</button>
  <button id="import-state" class="host-only" type="button" title="Make a .state file the quick save">Import state</button>
  <input id="import-state-file" type="file" accept=".state" hidden>
  <label id="aa-label" class="host-only" title="Smooth jagged edges, applied immediately"><input id="aa" type="checkbox" disabled> Smooth edges</label>
  <label id="stats-label"><input id="stats-toggle" type="checkbox"> Show stats</label>
  <button id="controls-toggle" type="button" hidden>Hide controls</button>
  <button id="export-card" class="host-only" type="button" title="Download the memory card in slot 1 as a .ps2 file">Export card</button>
  <button id="import-card" class="host-only" type="button" title="Put a .ps2 memory card file in slot 1">Import card</button>
  <input id="import-file" type="file" accept=".ps2" hidden>
</div>
<button id="exit-fullscreen" type="button">Exit fullscreen</button>
<div id="overlay"><div id="panel"><p id="help" hidden></p><button id="start" disabled>Loading…</button></div></div>
<template id="engine">{{{ SCRIPT }}}</template>
<script>
const statusEl = document.getElementById('status');
const CARD_DIR = '/memcard', CARD_FILE = '/memcard/Mcd001.ps2', CARD_BYTES = 8650752;
let noteTimer = 0, noteRestore = '';
function note(text) {
  if (!noteTimer) noteRestore = statusEl.textContent;
  clearTimeout(noteTimer);
  statusEl.textContent = text;
  noteTimer = setTimeout(() => {
    statusEl.textContent = noteRestore;
    noteTimer = 0;
  }, 5000);
}
let cardTimer = 0;
function storeCard(then) {
  clearTimeout(cardTimer);
  cardTimer = setTimeout(() => {
    try {
      FS.syncfs(false, (err) => {
        if (err) console.warn('memory card: could not write browser storage', err);
        if (then) then();
      });
    } catch (e) {
      if (then) then();
    }
  }, 300);
}
document.getElementById('export-card').addEventListener('click', () => {
  let data = null;
  try { data = FS.readFile(CARD_FILE); } catch (e) {}
  if (!data) {
    note('Nothing saved on the memory card yet');
    return;
  }
  const link = document.createElement('a');
  link.href = URL.createObjectURL(new Blob([data], { type: 'application/octet-stream' }));
  link.download = 'Mcd001.ps2';
  link.click();
  setTimeout(() => URL.revokeObjectURL(link.href), 10000);
});
const importInput = document.getElementById('import-file');
document.getElementById('import-card').addEventListener('click', () => importInput.click());
importInput.addEventListener('change', async () => {
  const file = importInput.files[0];
  importInput.value = '';
  if (!file) return;
  if (file.size !== CARD_BYTES) {
    note('That is not an 8 MB PS2 memory card image (' + CARD_BYTES + ' bytes)');
    return;
  }
  const data = new Uint8Array(await file.arrayBuffer());
  if (new TextDecoder().decode(data.subarray(0, 28)) !== 'Sony PS2 Memory Card Format ') {
    note('That file is not a formatted PS2 memory card');
    return;
  }
  if (!confirm('Replace the memory card in slot 1 with ' + file.name + '? The page reloads to use it.')) return;
  try {
    FS.writeFile(CARD_FILE, data);
  } catch (e) {
    note('Import failed: ' + e.message);
    return;
  }
  storeCard(() => location.reload());
});
const statsEl = document.getElementById('stats');
const statsLog = new URLSearchParams(location.search).has('statslog');
const statsToggle = document.getElementById('stats-toggle');
let showStats = !(matchMedia('(pointer: coarse)').matches || /[?&]touch\b/.test(location.search));
try { const stored = localStorage.getItem('ps2web-stats'); if (stored) showStats = stored === '1'; } catch (e) {}
statsToggle.checked = showStats;
statsEl.hidden = !showStats;
statsToggle.addEventListener('change', () => {
  showStats = statsToggle.checked;
  statsEl.hidden = !showStats;
  try { localStorage.setItem('ps2web-stats', showStats ? '1' : '0'); } catch (e) {}
});
const menu = document.getElementById('menu'), menuToggle = document.getElementById('menu-toggle');
function setMenu(open) {
  if (open) menu.style.bottom = document.getElementById('bar').offsetHeight + 8 + 'px';
  menu.hidden = !open;
  menuToggle.setAttribute('aria-expanded', open ? 'true' : 'false');
  menuToggle.textContent = open ? 'Menu ▾' : 'Menu ▴';
}
menuToggle.addEventListener('click', () => setMenu(menu.hidden));
document.addEventListener('pointerdown', (e) => {
  if (!menu.hidden && !menu.contains(e.target) && !menuToggle.contains(e.target)) setMenu(false);
});
const canvas = document.getElementById('canvas');
const params = new URLSearchParams(location.search);
const guestRoom = params.get('join');
if (guestRoom) document.body.classList.add('guest');

function missingFeatures() {
  const header = [0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 2, 1, 0, 10];
  const accepts = (body) => {
    try {
      return WebAssembly.validate(new Uint8Array(header.concat([body.length + 2, 1, body.length], body)));
    } catch (e) {
      return false;
    }
  };
  const missing = [];
  if (!window.crossOriginIsolated) missing.push('cross-origin isolation (COOP and COEP headers)');
  if (typeof WebAssembly.Suspending !== 'function') missing.push('WebAssembly JSPI');
  if (!accepts([0, 0x1F, 0x40, 0, 0x0B, 0x0B])) missing.push('WebAssembly exception handling (try_table)');
  if (!accepts([0, 0x12, 0, 0x0B])) missing.push('WebAssembly tail calls');
  if (!accepts([0, 0xFD, 0x0C].concat(new Array(16).fill(0), [0x1A, 0x0B]))) missing.push('WebAssembly SIMD');
  return missing;
}
const missing = guestRoom ? [] : missingFeatures();

const touchRoot = document.getElementById('touch'), knob = document.getElementById('knob');
let touchPad = { buttons: 0, x: 0, y: 0, stick: false };
const fingers = new Map();
if (matchMedia('(pointer: coarse)').matches || params.has('touch')) document.body.classList.add('touch');
function circleOf(el) {
  const r = el.getBoundingClientRect();
  return { x: r.left + r.width / 2, y: r.top + r.height / 2, r: r.width / 2 };
}
function onTouch(e) {
  e.preventDefault();
  const seen = new Set();
  let buttons = 0, sx = 0, sy = 0, stick = false;
  for (const t of e.touches) {
    seen.add(t.identifier);
    let f = fingers.get(t.identifier);
    if (!f) {
      const start = document.elementFromPoint(t.clientX, t.clientY);
      const region = start && start.closest('[data-stick],[data-dpad]');
      f = region ? { kind: region.hasAttribute('data-stick') ? 'stick' : 'dpad', el: region } : { kind: 'button' };
      fingers.set(t.identifier, f);
    }
    if (f.kind === 'stick') {
      const c = circleOf(f.el);
      let dx = (t.clientX - c.x) / c.r, dy = (t.clientY - c.y) / c.r;
      const len = Math.hypot(dx, dy);
      if (len > 1) { dx /= len; dy /= len; }
      sx = dx; sy = dy; stick = true;
      knob.style.transform = 'translate(' + (dx * c.r * 0.6) + 'px,' + (dy * c.r * 0.6) + 'px)';
    } else if (f.kind === 'dpad') {
      const d = circleOf(f.el), ox = t.clientX - d.x, oy = t.clientY - d.y;
      if (Math.hypot(ox, oy) > d.r * 0.2) {
        const angle = Math.atan2(oy, ox) * 180 / Math.PI;
        if (angle > -67.5 && angle < 67.5) buttons |= 0x20;
        if (angle > 22.5 && angle < 157.5) buttons |= 0x40;
        if (angle > 112.5 || angle < -112.5) buttons |= 0x80;
        if (angle > -157.5 && angle < -22.5) buttons |= 0x10;
      }
    } else {
      const over = document.elementFromPoint(t.clientX, t.clientY);
      const button = over && over.closest('[data-btn]');
      if (button && touchRoot.contains(button)) buttons |= Number(button.dataset.btn);
    }
  }
  for (const id of [...fingers.keys()]) if (!seen.has(id)) fingers.delete(id);
  if (!stick) knob.style.transform = '';
  touchPad = { buttons, x: sx, y: sy, stick };
  touchRoot.querySelectorAll('[data-btn]').forEach((el) => el.classList.toggle('on', (buttons & Number(el.dataset.btn)) !== 0));
  touchRoot.querySelectorAll('[data-dir]').forEach((el) => el.classList.toggle('on', (buttons & Number(el.dataset.dir)) !== 0));
}
for (const type of ['touchstart', 'touchmove', 'touchend', 'touchcancel']) touchRoot.addEventListener(type, onTouch, { passive: false });

const scaleSelect = document.getElementById('scale');
let scale = params.get('PS2_SCALE');
if (!scale) {
  try { scale = localStorage.getItem('ps2web-scale'); } catch (e) {}
}
scale = ['1', '2', '3'].includes(scale) ? scale : '1';
scaleSelect.value = scale;
scaleSelect.addEventListener('change', () => {
  try { localStorage.setItem('ps2web-scale', scaleSelect.value); } catch (e) {}
  const url = new URL(location.href);
  url.searchParams.delete('PS2_SCALE');
  location.href = url.href;
});

const aspectSelect = document.getElementById('aspect');
let aspect = params.get('aspect');
if (!aspect) {
  try { aspect = localStorage.getItem('ps2web-aspect'); } catch (e) {}
}
aspect = aspect === '4:3' ? '4:3' : '16:9';
aspectSelect.value = aspect;
document.body.classList.toggle('wide', aspect === '16:9');
aspectSelect.addEventListener('change', () => {
  try { localStorage.setItem('ps2web-aspect', aspectSelect.value); } catch (e) {}
  const url = new URL(location.href);
  url.searchParams.delete('aspect');
  location.href = url.href;
});

// One quick save per player URL, kept in this browser's IndexedDB. The state
// file itself is captured by the emulation thread, so saving never pauses it
// mid-instruction.
const saveStateButton = document.getElementById('save-state');
const loadStateButton = document.getElementById('load-state');
const STATE_FILE = '/quicksave.state';
let stateBusy = false, statePending = null;

function stateKey() {
  return location.pathname + '|' + new URL(Module.discUrl, location.href).href;
}

function stateSlot(value) {
  return new Promise((resolve, reject) => {
    const open = indexedDB.open('ps2-player-quicksave', 1);
    open.onupgradeneeded = () => open.result.createObjectStore('slots');
    open.onerror = () => reject(open.error);
    open.onblocked = () => reject(new Error('Close other player tabs and try again.'));
    open.onsuccess = () => {
      const db = open.result;
      // A put commits atomically: a failed write preserves the previous save.
      const transaction = db.transaction('slots', value === undefined ? 'readonly' : 'readwrite');
      const store = transaction.objectStore('slots');
      const request = value === undefined ? store.get(stateKey()) : store.put(value, stateKey());
      transaction.oncomplete = () => { db.close(); resolve(request.result); };
      transaction.onabort = () => { db.close(); reject(transaction.error || new Error('Browser storage write failed.')); };
    };
  });
}

async function stateDigest(bytes) {
  if (!crypto.subtle) return '';
  const hash = await crypto.subtle.digest('SHA-256', bytes);
  return Array.from(new Uint8Array(hash), (byte) => byte.toString(16).padStart(2, '0')).join('');
}

function requestState(loading) {
  return new Promise((resolve, reject) => {
    statePending = { loading, resolve, reject };
    if (!Module._ps2web_quick_state(loading ? 1 : 0)) {
      statePending = null;
      reject(new Error('The player is busy. Try again.'));
    }
  });
}

function setStateBusy(busy) {
  stateBusy = busy;
  saveStateButton.disabled = loadStateButton.disabled = busy || !Module.running;
}

async function saveState() {
  if (stateBusy || !Module.running) return;
  setStateBusy(true);
  note('Saving…');
  try {
    await requestState(false);
    const bytes = FS.readFile(STATE_FILE);
    const record = { bytes, digest: await stateDigest(bytes), savedAt: Date.now() };
    await stateSlot(record);
    note('Saved ' + new Date(record.savedAt).toLocaleString());
  } catch (error) {
    note(error.name === 'QuotaExceededError' ? 'Not enough device storage. Your previous quick save is unchanged.' : error.message);
  } finally {
    try { FS.unlink(STATE_FILE); } catch (e) {}
    setStateBusy(false);
  }
}

async function loadState() {
  if (stateBusy || !Module.running) return;
  setStateBusy(true);
  note('Loading quick save…');
  try {
    const record = await stateSlot();
    if (!record) throw new Error('No quick save yet.');
    if (!(record.bytes instanceof Uint8Array) || (record.digest && await stateDigest(record.bytes) !== record.digest)) {
      throw new Error('The quick save is damaged. It has not been loaded.');
    }
    FS.writeFile(STATE_FILE, record.bytes);
    await requestState(true);
    note('Quick save loaded.');
  } catch (error) {
    note(error.message);
  } finally {
    try { FS.unlink(STATE_FILE); } catch (e) {}
    setStateBusy(false);
  }
}

saveStateButton.addEventListener('click', saveState);
loadStateButton.addEventListener('click', loadState);
document.getElementById('export-state').addEventListener('click', async () => {
  try {
    const record = await stateSlot();
    if (!record) throw new Error('No quick save yet.');
    const link = document.createElement('a');
    link.href = URL.createObjectURL(new Blob([record.bytes], { type: 'application/octet-stream' }));
    link.download = 'quicksave-' + new Date(record.savedAt).toISOString().replace(/[:.]/g, '-') + '.state';
    link.click();
    setTimeout(() => URL.revokeObjectURL(link.href), 10000);
  } catch (error) {
    note(error.message);
  }
});
const importStateInput = document.getElementById('import-state-file');
document.getElementById('import-state').addEventListener('click', () => importStateInput.click());
importStateInput.addEventListener('change', async () => {
  const file = importStateInput.files[0];
  importStateInput.value = '';
  if (!file) return;
  try {
    const bytes = new Uint8Array(await file.arrayBuffer());
    await stateSlot({ bytes, digest: await stateDigest(bytes), savedAt: Date.now() });
    note('Imported ' + file.name + ' as the quick save. Load state to use it.');
  } catch (error) {
    note(error.name === 'QuotaExceededError' ? 'Not enough device storage.' : error.message);
  }
});
// Edge antialiasing is a display option, so it lives outside the save state
// and takes effect on the next presented frame.
const aaInput = document.getElementById('aa');
const aaLabel = document.getElementById('aa-label');
let aa = false;
try { aa = localStorage.getItem('ps2web-aa') === '1'; } catch (e) {}
aaInput.checked = aa;
function applyVideo() {
  if (Module._ps2web_video_options) Module._ps2web_video_options(aa ? 1 : 0);
}
aaInput.addEventListener('change', () => {
  aa = aaInput.checked;
  try { localStorage.setItem('ps2web-aa', aa ? '1' : '0'); } catch (e) {}
  applyVideo();
});

const controlsButton = document.getElementById('controls-toggle');
let hideControls = false;
try { hideControls = localStorage.getItem('ps2web-hide-controls') === '1'; } catch (e) {}
function updateControls() {
  const touch = document.body.classList.contains('touch');
  document.body.classList.toggle('hide-controls', hideControls);
  controlsButton.hidden = !touch;
  controlsButton.textContent = hideControls ? 'Show controls' : 'Hide controls';
  fitCanvas();
}
controlsButton.addEventListener('click', () => {
  hideControls = !hideControls;
  try { localStorage.setItem('ps2web-hide-controls', hideControls ? '1' : '0'); } catch (e) {}
  updateControls();
});

function fitCanvas() {
  if (guestRoom) return;
  const ratio = Math.min(window.devicePixelRatio || 1, 2);
  const width = Math.max(1, Math.round(canvas.clientWidth * ratio));
  const height = Math.max(1, Math.round(canvas.clientHeight * ratio));
  if (canvas.width !== width || canvas.height !== height) {
    canvas.width = width;
    canvas.height = height;
    if (Module.running && Module._ps2web_resize) Module._ps2web_resize(width, height);
  }
}
window.addEventListener('resize', fitCanvas);

const fullscreenButton = document.getElementById('fullscreen');
const root = document.documentElement;
const requestFullscreen = root.requestFullscreen || root.webkitRequestFullscreen;
const exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen;
const nativeFullscreen = () => document.fullscreenElement || document.webkitFullscreenElement;
let fullscreen = false;
function setFullscreen(on) {
  fullscreen = on;
  document.body.classList.toggle('fullscreen', on);
  fullscreenButton.textContent = on ? 'Exit fullscreen' : 'Fullscreen';
  fitCanvas();
}
function toggleFullscreen() {
  if (fullscreen) {
    if (nativeFullscreen() && exitFullscreen) exitFullscreen.call(document);
    setFullscreen(false);
    return;
  }
  setFullscreen(true);
  if (!requestFullscreen) return;
  const result = requestFullscreen.call(root, { navigationUI: 'hide' });
  if (result && result.then) {
    result.then(() => {
      if (document.body.classList.contains('touch') && screen.orientation && screen.orientation.lock) screen.orientation.lock('landscape').catch(() => {});
    }).catch(() => {});
  }
}
function onFullscreenChange() {
  if (!nativeFullscreen() && fullscreen && requestFullscreen) setFullscreen(false);
  else fitCanvas();
}
document.addEventListener('fullscreenchange', onFullscreenChange);
document.addEventListener('webkitfullscreenchange', onFullscreenChange);
fullscreenButton.addEventListener('click', toggleFullscreen);
document.getElementById('exit-fullscreen').addEventListener('click', toggleFullscreen);
canvas.addEventListener('dblclick', toggleFullscreen);
window.addEventListener('keydown', (e) => {
  if (e.code !== 'KeyF' || e.repeat || e.target.tagName === 'SELECT') return;
  e.preventDefault();
  toggleFullscreen();
});

const workletSource = `
class Output extends AudioWorkletProcessor {
  constructor(options) {
    super();
    const { buffer, base } = options.processorOptions;
    this.ring = new Uint32Array(buffer, base, 4);
    this.capacity = this.ring[2];
    this.samples = new Int16Array(buffer, base + 16, this.capacity * 2);
    this.left = 0;
    this.right = 0;
  }
  process(inputs, outputs) {
    const left = outputs[0][0], right = outputs[0][1];
    const write = Atomics.load(this.ring, 0), mask = this.capacity - 1;
    let read = Atomics.load(this.ring, 1);
    for (let i = 0; i < left.length; ++i) {
      if (read !== write) {
        const at = (read & mask) * 2;
        this.left = this.samples[at] / 32768;
        this.right = this.samples[at + 1] / 32768;
        read = (read + 1) >>> 0;
      } else {
        this.left *= 0.995;
        this.right *= 0.995;
      }
      left[i] = this.left;
      right[i] = this.right;
    }
    Atomics.store(this.ring, 1, read);
    Atomics.store(this.ring, 3, 1);
    return true;
  }
}
registerProcessor('ps2-output', Output);`;

let audio = null, node = null;
async function startAudio() {
  audio = new AudioContext({ sampleRate: 48000, latencyHint: 'interactive' });
  await audio.audioWorklet.addModule(URL.createObjectURL(new Blob([workletSource], { type: 'application/javascript' })));
  node = new AudioWorkletNode(audio, 'ps2-output', {
    outputChannelCount: [2],
    processorOptions: { buffer: Module.HEAPU8.buffer, base: Module._ps2web_audio_ring() },
  });
  node.connect(audio.destination);
}

const keys = new Set();
const keyMap = { ArrowUp: 4, ArrowRight: 5, ArrowDown: 6, ArrowLeft: 7, KeyZ: 14, KeyX: 13, KeyA: 15, KeyS: 12,
                 KeyQ: 10, KeyW: 11, Digit1: 8, Digit2: 9, Enter: 3, Backspace: 0 };
const stickKeys = new Set(['KeyI', 'KeyJ', 'KeyK', 'KeyL']);
window.addEventListener('keydown', (e) => { if (e.code in keyMap || stickKeys.has(e.code)) { keys.add(e.code); e.preventDefault(); } });
window.addEventListener('keyup', (e) => { keys.delete(e.code); });
const padButtons = [[0, 14], [1, 13], [2, 15], [3, 12], [4, 10], [5, 11], [6, 8], [7, 9], [8, 0], [9, 3], [10, 1], [11, 2],
                    [12, 4], [13, 6], [14, 7], [15, 5]];
const axis = (v) => Math.max(0, Math.min(255, Math.round((v + 1) * 127.5)));
// the keyboard and touch controls are player 1 along with the first gamepad, a second gamepad is player 2
const players = [0, 1].map(() => ({ plugged: false, pad: -1, pressure: '', strong: 0, weak: 0, rumbleAt: 0 }));
const motorStrength = (v) => v < 16 ? 0 : Math.sqrt(v / 255);
function pollPlayer(port, gamepad, own) {
  const player = players[port];
  const plugged = port === 0 || !!gamepad;
  if (plugged !== player.plugged) {
    player.plugged = plugged;
    Module._ps2web_pad_connected(port, plugged ? 1 : 0);
  }
  if (!plugged) return;
  let buttons = 0, lx = 128, ly = 128, rx = 128, ry = 128;
  const pressure = new Array(16).fill(255);
  if (own) {
    buttons |= touchPad.buttons;
    for (const k of keys) if (k in keyMap) buttons |= 1 << keyMap[k];
    if (keys.has('KeyJ')) lx = 0;
    if (keys.has('KeyL')) lx = 255;
    if (keys.has('KeyI')) ly = 0;
    if (keys.has('KeyK')) ly = 255;
    if (touchPad.stick) {
      lx = axis(touchPad.x);
      ly = axis(touchPad.y);
    }
  }
  const full = buttons;
  if (gamepad) {
    for (const [index, bit] of padButtons) {
      const b = gamepad.buttons[index];
      if (!b || !(b.pressed || b.value > 0.05)) continue;
      buttons |= 1 << bit;
      if (!(full & (1 << bit))) pressure[bit] = Math.max(1, Math.round((b.value > 0 ? b.value : 1) * 255));
    }
    if (gamepad.axes.length >= 4) {
      if (lx === 128) lx = axis(gamepad.axes[0]);
      if (ly === 128) ly = axis(gamepad.axes[1]);
      rx = axis(gamepad.axes[2]);
      ry = axis(gamepad.axes[3]);
    }
  }
  const state = buttons + lx * 65536 + ly * 16777216 + rx * 4294967296 + ry * 1099511627776;
  if (state !== player.pad) {
    player.pad = state;
    Module._ps2web_pad(port, buttons, lx, ly, rx, ry);
  }
  const packed = [0, 1, 2, 3].map((i) => pressure[i * 4] | (pressure[i * 4 + 1] << 8) | (pressure[i * 4 + 2] << 16) | (pressure[i * 4 + 3] << 24));
  if (packed.join() !== player.pressure) {
    player.pressure = packed.join();
    Module._ps2web_pressure(port, packed[0], packed[1], packed[2], packed[3]);
  }
  const rumble = Module._ps2web_rumble(port), now = performance.now();
  const strong = motorStrength(rumble >> 8), weak = rumble & 1;
  const actuator = gamepad && gamepad.vibrationActuator;
  if (actuator && (Math.abs(strong - player.strong) > 0.08 || weak !== player.weak || ((strong || weak) && now - player.rumbleAt > 100))) {
    player.strong = strong;
    player.weak = weak;
    player.rumbleAt = now;
    const done = strong || weak ? actuator.playEffect('dual-rumble', { duration: 200, weakMagnitude: weak, strongMagnitude: strong }) : actuator.reset();
    if (done && done.catch) done.catch(() => {});
  }
}
// which gamepad (by its browser index) is player 1, the next connected one is player 2
const padSelect = document.getElementById('pad');
let padChoice = params.get('pad');
if (padChoice === null) {
  try { padChoice = localStorage.getItem('ps2web-pad'); } catch (e) {}
}
padChoice = padChoice || '';
function listPads() {
  const pads = [...(navigator.getGamepads ? navigator.getGamepads() : [])].filter((pad) => pad);
  const options = [['', 'Pad: auto']].concat(pads.map((pad) => [String(pad.index), 'P1: pad ' + (pad.index + 1) + ' ' + pad.id.replace(/\s*\(.*$/, '').slice(0, 24)]));
  if (padChoice && !pads.some((pad) => String(pad.index) === padChoice)) options.push([padChoice, 'P1: pad ' + (Number(padChoice) + 1) + ' (not connected)']);
  padSelect.replaceChildren(...options.map(([value, text]) => new Option(text, value)));
  padSelect.value = padChoice;
}
padSelect.addEventListener('change', () => {
  padChoice = padSelect.value;
  try { localStorage.setItem('ps2web-pad', padChoice); } catch (e) {}
});
window.addEventListener('gamepadconnected', listPads);
window.addEventListener('gamepaddisconnected', listPads);
listPads();
function orderedPads() {
  const pads = [...(navigator.getGamepads ? navigator.getGamepads() : [])].filter((pad) => pad);
  const chosen = pads.findIndex((pad) => String(pad.index) === padChoice);
  if (chosen > 0) pads.unshift(pads.splice(chosen, 1)[0]);
  return pads;
}
function pollInput() {
  const pads = orderedPads();
  pollPlayer(0, pads[0] || null, true);
  if (remotePlayer && performance.now() - remoteSeen > 3000) (guestLeaves.get(remotePlayer) || releaseRemote)(remotePlayer);
  if (!remotePlayer) pollPlayer(1, pads[1] || null, false);
}

const rtcConfig = { iceServers: [{ urls: ['stun:stun.cloudflare.com:3478', 'stun:stun.l.google.com:19302'] }] };
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function roomSend(code, to, message) {
  const r = await fetch('room/' + code + '/' + to, { method: 'POST', body: JSON.stringify(message) });
  if (!r.ok) throw new Error(r.status === 404 ? 'Room ' + code + ' does not exist any more.' : 'The room server answered ' + r.status + '.');
}
async function* roomMessages(code, me) {
  let after = 0;
  for (;;) {
    let r;
    try {
      r = await fetch('room/' + code + '/' + me + '?after=' + after, { cache: 'no-store' });
    } catch (e) {
      await sleep(2000);
      continue;
    }
    if (r.status === 404) return;
    if (!r.ok) {
      await sleep(2000);
      continue;
    }
    const data = await r.json();
    after = data.next;
    yield* data.messages;
  }
}
function gathered(pc) {
  if (pc.iceGatheringState === 'complete') return Promise.resolve();
  return new Promise((resolve) => {
    pc.addEventListener('icegatheringstatechange', () => { if (pc.iceGatheringState === 'complete') resolve(); });
    setTimeout(resolve, 3000);
  });
}

const inviteButton = document.getElementById('invite');
let room = null, hostStream = null, remotePlayer = null, remoteSeen = 0;
const guestLeaves = new Map();
function inviteLink() {
  const url = new URL(location.href);
  url.search = '?join=' + room;
  return url.href;
}
function copyInvite() {
  const link = inviteLink();
  const copied = navigator.clipboard ? navigator.clipboard.writeText(link) : Promise.reject(new Error('no clipboard'));
  copied.then(() => note('Invite link copied: ' + link), () => note('Invite link: ' + link));
}
let streamShape = 4 / 3;
function streamTrack() {
  if (typeof MediaStreamTrackGenerator !== 'function' || typeof VideoFrame !== 'function') {
    const track = canvas.captureStream(60).getVideoTracks()[0];
    track.contentHint = 'motion';
    streamShape = canvas.width / canvas.height;
    return track;
  }
  const generator = new MediaStreamTrackGenerator({ kind: 'video' });
  const writer = generator.writable.getWriter();
  let busy = false;
  Module.onStreamFrame = (pixels, width, height) => {
    if (busy) return;
    busy = true;
    const frame = new VideoFrame(pixels.slice(), { format: 'RGBA', codedWidth: width, codedHeight: height, timestamp: Math.round(performance.now() * 1000) });
    writer.write(frame).then(() => { busy = false; }, () => { busy = false; });
  };
  Module._ps2web_stream(1);
  generator.contentHint = 'motion';
  streamShape = aspect === '16:9' ? 16 / 9 : 4 / 3;
  return generator;
}
inviteButton.addEventListener('click', async () => {
  if (room) {
    copyInvite();
    return;
  }
  inviteButton.disabled = true;
  try {
    const r = await fetch('room', { method: 'POST' });
    if (!r.ok) throw new Error('This server cannot make rooms. Serve the page with scripts/serve.py.');
    room = (await r.json()).room;
    const sound = audio.createMediaStreamDestination();
    node.connect(sound);
    hostStream = new MediaStream([streamTrack(), ...sound.stream.getAudioTracks()]);
    inviteButton.textContent = 'Room ' + room;
    inviteButton.title = 'Copy the invite link again';
    copyInvite();
    hostRoom(room);
  } catch (error) {
    room = null;
    note(error.message);
  }
  inviteButton.disabled = false;
});
async function hostRoom(code) {
  const guests = new Map();
  for await (const m of roomMessages(code, 'host')) {
    if (m.type === 'join' && typeof m.from === 'string' && !guests.has(m.from)) acceptGuest(code, m.from, guests).catch((e) => console.warn('[room] ' + e));
    else if (m.type === 'answer' && guests.has(m.from)) guests.get(m.from).setRemoteDescription({ type: 'answer', sdp: m.sdp }).catch((e) => console.warn('[room] ' + e));
  }
  note('Room ' + code + ' has closed.');
}
async function acceptGuest(code, id, guests) {
  const pc = new RTCPeerConnection(rtcConfig);
  guests.set(id, pc);
  for (const track of hostStream.getTracks()) pc.addTrack(track, hostStream);
  const channel = pc.createDataChannel('pad', { ordered: false, maxRetransmits: 0 });
  const leave = () => {
    guests.delete(id);
    guestLeaves.delete(id);
    pc.close();
    releaseRemote(id);
  };
  guestLeaves.set(id, leave);
  channel.onmessage = (e) => remoteInput(id, e.data);
  channel.onclose = leave;
  pc.addEventListener('connectionstatechange', () => {
    if (pc.connectionState === 'connected') {
      for (const sender of pc.getSenders()) {
        if (!sender.track || sender.track.kind !== 'video') continue;
        const parameters = sender.getParameters();
        if (!parameters.encodings || !parameters.encodings.length) parameters.encodings = [{}];
        parameters.encodings[0].maxBitrate = 8000000;
        parameters.encodings[0].maxFramerate = 60;
        parameters.degradationPreference = 'maintain-resolution';
        sender.setParameters(parameters).catch(() => {});
      }
    }
    if (pc.connectionState === 'failed' || pc.connectionState === 'closed') leave();
  });
  await pc.setLocalDescription(await pc.createOffer());
  await gathered(pc);
  await roomSend(code, id, { type: 'offer', sdp: pc.localDescription.sdp, shape: streamShape });
}
function remoteInput(id, data) {
  if (remotePlayer && remotePlayer !== id) return;
  let m;
  try {
    m = JSON.parse(data);
  } catch (e) {
    return;
  }
  remoteSeen = performance.now();
  if (!remotePlayer) {
    remotePlayer = id;
    players[1].plugged = true;
    Module._ps2web_pad_connected(1, 1);
    note('Player 2 joined');
  }
  Module._ps2web_pad(1, m.b, m.lx, m.ly, m.rx, m.ry);
  if (Array.isArray(m.p)) Module._ps2web_pressure(1, m.p[0], m.p[1], m.p[2], m.p[3]);
}
function releaseRemote(id) {
  if (remotePlayer !== id) return;
  remotePlayer = null;
  Object.assign(players[1], { plugged: false, pad: -1, pressure: '' });
  Module._ps2web_pad_connected(1, 0);
  note('Player 2 left');
}

let guestShape = 4 / 3;
function fitRemote() {
  const video = document.body.classList.contains('frames') ? canvas : document.getElementById('remote'), stage = document.getElementById('stage');
  let width = stage.clientWidth, height = width / guestShape;
  if (height > stage.clientHeight) {
    height = stage.clientHeight;
    width = height * guestShape;
  }
  video.style.width = Math.floor(width) + 'px';
  video.style.height = Math.floor(height) + 'px';
}
async function drawFrames(track) {
  document.body.classList.add('frames');
  fitRemote();
  const reader = new MediaStreamTrackProcessor({ track }).readable.getReader();
  const context = canvas.getContext('2d', { alpha: false });
  let image = null, copyFrames = true;
  for (;;) {
    const { value: frame, done } = await reader.read();
    if (done) return;
    try {
      const width = frame.displayWidth, height = frame.displayHeight;
      if (!image || image.width !== width || image.height !== height) {
        image = new ImageData(width, height);
        canvas.width = width;
        canvas.height = height;
      }
      if (copyFrames) {
        try {
          await frame.copyTo(image.data, { format: 'RGBA', colorSpace: 'srgb' });
          context.putImageData(image, 0, 0);
          continue;
        } catch (e) {
          copyFrames = false;
        }
      }
      context.drawImage(frame, 0, 0);
    } catch (e) {
      console.warn('[room] ' + e);
    } finally {
      frame.close();
    }
  }
}
async function startGuest() {
  window.addEventListener('resize', fitRemote);
  statusEl.textContent = 'Joining room ' + guestRoom + '…';
  const id = Math.random().toString(36).slice(2, 12);
  const video = document.getElementById('remote');
  const pc = new RTCPeerConnection(rtcConfig);
  let channel = null;
  const sent = { b: 0, lx: 128, ly: 128, rx: 128, ry: 128, p: [-1, -1, -1, -1] };
  Object.assign(Module, {
    _ps2web_pad_connected: () => {},
    _ps2web_pad: (port, b, lx, ly, rx, ry) => Object.assign(sent, { b, lx, ly, rx, ry }),
    _ps2web_pressure: (port, a, b, c, d) => { sent.p = [a, b, c, d]; },
    _ps2web_rumble: () => 0,
  });
  const sound = new Audio();
  pc.ontrack = (e) => {
    if (typeof MediaStreamTrackProcessor === 'function') {
      if (e.track.kind === 'video') drawFrames(e.track);
      else {
        sound.srcObject = new MediaStream([e.track]);
        sound.play().catch(() => {});
      }
      return;
    }
    if (video.srcObject === e.streams[0]) return;
    video.muted = true;
    video.srcObject = e.streams[0];
    video.play().catch(() => {});
    const unmute = () => {
      video.muted = false;
      video.play().catch(() => {});
      window.removeEventListener('pointerdown', unmute, true);
      window.removeEventListener('keydown', unmute, true);
    };
    window.addEventListener('pointerdown', unmute, true);
    window.addEventListener('keydown', unmute, true);
  };
  pc.ondatachannel = (e) => { channel = e.channel; };
  pc.addEventListener('connectionstatechange', () => {
    if (pc.connectionState === 'connected') statusEl.textContent = 'Playing as player 2 in room ' + guestRoom;
    else if (pc.connectionState === 'failed') statusEl.textContent = 'Could not reach the host. Your networks may need a relay (TURN) server between them.';
    else if (pc.connectionState === 'closed' || pc.connectionState === 'disconnected') statusEl.textContent = 'Lost the host.';
  });
  const send = () => {
    pollPlayer(0, orderedPads()[0] || null, true);
    if (channel && channel.readyState === 'open') channel.send(JSON.stringify(sent));
    requestAnimationFrame(send);
  };
  requestAnimationFrame(send);
  try {
    const messages = roomMessages(guestRoom, id);
    await roomSend(guestRoom, 'host', { type: 'join', from: id });
    for await (const m of messages) {
      if (m.type !== 'offer') continue;
      if (m.shape > 0) guestShape = m.shape;
      document.body.classList.toggle('wide', guestShape > 1.5);
      fitRemote();
      await pc.setRemoteDescription({ type: 'offer', sdp: m.sdp });
      await pc.setLocalDescription(await pc.createAnswer());
      await gathered(pc);
      await roomSend(guestRoom, 'host', { type: 'answer', from: id, sdp: pc.localDescription.sdp });
      return;
    }
    statusEl.textContent = 'Room ' + guestRoom + ' does not exist any more.';
  } catch (error) {
    statusEl.textContent = error.message;
  }
}

// some browsers cannot show a canvas drawn by another GPU (hybrid laptops on Linux), so each adapter draws a few test frames first
async function canPresent(power) {
  const adapter = await navigator.gpu.requestAdapter({ powerPreference: power });
  if (!adapter) return null;
  const device = await adapter.requestDevice();
  let failed = false;
  device.lost.then((info) => {
    if (info.reason === 'destroyed') return;
    failed = true;
    console.warn('[gpu check] ' + power + ' device lost: ' + info.message);
  });
  device.onuncapturederror = (e) => {
    failed = true;
    console.warn('[gpu check] ' + power + ': ' + e.error.message);
  };
  const probe = document.createElement('canvas');
  probe.width = probe.height = 64;
  probe.style.cssText = 'position:fixed;left:0;top:0;width:2px;height:2px;opacity:0.01;pointer-events:none';
  document.body.appendChild(probe);
  try {
    const context = probe.getContext('webgpu');
    context.configure({ device, format: navigator.gpu.getPreferredCanvasFormat(), alphaMode: 'opaque' });
    for (let i = 0; i < 3 && !failed; ++i) {
      const encoder = device.createCommandEncoder();
      encoder.beginRenderPass({ colorAttachments: [{ view: context.getCurrentTexture().createView(), loadOp: 'clear', storeOp: 'store', clearValue: [0, 0, 0, 1] }] }).end();
      device.queue.submit([encoder.finish()]);
      await new Promise((resolve) => requestAnimationFrame(resolve));
      await device.queue.onSubmittedWorkDone();
    }
  } catch (e) {
    failed = true;
    console.warn('[gpu check] ' + power + ': ' + e);
  }
  probe.remove();
  const name = [adapter.info.vendor, adapter.info.architecture].filter(Boolean).join(' ') || power;
  device.destroy();
  return failed ? null : name;
}

function webgpuHelp(onCpu) {
  const firefox = navigator.userAgent.includes('Firefox/');
  const linux = navigator.userAgent.includes('Linux') && !navigator.userAgent.includes('Android');
  if (firefox) return 'WebGPU is turned off in this Firefox, so the game runs on the slow software renderer. Set dom.webgpu.enabled to true in about:config and reload.';
  if (linux && onCpu) return 'WebGPU runs on the CPU here, so the game is slow. Turn on chrome://flags/#enable-vulkan as well, then restart the browser.';
  if (linux) return 'WebGPU is turned off in this browser, so the game runs on the slow software renderer. Turn on chrome://flags/#enable-unsafe-webgpu and chrome://flags/#enable-vulkan, then restart the browser.';
  return 'This browser has no WebGPU, so the game runs on the slow software renderer. A current Chrome, Edge or Safari is much faster.';
}

async function chooseGpu() {
  if (!navigator.gpu) {
    Module.gpuHelp = webgpuHelp(false);
    return 'WebGPU unavailable, software renderer';
  }
  const adapter = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' });
  if (!adapter) {
    Module.gpuHelp = webgpuHelp(false);
    return 'WebGPU has no adapter, software renderer';
  }
  if (adapter.info.isFallbackAdapter || adapter.info.architecture === 'swiftshader') Module.gpuHelp = webgpuHelp(true);
  if (navigator.userAgent.includes('Firefox/')) {
    Module.presentCopy = true;
    return 'Firefox, frames copied to the page';
  }
  const forced = params.get('gpu');
  if (forced !== 'low') {
    const name = await canPresent('high-performance');
    if (name) return 'GPU ' + name;
  }
  const name = await canPresent('low-power');
  if (name) {
    Module.ENV.PS2_GPU_LOW_POWER = '1';
    return 'GPU ' + name;
  }
  Module.presentCopy = true;
  return 'GPU cannot draw to the page, copying frames';
}

let frames = 0, last = performance.now(), lastGpu = 0, lastEmuIdle = 0, lastRenderIdle = 0, lastVuIdle = 0, lastInterpreted = 0;
let shown = 0, fresh = false;
const countShown = () => {
  if (fresh) ++shown;
  fresh = false;
  requestAnimationFrame(countShown);
};
requestAnimationFrame(countShown);
var Module = {
  canvas,
  arguments: ['/game/core.elf'].concat(params.has('arg') ? ['--arg', params.get('arg')] : [], aspect === '16:9' ? ['--widescreen'] : [], params.getAll('press').flatMap((p) => p.split(',').flatMap((x) => ['--press', x]))),
  discUrl: params.get('disc') || 'disc.iso',
  stateUrl: params.get('state'),
  noSurface: params.has('nosurface'),
  noCard: params.has('nocard'),
  presentCopy: params.has('copy'),
  onHalt: (reason) => {
    if (statePending) {
      statePending.reject(new Error('The game stopped before the operation completed.'));
      statePending = null;
    }
    clearTimeout(noteTimer);
    noteTimer = 0;
    statusEl.textContent = 'Halted: ' + reason;
    statusEl.style.color = '#f66';
  },
  onQuickState: (loading, success) => {
    if (!statePending || statePending.loading !== loading) return;
    const { resolve, reject } = statePending;
    statePending = null;
    if (success) resolve();
    else reject(new Error(loading ? 'Quick load failed. Reload the player to continue safely.' : 'Could not capture the game. Your previous quick save is unchanged.'));
  },
  refreshVideoControls: () => {
    const available = Module.videoEffectsAvailable ?? (!!navigator.gpu && !Module.gpuHelp && !Module.presentCopy && !Module.noSurface);
    aaInput.disabled = !available;
    aaLabel.title = available ? 'Smooth jagged edges, applied immediately' : 'Antialiasing needs direct WebGPU presentation';
    applyVideo();
  },
  print: (text) => console.log(text),
  printErr: (text) => console.log(text),
  setStatus: (text) => {
    if (!text || Module.gpuInfo) return;
    const progress = text.match(/^Downloading data\.\.\. \((\d+)\/\d+\)/);
    statusEl.textContent = progress ? 'Downloading game data, ' + (Number(progress[1]) / 1048576).toFixed(1) + ' MB unpacked' : text;
  },
  onRuntimeInitialized: () => {
    const start = document.getElementById('start');
    if (missing.length) return;
    start.disabled = false;
    start.textContent = 'Start';
  },
  preRun: [() => {
    if (!Module.noCard) {
      try {
        FS.mkdir(CARD_DIR);
        FS.mount(IDBFS, {}, CARD_DIR);
        Module.addRunDependency('card');
        FS.syncfs(true, (err) => {
          if (err) console.warn('memory card: could not read browser storage', err);
          Module.removeRunDependency('card');
        });
      } catch (e) {
        console.warn('memory card: browser storage is not available', e);
      }
    }
    for (const [key, value] of params) if (key.startsWith('PS2_')) Module.ENV[key] = value;
    Module.ENV.PS2_SCALE = scale;
    Module.addRunDependency('disc');
    Promise.all([fetch(Module.discUrl, { method: 'HEAD' }), chooseGpu().catch((e) => 'GPU check failed: ' + e)]).then(([r, gpu]) => {
      Module.discSize = Number(r.headers.get('content-length')) || 0;
      Module.gpuInfo = gpu;
      if (Module.gpuHelp && !missing.length) {
        const help = document.getElementById('help');
        help.textContent = Module.gpuHelp;
        help.hidden = false;
      }
      statusEl.textContent = (Module.discSize ? 'Disc ' + (Module.discSize / 1073741824).toFixed(2) + ' GB' : 'No disc image at ' + Module.discUrl) + ', ' + gpu;
      Module.removeRunDependency('disc');
    });
  }],
  audioQueuedMs: () => Module._ps2web_audio_queued_ms(),
  ps2CardSaved: () => storeCard(),
  onFrame: () => {
    pollInput();
    ++frames;
    fresh = true;
    const now = performance.now();
    if (now - last >= 1000) {
      const gpu = Module._ps2web_gpu_ms();
      const memory = (Module.HEAPU8.length / 1048576).toFixed(0);
      const emuIdle = Module._ps2web_idle_ms(0), renderIdle = Module._ps2web_idle_ms(1), vuIdle = Module._ps2web_idle_ms(2), span = now - last;
      const interpreted = Module._ps2web_vu_interpreted();
      statsEl.textContent = 'frame ' + Module._ps2web_frames() + '   ' + (frames * 1000 / span).toFixed(1) + ' fps (' + (shown * 1000 / span).toFixed(0) + ' on screen)   GPU ' + ((gpu - lastGpu) / span * 100).toFixed(0) +
                            '%   idle emu ' + ((emuIdle - lastEmuIdle) / span * 100).toFixed(0) + '% vu ' + ((vuIdle - lastVuIdle) / span * 100).toFixed(0) +
                            '% gs ' + ((renderIdle - lastRenderIdle) / span * 100).toFixed(0) +
                            '%   heap ' + memory + ' MB   audio ' + Module.audioQueuedMs().toFixed(0) + ' ms' +
                            (interpreted > lastInterpreted ? '   vu1 interpreted ' + Math.round((interpreted - lastInterpreted) * 1000 / span) + '/s' : '');
      if (statsLog) console.log('[stats] ' + statsEl.textContent.replace(/\s+/g, ' '));
      lastInterpreted = interpreted;
      lastEmuIdle = emuIdle;
      lastRenderIdle = renderIdle;
      lastVuIdle = vuIdle;
      lastGpu = gpu;
      frames = 0;
      shown = 0;
      last = now;
    }
  },
  noInitialRun: true,
};

updateControls();
if (missing.length) {
  const help = document.getElementById('help');
  help.textContent = 'This browser cannot run the game yet. It lacks ' + missing.join(', ') + '. A current Chrome or Edge has everything it needs.';
  help.hidden = false;
  document.getElementById('start').textContent = 'Unsupported browser';
}

if (guestRoom) {
  const start = document.getElementById('start');
  start.disabled = false;
  start.textContent = 'Join room ' + guestRoom;
  statusEl.textContent = 'Invited to room ' + guestRoom;
}

document.getElementById('start').addEventListener('click', async () => {
  document.getElementById('overlay').remove();
  if (guestRoom) {
    startGuest();
    return;
  }
  canvas.focus();
  fitCanvas();
  await startAudio();
  statusEl.textContent = 'Running, ' + Module.gpuInfo;
  Module.running = true;
  setStateBusy(false);
  inviteButton.disabled = false;
  Module.callMain(Module.arguments);
});

if (!guestRoom) {
  const engine = document.createElement('script');
  engine.src = document.getElementById('engine').content.querySelector('script').getAttribute('src');
  engine.async = true;
  document.body.appendChild(engine);
}
</script>
</body>
</html>