Skip to content

Commit

Permalink
feat: optimize file loading in WASM
Browse files Browse the repository at this point in the history
  • Loading branch information
BigJk committed Aug 31, 2024
1 parent 1c4ecf2 commit 1604f87
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 2 deletions.
62 changes: 61 additions & 1 deletion cmd/game_wasm/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,65 @@
term.onData((data) => bubbletea_write(data));
}

function ensureAllFiles() {
// Wait for WASM to be loaded
if (!globalThis.version) {
setTimeout(ensureAllFiles, 100);
return;
}

// Clear cache if version mismatch
const lastVersion = globalThis.settings.getString("lastCachedVersion");
if (!lastVersion || lastVersion === "" || globalThis.version !== lastVersion) {
console.log("Clearing file cache due to version mismatch");

const keys = Object.keys(window.localStorage);
for (const key of keys) {
if (key.indexOf("assets") !== -1) {
window.localStorage.removeItem(key);
}
}
}

// Cache files if they don't exist
fetch("./assets/file_index.json")
.then((index) => index.json())
.then((index) => {
const promises = [];
for (const file of index) {
if (!file.isFile) {
continue;
}

// only ensure files that end in .lua or .text
if (!file.path.endsWith(".lua") && !file.path.endsWith(".txt")) {
continue;
}

if (window.fsRead(file.path)) {
continue;
}

promises.push(
fetch(file.path)
.then((response) => response.text())
.then((text) => {
window.fsWrite(file.path, text);
}),
);
}

if (promises.length === 0) {
return;
}

Promise.all(promises).then(() => {
console.log("All files loaded");
globalThis.settings.set("lastCachedVersion", globalThis.version);
});
});
}

function init() {
const go = new Go();
WebAssembly.instantiateStreaming(fetch("./eoe.wasm"), go.importObject).then((result) => {
Expand All @@ -206,10 +265,11 @@
});

// Init terminal. This should be done after bubbletea is initialized. For now, I use a timeout.
document.fonts.load((globalThis.settings.getInt("font_size") ?? 14) + 'px "IosevkaTermNerdFontMono"').then(() => initTerminal());
document.fonts.load((globalThis.settings.getInt("font_size") ?? 12) + 'px "IosevkaTermNerdFontMono"').then(() => initTerminal());
});
}

ensureAllFiles();
init();
</script>
</body>
Expand Down
6 changes: 5 additions & 1 deletion internal/fs/fs_js.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,16 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/samber/lo"
"io"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"syscall/js"

"github.com/BigJk/end_of_eden/internal/git"
"github.com/samber/lo"
)

type noOpWriteCloser struct{}
Expand Down Expand Up @@ -51,6 +53,8 @@ func init() {
}
return nil
}))

js.Global().Set("version", git.Tag)
}

func ReadDir(path string) ([]FileInfo, error) {
Expand Down

0 comments on commit 1604f87

Please sign in to comment.