Save game to indexeddb

This commit is contained in:
Varun Patil 2020-05-05 23:19:00 +05:30
parent 17517a5849
commit ad9474a6e9
5 changed files with 65 additions and 1 deletions

View File

@ -37,6 +37,10 @@
#include "filesystem.h"
#include "binding.h"
#ifdef __EMSCRIPTEN__
#include "emscripten.hpp"
#endif
void mrbBindingTerminate();
MRB_FUNCTION(kernelLoadData)
@ -82,10 +86,23 @@ MRB_FUNCTION(kernelSaveData)
return mrb_nil_value();
}
MRB_FUNCTION(kernelSaveAsync)
{
mrb_value obj;
const char *filename;
mrb_get_args(mrb, "z", &filename);
save_file_async_js(filename);
return mrb_nil_value();
}
void kernelBindingInit(mrb_state *mrb)
{
RClass *module = mrb->kernel_module;
mrb_define_module_function(mrb, module, "load_data", kernelLoadData, MRB_ARGS_REQ(1));
mrb_define_module_function(mrb, module, "save_data", kernelSaveData, MRB_ARGS_REQ(2));
mrb_define_module_function(mrb, module, "save_file_async", kernelSaveAsync, MRB_ARGS_REQ(1));
}

7
js/localforage.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -3,6 +3,8 @@
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="js/localforage.min.js"></script>
<title>MKXP</title>
<style>
body {
@ -100,9 +102,41 @@
</div>
<script type='text/javascript'>
var namespace = 'kne';
window.saveFile = function(filename) {
const buf = FS.readFile('/game/' + filename);
const b64 = btoa(String.fromCharCode.apply(null, buf));
localforage.setItem(namespace + filename, b64);
localforage.getItem(namespace, function(err, res) {
if (err || !res) res = {};
res[filename] = 1;
localforage.setItem(namespace, res);
});
};
var loadFiles = function() {
localforage.getItem(namespace, function(err, res) {
if (err || !res) return;
const keys = Object.keys(res);
console.log('Locally stored savefiles', keys);
keys.forEach((key) => {
localforage.getItem(namespace + key, (err, res) => {
if (err) return;
const buf = new Uint8Array(atob(res).split('').map((c) => c.charCodeAt(0)));
FS.writeFile('/game/' + key, buf);
});
});
});
}
var Module = {
preRun: [],
postRun: [],
postRun: [loadFiles],
print: (function() {
return function(text) {
console.log(text);

View File

@ -59,5 +59,9 @@ void load_file_async(const char * filename) {
shState->fileSystem().openRead(handler, filename);
}
EM_JS(void, save_file_async_js, (const char* fullPathC), {
if (window.saveFile) window.saveFile(UTF8ToString(fullPathC));
});
#endif

View File

@ -8,6 +8,8 @@ extern "C" {
void load_file_async_js(const char* fullPathC);
void load_file_async(const char* filename);
void save_file_async_js(const char* fullPathC);
}
#endif