Skip to content

Commit

Permalink
Emscripten: Add FWAD file lump support
Browse files Browse the repository at this point in the history
* Make Asyncify toggleable by NOASYNCIFY
* Miscellaneous shell improvements
  • Loading branch information
mazmazz committed Jun 2, 2020
1 parent 85507ac commit f9c1a52
Show file tree
Hide file tree
Showing 5 changed files with 126 additions and 13 deletions.
68 changes: 64 additions & 4 deletions srb2.html
Original file line number Diff line number Diff line change
Expand Up @@ -474,12 +474,18 @@
};

var StartLoad = async () => {
// TODO multiple binaries
ActiveVersion = '{{{ PACKAGE_VERSION }}}';

SaveFormToStorage(ControlsFormElement);
window.removeEventListener('focus', CheckVersion, false);
await UXInstallProgram(false); // hides the UI
await GetWasm();
var script = document.createElement('script');
script.setAttribute('src','./srb2.js');
//let scriptSrc = await GetJs(ActiveVersion);
//let scriptSrc = `data/${ActiveVersion}/srb2.js?v={{{ VERSION }}}`;
let scriptSrc = 'srb2.js';
let script = document.createElement('script');
script.setAttribute('src',scriptSrc);
document.head.appendChild(script);
document.body.classList.add('calledRun');
};
Expand Down Expand Up @@ -696,7 +702,7 @@
console.log(`SRB2 Program Version: {{{ PACKAGE_VERSION }}}`);
if (data.trim() && data.trim() !== "{{{ PACKAGE_VERSION }}}") {
console.log(`New Program Version Found: ${data}`);
alert(`SRB2 Version ${data} is released! The game will be updated when you ${userAgentIsMobile() ? 'tap' : 'click'} "Play".`);
alert(`SRB2 Version ${data} is released! The game will be updated when you ${UserAgentIsMobile() ? 'tap' : 'click'} "Play".`);
localStorage.setItem('srb2program_update', (1).toString());
}
})
Expand Down Expand Up @@ -912,6 +918,21 @@
// Files are listed as [fullPath]: {timestamp, mode, contents}
if (typeof deletePath === 'undefined')
throw 'DeleteFS: Must specify a path';

if (FS) {
try {
FS.unlink(`${deletePath}`);
} catch (e) {
console.error(`DeleteFS: ${deletePath} - `, e);
}

return SyncFS().then(_ => {
if (typeof callback === 'function')
callback();
if (manageLoop && Module['calledRun'])
ResumeLoop();
});
}

let customStore = new idbKeyval.Store('/home/web_user', 'FILE_DATA', 21);

Expand Down Expand Up @@ -995,6 +1016,8 @@

var CompositeKey = (fn, version) => `data/${version}/${fn}`;

var StripLeadingSeparators = (fn) => fn.replace(/^\/*/, '');

// !!!!!!!!!! OLD, DEPRECATED !!!!!!!!!!
var CheckDownloadFileToFS = (url, destBaseDir) => {
let dependencyId = `download-${GetBasenameFromPath(url)}`;
Expand Down Expand Up @@ -1304,7 +1327,7 @@
alert('Finished install.');
window.location.reload();
} else {
StatusElement.innerText = '';
StatusElement.innerText = 'Loading...';
ProgressElement.value = 0;
}
});
Expand Down Expand Up @@ -1537,6 +1560,20 @@
Module['alive'].fill(true);
};

var GetJs = async (version = '{{{ PACKAGE_VERSION }}}') => {
let customStore = new idbKeyval.Store('SRB2_DATA', 'FILES', 1);
let js = await idbKeyval.get(CompositeKey('srb2.js', version), customStore);
if (!(js instanceof Object) || !('contents' in js) || !js['contents']) {
let msg = 'Runtime Error: Program JS not found!\n\nIf you see this error again, try resetting your program data under Settings > Storage.';
console.log(msg);
alert(msg);
window.location.reload();
} else {
let string = new TextDecoder('utf-8').decode(js['contents']);
return `data:text/javascript;base64,${btoa(string)}`;
}
};

var GetWasm = async (version = '{{{ PACKAGE_VERSION }}}') => {
let customStore = new idbKeyval.Store('SRB2_DATA', 'FILES', 1);
let wasm = await idbKeyval.get(CompositeKey('srb2.wasm', version), customStore);
Expand All @@ -1549,6 +1586,8 @@
Module['wasmBinary'] = wasm['contents'];
};

var ActiveVersion;

var Module = {
arguments: [],

Expand All @@ -1560,6 +1599,11 @@

wasmBinary: null,

StripLeadingSeparators: StripLeadingSeparators,
WriteInstalledFileToFS: WriteInstalledFileToFS,
DeleteInstalledFileFromFS: DeleteInstalledFileFromFS,
PersistentLumpFiles: PersistentLumpFiles,

preRun: [() => {
BuildControlArguments();
BuildUserArguments();
Expand Down Expand Up @@ -1718,6 +1762,22 @@
// Pause/Resume
////////////////////////////////

var SuspendAudioContext = () => {
if ('SDL2' in Module
&& Module['SDL2'] instanceof object
&& 'audioContext' in Module['SDL2']
&& Module['SDL2'].audioContext)
Module['SDL2'].audioContext.suspend();
};

var ResumeAudioContext = () => {
if ('SDL2' in Module
&& Module['SDL2'] instanceof object
&& 'audioContext' in Module['SDL2']
&& Module['SDL2'].audioContext)
Module['SDL2'].audioContext.resume();
};

var PauseLoop = () => {
if (Module['calledRun'])
Module.ccall('pause_loop',
Expand Down
3 changes: 3 additions & 0 deletions src/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,9 @@ NOHS=1
NOOBJDUMP=1
LOWMEMORY=1
FWAD=1
ifndef NOASYNCIFY
HAVE_ASYNCIFY=1
endif
include emscripten/Makefile.cfg
endif

Expand Down
11 changes: 10 additions & 1 deletion src/emscripten/Makefile.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ CXX = em++

OPTS += -DEMSCRIPTEN -DTOUCHINPUTS

ifdef HAVE_ASYNCIFY
OPTS += -DHAVE_ASYNCIFY
else
OPTS += -DNOWIPE
endif

ifdef DEBUGMODE
TOTALMEMORY=101187584
else
Expand All @@ -25,9 +31,12 @@ EMFLAGS = \
-lidbfs.js \
-s EXPORTED_FUNCTIONS='["_main","_change_resolution","_inject_keycode","_inject_text","_pause_loop","_resume_loop","_COM_ImmedExecute"]' \
-s EXTRA_EXPORTED_RUNTIME_METHODS='["ccall"]' \
-s ASYNCIFY=1 \
--shell-file ../srb2.html

ifdef HAVE_ASYNCIFY
EMFLAGS += -s ASYNCIFY=1
endif

# Note about ASYNCIFY:
# To mitigate the performance penalty, it would be ideal to use
# -s ASYNCIFY_IGNORE_INDIRECT or specify a ASYNCIFY_WHITELIST.
Expand Down
9 changes: 1 addition & 8 deletions src/sdl/i_system.c
Original file line number Diff line number Diff line change
Expand Up @@ -2229,11 +2229,7 @@ void I_StartupTimer(void)
void I_Sleep(void)
{
if (cv_sleep.value != -1)
#ifdef __EMSCRIPTEN__
emscripten_sleep(cv_sleep.value);
#else
SDL_Delay(cv_sleep.value);
#endif
}

#ifdef NEWSIGNALHANDLER
Expand Down Expand Up @@ -2327,10 +2323,7 @@ INT32 I_StartupSystem(void)
SDL_version SDLlinked;
SDL_VERSION(&SDLcompiled)
SDL_GetVersion(&SDLlinked);
#ifdef __EMSCRIPTEN__
// Dodges an "unreachable executed" in ASYNCIFY
SDL_SetHint(SDL_HINT_EMSCRIPTEN_ASYNCIFY, "0");
#endif

I_StartupConsole();
I_SetupSignalHandler();
I_OutputMsg("Compiled for SDL version: %d.%d.%d\n",
Expand Down
48 changes: 48 additions & 0 deletions src/w_wad.c
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@
#include <unistd.h>
#endif

#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif

#define ZWAD

#ifdef ZWAD
Expand Down Expand Up @@ -393,6 +397,28 @@ FILE *W_OpenFileLump (UINT16 wad, UINT16 lump)
{
if(!l->handle)
{
#if defined(__EMSCRIPTEN__) && defined(HAVE_ASYNCIFY)
// Retrieve the file from IDB or server
EM_ASM({
// Strip leading path separators
Module['fsDone'] = false;
let fn = Module['StripLeadingSeparators'](UTF8ToString($0));
if (Module['PersistentLumpFiles'].includes(fn))
Module['fsDone'] = true;
else
Module['WriteInstalledFileToFS'](fn, ActiveVersion, true)
.then(_ => { Module['fsDone'] = true; });
}, l->filename);

for(;;)
{
INT32 x = EM_ASM_INT({ return Module['fsDone']; });
if (x)
break;
I_Sleep();
}
#endif

if ((l->handle = fopen(l->filename, "rb")) == NULL)
return NULL;
CONS_Debug(DBG_MEMORY, "W_OpenFileLump: Loaded %s at: %s\n", l->name, l->filename);
Expand All @@ -410,6 +436,28 @@ void W_CloseFileLump (UINT16 wad, UINT16 lump)
fclose((wadfiles[wad]->lumpinfo + lump)->handle);
(wadfiles[wad]->lumpinfo + lump)->handle = 0;
CONS_Debug(DBG_MEMORY, "W_CloseFileLump: Closed %s\n", (wadfiles[wad]->lumpinfo + lump)->name);

#if defined(__EMSCRIPTEN__) && defined(HAVE_ASYNCIFY)
// Delete the file from IDB or server
EM_ASM({
// Strip leading path separators
Module['fsDone'] = false;
let fn = Module['StripLeadingSeparators'](UTF8ToString($0));
if (Module['PersistentLumpFiles'].includes(fn))
Module['fsDone'] = true;
else
Module['DeleteInstalledFileFromFS'](fn, PersistentLumpFiles)
.then(_ => { Module['fsDone'] = true; });
}, (wadfiles[wad]->lumpinfo + lump)->filename);

for(;;)
{
INT32 x = EM_ASM_INT({ return Module['fsDone']; });
if (x)
break;
I_Sleep();
}
#endif
}
}

Expand Down

0 comments on commit f9c1a52

Please sign in to comment.