-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwasm.js
107 lines (88 loc) · 2.75 KB
/
wasm.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
function handleOnline(msg) {
updateOverlay(true, msg);
if (globalThis.onlineFunc) {
globalThis.onlineFunc();
}
}
function handleOffline(msg) {
updateOverlay(false, msg);
if (globalThis.offlineFunc) {
globalThis.offlineFunc();
}
}
async function loadWasm() {
const go = new Go(); // Defined in wasm_exec.js
// Show the loading overlay and apply the background effects
updateOverlay(false, "Loading...");
// Initialize the environment variables
globalThis.go_env = {};
// Define the pause and resume functions
globalThis.offlineFunc = function () {
console.log("Not implemented: offlineFunc");
};
globalThis.onlineFunc = function () {
console.log("Not implemented: onlineFunc");
};
try {
// Load and instantiate the WebAssembly module
const wasmModule = await WebAssembly.instantiateStreaming(
fetch("main.wasm"),
go.importObject
);
// Change overlay text to "Running..."
updateOverlay(true, "Game loaded. Running...");
// Introduce a small delay to ensure the DOM is updated before running the Wasm module
await new Promise((resolve) => setTimeout(resolve, 100)); // 100ms delay
// Run the WebAssembly module
go.run(wasmModule.instance);
} catch (error) {
console.error("Failed to load WASM module:", error);
handleOffline("Failed to load game. Check your connection and try again.");
return;
}
const worker = new Worker("health-worker.js");
worker.onmessage = function (e) {
switch (e.data.type) {
case "offline":
handleOffline("Game server is down. Waiting for connection...");
break;
case "online":
handleOnline("Game server is up. Resuming...");
break;
}
worker.postMessage({ type: "ack" });
};
worker.postMessage({ type: "start" });
}
function updateOverlay(activate, msg) {
const overlay = document.getElementById("loadingOverlay");
const overlayText = document.getElementById("loadingMessage");
overlayText.innerText = msg;
if (activate) {
overlay.classList.add("hidden");
overlay.classList.remove("active");
} else {
overlay.classList.add("active");
overlay.classList.remove("hidden");
}
}
window.addEventListener("load", loadWasm);
window.addEventListener("online", () => {
handleOnline("Connection restored. Resuming...");
});
window.addEventListener("offline", () => {
handleOffline("Connection lost. Waiting for connection...");
});
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("service-worker.js").then(
(registration) => {
console.log(
"ServiceWorker registration successful with scope: ",
registration.scope
);
},
(error) => {
console.log("ServiceWorker registration failed: ", error);
}
);
}