Archive incari-client (client, 26.3, clean)

This commit is contained in:
2026-11-28 00:54:38 -06:00
parent 7a6174687f
commit 12838e838c
2383 changed files with 280266 additions and 0 deletions
@@ -0,0 +1,79 @@
package incari.app.web;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import incari.classlib.resources.ClassPathResources;
import incari.platform.web.storage.WebFileSystem;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.jspecify.annotations.Nullable;
/**
* The asset pack (ADR 0014): what the build prepares for the game ahead of time, in one zip
* the page mounts read-only at {@value #ROOT}: the translated shaders, and the vanilla sprites
* decoded with their mip levels (ADR 0026). Like the client jar, the storage worker keeps it
* (under its hash, so a new build's pack is fetched once) and it's mounted in place, each file
* inflated when opened.
*
* <p>The pack holds translated Mojang files, so it's made on the machine that builds the game
* ({@code :app-web:assetPack}) and never published.
*
* <p>Its layout: {@code pack.json} ({@code {"format": 1, "game": "26.3"}}), then the files by the
* names the game's loaders read ({@code shaders.json}, {@code sprites.bin}), and under {@value #CLASSPATH} resources
* libraries read from the class path (Via's mapping data).
*/
final class AssetPack {
/** Where the pack's files appear in the page's file system. */
static final String ROOT = "/incari-pack";
/** The pack's directory of class-path resources. */
static final String CLASSPATH = "classpath";
/** The layout this code reads; a pack of another format is refused. */
static final int FORMAT = 1;
private AssetPack() {}
/**
* Mounts the build's pack, if the build manifest names one; suspends while it's fetched.
*
* @return whether a pack is mounted
*/
static boolean mount(WebFileSystem files) throws IOException {
String url = LoaderPage.packUrl();
if (url == null) {
return false;
}
double start = Fetch.now();
WebFileSystem.Mounted mounted = files.mountZip(ROOT, url, cacheKey(url), name -> true);
JsonObject manifest = JsonParser.parseString(
new String(Files.readAllBytes(Path.of(ROOT, "pack.json")), StandardCharsets.UTF_8))
.getAsJsonObject();
int format = manifest.get("format").getAsInt();
String game = manifest.get("game").getAsString();
if (format != FORMAT || !game.equals(ClientJar.VERSION)) {
throw new IOException("The asset pack is format " + format + " for " + game + "; this build reads format "
+ FORMAT + " for " + ClientJar.VERSION);
}
ClassPathResources.addRoot(ROOT + "/" + CLASSPATH);
System.out.println("[Incari] Asset pack: " + mounted.files() + " files, "
+ (mounted.cached() ? "from storage" : "downloaded") + ", in " + Math.round(Fetch.now() - start)
+ " ms");
return true;
}
/** A file of the mounted pack, or null if there's no pack or it lacks the file. */
static byte @Nullable [] read(String name) throws IOException {
Path file = Path.of(ROOT, name);
return Files.isRegularFile(file) ? Files.readAllBytes(file) : null;
}
/** The storage key: the pack's version (its URL's {@code ?v=}), so each build's is kept apart. */
static String cacheKey(String url) {
int version = url.indexOf("?v=");
return "pack-" + (version < 0 ? "unversioned" : url.substring(version + 3));
}
}
@@ -0,0 +1,42 @@
package incari.app.web;
import incari.classlib.resources.ClassPathResources;
import incari.client.IncariBuild;
import incari.platform.web.storage.WebFileSystem;
import java.io.IOException;
/**
* Puts the client jar's resources where the game looks for them ({@link ClassPathResources}):
* the build compiles the game's classes but not the rest of the jar, which is Mojang's to
* distribute. The page fetches the jar the player's machine already has; for development that's
* the one {@code ./incari setup} downloaded, which {@code :app-web:serve} offers at {@value #URL}.
*
* <p>The jar isn't unpacked: the storage worker keeps it (so later loads don't fetch
* it again), and it's mounted read-only in place, each resource inflated when the game opens it.
* Its bytes stay in the page, outside the game's heap (ADR 0011).
*/
final class ClientJar {
static final String URL = "client.jar";
/**
* The game version the jar is, which names its cached copy: a new version's replaces it. From
* incari.properties, so a version bump can't leave players on a stale cached jar.
*/
static final String VERSION = IncariBuild.MINECRAFT_VERSION;
private ClientJar() {}
/** Mounts every resource that isn't a class or jar metadata; suspends while it's fetched. */
static void mount(WebFileSystem files) throws IOException {
double start = Fetch.now();
WebFileSystem.Mounted mounted = files.mountZip(
ClassPathResources.ROOT,
URL,
"client-" + VERSION + ".jar",
name -> !name.endsWith(".class") && !name.startsWith("META-INF/"));
System.out.println("[Incari] Client jar: " + mounted.files() + " resources mounted, "
+ (mounted.cached() ? "from storage" : "downloaded") + ", in " + Math.round(Fetch.now() - start)
+ " ms");
}
}
@@ -0,0 +1,155 @@
package incari.app.web;
import java.io.IOException;
import java.util.List;
import org.jspecify.annotations.Nullable;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.ArrayBuffer;
import org.teavm.jso.typedarrays.Int8Array;
/** Downloads files from next to the page: before the game starts, and for its resource reloads. */
final class Fetch {
private Fetch() {}
/**
* The whole file at {@code url}. Suspends the calling coroutine until the download finishes:
* must not block the page.
*
* @param hint what to check if it fails, for the error message
*/
static byte[] bytes(String url, String hint) throws IOException {
Outcome outcome = fetch(url);
ArrayBuffer buffer = outcome.buffer();
if (buffer == null) {
throw new IOException("Couldn't fetch " + url + ": " + outcome.error() + " (" + hint + ")");
}
return new Int8Array(buffer).copyToJavaArray();
}
/**
* The whole file at {@code url}, tried up to {@code attempts} times while it fails for a reason
* that may pass (no connection, a server error, too many requests), waiting longer each time.
* Suspends the calling thread: never the page's own.
*
* @param hint what to check if it fails, for the error message
*/
static byte[] bytesRetrying(String url, String hint, int attempts) throws IOException {
for (int attempt = 1; ; attempt++) {
Outcome outcome = fetch(url);
ArrayBuffer buffer = outcome.buffer();
if (buffer != null) {
return new Int8Array(buffer).copyToJavaArray();
}
String error = String.valueOf(outcome.error());
if (attempt >= attempts || !passing(error)) {
throw new IOException("Couldn't fetch " + url + ": " + error + " (" + hint + ")");
}
try {
Thread.sleep(500L * attempt);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted fetching " + url, e);
}
}
}
/** Whether a fetch's failure may pass: anything but a 4xx answer, except time-outs and rate limits. */
static boolean passing(String error) {
if (!error.startsWith("Error: HTTP 4")) {
return true;
}
return error.equals("Error: HTTP 408") || error.equals("Error: HTTP 429");
}
/**
* The whole files at {@code urls}, in their order, downloaded side by side. Suspends the calling
* coroutine until all have finished: must not block the page.
*
* @param hint what to check if one fails, for the error message
*/
static byte[][] all(List<String> urls, String hint) throws IOException {
Outcome[] outcomes = fetchAll(urls.toArray(String[]::new));
byte[][] files = new byte[outcomes.length][];
for (int i = 0; i < outcomes.length; i++) {
ArrayBuffer buffer = outcomes[i].buffer();
if (buffer == null) {
throw new IOException("Couldn't fetch " + urls.get(i) + ": " + outcomes[i].error() + " (" + hint + ")");
}
files[i] = new Int8Array(buffer).copyToJavaArray();
}
return files;
}
/**
* A download's contents, or why it failed. A failure comes back as a value and is thrown here, not
* through {@code AsyncCallback.error}: TeaVM's WebAssembly GC runtime rethrows an error it
* resumes with out of the JavaScript callback as well, after the caller has caught it, and the
* page crashes on the unhandled rejection (probe: {@code app-web/probes/FetchFailureProbe}).
*/
private record Outcome(
@Nullable ArrayBuffer buffer, @Nullable String error) {}
@Async
private static native Outcome fetch(String url);
private static void fetch(String url, AsyncCallback<Outcome> callback) {
start(
url,
buffer -> callback.complete(new Outcome(buffer, null)),
message -> callback.complete(new Outcome(null, message)));
}
@Async
private static native Outcome[] fetchAll(String[] urls);
private static void fetchAll(String[] urls, AsyncCallback<Outcome[]> callback) {
Outcome[] outcomes = new Outcome[urls.length];
if (urls.length == 0) {
callback.complete(outcomes);
return;
}
int[] left = {urls.length};
for (int i = 0; i < urls.length; i++) {
int index = i;
start(
urls[i],
buffer -> {
outcomes[index] = new Outcome(buffer, null);
if (--left[0] == 0) {
callback.complete(outcomes);
}
},
message -> {
outcomes[index] = new Outcome(null, message);
if (--left[0] == 0) {
callback.complete(outcomes);
}
});
}
}
@JSFunctor
interface Done extends JSObject {
void done(ArrayBuffer buffer);
}
@JSFunctor
interface Failed extends JSObject {
void failed(String message);
}
@JSBody(
params = {"url", "done", "failed"},
script = "fetch(url).then(function(r) {"
+ " if (!r.ok) throw new Error('HTTP ' + r.status); return r.arrayBuffer(); })"
+ ".then(function(b) { done(b); }, function(e) { failed(String(e)); });")
private static native void start(String url, Done done, Failed failed);
@JSBody(script = "return performance.now();")
static native double now();
}
@@ -0,0 +1,137 @@
package incari.app.web;
import incari.classlib.concurrent.Waits;
import incari.classlib.resources.ClassPathResources;
import incari.client.datafix.DataFixing;
import incari.client.memory.LightCopies;
import incari.client.net.PacketHandoff;
import incari.client.net.PlatformEventLoopGroupHolder;
import incari.client.singleplayer.ChannelLink;
import incari.client.singleplayer.WorldWorker;
import incari.client.startup.CriterionCodecs;
import incari.client.world.BiomeCells;
import incari.client.world.ChunkCompression;
import incari.client.world.Collisions;
import incari.client.world.DensityBranches;
import incari.client.world.GoalFlags;
import incari.client.world.Heights;
import incari.client.world.PositionalRandoms;
import incari.client.world.RemoteTerrain;
import incari.client.world.SpawnCosts;
import incari.client.world.StrongholdRings;
import incari.client.world.SurfaceBuffers;
import incari.client.world.SurfaceWrites;
import incari.platform.api.Platforms;
import incari.platform.web.WebPlatform;
import incari.platform.web.WorkerPlatform;
import incari.platform.web.storage.WebFileSystem;
import java.io.IOException;
import java.util.List;
import org.teavm.jso.JSBody;
import org.teavm.jso.typedarrays.ArrayBuffer;
/**
* The entry point of a copy of the game in a worker (ADR 0039): {@code WebMain.main(["--worker",
* role])}, as {@code game-worker.ts} starts it. It sets up what the role needs and nothing of the
* client: a file system of its own (filled by the page), the client jar's resources, the headless
* platform, and the settings the page makes that the server's code reads too.
*/
final class GameWorkerMain {
/** Where the page's storage worker keeps the client jar, from the private file system's root. */
private static final String CACHED_JAR = ".incari-cache/client-" + ClientJar.VERSION + ".jar";
private GameWorkerMain() {}
/** {@code query}: the page's query string, for the page options read here too. */
static void main(String role, String query) throws IOException {
LibraryDefaults.apply();
// A background pool task that blocks gives the pool up, as on the page.
Waits.beforeWait(WebPlatform::beforeWait);
WebFileSystem files = WebFileSystem.installDetached(List.of(ClassPathResources.ROOT));
int mounted = mountClientJar(files, !"all".equals(option(query, "workerjar")));
System.out.println("[Incari] Worker (" + role + "): " + mounted + " of the client jar's resources mounted");
Platforms.install(new WorkerPlatform(WebStorage.DEFAULT, files));
PlatformEventLoopGroupHolder.useLocalEventLoops();
// The page's defaults for what the server's code reads as well (WebMain).
DataFixing.buildLazily();
LightCopies.setEnabled(true);
Collisions.setEnabled(true);
PacketHandoff.setEnabled(true);
StrongholdRings.setEnabled(!"game".equals(option(query, "rings")));
SpawnCosts.setEnabled(!"game".equals(option(query, "spawncosts")));
SpawnCosts.setVerify("verify".equals(option(query, "spawncosts")));
SurfaceWrites.setEnabled(!"game".equals(option(query, "surface")));
BiomeCells.setEnabled(!"game".equals(option(query, "biomecells")));
BiomeCells.setVerify("verify".equals(option(query, "biomecells")));
Heights.setEnabled(!"game".equals(option(query, "heights")));
GoalFlags.setEnabled(!"game".equals(option(query, "goalflags")));
DensityBranches.setEnabled(!"game".equals(option(query, "densitychoices")));
RemoteTerrain.setHelpers(terrainHelpers(option(query, "terrainworkers")));
CriterionCodecs.setEnabled(!"game".equals(option(query, "criteria")));
ChunkCompression.setEnabled(!"game".equals(option(query, "deflate")));
PositionalRandoms.setEnabled(!"game".equals(option(query, "randoms")));
SurfaceBuffers.setEnabled(!"game".equals(option(query, "surfacebuffers")));
// ADR 0041's packets a flush per message (?packets=each: one each, as before).
ChannelLink.setBatched(!"each".equals(option(query, "packets")));
switch (role) {
case "server" -> WorldWorker.run();
case "terrain" -> RemoteTerrain.serve();
default -> throw new IllegalArgumentException("No such worker role: " + role);
}
}
/**
* Mounts the client jar's resources a worker reads, and returns how many. A server (or a
* terrain helper) reads the data packs, the language file and the root files (the version, the
* markers that find the vanilla pack's roots), never the client's assets: those stay out, and
* the jar's buffer is let go once they're copied (ADR 0043). {@code ?workerjar=all} mounts
* every resource, as before. The buffer is a local here so that it isn't held for the
* program's life by {@code main}'s frame, which never returns.
*/
private static int mountClientJar(WebFileSystem files, boolean serverOnly) throws IOException {
ArrayBuffer jar = WorkerPlatform.cachedZip(CACHED_JAR, ClientJar.URL);
return files.mountZip(
ClassPathResources.ROOT, jar, serverOnly ? GameWorkerMain::serverResource : GameWorkerMain::resource);
}
/** Every resource of the jar: not a class, not its signature. */
private static boolean resource(String name) {
return !name.endsWith(".class") && !name.startsWith("META-INF/");
}
/** A resource a server reads: the data packs, the languages, and the files at the root. */
private static boolean serverResource(String name) {
return resource(name)
&& (name.startsWith("data/")
|| name.startsWith("assets/minecraft/lang/")
|| name.equals("assets/.mcassetsroot")
|| name.indexOf('/') < 0);
}
/**
* How many terrain helpers singleplayer's server starts (ADR 0042): the page's
* {@code ?terrainworkers=N}, none otherwise. Off by default: no gain was measured where the
* server keeps up, and where the page and the server have two cores between them a helper would
* only take from both.
*/
private static int terrainHelpers(String option) {
if (option.isEmpty()) {
return 0;
}
try {
return Math.min(Integer.parseInt(option), Math.max(1, hardwareConcurrency() - 2));
} catch (NumberFormatException e) {
return 0;
}
}
@JSBody(script = "return (self.navigator && self.navigator.hardwareConcurrency) || 1;")
private static native int hardwareConcurrency();
/** A parameter of the page's query string, or "" if it has none. */
@JSBody(
params = {"query", "name"},
script = "return new URLSearchParams(query).get(name) || '';")
private static native String option(String query, String name);
}
@@ -0,0 +1,49 @@
package incari.app.web;
/**
* Library settings for the page, set as system properties before the libraries read them (they
* read them once, in static initializers).
*
* <p>Netty's buffers (ADR 0008):
*
* <ul>
* <li>{@code io.netty.allocator.type=unpooled}: Netty 4.2's default adaptive allocator can't
* start without method handles ({@code ConcurrentSkipListIntObjMultimap} looks up its own
* fallback through one). Unpooled heap buffers are plain {@code byte[]}, which WebAssembly GC
* allocates cheaply, and a page with one thread gains little from pooling.
* <li>{@code io.netty.noUnsafe=true}: there is no {@code Unsafe}; saying so skips the reflective
* probing and the warning about it. With no cleaner, Netty prefers heap buffers; a direct
* buffer, where a caller asks for one, is TeaVM's, in the module's linear memory.
* <li>{@code io.netty.leakDetection.level=disabled}: leak records capture stack traces and rely
* on reference queues, costly here; leaks are found on the desktop build.
* <li>{@code io.netty.machineId} and {@code io.netty.processId}: what Netty's channel ids
* ({@code DefaultChannelId}) are made from, otherwise found from the network interfaces' MAC
* addresses and the process handle, neither of which a page has. Singleplayer's in-memory
* channels are the first to use them. A fixed machine and process are fine: the ids only
* have to differ within the page, which the counter and the time in each id see to.
* </ul>
*
* <p>JOML: {@code joml.format=false}. JOML's {@code Options} builds a {@code DecimalFormat} from a
* pattern TeaVM's parser rejects (a leading space), which failed the first {@code org.joml.Math}
* call (vertex sorting by distance); without it JOML formats with the locale's number format.
*/
final class LibraryDefaults {
private LibraryDefaults() {}
static void apply() {
setDefault("io.netty.allocator.type", "unpooled");
setDefault("io.netty.noUnsafe", "true");
setDefault("io.netty.leakDetection.level", "disabled");
setDefault("io.netty.machineId", "00:00:00:00:00:00:00:01");
setDefault("io.netty.processId", "1");
setDefault("joml.format", "false");
}
/** Keeps a value set before, so a development page can still choose another. */
private static void setDefault(String key, String value) {
if (System.getProperty(key) == null) {
System.setProperty(key, value);
}
}
}
@@ -0,0 +1,36 @@
package incari.app.web;
import org.jspecify.annotations.Nullable;
import org.teavm.jso.JSBody;
/**
* The host page's loader ({@code src/main/ts/boot.ts}), as the game's start-up sees it: the
* steps it shows under the progress bar, and what the build manifest says about the build. Without
* the loader (an experiment's page), every call does nothing.
*/
final class LoaderPage {
private LoaderPage() {}
/** Shows a start-up step on the loading screen, and logs it. */
static void status(String text) {
System.out.println("[Incari] Loading: " + text);
show(text);
}
@JSBody(params = "text", script = "var loader = window.incariLoader; if (loader) loader.status(text);")
private static native void show(String text);
/** The asset pack's URL (versioned by its hash) from the build manifest, or null if the build has none. */
@JSBody(script = "var build = window.incariBuild; return build && build.pack ? build.pack : null;")
static native @Nullable String packUrl();
/**
* The build's id from the build manifest (a hash over its files), or null without a manifest or
* for a development build, whose id names no particular files.
*/
@JSBody(
script = "var build = window.incariBuild;"
+ " return build && build.id && build.id !== 'development' ? build.id : null;")
static native @Nullable String buildId();
}
@@ -0,0 +1,165 @@
package incari.app.web;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import incari.client.audio.RemoteSounds;
import incari.client.resources.RemoteAssets;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The game's files from the asset index, laid out by name under the assets directory (the layout
* the game reads when it's given no {@code --assetIndex}), where the vanilla pack finds them.
*
* <p>The index is hundreds of megabytes, so little is downloaded up front. At start: the sound list
* ({@code sounds.json}), the pack's metadata ({@code pack.mcmeta}, which lists the languages and
* is read before the first reload) and the built-in packs' zips (ADR 0055). The sounds get an empty placeholder each, so the game knows they
* exist, and {@link RemoteSounds} fetches one the first time it plays (ADR 0013). The
* Unicode font and the selected language are fetched by {@link RemoteAssets} before
* each resource reload that reads them (ADR 0037). The page gets all of it from next to itself: the
* index at {@value #INDEX_URL} and its objects under {@value #OBJECTS_URL}, which the dev server
* serves from {@code ./incari assets}' download and {@code ./incari build} copies into its folder.
*
* <p>Not the launcher's layout with an index: the game reads that through its own link file
* system, which TeaVM's {@code java.nio.file} can't walk.
*/
final class WebAssets {
static final String INDEX_URL = "asset-index.json";
static final String OBJECTS_URL = "assets/objects/";
/** Fetched before the game starts, because it reads them while loading. */
private static final List<String> AT_START = List.of("minecraft/sounds.json", "pack.mcmeta");
/**
* The built-in packs (Programmer Art, High Contrast; 0.7 MB), fetched at start too: the pack
* repository lists them once, before the first reload (ADR 0055).
*/
private static final List<String> BUILT_IN_PACKS = List.of("minecraft/resourcepacks/");
/** Tries for each sound's download before it plays silent (and is asked for again later). */
private static final int SOUND_ATTEMPTS = 3;
private static final String HINT = "is the dev server serving the assets?";
private WebAssets() {}
/**
* Stores the files read at start and a placeholder for every sound, and installs the fetchers
* for the rest. Without an asset index the page runs silent and in
* English only.
*/
static void install(String assetsDirectory) {
double start = Fetch.now();
byte[] indexFile;
try {
indexFile = Fetch.bytes(INDEX_URL, "has ./incari assets downloaded the asset index?");
} catch (IOException e) {
System.out.println("[Incari] No asset index, so no sounds: " + e.getMessage());
return;
}
try {
File root = new File(assetsDirectory);
JsonObject objects = JsonParser.parseString(new String(indexFile, StandardCharsets.UTF_8))
.getAsJsonObject()
.getAsJsonObject("objects");
Map<String, String> sounds = new HashMap<>();
Map<String, String> others = new HashMap<>();
for (Map.Entry<String, JsonElement> entry : objects.entrySet()) {
String name = entry.getKey();
String hash = entry.getValue().getAsJsonObject().get("hash").getAsString();
if (name.endsWith(".ogg")) {
sounds.put(name, hash);
File placeholder = new File(root, name);
if (!placeholder.exists()) {
write(placeholder, new byte[0]);
}
} else {
others.put(name, hash);
}
}
Index index = new Index(root, others);
index.fetch(AT_START);
try {
index.fetch(BUILT_IN_PACKS);
} catch (IOException e) {
// Sounds and languages still work; the Resource Packs screen lists no built-in packs.
System.out.println("[Incari] No built-in resource packs: " + e.getMessage());
}
RemoteSounds.install(name -> {
String hash = sounds.get(name);
// A sound fetched as it first plays meets whatever the network is doing then.
return hash == null ? null : Fetch.bytesRetrying(objectUrl(hash), HINT, SOUND_ATTEMPTS);
});
RemoteAssets.install(index::fetch);
System.out.println("[Incari] Assets: " + sounds.size() + " sounds listed in "
+ Math.round(Fetch.now() - start) + " ms");
} catch (IOException | RuntimeException e) {
System.out.println("[Incari] Couldn't set up the assets, so no sounds: " + e);
}
}
/** The index's files other than sounds, written under {@code root} as they're fetched. */
private record Index(File root, Map<String, String> hashes) {
/**
* Downloads, side by side, each of {@code assets} (names, or folders ending in {@code /})
* that isn't written yet, and writes it. Suspends the calling coroutine: the entry point at
* start, a background thread before a reload.
*/
void fetch(List<String> assets) throws IOException {
double start = Fetch.now();
List<String> names = new ArrayList<>();
List<String> urls = new ArrayList<>();
for (Map.Entry<String, String> entry : hashes.entrySet()) {
String name = entry.getKey();
if (wanted(assets, name) && !new File(root, name).exists()) {
names.add(name);
urls.add(objectUrl(entry.getValue()));
}
}
if (names.isEmpty()) {
return;
}
byte[][] files = Fetch.all(urls, HINT);
long bytes = 0;
for (int i = 0; i < files.length; i++) {
write(new File(root, names.get(i)), files[i]);
bytes += files[i].length;
}
System.out.println("[Incari] Assets: fetched " + names.size() + " files (" + bytes / 1024 + " KB) in "
+ Math.round(Fetch.now() - start) + " ms");
}
private static boolean wanted(List<String> assets, String name) {
for (String asset : assets) {
if (asset.endsWith("/") ? name.startsWith(asset) : name.equals(asset)) {
return true;
}
}
return false;
}
}
private static String objectUrl(String hash) {
return OBJECTS_URL + hash.substring(0, 2) + "/" + hash;
}
private static void write(File file, byte[] contents) throws IOException {
File parent = file.getParentFile();
if (parent != null && !parent.isDirectory() && !parent.mkdirs()) {
throw new IOException("Can't create " + parent);
}
try (OutputStream out = new FileOutputStream(file)) {
out.write(contents);
}
}
}
@@ -0,0 +1,39 @@
package incari.app.web;
import incari.client.credits.Credit;
import incari.client.credits.Credits;
import java.net.URI;
/**
* What the browser build contains that the desktop doesn't, for the credits screen: TeaVM's
* runtime and class library, ThreeTen Backport, which TeaVM maps {@code java.time} onto, and JZlib,
* the deflate engine under TeaVM's zip classes. All are compiled into the build's WebAssembly.
*/
final class WebCredits {
private WebCredits() {}
static void install() {
Credits.add(new Credit(
"TeaVM",
null,
"Alexey Andreev and contributors",
"Apache-2.0",
Credits.APACHE_2,
URI.create("https://github.com/konsoletyper/teavm")));
Credits.add(new Credit(
"ThreeTen Backport",
null,
"Stephen Colebourne and Michael Nascimento Santos",
"BSD-3-Clause",
Credits.BSD_3_CLAUSE,
URI.create("https://github.com/ThreeTen/threetenbp")));
Credits.add(new Credit(
"JZlib",
null,
"ymnk, JCraft, Inc.",
"BSD-3-Clause",
Credits.BSD_3_CLAUSE,
URI.create("https://github.com/ymnk/jzlib")));
}
}
@@ -0,0 +1,388 @@
package incari.app.web;
import com.mojang.renderpearl.api.device.GpuBackend;
import incari.app.web.headless.HeadlessBackend;
import incari.classlib.concurrent.Waits;
import incari.classlib.resources.ClassPathResources;
import incari.client.TickPacing;
import incari.client.datafix.DataFixing;
import incari.client.gui.HudCache;
import incari.client.memory.LightCopies;
import incari.client.memory.PackedUnihex;
import incari.client.modules.IncariModules;
import incari.client.net.PacketHandoff;
import incari.client.net.PlatformEventLoopGroupHolder;
import incari.client.online.IncariOnline;
import incari.client.online.UpdateNotice;
import incari.client.particle.AmbientParticles;
import incari.client.particle.ParticleBudget;
import incari.client.particle.ParticleInstancing;
import incari.client.particle.ParticleLight;
import incari.client.platform.GraphicsBackends;
import incari.client.platform.OnlineServices;
import incari.client.profile.PlayerName;
import incari.client.profiler.Profiling;
import incari.client.render.AnimatedSprites;
import incari.client.render.EntityOcclusion;
import incari.client.render.GlyphQuads;
import incari.client.render.GraphUpdates;
import incari.client.render.QuadSort;
import incari.client.render.SignLines;
import incari.client.render.SpriteCache;
import incari.client.render.TerrainVertexFormat;
import incari.client.render.TextLayouts;
import incari.client.render.TintBlend;
import incari.client.render.VertexMath;
import incari.client.render.entity.ModelBatches;
import incari.client.render.entity.OpaqueSkins;
import incari.client.render.mesher.ChestBaking;
import incari.client.render.mesher.MeshTableCache;
import incari.client.render.mesher.Meshing;
import incari.client.render.terrain.TerrainDrawLists;
import incari.client.singleplayer.ChannelLink;
import incari.client.singleplayer.QuickWorlds;
import incari.client.singleplayer.WorkerWorlds;
import incari.client.startup.CriterionCodecs;
import incari.client.startup.DeferredModels;
import incari.client.startup.LoadingFade;
import incari.client.tier.DeviceTier;
import incari.client.world.BiomeCells;
import incari.client.world.ChunkCompression;
import incari.client.world.Collisions;
import incari.client.world.DensityBranches;
import incari.client.world.GoalFlags;
import incari.client.world.Heights;
import incari.client.world.PositionalRandoms;
import incari.client.world.SpawnCosts;
import incari.client.world.StrongholdRings;
import incari.client.world.SurfaceBuffers;
import incari.client.world.SurfaceWrites;
import incari.platform.api.Platforms;
import incari.platform.web.WebPlatform;
import incari.platform.web.storage.WebFileSystem;
import incari.render.webgl2.WebGl2Backend;
import incari.render.webgl2.shaders.ShaderManifest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.teavm.jso.JSBody;
/**
* The browser build's entry point: opens the stored files ({@link WebFileSystem}), mounts the
* client jar ({@link ClientJar}) and asset pack ({@link AssetPack}), loads the translated shaders
* ({@link WebShaders}), installs {@link WebPlatform} and the WebGL2 backend, then starts the
* game's {@code Main}. Each step shows on the loading screen ({@link LoaderPage}).
*
* <p>Page options, for development:
*
* <ul>
* <li>{@code ?renderer=headless}: run without drawing.
* <li>{@code ?shaders=eager}: link every WebGL program at start-up, so all compile errors show
* at once.
* <li>{@code ?server=ws://...}: join that server once started. {@code ?name=...}: the offline
* name.
* <li>{@code ?world=<name>}: open that singleplayer world; with {@code &seed=<seed>}, create it
* first (the singleplayer benchmark).
* <li>{@code ?share=<relay>}: share the open world on that relay. {@code ?shared=<relay>|<code>}:
* join a shared world (ADR 0062).
* <li>{@code ?options=<file>}: start with that options file from beside the page (the
* screenshot diffs pin their options this way).
* <li>{@code ?profile}: collect frame measurements from the start, for the benchmark.
* {@code ?overlay}: show the profiler's overlay.
* <li>{@code ?drawcensus}: log each pipeline's draws a frame every 600 frames.
* {@code ?gpucensus}: the same for GPU time.
* <li>{@code ?tier=potato|standard|high}: the device tier budgets scale by (particles, largest
* atlas, terrain heaps, decoded sounds). Standard is the default.
* <li>{@code ?mesher=inline|vanilla|verify}: mesh terrain on the page's thread, with the game's
* compiler, or both and compare, instead of in Incari's workers.
* </ul>
*
* <p>To compare an Incari change with the game's own way:
*
* <ul>
* <li>Memory and start-up: {@code ?text=game} (lay out world text every frame),
* {@code ?quads=game}, {@code ?copies=all} (keep a copy of every WebGL buffer),
* {@code ?models=now} (load models before the title screen), {@code ?sprites=off} (decode
* every sprite).
* <li>{@code ?multidraw=off}: one draw per terrain section, not WEBGL_multi_draw (ADR 0022).
* <li>ADR 0027: {@code ?uniforms=each} (upload each uniform write alone), {@code ?rebase=off}
* (move the vertex attributes for each base vertex).
* <li>ADR 0030: {@code ?sort=game}, {@code ?tint=game}, {@code ?items=game} (no instancing),
* {@code ?skins=game}, {@code ?drawlists=game}, {@code ?faces=all} (draw back faces),
* {@code ?animations=all} (animate unseen sprites), {@code ?hud=live} (draw the HUD every
* frame), {@code ?chests=game} (closed chests as block entities).
* <li>ADR 0031: {@code ?ambient=game}, {@code ?glyphs=game}, {@code ?signs=game} (submit blank
* lines), {@code ?graph=game} (full occlusion update at once), {@code ?particlelight=frame}
* (read particle light every frame).
* </ul>
*/
public final class WebMain {
/** The background pool's least share of a frame while it has work (ADR 0035). */
private static final double DEFAULT_POOL_FLOOR_MILLIS = 4.0;
private WebMain() {}
public static void main(String[] args) throws IOException {
if (args.length >= 2 && args[0].equals("--worker")) {
// A copy of the game in a worker (ADR 0039): singleplayer's server, never the client.
// The page's query comes third, for the page options the server's code reads too.
GameWorkerMain.main(args[1], args.length > 2 ? args[2] : "");
return;
}
// Before any library reads them: Netty and JOML read their settings once, at class load.
LibraryDefaults.apply();
// This thread becomes the game's render thread: its waits hold back the page's frame, so
// they're timed for the frame monitor.
Waits.watch(Thread.currentThread());
// A background pool task that blocks gives the pool up, so what it waits for can run.
Waits.beforeWait(WebPlatform::beforeWait);
// Before anything touches a file. Dropped files, the jar's resources and the sound
// placeholders (rewritten from the asset index on every load) are never stored.
LoaderPage.status("Opening saved files");
WebFileSystem files = WebFileSystem.install(List.of(
WebPlatform.DROP_DIRECTORY,
ClassPathResources.ROOT,
AssetPack.ROOT,
WebStorage.DEFAULT.assetsDirectory()));
LoaderPage.status("Loading game files");
ClientJar.mount(files);
LoaderPage.status("Loading textures");
boolean pack = AssetPack.mount(files);
if (pack && !"off".equals(option("sprites"))) {
// The vanilla sprites the build decoded, with their mip levels (ADR 0026).
SpriteCache.install(Path.of(AssetPack.ROOT, "sprites.bin"));
}
LoaderPage.status("Loading sounds");
WebAssets.install(WebStorage.DEFAULT.assetsDirectory());
Platforms.install(new WebPlatform(WebStorage.DEFAULT, files));
WebCredits.install();
// Realms is stripped from the browser build (tools/survey/rules.txt).
OnlineServices.disableRealms();
// Nor does it call Mojang's other services: no discovery, profile, key or telemetry requests.
OnlineServices.disableMojang();
// No sockets, so no selector for Netty's event loops to wait on (ADR 0008).
PlatformEventLoopGroupHolder.useLocalEventLoops();
// Terrain meshing (ADR 0023): Incari's mesher in Web Workers, writing the compact
// terrain vertex. ?mesher=inline meshes on the page's thread instead; ?mesher=vanilla uses
// the game's compiler and vertex format; ?mesher=verify meshes both ways and compares.
String mesher = option("mesher");
switch (mesher) {
case "vanilla" -> Meshing.configure(Meshing.Mode.VANILLA, false);
case "verify" -> Meshing.configure(Meshing.Mode.VERIFY, false);
default -> {
TerrainVertexFormat.useCompact();
Meshing.configure(Meshing.Mode.INCARI, !"inline".equals(mesher));
// Translucent layers in an order that holds from every camera are never re-sorted
// (ADR 0034); ?resort=game sorts them all as the game does.
Meshing.setFixedOrder(!"game".equals(option("resort")));
// Snapshots read each section's copied blocks directly (ADR 0034);
// ?snapshotreads=game reads them a block at a time through the region.
Meshing.setDirectReads(!"game".equals(option("snapshotreads")));
// The mesher's tables kept from start to start (ADR 0032); ?meshtables=build builds
// them every time.
String build = LoaderPage.buildId();
if (build != null && !"build".equals(option("meshtables"))) {
MeshTableCache.enable(Path.of("/incari/cache/mesher-tables.bin"), build);
}
// Closed chests meshed into terrain (ADR 0030); ?chests=game draws them the game's way.
if (!"game".equals(option("chests"))) {
ChestBaking.enable();
}
}
}
// Entities, particles and text (ADR 0024): ?entityculling=off draws entities no visible
// section holds, and ?instancing=off entity models the game's way, to compare; ?particles=potato,
// standard or high picks the particle cap whatever the device's tier.
EntityOcclusion.setEnabled(!"off".equals(option("entityculling")));
if (!"off".equals(option("instancing")) && !"headless".equals(option("renderer"))) {
ModelBatches.enable();
// Particles too (ADR 0032); ?particlequads=game builds their vertices as the game does.
if (!"game".equals(option("particlequads"))) {
ParticleInstancing.enable();
}
}
// The device's tier (not yet picked from the device): ?tier=potato, standard (the default) or high.
DeviceTier tier = DeviceTier.named(option("tier"));
DeviceTier.set(tier == null ? DeviceTier.STANDARD : tier);
ParticleBudget.setTier(DeviceTier.named(option("particles")));
// The memory diet (ADR 0025): the data fixer is built only if something old arrives.
DataFixing.buildLazily();
// Start-up (ADR 0026): the loading screen fades in half a second, not two, and the
// title screen shows before the block, item and entity models are loaded.
LoadingFade.set(250);
if (!"now".equals(option("models"))) {
DeferredModels.enable();
}
// The memory diet's reuse of world text and its baked-quad writer: ?text=game and
// ?quads=game take the game's own paths, to compare.
TextLayouts.setEnabled(!"game".equals(option("text")));
VertexMath.setQuadsEnabled(!"game".equals(option("quads")));
// ADR 0027's changes, each with the game's (or ADR 0025's) way to compare.
QuadSort.setEnabled(!"game".equals(option("sort")));
ModelBatches.setItemsEnabled(!"game".equals(option("items")));
OpaqueSkins.setEnabled(!"game".equals(option("skins")));
TintBlend.setEnabled(!"game".equals(option("tint")));
// ADR 0030's terrain draw list and sprite animation, each with the game's way to compare.
TerrainDrawLists.setEnabled(!"game".equals(option("drawlists")));
TerrainDrawLists.setFacingCulling(!"all".equals(option("faces")));
AnimatedSprites.setEnabled(!"all".equals(option("animations")));
HudCache.setEnabled(!"live".equals(option("hud")));
// Development: ?modules=minimap,coordinates (or all) turns those modules on at start.
if (!option("modules").isEmpty()) {
IncariModules.startWith(Arrays.asList(option("modules").split(",")));
}
// ADR 0031's changes, each with the game's way to compare.
AmbientParticles.setEnabled(!"game".equals(option("ambient")));
GlyphQuads.setEnabled(!"game".equals(option("glyphs")));
SignLines.setEnabled(!"game".equals(option("signs")));
GraphUpdates.setEnabled(!"game".equals(option("graph")));
ParticleLight.setAcrossFrames(!"frame".equals(option("particlelight")));
// ADR 0032's catch-up ticks spread over frames; ?ticks=game runs them back to back.
TickPacing.setEnabled(!"game".equals(option("ticks")));
// The background pool's least share of a frame while it has work (ADR 0035);
// ?poolfloor=<ms> to compare, 1 being the old minimum.
String poolFloor = option("poolfloor");
WebPlatform.setPoolFloor(poolFloor.isEmpty() ? DEFAULT_POOL_FLOOR_MILLIS : Double.parseDouble(poolFloor));
Collisions.setEnabled(!"game".equals(option("collisions")));
// Singleplayer's server on the page (?singleplayer=page); the worker reads the same options.
StrongholdRings.setEnabled(!"game".equals(option("rings")));
SpawnCosts.setEnabled(!"game".equals(option("spawncosts")));
SpawnCosts.setVerify("verify".equals(option("spawncosts")));
// ADR 0041's world generation and loading changes, each with the game's way to compare.
SurfaceWrites.setEnabled(!"game".equals(option("surface")));
BiomeCells.setEnabled(!"game".equals(option("biomecells")));
BiomeCells.setVerify("verify".equals(option("biomecells")));
Heights.setEnabled(!"game".equals(option("heights")));
CriterionCodecs.setEnabled(!"game".equals(option("criteria")));
// Saved chunks deflated at zlib's fastest level (?deflate=game: its default).
ChunkCompression.setEnabled(!"game".equals(option("deflate")));
// The surface rules' positional randoms drawn without making them (?randoms=game: made).
PositionalRandoms.setEnabled(!"game".equals(option("randoms")));
SurfaceBuffers.setEnabled(!"game".equals(option("surfacebuffers")));
// The Unicode font's glyphs packed into arrays (?unihex=game: an object each, as the game keeps them).
PackedUnihex.setEnabled(!"game".equals(option("unihex")));
// ADR 0042's lazy range choices (the server worker reads the same option).
GoalFlags.setEnabled(!"game".equals(option("goalflags")));
DensityBranches.setEnabled(!"game".equals(option("densitychoices")));
// ADR 0041's packets a flush per message (?packets=each: one each, as before).
ChannelLink.setBatched(!"each".equals(option("packets")));
// ADR 0041's region files left in place for the worker (?inplace=off: handed over whole, as before).
WebFileSystem.setInPlaceHandOver(!"off".equals(option("inplace")));
// ADR 0032's light maps brought up to date in place; ?light=game copies them as the game does.
LightCopies.setEnabled(!"game".equals(option("light")));
LightCopies.setVerify("verify".equals(option("light")));
// ADR 0033: packets their handlers only hand to the game's thread queued without the round
// trip; ?handoff=game calls the handler on the network's thread first, as the game does.
PacketHandoff.setEnabled(!"game".equals(option("handoff")));
// ADR 0039: singleplayer's server in a worker; ?singleplayer=page runs it on the page, as ADR 0038 did.
WorkerWorlds.setEnabled(!"page".equals(option("singleplayer")));
WebGl2Backend.uploadEachUniformWrite("each".equals(option("uniforms")));
WebGl2Backend.movePointersForQuadDraws("off".equals(option("rebase")));
// Development: ?drawcensus logs each pipeline's draws a frame to the console.
WebGl2Backend.countDrawsByPipeline(present("drawcensus"));
// Development: ?gpucensus logs each pipeline's GPU time a frame (ADR 0031).
WebGl2Backend.timeDrawsByPipeline(present("gpucensus"));
// ?copies=all: every WebGL buffer keeps the game's copy, as before ADR 0025, to compare.
WebGl2Backend.keepAllCopies("all".equals(option("copies")));
if ("headless".equals(option("renderer"))) {
GraphicsBackends.install(preference -> new GpuBackend[] {new HeadlessBackend()});
GraphicsBackends.setRendering(false);
} else {
ShaderManifest shaders = WebShaders.load(pack);
boolean eager = "eager".equals(option("shaders"));
boolean multiDraw = !"off".equals(option("multidraw"));
GraphicsBackends.install(preference ->
new GpuBackend[] {new WebGl2Backend(WebPlatform.CANVAS_ID, shaders, eager, multiDraw)});
}
if (present("profile")) {
Profiling.collect(true);
}
if (present("overlay")) {
Profiling.showOverlay(true);
}
String options = option("options");
if (!options.isEmpty()) {
// Development: start with these options (the screenshot-diff harness pins its scenes'
// options this way), in place of whatever the game directory holds.
Path gameDirectory = Path.of(WebStorage.DEFAULT.gameDirectory());
Files.createDirectories(gameDirectory);
Files.write(
gameDirectory.resolve("options.txt"), Fetch.bytes(options, "is the page serving " + options + "?"));
}
if (present("online")) {
// Development: Incari accounts against another service (ADR 0058), ?online=ws://localhost:8080/v1/ws;
// ?online= (empty) turns them off.
IncariOnline.useUrl(option("online"));
}
if ("on".equals(option("updates"))) {
// Testing: the title screen's update notice in a dev build too, ?updates=on (with
// ?online= against tools/onlinedev --release <version>).
UpdateNotice.force(true);
}
String name = option("name");
if (!name.isEmpty() || !option("server").isEmpty()) {
// The page names the player, or joins a server straight away: no Edit Profile first.
PlayerName.fixAtLaunch();
}
List<String> arguments = new ArrayList<>(Arrays.asList(new String[] {
"--version",
ClientJar.VERSION,
"--versionType",
"incari-web",
"--gameDir",
WebStorage.DEFAULT.gameDirectory(),
"--assetsDir",
WebStorage.DEFAULT.assetsDirectory(),
"--accessToken",
"0",
// No profile, user property or chat key requests to Mojang (OnlineServices).
"--offlineDeveloperMode",
"--username",
// A first start suggests a name of its own, as Eagler clients do; Edit Profile keeps it.
name.isEmpty() ? PlayerName.suggest(new Random()) : name
}));
String server = option("server");
if (!server.isEmpty()) {
// Straight into a server, as a launcher's quick play does.
arguments.addAll(List.of("--quickPlayMultiplayer", server));
String via = option("via");
if (!via.isEmpty() && !incari.client.net.ServerVersions.setQuickPlay(server, via)) {
System.err.println("Not a Via choice: ?via=" + via + " (off, auto or a release)");
}
}
String world = option("world");
String seed = option("seed");
if (!world.isEmpty() && !seed.isEmpty()) {
// The singleplayer benchmark's world: made from the seed at the title screen, or opened.
QuickWorlds.createAtTitle(world, Long.parseLong(seed));
} else if (!world.isEmpty()) {
arguments.addAll(List.of("--quickPlaySingleplayer", world));
}
String sharedWorld = option("shared");
int bar = sharedWorld.lastIndexOf('|');
if (bar > 0) {
// The shared-world check's guest (ADR 0062): joins a shared world from the title screen.
QuickWorlds.joinSharedAtTitle(sharedWorld.substring(0, bar), sharedWorld.substring(bar + 1));
}
String share = option("share");
if (!share.isEmpty()) {
// The shared-world check's host (ADR 0062): the world shared on this relay once it's open.
incari.client.singleplayer.WorkerWorlds.shareWhenOpen(share);
}
LoaderPage.status("Starting the game");
net.minecraft.client.main.Main.main(arguments.toArray(String[]::new));
}
/** A query parameter of the page's URL, or "" if it has none. */
@JSBody(params = "name", script = "return new URLSearchParams(location.search).get(name) || '';")
private static native String option(String name);
/** Whether the page's URL has a query parameter, with or without a value. */
@JSBody(params = "name", script = "return new URLSearchParams(location.search).has(name);")
private static native boolean present(String name);
}
@@ -0,0 +1,34 @@
package incari.app.web;
import incari.render.webgl2.shaders.ShaderManifest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* The game's shaders as the build translated them for WebGL2 ({@code tools/shaders}). They're
* translated Mojang files, so like the client jar they're kept beside the page, never built into
* it: in the asset pack ({@link AssetPack}), or as the manifest {@code :app-web:shaders} wrote, which
* {@code :app-web:serve} offers at {@value #URL}.
*/
final class WebShaders {
static final String URL = "shaders.json";
private WebShaders() {}
/**
* The translated shaders: from the asset pack if one is mounted, else fetched from beside
* the page, as an experiment's build without a pack has them.
*/
static ShaderManifest load(boolean fromPack) throws IOException {
double start = Fetch.now();
byte[] bytes = fromPack ? AssetPack.read(URL) : null;
if (bytes == null) {
bytes = Fetch.bytes(URL, "is the development server serving the shaders? run ./gradlew :app-web:shaders");
}
ShaderManifest manifest = ShaderManifest.parse(new String(bytes, StandardCharsets.UTF_8));
System.out.println("[Incari] Shaders: " + manifest.stages().size() + " translated stages loaded "
+ (fromPack ? "from the asset pack " : "") + "in " + Math.round(Fetch.now() - start) + " ms");
return manifest;
}
}
@@ -0,0 +1,13 @@
package incari.app.web;
import incari.platform.api.storage.PlatformStorage;
import org.jspecify.annotations.Nullable;
/** Where the browser build keeps its files: under {@code WebFileSystem.ROOT}, which survives a reload. */
record WebStorage(
String gameDirectory,
String assetsDirectory,
@Nullable String assetIndex) implements PlatformStorage {
static final WebStorage DEFAULT = new WebStorage("/incari/game", "/incari/assets", null);
}
@@ -0,0 +1,36 @@
package incari.app.web.headless;
import com.mojang.renderpearl.api.device.GpuBackend;
import com.mojang.renderpearl.api.device.GpuDebugOptions;
import com.mojang.renderpearl.api.device.GpuDevice;
import org.jspecify.annotations.Nullable;
/**
* A graphics backend that draws nothing, for running the game before the browser has a renderer
* (as before the WebGL2 backend existed). Its device accepts every call and keeps no GPU state;
* the entry point also switches the frame's render step off, so the game only ticks.
*/
public final class HeadlessBackend implements GpuBackend {
@Override
public String getName() {
return "Headless";
}
@Override
public void loadLibrary() {}
@Override
public void unloadLibrary() {}
/** The canvas is the window; the handle only has to be non-zero. */
@Override
public long createWindow(@Nullable String title, int width, int height, long flags) {
return 1L;
}
@Override
public GpuDevice createDevice(GpuDebugOptions debugOptions) {
return new HeadlessDevice();
}
}
@@ -0,0 +1,72 @@
package incari.app.web.headless;
import com.mojang.renderpearl.api.buffers.GpuBuffer;
import com.mojang.renderpearl.api.buffers.GpuBufferSlice;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.jspecify.annotations.Nullable;
import org.lwjgl.system.MemoryUtil;
/**
* A buffer as plain memory, allocated when first mapped or written: the game writes uniforms and
* vertices into mapped buffers and sometimes reads them back, so that has to work even with
* nothing to draw. The memory comes from LWJGL's {@code MemoryUtil}, since the game treats mapped
* memory as native ({@code memCopy}, {@code memAddress}); closing frees it.
*/
final class HeadlessBuffer implements GpuBuffer {
private final @GpuBuffer.Usage int usage;
private final long size;
private @Nullable ByteBuffer memory;
private boolean closed;
HeadlessBuffer(@GpuBuffer.Usage int usage, long size) {
this.usage = usage;
this.size = size;
}
@Override
public long size() {
return size;
}
@Override
public @GpuBuffer.Usage int usage() {
return usage;
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public GpuBufferSlice.MappedView map(long offset, long length, boolean read, boolean write) {
ByteBuffer view = memory().duplicate().order(ByteOrder.nativeOrder());
view.limit(Math.toIntExact(offset + length)).position(Math.toIntExact(offset));
return new GpuBufferSlice.MappedView(
slice(offset, length), view.slice().order(ByteOrder.nativeOrder()), () -> {});
}
void write(long offset, ByteBuffer data) {
ByteBuffer target = memory().duplicate();
target.position(Math.toIntExact(offset));
target.put(data.duplicate());
}
private ByteBuffer memory() {
ByteBuffer current = memory;
if (current == null) {
current = MemoryUtil.memCalloc(Math.toIntExact(size)).order(ByteOrder.nativeOrder());
memory = current;
}
return current;
}
@Override
public void close() {
closed = true;
MemoryUtil.memFree(memory);
memory = null;
}
}
@@ -0,0 +1,150 @@
package incari.app.web.headless;
import com.mojang.renderpearl.api.GpuFormat;
import com.mojang.renderpearl.api.buffers.GpuBuffer;
import com.mojang.renderpearl.api.commands.CommandEncoder;
import com.mojang.renderpearl.api.commands.GpuQueryPool;
import com.mojang.renderpearl.api.device.DeviceFeatures;
import com.mojang.renderpearl.api.device.DeviceInfo;
import com.mojang.renderpearl.api.device.DeviceLimits;
import com.mojang.renderpearl.api.device.DeviceType;
import com.mojang.renderpearl.api.device.GpuDevice;
import com.mojang.renderpearl.api.device.GpuSurface;
import com.mojang.renderpearl.api.device.HintsAndWorkarounds;
import com.mojang.renderpearl.api.pipeline.CompiledRenderPipeline;
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
import com.mojang.renderpearl.api.pipeline.ShaderSource;
import com.mojang.renderpearl.api.textures.AddressMode;
import com.mojang.renderpearl.api.textures.FilterMode;
import com.mojang.renderpearl.api.textures.GpuSampler;
import com.mojang.renderpearl.api.textures.GpuTexture;
import com.mojang.renderpearl.api.textures.GpuTextureView;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.OptionalDouble;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.BooleanSupplier;
import java.util.function.Supplier;
import org.jspecify.annotations.Nullable;
/**
* A device with no GPU behind it: textures and samplers are descriptions, buffers are plain memory
* (so mapped writes and reads behave), pipelines "compile" at once, and commands do nothing.
*/
final class HeadlessDevice implements GpuDevice {
private static final DeviceInfo INFO = new DeviceInfo(
"Headless",
"Incari",
"none",
false,
"Headless",
1.0F,
new DeviceLimits(1, 256, 8192, 256L * 1024 * 1024, 0, 8, 0),
new DeviceFeatures(false, false, false, false, false, false, false, false),
Set.of(),
new HintsAndWorkarounds(false, false, false, false),
DeviceType.CPU);
private final CommandEncoder encoder = new HeadlessEncoder();
@Override
public GpuSurface createSurface(long windowHandle, BooleanSupplier isIconified) {
return new HeadlessSurface();
}
@Override
public CommandEncoder createCommandEncoder() {
return encoder;
}
@Override
public GpuSampler createSampler(
AddressMode addressModeU,
AddressMode addressModeV,
FilterMode minFilter,
FilterMode magFilter,
int maxAnisotropy,
OptionalDouble maxLod) {
return new HeadlessSampler(addressModeU, addressModeV, minFilter, magFilter, maxAnisotropy, maxLod);
}
@Override
public GpuTexture createTexture(
@Nullable Supplier<String> label,
@GpuTexture.Usage int usage,
GpuFormat format,
int width,
int height,
int depthOrLayers,
int mipLevels) {
return createTexture(
label == null ? null : label.get(), usage, format, width, height, depthOrLayers, mipLevels);
}
@Override
public GpuTexture createTexture(
@Nullable String label,
@GpuTexture.Usage int usage,
GpuFormat format,
int width,
int height,
int depthOrLayers,
int mipLevels) {
return new HeadlessTexture(label == null ? "" : label, usage, format, width, height, depthOrLayers, mipLevels);
}
@Override
public GpuTextureView createTextureView(GpuTexture texture) {
return new HeadlessTextureView(texture, 0, texture.getMipLevels());
}
@Override
public GpuTextureView createTextureView(GpuTexture texture, int baseMipLevel, int mipLevels) {
return new HeadlessTextureView(texture, baseMipLevel, mipLevels);
}
@Override
public GpuBuffer createBuffer(@Nullable Supplier<String> label, @GpuBuffer.Usage int usage, long size) {
return new HeadlessBuffer(usage, size);
}
@Override
public GpuBuffer createBuffer(@Nullable Supplier<String> label, @GpuBuffer.Usage int usage, ByteBuffer data) {
HeadlessBuffer buffer = new HeadlessBuffer(usage, data.remaining());
buffer.write(0, data);
return buffer;
}
@Override
public List<String> getLastDebugMessages() {
return List.of();
}
@Override
public boolean isDebuggingEnabled() {
return false;
}
@Override
public CompletableFuture<CompiledRenderPipeline.Pending> compilePipeline(
RenderPipeline pipeline, ShaderSource shaderSource, Executor executor) {
CompiledRenderPipeline compiled = new HeadlessPipeline();
return CompletableFuture.completedFuture(() -> compiled);
}
@Override
public void close() {}
@Override
public GpuQueryPool createTimestampQueryPool(int size) {
return new HeadlessQueryPool(size);
}
@Override
public DeviceInfo getDeviceInfo() {
return INFO;
}
}
@@ -0,0 +1,155 @@
package incari.app.web.headless;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.renderpearl.api.buffers.GpuBuffer;
import com.mojang.renderpearl.api.buffers.GpuBufferSlice;
import com.mojang.renderpearl.api.buffers.TransientMemory;
import com.mojang.renderpearl.api.commands.CommandEncoder;
import com.mojang.renderpearl.api.commands.GpuFence;
import com.mojang.renderpearl.api.commands.GpuQueryPool;
import com.mojang.renderpearl.api.commands.RenderPass;
import com.mojang.renderpearl.api.commands.RenderPassDescriptor;
import com.mojang.renderpearl.api.textures.GpuTexture;
import java.nio.ByteBuffer;
import org.joml.Vector4fc;
/**
* Commands that do nothing, except where the game can see the result: buffer writes and copies
* land in {@link HeadlessBuffer} memory, and read-back callbacks run at once.
*/
final class HeadlessEncoder implements CommandEncoder {
private final HeadlessTransientMemory transientMemory = new HeadlessTransientMemory();
@Override
public void submit() {
transientMemory.release();
}
@Override
public TransientMemory transientMemory() {
return transientMemory;
}
@Override
public RenderPass createRenderPass(RenderPassDescriptor descriptor) {
return new HeadlessRenderPass();
}
@Override
public void clearColorTexture(GpuTexture colorTexture, Vector4fc clearColor) {}
@Override
public void clearColorAndDepthTextures(
GpuTexture colorTexture, Vector4fc clearColor, GpuTexture depthTexture, double clearDepth) {}
@Override
public void clearColorAndDepthTextures(
GpuTexture colorTexture,
Vector4fc clearColor,
GpuTexture depthTexture,
double clearDepth,
int regionX,
int regionY,
int regionWidth,
int regionHeight,
int mipLevel) {}
@Override
public void clearDepthTexture(GpuTexture depthTexture, double clearDepth) {}
@Override
public void writeToBuffer(GpuBufferSlice destination, ByteBuffer data) {
if (destination.buffer() instanceof HeadlessBuffer buffer) {
buffer.write(destination.offset(), data);
}
}
@Override
public void copyToBuffer(GpuBufferSlice source, GpuBufferSlice target) {
try (GpuBufferSlice.MappedView from = source.map(true, false)) {
writeToBuffer(target, from.data());
}
}
@Override
public void writeToTexture(GpuTexture destination, NativeImage source) {}
@Override
public void writeToTexture(
GpuTexture destination, NativeImage source, int mipLevel, int depthOrLayer, int destX, int destY) {}
@Override
public void writeToTexture(
GpuTexture destination,
ByteBuffer source,
int mipLevel,
int depthOrLayer,
int destX,
int destY,
int width,
int height) {}
@Override
public void copyBufferToTexture(
GpuBufferSlice source,
int sourceX,
int sourceY,
int sourceWidth,
int sourceHeight,
GpuTexture destination,
int destinationX,
int destinationY,
int copyWidth,
int copyHeight,
int mipLevel,
int arrayLayer) {}
@Override
public void copyTextureToBuffer(
GpuTexture source, GpuBuffer destination, long offset, Runnable callback, int mipLevel) {
callback.run();
}
@Override
public void copyTextureToBuffer(
GpuTexture source,
GpuBuffer destination,
long offset,
Runnable callback,
int mipLevel,
int x,
int y,
int width,
int height) {
callback.run();
}
@Override
public void copyTextureToTexture(
GpuTexture source,
GpuTexture destination,
int mipLevel,
int destX,
int destY,
int sourceX,
int sourceY,
int width,
int height) {}
@Override
public GpuFence createFence() {
return new GpuFence() {
@Override
public void close() {}
@Override
public boolean awaitCompletion(long timeoutNS) {
return true;
}
};
}
@Override
public void writeTimestamp(GpuQueryPool pool, int index) {}
}
@@ -0,0 +1,19 @@
package incari.app.web.headless;
import com.mojang.renderpearl.api.pipeline.CompiledRenderPipeline;
/** A pipeline that "compiled" at once: there are no shaders to run. */
final class HeadlessPipeline implements CompiledRenderPipeline {
private boolean closed;
@Override
public boolean isClosed() {
return closed;
}
@Override
public void close() {
closed = true;
}
}
@@ -0,0 +1,35 @@
package incari.app.web.headless;
import com.mojang.renderpearl.api.commands.GpuQueryPool;
import java.util.Arrays;
import java.util.OptionalLong;
/** Timestamp queries that never get a value: there's no GPU time to measure. */
final class HeadlessQueryPool implements GpuQueryPool {
private final int size;
HeadlessQueryPool(int size) {
this.size = size;
}
@Override
public int size() {
return size;
}
@Override
public OptionalLong getValue(int index) {
return OptionalLong.empty();
}
@Override
public OptionalLong[] getValues(int index, int count) {
OptionalLong[] values = new OptionalLong[count];
Arrays.fill(values, OptionalLong.empty());
return values;
}
@Override
public void close() {}
}
@@ -0,0 +1,91 @@
package incari.app.web.headless;
import com.mojang.renderpearl.api.buffers.GpuBuffer;
import com.mojang.renderpearl.api.buffers.GpuBufferSlice;
import com.mojang.renderpearl.api.commands.GpuQueryPool;
import com.mojang.renderpearl.api.commands.RenderPass;
import com.mojang.renderpearl.api.pipeline.CompiledRenderPipeline;
import com.mojang.renderpearl.api.pipeline.IndexType;
import com.mojang.renderpearl.api.textures.GpuSampler;
import com.mojang.renderpearl.api.textures.GpuTextureView;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.Collection;
import org.jspecify.annotations.Nullable;
import org.lwjgl.PointerBuffer;
/** A render pass that draws nothing. */
final class HeadlessRenderPass implements RenderPass {
@Override
public void pushDebugGroup(java.util.function.Supplier<String> label) {}
@Override
public void popDebugGroup() {}
@Override
public void writeTimestamp(GpuQueryPool pool, int index) {}
@Override
public void setPipeline(CompiledRenderPipeline pipeline) {}
@Override
public void setUniform(String name, @Nullable GpuTextureView textureView, @Nullable GpuSampler sampler) {}
@Override
public void setUniform(String name, GpuBuffer value) {}
@Override
public void setUniform(String name, GpuBufferSlice value) {}
@Override
public void pushConstants(ByteBuffer value) {}
@Override
public void enableScissor(int x, int y, int width, int height) {}
@Override
public void disableScissor() {}
@Override
public void setVertexBuffer(int slot, @Nullable GpuBufferSlice vertexBuffer) {}
@Override
public void setIndexBuffer(GpuBuffer indexBuffer, IndexType indexType) {}
@Override
public void drawIndexed(int indexCount, int instanceCount, int firstIndex, int vertexOffset, int firstInstance) {}
@Override
public void multiDrawIndexed(IntBuffer drawParameters, int instanceCount, int firstInstance, int drawCount) {}
@Override
public void multiDrawIndexed(
PointerBuffer firstIndexOffsets, IntBuffer indexCounts, IntBuffer vertexOffsets, int drawCount) {}
@Override
public void drawIndexedIndirect(GpuBufferSlice commands, int drawCount) {}
@Override
public <T> void drawMultipleIndexed(
Collection<RenderPass.Draw<T>> draws,
@Nullable GpuBuffer defaultIndexBuffer,
@Nullable IndexType defaultIndexType,
Collection<String> dynamicUniforms,
T uniformArgument) {}
@Override
public void draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance) {}
@Override
public void multiDraw(IntBuffer drawParameters, int instanceCount, int firstInstance, int drawCount) {}
@Override
public void multiDraw(IntBuffer firstVertices, IntBuffer vertexCounts, int drawCount) {}
@Override
public void drawIndirect(GpuBufferSlice commands, int drawCount) {}
@Override
public void close() {}
}
@@ -0,0 +1,73 @@
package incari.app.web.headless;
import com.mojang.renderpearl.api.textures.AddressMode;
import com.mojang.renderpearl.api.textures.FilterMode;
import com.mojang.renderpearl.api.textures.GpuSampler;
import java.util.OptionalDouble;
/** A sampler's settings, kept only so the game can read them back. */
final class HeadlessSampler implements GpuSampler {
private final AddressMode addressModeU;
private final AddressMode addressModeV;
private final FilterMode minFilter;
private final FilterMode magFilter;
private final int maxAnisotropy;
private final OptionalDouble maxLod;
private boolean closed;
HeadlessSampler(
AddressMode addressModeU,
AddressMode addressModeV,
FilterMode minFilter,
FilterMode magFilter,
int maxAnisotropy,
OptionalDouble maxLod) {
this.addressModeU = addressModeU;
this.addressModeV = addressModeV;
this.minFilter = minFilter;
this.magFilter = magFilter;
this.maxAnisotropy = maxAnisotropy;
this.maxLod = maxLod;
}
@Override
public AddressMode getAddressModeU() {
return addressModeU;
}
@Override
public AddressMode getAddressModeV() {
return addressModeV;
}
@Override
public FilterMode getMinFilter() {
return minFilter;
}
@Override
public FilterMode getMagFilter() {
return magFilter;
}
@Override
public int getMaxAnisotropy() {
return maxAnisotropy;
}
@Override
public OptionalDouble getMaxLod() {
return maxLod;
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public void close() {
closed = true;
}
}
@@ -0,0 +1,55 @@
package incari.app.web.headless;
import com.mojang.renderpearl.api.commands.CommandEncoder;
import com.mojang.renderpearl.api.device.GpuSurface;
import com.mojang.renderpearl.api.textures.GpuTextureView;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.jspecify.annotations.Nullable;
/**
* A surface that never has an image to draw into: acquiring one does nothing, so the game skips
* its blit and present each frame.
*/
final class HeadlessSurface implements GpuSurface {
private GpuSurface.@Nullable Configuration configuration;
@Override
public void configure(GpuSurface.Configuration config) {
configuration = config;
}
@Override
public Optional<GpuSurface.Configuration> currentConfiguration() {
return Optional.ofNullable(configuration);
}
@Override
public Collection<GpuSurface.PresentMode> supportedPresentModes() {
return List.of(GpuSurface.PresentMode.FIFO, GpuSurface.PresentMode.IMMEDIATE);
}
@Override
public boolean isSuboptimal() {
return false;
}
@Override
public boolean isAcquired() {
return false;
}
@Override
public void acquireNextTexture() {}
@Override
public void blitFromTexture(CommandEncoder commandEncoder, GpuTextureView textureView) {}
@Override
public void present() {}
@Override
public void close() {}
}
@@ -0,0 +1,79 @@
package incari.app.web.headless;
import com.mojang.renderpearl.api.GpuFormat;
import com.mojang.renderpearl.api.textures.GpuTexture;
/** A texture's description with no pixels: writes to it are dropped. */
final class HeadlessTexture implements GpuTexture {
private final String label;
private final @GpuTexture.Usage int usage;
private final GpuFormat format;
private final int width;
private final int height;
private final int depthOrLayers;
private final int mipLevels;
private boolean closed;
HeadlessTexture(
String label,
@GpuTexture.Usage int usage,
GpuFormat format,
int width,
int height,
int depthOrLayers,
int mipLevels) {
this.label = label;
this.usage = usage;
this.format = format;
this.width = width;
this.height = height;
this.depthOrLayers = depthOrLayers;
this.mipLevels = mipLevels;
}
@Override
public int getWidth(int mipLevel) {
return Math.max(1, width >> mipLevel);
}
@Override
public int getHeight(int mipLevel) {
return Math.max(1, height >> mipLevel);
}
@Override
public int getDepthOrLayers() {
return depthOrLayers;
}
@Override
public int getMipLevels() {
return mipLevels;
}
@Override
public GpuFormat getFormat() {
return format;
}
@Override
public @GpuTexture.Usage int usage() {
return usage;
}
@Override
public String getLabel() {
return label;
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public void close() {
closed = true;
}
}
@@ -0,0 +1,54 @@
package incari.app.web.headless;
import com.mojang.renderpearl.api.textures.GpuTexture;
import com.mojang.renderpearl.api.textures.GpuTextureView;
/** A view of a {@link HeadlessTexture}'s mip levels. */
final class HeadlessTextureView implements GpuTextureView {
private final GpuTexture texture;
private final int baseMipLevel;
private final int mipLevels;
private boolean closed;
HeadlessTextureView(GpuTexture texture, int baseMipLevel, int mipLevels) {
this.texture = texture;
this.baseMipLevel = baseMipLevel;
this.mipLevels = mipLevels;
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public GpuTexture texture() {
return texture;
}
@Override
public int baseMipLevel() {
return baseMipLevel;
}
@Override
public int mipLevels() {
return mipLevels;
}
@Override
public int getWidth(int mipLevel) {
return texture.getWidth(baseMipLevel + mipLevel);
}
@Override
public int getHeight(int mipLevel) {
return texture.getHeight(baseMipLevel + mipLevel);
}
@Override
public void close() {
closed = true;
}
}
@@ -0,0 +1,116 @@
package incari.app.web.headless;
import com.mojang.renderpearl.api.buffers.GpuBuffer;
import com.mojang.renderpearl.api.buffers.GpuBufferSlice;
import com.mojang.renderpearl.api.buffers.TransientMemory;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import org.lwjgl.system.MemoryUtil;
/**
* Per-frame scratch memory as fresh {@code MemoryUtil} allocations: nothing is uploaded, so
* nothing needs pooling. Uploads copy their data, so later reads of the slices see it. Everything
* handed out lives until the frame's commands are submitted ({@link #release}), as transient
* memory does on a real device.
*/
final class HeadlessTransientMemory implements TransientMemory {
private final List<ByteBuffer> cpu = new ArrayList<>();
private final List<HeadlessBuffer> buffers = new ArrayList<>();
/** Frees this frame's allocations; the encoder calls it on submit. */
void release() {
for (ByteBuffer buffer : cpu) {
MemoryUtil.memFree(buffer);
}
cpu.clear();
for (HeadlessBuffer buffer : buffers) {
buffer.close();
}
buffers.clear();
}
private HeadlessBuffer track(HeadlessBuffer buffer) {
buffers.add(buffer);
return buffer;
}
@Override
public ByteBuffer allocateCpu(long size, long alignment, long minimumAllocation, long elementSize) {
ByteBuffer buffer = MemoryUtil.memCalloc(Math.toIntExact(size)).order(ByteOrder.nativeOrder());
cpu.add(buffer);
return buffer;
}
@Override
public GpuBufferSlice.MappedView allocateStaging(
long size, long alignment, @GpuBuffer.Usage int usage, long minimumAllocation, long elementSize) {
return track(new HeadlessBuffer(usage, size)).map(true, true);
}
@Override
public GpuBufferSlice allocateGpu(
long size, long alignment, @GpuBuffer.Usage int usage, long minimumAllocation, long elementSize) {
return track(new HeadlessBuffer(usage, size)).slice();
}
@Override
public GpuBufferSlice.MappedView allocateGpuMapped(
long size, long alignment, @GpuBuffer.Usage int usage, long minimumAllocation, long elementSize) {
return track(new HeadlessBuffer(usage, size)).map(true, true);
}
@Override
public GpuBufferSlice uploadStaging(
List<ByteBuffer> data,
long alignment,
@GpuBuffer.Usage int usage,
long minimumAllocation,
long elementSize) {
return upload(data, usage);
}
@Override
public GpuBufferSlice uploadGpu(
List<ByteBuffer> data,
long alignment,
@GpuBuffer.Usage int usage,
long minimumAllocation,
long elementSize) {
return upload(data, usage);
}
@Override
public List<GpuBufferSlice> multiUploadStaging(List<ByteBuffer> data, long alignment, @GpuBuffer.Usage int usage) {
return multiUpload(data, usage);
}
@Override
public List<GpuBufferSlice> multiUploadGpu(List<ByteBuffer> data, long alignment, @GpuBuffer.Usage int usage) {
return multiUpload(data, usage);
}
private GpuBufferSlice upload(List<ByteBuffer> data, @GpuBuffer.Usage int usage) {
long size = 0;
for (ByteBuffer part : data) {
size += part.remaining();
}
HeadlessBuffer buffer = track(new HeadlessBuffer(usage, size));
long offset = 0;
for (ByteBuffer part : data) {
buffer.write(offset, part);
offset += part.remaining();
}
return buffer.slice();
}
private List<GpuBufferSlice> multiUpload(List<ByteBuffer> data, @GpuBuffer.Usage int usage) {
List<GpuBufferSlice> slices = new ArrayList<>(data.size());
for (ByteBuffer part : data) {
slices.add(upload(List.of(part), usage));
}
return slices;
}
}
@@ -0,0 +1,80 @@
package incari.app.web.mesher;
import incari.mesher.Bytes;
import incari.mesher.MeshJobs;
import java.nio.ByteBuffer;
import org.jspecify.annotations.Nullable;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.Int8Array;
/**
* The mesher workers' program (ADR 0023): compiled by TeaVM on its own into
* {@code mesher.wasm}, which each of the page's mesher workers loads. It holds the mesher and
* answers the game's messages ({@link MeshJobs}); the worker's bootstrap script
* ({@code platform-web}'s {@code program-worker.js}) moves the bytes in and out.
*
* <p>Worker-side: no game objects, nothing but the mesher. Messages arrive in a direct buffer (the
* module's linear memory, where the bootstrap can copy them in one go), and replies leave the same
* way.
*/
public final class MesherWorker {
private static final MeshJobs JOBS = new MeshJobs();
private static ByteBuffer input = ByteBuffer.allocateDirect(64 * 1024);
private static ByteBuffer output = ByteBuffer.allocateDirect(256 * 1024);
private static byte[] message = new byte[64 * 1024];
private MesherWorker() {}
public static void main(String[] args) {
install(MesherWorker::input, MesherWorker::handle, MesherWorker::output);
}
/** A view of {@code length} bytes to copy the next message into. */
private static Int8Array input(int length) {
if (input.capacity() < length) {
input = ByteBuffer.allocateDirect(Math.max(length, input.capacity() * 2));
}
return Int8Array.fromJavaBuffer(input.slice(0, length));
}
/** Handles the message just copied in; returns its reply's length, or -1 for none. */
private static int handle(int length) {
if (message.length < length) {
message = new byte[Math.max(length, message.length * 2)];
}
input.get(0, message, 0, length);
Bytes.@Nullable Out reply = JOBS.handle(message, 0, length);
if (reply == null) {
return -1;
}
int size = reply.size();
if (output.capacity() < size) {
output = ByteBuffer.allocateDirect(Math.max(size, output.capacity() * 2));
}
output.put(0, reply.array(), 0, size);
return size;
}
/** A view of the reply's {@code length} bytes. */
private static Int8Array output(int length) {
return Int8Array.fromJavaBuffer(output.slice(0, length));
}
@JSFunctor
interface View extends JSObject {
Int8Array view(int length);
}
@JSFunctor
interface Handle extends JSObject {
int handle(int length);
}
@JSBody(
params = {"input", "handle", "output"},
script = "self.__incariProgram = {input: input, handle: handle, output: output};")
private static native void install(View input, Handle handle, View output);
}
@@ -0,0 +1,5 @@
/** The mesher workers' program: compiled apart from the game, for the page's Web Workers. */
@NullMarked
package incari.app.web.mesher;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,5 @@
/** The browser build's entry point. */
@NullMarked
package incari.app.web;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,451 @@
/**
* The host page's loader: checks the browser, reads the build manifest, offers Fast (recommended) or
* Compatible where both run (ADR 0036), streams the build with a progress bar, registers the service
* worker that caches it, and starts the game. The game then reports its start-up steps through
* `window.incariLoader` until its first frame, when the loading screen goes.
*
* Loaded by `index.html` as a module; `:app-web:pageScripts` strips the types.
*/
import { detectFeatures } from "./features.ts";
import { createJspiImports, supportsJspi } from "./jspi.ts";
import {
createAsyncImports,
createPageAsyncImports,
createPageTimer,
pageWakeupScope,
startTimerWorker,
type PageTimer,
} from "./wakeups.ts";
import {
buildFor,
buildName,
buildOptions,
countingResponse,
DEFAULT_MANIFEST,
formatBytes,
initialBuild,
missingWasmGc,
missingWebgl2,
parseManifest,
requestedBuild,
rustPage,
sizeOf,
versioned,
type BuildKind,
type BuildManifest,
type BuildOption,
type WasmTarget,
} from "./loader.ts";
/** What the game's code calls while it starts (`incari.app.web.LoaderPage`, platform-web's first frame). */
export interface LoaderHooks {
/** A start-up step, shown under the bar. */
status(text: string): void;
/** The game has drawn its first frame: the loading screen goes. */
done(): void;
}
/** TeaVM's WebAssembly GC loader, which `incari.wasm-runtime.js` defines. */
interface TeaVmRuntime {
wasmGC: {
load(
url: string,
options: {
stackDeobfuscator?: { enabled: boolean; path?: string; externalInfoPath?: string };
installImports?: (imports: Record<string, unknown>) => void;
},
): Promise<{ exports: { main(args: string[]): void }; instance: WebAssembly.Instance }>;
};
}
interface IncariWindow {
incariLoader?: LoaderHooks;
/** What the game reads about its build (`incari.app.web.LoaderPage`). */
incariBuild?: {
id: string;
game: string;
release: boolean;
pack: string | null;
programs: Record<string, { runtime: string; module: string }>;
/** The game's own build as this page loaded it, for copies of it in workers (ADR 0039). */
program?: { runtime: string; module: string; jspi: boolean };
};
TeaVM?: TeaVmRuntime;
/**
* A timer a hidden page still gets on time (wakeups.ts): platform-web's frames and background
* pool fall back on it while the page is hidden.
*/
incariTimer?: PageTimer;
/**
* Calls `wake`, then runs the thread wake-ups it caused (wakeups.ts, `runWoken`): platform-web's
* network wake calls it rather than leave them to timers the browser runs late in play.
*/
incariRunWoken?: (wake: () => void) => void;
/** The single-file page's embedded files (offline.ts): where a script of theirs loads from. */
incariFiles?: { base: string; url(href: string): string };
}
const page = window as unknown as IncariWindow & Window;
const options = new URLSearchParams(location.search);
/** What page-relative URLs resolve against: the single-file page's folder, whose own URL may have none. */
const pageUrl = page.incariFiles?.base ?? location.href;
const screen = element("incari-loader");
const track = element("incari-track");
const picker = element("incari-choose");
const bar = element("incari-bar");
const statusLine = element("incari-status");
const detailLine = element("incari-detail");
function element(id: string): HTMLElement {
const found = document.getElementById(id);
if (found === null) {
throw new Error(`index.html has no #${id}`);
}
return found;
}
function show(status: string, detail = ""): void {
statusLine.textContent = status;
detailLine.textContent = detail;
}
/** The bar's fill, 0 to 1; null for a step that can't say how far it is (the bar pulses). */
function progress(fraction: number | null): void {
bar.classList.toggle("indeterminate", fraction === null);
bar.style.width = fraction === null ? "100%" : `${String(Math.round(fraction * 1000) / 10)}%`;
}
let failed = false;
/** Stops with a message the player can act on. tools/webbuild's checks watch for the console line. */
function fail(error: unknown): void {
if (failed) {
return;
}
failed = true;
const text = error instanceof Error ? error.message : String(error);
screen.classList.add("failed");
screen.hidden = false;
progress(1);
show("The game couldn't start", text);
// One line, so log readers that split on newlines still get the whole stack.
const stack = error instanceof Error && error.stack !== undefined ? error.stack : text;
console.error("[Incari] Crashed: " + stack.replace(/\n\s*/g, " | "));
}
/** Where the player's last pick is kept, to start the next choice on it. */
const BUILD_KEY = "incari.build";
function rememberedBuild(): string | null {
try {
return localStorage.getItem(BUILD_KEY);
} catch {
return null;
}
}
function rememberBuild(kind: BuildKind): void {
try {
localStorage.setItem(BUILD_KEY, kind);
} catch {
// Storage blocked: the next choice starts on the recommended build.
}
}
/**
* Shows the choice between the builds and waits for the player's pick. A build that can't run here
* is shown disabled, with the reason. Fast is marked as the one to use wherever it works.
*/
function askForBuild(builds: readonly BuildOption[], initial: BuildKind): Promise<BuildKind> {
show("Choose a version", "");
track.hidden = true;
picker.hidden = false;
return new Promise((resolve) => {
for (const build of builds) {
const button = element(`incari-pick-${build.kind}`) as HTMLButtonElement;
// Rust's button is hidden unless this copy has it.
button.hidden = false;
button.disabled = !build.available;
element(`incari-why-${build.kind}`).textContent = build.reason ?? "";
button.addEventListener("click", () => {
picker.hidden = true;
track.hidden = false;
rememberBuild(build.kind);
resolve(build.kind);
});
if (build.kind === initial) {
button.focus();
}
}
});
}
async function readManifest(): Promise<BuildManifest> {
let response: Response;
try {
response = await fetch("build.json", { cache: "no-cache" });
} catch {
return DEFAULT_MANIFEST;
}
// An experiment's build (a probe) has no manifest: TeaVM's development output.
return response.ok ? parseManifest(await response.json()) : DEFAULT_MANIFEST;
}
/**
* Registers the service worker and waits a moment for it to take the page over, so this visit's
* download already goes through its cache. `?sw=off` skips it (and unregisters it) for development.
*/
async function registerWorker(manifest: BuildManifest): Promise<void> {
const workers = navigator.serviceWorker as ServiceWorkerContainer | undefined;
// The single-file page holds every file itself, and a page opened from the disk can't have one.
if (workers === undefined || page.incariFiles !== undefined) {
return;
}
if (options.get("sw") === "off") {
for (const registration of await workers.getRegistrations()) {
await registration.unregister();
}
return;
}
try {
await workers.register("sw.js", { type: "module", scope: "./" });
await Promise.race([workers.ready, new Promise((resolve) => setTimeout(resolve, 3000))]);
if (workers.controller !== null && manifest.files.length > 0) {
workers.controller.postMessage({ type: "build", keep: manifest.files.map((f) => versioned(manifest, f.path)) });
}
} catch (error) {
// Older browsers have no module workers: the game runs, uncached.
console.warn("[Incari] No service worker, so nothing is cached between visits: " + String(error));
}
}
function loadScript(src: string): Promise<void> {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
// A script element fetches without `fetch`, so the single-file page's shim can't answer it.
script.src = page.incariFiles?.url(src) ?? src;
script.onload = () => {
resolve();
};
script.onerror = () => {
reject(new Error(`Couldn't load ${src}`));
};
document.head.append(script);
});
}
/** Whether the service worker's cache already holds `url` (false where there's no cache to ask). */
async function cachedByWorker(url: string): Promise<boolean> {
try {
return (await caches.match(url)) !== undefined;
} catch {
return false;
}
}
/**
* Downloads `url` through `fetch` with a progress bar. TeaVM's loader fetches the module itself, so
* the page's `fetch` is wrapped for that one URL while it does: the response it gets counts its
* bytes and still compiles as it streams.
*
* Not when the service worker already has the file: nothing downloads, and the wrapper would copy
* every chunk through JavaScript on the page's thread (a quarter of a second for the development
* build on the desktop) and hand the browser a made-up response its compiled-code cache can't
* recognise.
*/
async function withDownloadProgress<T>(url: string, total: number, label: string, work: () => Promise<T>): Promise<T> {
const absolute = new URL(url, pageUrl).href;
if (await cachedByWorker(absolute)) {
progress(null);
show("Starting the game", "From this browser's cache");
return work();
}
const original = window.fetch.bind(window);
window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
const target = input instanceof Request ? input.url : new URL(String(input), pageUrl).href;
const response = await original(input, init);
if (target !== absolute) {
return response;
}
return countingResponse(response, (received) => {
progress(total > 0 ? Math.min(received / total, 1) : null);
show(label, total > 0 ? `${formatBytes(received)} of ${formatBytes(total)}` : formatBytes(received));
if (total > 0 && received >= total) {
progress(null);
show("Compiling the game", "");
}
});
};
try {
return await work();
} finally {
window.fetch = original;
}
}
async function startBuild(manifest: BuildManifest, kind: BuildKind, target: WasmTarget): Promise<void> {
show("Loading", `The ${buildName(kind)} build`);
await loadScript(versioned(manifest, target.runtime));
const runtime = page.TeaVM;
if (runtime === undefined) {
throw new Error(`${target.runtime} didn't define TeaVM's loader`);
}
const moduleUrl = versioned(manifest, target.module);
const debug =
target.deobfuscator !== undefined && target.debugInfo !== undefined
? {
enabled: true,
path: versioned(manifest, target.deobfuscator),
externalInfoPath: versioned(manifest, target.debugInfo),
}
: { enabled: false };
// The Fast build suspends through JSPI (jspi.ts); Compatible imports none of it. Given wherever the
// browser has JSPI, so an experiment's Fast build (no manifest to say so) runs too.
const jspi = supportsJspi() ? createJspiImports(fail) : null;
// A hidden page's own timers are held to a wake-up a second, then a minute (Chrome, after five
// minutes hidden and silent): too few to answer a server's keep-alives. While hidden, the game's
// threads wake through a channel and a worker's timer instead (wakeups.ts); `?wakeups=timers`
// keeps TeaVM's own timers throughout.
const timerWorker = options.get("wakeups") === "timers" ? null : startTimerWorker();
const pageTimer = timerWorker === null ? null : createPageTimer(timerWorker);
if (pageTimer !== null) {
page.incariTimer = pageTimer;
}
if (page.incariBuild !== undefined) {
page.incariBuild.program = { runtime: versioned(manifest, target.runtime), module: moduleUrl, jspi: jspi !== null };
}
const teavm = await withDownloadProgress(moduleUrl, sizeOf(manifest, target.module), "Downloading the game", () =>
runtime.wasmGC.load(moduleUrl, {
stackDeobfuscator: debug,
installImports: (imports) => {
if (jspi !== null) {
imports.teavmJspi = jspi.module;
}
// Threads woken without the browser's 4 ms timer clamp (wakeups.ts), as in singleplayer's
// worker; on the page always only when asked, until the page's frames are measured with
// it, and otherwise only while the page is hidden.
if (options.get("wakeups") === "channel") {
imports.teavmAsync = createAsyncImports();
} else if (pageTimer !== null) {
const pageImports = createPageAsyncImports(pageWakeupScope(pageTimer));
imports.teavmAsync = pageImports;
// A server message's connection thread runs as the message comes (ADR 0075);
// `?netwake=timers` leaves it to TeaVM's timer, which play delays ~35 ms.
if (options.get("netwake") !== "timers") {
page.incariRunWoken = (wake) => {
pageImports.runWoken(wake);
};
}
}
},
}),
);
if (jspi !== null) {
jspi.attach(teavm.instance.exports);
// The engine never frees a waiting fiber's stack: a page going away ends them all, or the
// whole game stays in the tab's memory through the next load (jspi.ts). That includes a page
// the back/forward cache keeps, whose game can't run again: it reloads if it comes back.
window.addEventListener("pagehide", (event) => {
console.log(
`[Incari] Loader: page hidden${event.persisted ? " into the back/forward cache" : ""}; ending its threads`,
);
jspi.terminate();
});
window.addEventListener("pageshow", (event) => {
if (event.persisted) {
location.reload();
}
});
}
show("Starting", "");
// main() returns at the game's first suspension; the rest runs from the page's event loop.
teavm.exports.main([]);
}
async function boot(): Promise<void> {
// The game's stacks run deep; JavaScript keeps 10 frames of a trace by default.
Error.stackTraceLimit = 1000;
// An error that escapes Java (a JavaScript exception in the runtime) ends the game. main()
// returns at the first suspension, so later ones only reach the window's handlers.
// Not one from a browser extension's script, which isn't the game's to end.
window.addEventListener("error", (event) => {
if (/^(chrome|moz|safari(-web)?)-extension:/.test(event.filename)) {
console.warn(`[Incari] Ignored an extension's error: ${event.message}`);
return;
}
fail(event.error ?? event.message);
});
window.addEventListener("unhandledrejection", (event) => {
fail(event.reason);
});
page.incariLoader = {
status: (text) => {
if (!failed) {
progress(null);
show(text, "");
}
},
done: () => {
if (!failed) {
screen.hidden = true;
}
},
};
show("Checking your browser");
progress(null);
const features = await detectFeatures();
const manifest = await readManifest();
const builds = buildOptions(features, manifest);
// Rust needs neither (it draws through WebGPU); where it can run, the choice says what can't.
const missing = missingWebgl2(features) ?? missingWasmGc(features);
if (missing !== null && !builds.some((build) => build.kind === "rust" && build.available)) {
throw new Error(missing);
}
// The player picks where more than one build can run; `?build=fast`, `compatible` or `rust`
// picks in the address (the checks and the benchmark do), and a browser that can run only one runs it.
const runnable = builds.filter((build) => build.available);
if (runnable.length === 0) {
throw new Error(builds.map((build) => build.reason).join(" "));
}
const requested = requestedBuild(options.get("build"));
const only = runnable.length === 1 ? runnable[0]?.kind : undefined;
const picked = requested ?? only ?? (await askForBuild(builds, initialBuild(builds, rememberedBuild())));
const choice = buildFor(picked, builds, manifest);
if (choice.kind === "unsupported") {
throw new Error(choice.reason);
}
if (choice.kind === "rust") {
// Its own page, files and service worker (ADR 0068).
console.log("[Incari] Loader: opening the Rust build");
location.assign(rustPage(choice.target, location.href));
return;
}
page.incariBuild = {
id: manifest.id,
game: manifest.game,
release: manifest.release,
pack: manifest.pack === undefined ? null : versioned(manifest, manifest.pack),
// The workers' programs, by the versioned URLs their loaders fetch them from.
programs: Object.fromEntries(
Object.entries(manifest.programs ?? {}).map(([name, program]) => [
name,
{ runtime: versioned(manifest, program.runtime), module: versioned(manifest, program.module) },
]),
),
};
const why =
requested !== null ? "asked for in the address" : only !== undefined ? "the only one that runs here" : "picked";
console.log(
`[Incari] Loader: build ${manifest.id.slice(0, 12)} (${manifest.release ? "release" : "development"}), running ${buildName(
choice.kind,
)} (${why}); JSPI ${features.jspi ? "yes" : "no"}, cross-origin isolated ${features.crossOriginIsolated ? "yes" : "no"}`,
);
await registerWorker(manifest);
const started = performance.now();
await startBuild(manifest, choice.kind, choice.target);
console.log(`[Incari] Loader: build loaded and started in ${String(Math.round(performance.now() - started))} ms`);
}
boot().catch(fail);
@@ -0,0 +1,70 @@
/**
* What the service worker (`sw.ts`) does with each request the page makes. Pure, so it can be
* tested; the worker only carries it out.
*/
/**
* - `build`: a build file, versioned by its hash in the URL (`?v=`): from the cache once it's there.
* - `immutable`: a game asset named by its content hash (`assets/objects/ab/abcd...`): the same.
* - `page`: the page and what it starts from: from the network while there is one, from the cache
* when offline, so a returning player can start without a connection.
* - `pass`: not the worker's business (the client jar, which the storage worker keeps itself;
* other origins; the development server's own files).
*/
export type Strategy = "build" | "immutable" | "page" | "pass";
/** The worker's caches. A new layout gets a new name; the worker deletes names it doesn't know. */
export const CACHES = {
build: "incari-build-v1",
immutable: "incari-assets-v1",
page: "incari-page-v1",
} as const;
/** Files the page starts from, kept for offline starts. */
const PAGE_FILES = new Set([
"",
"index.html",
"boot.js",
"loader.js",
"features.js",
"jspi.js",
"wakeups.js",
"game-worker.js",
"cache-policy.js",
"build.json",
"asset-index.json",
]);
export function strategyFor(url: URL, scope: URL, method = "GET"): Strategy {
if (method !== "GET" || url.origin !== scope.origin || !url.pathname.startsWith(scope.pathname)) {
return "pass";
}
const path = url.pathname.slice(scope.pathname.length);
if (path.startsWith("rust/")) {
// The Rust build's own service worker keeps its files (ADR 0068).
return "pass";
}
if (path === "client.jar") {
// Kept by the storage worker (OPFS or IndexedDB, ADR 0011): caching it here would store it twice.
return "pass";
}
if (url.searchParams.has("v")) {
return "build";
}
if (/^assets\/objects\/[0-9a-f]{2}\/[0-9a-f]{40}$/.test(path)) {
return "immutable";
}
if (PAGE_FILES.has(path)) {
return "page";
}
return "pass";
}
/**
* Which cached build files to drop once the page runs a build: every versioned URL the build
* doesn't list. `keep` holds the URLs, relative to the scope, that the running build loads.
*/
export function staleBuildEntries(cached: readonly string[], keep: readonly string[], scope: URL): string[] {
const wanted = new Set(keep.map((path) => new URL(path, scope).href));
return cached.filter((href) => !wanted.has(href));
}
@@ -0,0 +1,108 @@
/**
* What the browser supports, checked once before anything is downloaded. The loader uses it to
* offer the builds that can run here (Fast needs JSPI, both need WebAssembly GC, Rust needs WebGPU),
* and to explain a failure before the player waits through a download that can't run.
*/
import { supportsJspi } from "./jspi.ts";
export interface BrowserFeatures {
/** WebAssembly with the GC proposal: needed by both builds of the game. */
readonly wasmGc: boolean;
/** WebAssembly JavaScript Promise Integration: needed by the Fast build (ADR 0036). */
readonly jspi: boolean;
/**
* SharedArrayBuffer is usable, which needs COOP/COEP headers on the page. Worker meshing uses
* it; without it, workers fall back to transferring buffers.
*/
readonly crossOriginIsolated: boolean;
/** A WebGL2 context can be created: the graphics floor for Fast and Compatible. */
readonly webgl2: boolean;
/** WebGPU gives an adapter: what the experimental Rust build draws with (ADR 0068). */
readonly webgpu: boolean;
}
/**
* The smallest module that uses a GC type: the header, then a type section declaring one empty
* struct (0x5f). Engines without the GC proposal reject the struct type form.
*/
// prettier-ignore
const WASM_GC_PROBE = new Uint8Array([
0x00, 0x61, 0x73, 0x6d, // magic "\0asm"
0x01, 0x00, 0x00, 0x00, // version 1
0x01, 0x03, // type section, 3 bytes
0x01, // one type
0x5f, 0x00, // struct with no fields
]);
/** The parts of the global scope detection reads, so tests can supply their own. */
export interface FeatureScope {
readonly WebAssembly?: Pick<typeof WebAssembly, "validate">;
readonly crossOriginIsolated?: boolean;
readonly SharedArrayBuffer?: unknown;
readonly document?: Pick<Document, "createElement">;
readonly navigator?: { readonly gpu?: GpuLike };
}
/** The part of `navigator.gpu` detection calls; TypeScript's DOM types don't have WebGPU yet. */
export interface GpuLike {
requestAdapter(): Promise<unknown>;
}
/**
* Async because only asking for an adapter tells: a browser can have `navigator.gpu` and no GPU it
* will use (blocklisted drivers, software rendering off).
*/
export async function detectFeatures(scope: FeatureScope = globalThis): Promise<BrowserFeatures> {
return {
wasmGc: supportsWasmGc(scope),
jspi: supportsWasmGc(scope) && supportsJspi(scope),
crossOriginIsolated: scope.crossOriginIsolated === true && scope.SharedArrayBuffer !== undefined,
webgl2: supportsWebgl2(scope),
webgpu: await supportsWebgpu(scope),
};
}
async function supportsWebgpu(scope: FeatureScope): Promise<boolean> {
const gpu = scope.navigator?.gpu;
if (gpu === undefined) {
return false;
}
let timer: ReturnType<typeof setTimeout> | undefined;
try {
// Bounded: an adapter request on a wedged GPU process can take seconds, and this is before the
// player sees anything.
const adapter = await Promise.race([
gpu.requestAdapter(),
new Promise<null>((resolve) => {
timer = setTimeout(() => {
resolve(null);
}, 2000);
}),
]);
return adapter !== null && adapter !== undefined;
} catch {
return false;
} finally {
clearTimeout(timer);
}
}
function supportsWasmGc(scope: FeatureScope): boolean {
try {
return scope.WebAssembly?.validate(WASM_GC_PROBE) === true;
} catch {
// Some engines throw on unknown type forms instead of returning false.
return false;
}
}
function supportsWebgl2(scope: FeatureScope): boolean {
if (scope.document === undefined) {
return false;
}
const canvas = scope.document.createElement("canvas");
// Released straight away: this only asks whether a context can exist.
const context = canvas.getContext("webgl2");
context?.getExtension("WEBGL_lose_context")?.loseContext();
return context !== null;
}
@@ -0,0 +1,260 @@
/**
* A copy of the game's program in a module worker (ADR 0039): singleplayer's server, apart from the
* page's thread. The page (platform-web's `JsChannel`) starts it with the build it loaded itself;
* this loads TeaVM's runtime and that module, with the Fast build's JSPI imports (jspi.ts), and
* starts the program in the role it was given.
*
* The page and the program here talk through `__incariParent`, the same four calls the page's side
* offers: `send` a numbered message of bytes (the buffer is handed over), `take` the next one if any,
* `next` for a promise of it, `close`. A message only queues here: Java waits for it on a thread of
* its own. The worker's console lines show in the page's DevTools (and the browser checks) as they
* are; a start that fails is reported to the page, which prints it.
*/
import { createJspiImports } from "./jspi.ts";
import { createAsyncImports } from "./wakeups.ts";
/** A numbered message of bytes; kind -1 ends the channel. */
export interface Envelope {
kind: number;
data: ArrayBuffer;
}
/** What the page sends first, with a port of its storage worker's if it has one (ADR 0041). */
export interface StartMessage {
start: { runtime: string; module: string; jspi: boolean; role: string; query?: string };
storage?: MessagePort | null;
}
/** What the program here reaches the page through. */
export interface ParentChannel {
send(kind: number, data: ArrayBuffer): void;
take(): Envelope | null;
next(): Promise<Envelope | null>;
close(): void;
}
interface TeaVmRuntime {
wasmGC: {
load(
url: string,
options: { installImports?: (imports: Record<string, unknown>) => void },
): Promise<{ exports: { main(args: string[]): void }; instance: WebAssembly.Instance }>;
};
}
/** The parts of a worker's scope this uses, so tests can supply their own. */
export interface WorkerScope {
postMessage(message: unknown, transfer?: Transferable[]): void;
onmessage: ((event: { data: unknown }) => void) | null;
close(): void;
console: Console;
TeaVM?: TeaVmRuntime;
__incariParent?: ParentChannel;
/** The page's storage worker, for the program's file changes (platform-web's BrowserStore). */
__incariStorage?: MessagePort | null;
/** Starts another copy of the program, in a worker of this one's (platform-web's JsChannel). */
__incariStartWorker?: (role: string) => ParentChannel | null;
/** The single-file page's embedded files (offline.ts): where a script of theirs loads from. */
incariFiles?: { url(href: string): string };
}
/** A worker of this one's, as `startChild` uses it. */
export interface ChildWorker {
postMessage(message: unknown, transfer?: Transferable[]): void;
listen(onMessage: (data: unknown) => void, onError: (message: string) => void): void;
terminate(): void;
}
/** What a worker of this one's is made with, so tests can supply their own. */
export type WorkerFactory = (url: URL, options: WorkerOptions) => ChildWorker;
/** A real worker, for `startChild`. */
export function browserWorker(url: URL, options: WorkerOptions): ChildWorker {
const worker = new Worker(url, options);
return {
postMessage: (message, transfer) => {
worker.postMessage(message, transfer ?? []);
},
listen(onMessage, onError) {
worker.onmessage = (event) => {
onMessage(event.data);
};
worker.onerror = (event) => {
onError(event.message);
};
},
terminate: () => {
worker.terminate();
},
};
}
/**
* Starts the program again in a worker of this one's, with the build this one runs and in `role`
* (ADR 0042: singleplayer's server starts its terrain helpers so), and returns the channel to it:
* the same four calls the page has to this worker.
*/
export function startChild(
scope: Pick<WorkerScope, "console">,
build: StartMessage["start"],
role: string,
createWorker: WorkerFactory,
scriptUrl: URL,
): ParentChannel {
const inbox = createInbox();
const worker = createWorker(scriptUrl, { type: "module", name: `incari-${role}` });
worker.listen(
(message) => {
const data = message as Partial<Envelope>;
if (data.kind === -1) {
inbox.push(null);
} else if (typeof data.kind === "number" && data.data instanceof ArrayBuffer) {
inbox.push({ kind: data.kind, data: data.data });
}
},
(error) => {
scope.console.error(`[Incari] The ${role} worker failed: ${error}`);
inbox.push(null);
},
);
worker.postMessage({ start: { ...build, role }, storage: null });
return {
send(kind, data) {
worker.postMessage({ kind, data }, [data]);
},
take: () => inbox.take(),
next: () => inbox.next(),
close() {
worker.postMessage({ kind: -1, data: new ArrayBuffer(0) });
// It ends itself on that; this only makes sure.
setTimeout(() => {
worker.terminate();
}, 5000);
inbox.push(null);
},
};
}
/** A queue of envelopes that a waiting reader is handed as they come. */
export function createInbox(): {
push(envelope: Envelope | null): void;
take(): Envelope | null;
next(): Promise<Envelope | null>;
} {
const queue: (Envelope | null)[] = [];
let waiting: ((envelope: Envelope | null) => void) | null = null;
let ended = false;
return {
push(envelope) {
if (ended) {
return;
}
if (envelope === null) {
ended = true;
}
if (waiting !== null) {
const resolve = waiting;
waiting = null;
resolve(envelope);
} else {
queue.push(envelope);
}
},
take() {
const head = queue[0];
if (head === undefined || head === null) {
return null;
}
queue.shift();
return head;
},
next() {
if (queue.length > 0) {
return Promise.resolve(queue.shift() ?? null);
}
return new Promise((resolve) => {
waiting = resolve;
});
},
};
}
/** Starts serving the page's messages on `scope`. */
export function serve(scope: WorkerScope): void {
const inbox = createInbox();
// Ends the program's waiting fibers before the worker goes, as the page does on `pagehide`
// (jspi.ts): a worker closed with suspended stacks crashed the tab's process later (ADR 0042).
let unwind = (): void => undefined;
let role = "";
scope.__incariParent = {
send(kind, data) {
scope.postMessage({ kind, data }, [data]);
},
take: () => inbox.take(),
next: () => inbox.next(),
close() {
unwind();
scope.postMessage({ kind: -1, data: new ArrayBuffer(0) });
scope.close();
},
};
async function start(message: StartMessage["start"]): Promise<void> {
// An import fetches without `fetch`, so the single-file page's shim can't answer it.
await import(scope.incariFiles?.url(message.runtime) ?? message.runtime);
const runtime = scope.TeaVM;
if (runtime === undefined) {
throw new Error(`${message.runtime} didn't define TeaVM's loader`);
}
const jspi = message.jspi
? createJspiImports((error) => {
scope.console.error("[Incari] Worker:", error);
})
: null;
const teavm = await runtime.wasmGC.load(message.module, {
installImports: (imports) => {
if (jspi !== null) {
imports.teavmJspi = jspi.module;
}
// Threads woken without the browser's 4 ms timer clamp (wakeups.ts).
imports.teavmAsync = createAsyncImports();
},
});
jspi?.attach(teavm.instance.exports);
unwind = () => {
jspi?.terminate();
};
scope.__incariStartWorker = (role) =>
typeof Worker === "undefined"
? null
: startChild(scope, message, role, browserWorker, new URL("game-worker.js", import.meta.url));
// main() returns at the program's first wait; the rest runs from this worker's event loop.
teavm.exports.main(["--worker", message.role, message.query ?? ""]);
}
scope.onmessage = (event) => {
const data = event.data as Partial<StartMessage> & Partial<Envelope>;
if (data.start !== undefined) {
scope.__incariStorage = data.storage ?? null;
role = data.start.role;
start(data.start).catch((error: unknown) => {
scope.console.error("[Incari] Worker: couldn't start the program:", error);
scope.postMessage({ kind: -1, data: new ArrayBuffer(0) });
});
} else if (data.kind === -1) {
inbox.push(null);
// A terrain helper has nothing to hand back: it ends with its server's channel.
if (role === "terrain") {
unwind();
scope.close();
}
} else if (typeof data.kind === "number" && data.data instanceof ArrayBuffer) {
inbox.push({ kind: data.kind, data: data.data });
}
};
}
if (typeof (globalThis as { WorkerGlobalScope?: unknown }).WorkerGlobalScope !== "undefined") {
serve(globalThis as unknown as WorkerScope);
}
@@ -0,0 +1,120 @@
/**
* The JavaScript side of the Fast build's fibers (WebAssembly JavaScript Promise Integration; TeaVM's
* patched `Fiber.Jspi` in tools/teavm-patches; ADR 0036). The Fast build has no coroutines:
* a Java thread that blocks calls `teavmJspi.await`, which hands the engine a promise, and the engine
* keeps the thread's whole WebAssembly stack until the promise settles. Each thread runs in its own
* call of the module's `teavm.jspi.run` export through `WebAssembly.promising`, so suspending one
* returns to whoever started it. The Compatible build imports none of this.
*
* The engine never frees a suspended stack, nor anything it reaches: a fiber still waiting when the
* page goes away would keep the whole program alive in the tab's process through every reload. So
* `terminate` (on `pagehide`) resumes each waiting fiber with an order to end, which it obeys with a
* trap that unwinds its stack past every Java handler.
*/
/** What JSPI adds to `WebAssembly`; missing in engines without it. */
interface JspiApi {
Suspending: new (fn: (...args: never[]) => unknown) => object;
promising: (fn: (...args: never[]) => unknown) => (...args: never[]) => Promise<unknown>;
}
/** The parts of the global scope the imports read, so tests can supply their own. */
export interface JspiScope {
readonly WebAssembly?: object;
}
export function supportsJspi(scope: JspiScope = globalThis): boolean {
const api = scope.WebAssembly as Partial<JspiApi> | undefined;
return typeof api?.Suspending === "function" && typeof api.promising === "function";
}
export interface JspiImports {
/** The `teavmJspi` import module. */
readonly module: Record<string, unknown>;
/** Gives the imports the instance's exports, which they call to start a fiber. */
attach(exports: Record<string, unknown>): void;
/** Promises created and not yet settled or dropped, for tests and leak checks. */
pending(): number;
/** Ends every fiber: each waiting one now, any other at its next wait. */
terminate(): void;
}
/** What a fiber's wait resumes with: carry on, or end (`Fiber.Jspi.suspend`). */
const RESUME = 0;
const END = 1;
/**
* Builds the `teavmJspi` imports. `fail` gets an error that escapes a fiber: it can't reach the
* starter's stack, which has moved on by the time the fiber's promise settles.
*/
export function createJspiImports(fail: (error: unknown) => void, scope: JspiScope = globalThis): JspiImports {
const api = scope.WebAssembly as JspiApi;
const promises = new Map<number, { promise: Promise<number>; resolve: (value: number) => void }>();
let nextId = 1;
let run: ((id: number) => Promise<unknown>) | null = null;
let ending = false;
// The fibers' traps on the way out aren't failures.
const report = (error: unknown): void => {
if (!ending) {
fail(error);
}
};
const module: Record<string, unknown> = {
create(): number {
const id = nextId++;
let resolve!: (value: number) => void;
const promise = new Promise<number>((r) => {
resolve = r;
});
promises.set(id, { promise, resolve });
return id;
},
// Hands the engine the promise: the calling fiber's stack waits for it.
await: new api.Suspending((id: number): Promise<number> => {
const entry = promises.get(id);
if (entry === undefined) {
throw new Error(`No JSPI promise ${String(id)} to wait for`);
}
if (ending) {
promises.delete(id);
return Promise.resolve(END);
}
return entry.promise;
}),
resolve(id: number): void {
const entry = promises.get(id);
promises.delete(id);
entry?.resolve(ending ? END : RESUME);
},
// A call that completed before its fiber had to wait.
drop(id: number): void {
promises.delete(id);
},
run(id: number): void {
if (run === null) {
throw new Error("A fiber started before the module's exports were attached");
}
// Returns once the fiber ends or first waits; the rest runs as its promises settle.
run(id).catch(report);
},
};
return {
module,
attach(exports) {
const runExport = exports["teavm.jspi.run"];
if (typeof runExport === "function") {
run = api.promising(runExport as (id: number) => unknown) as (id: number) => Promise<unknown>;
}
},
pending: () => promises.size,
terminate() {
ending = true;
for (const entry of promises.values()) {
entry.resolve(END);
}
promises.clear();
},
};
}
@@ -0,0 +1,266 @@
/**
* The loader's decisions, kept apart from the page so they can be tested: which build to run, what
* the build manifest says, and how far a download has got. `boot.ts` does the page's side.
*/
import type { BrowserFeatures } from "./features.ts";
/** One file of the build, as `build.json` lists it. */
export interface BuildFile {
readonly path: string;
readonly size: number;
/** Hex SHA-256 of the file: its version, so a cache can keep it until it changes. */
readonly sha256: string;
}
/** A build of the game: TeaVM's loader script and the WebAssembly GC module it loads. */
export interface WasmTarget {
readonly runtime: string;
readonly module: string;
/** The development build's stack deobfuscator and its debug information, if it has them. */
readonly deobfuscator?: string;
readonly debugInfo?: string;
}
/** A program the page's workers run beside the game: its own module and loader. */
export interface ProgramTarget {
readonly runtime: string;
readonly module: string;
}
/**
* The Rust build (ADR 0068): Horizon's browser port with Incari's mods, a page of its own that the
* loader opens instead of loading a module.
*/
export interface RustTarget {
/** Its page, relative to this one. */
readonly page: string;
}
/**
* The builds of the game. What a player sees them called, and what they are:
*
* - **Fast**: suspends Java's threads through JSPI (JavaScript Promise Integration), so its code runs
* at full speed. It needs a browser with JSPI. WebAssembly GC, like Compatible (ADR 0036).
* - **Compatible**: emulates the threads with TeaVM's coroutines, which slows all of its code and
* doubles its size, but runs wherever WebAssembly GC does (Safari, older Chrome and Firefox).
* - **Rust**: experimental, a rewrite of the game in Rust drawing through WebGPU (ADR 0068). Never
* recommended; offered where WebGPU works and the copy includes it.
*/
export type BuildKind = "fast" | "compatible" | "rust";
/**
* `build.json`, which `:app-web:buildManifest` writes beside the builds: what there is to load, and
* each file's size and hash. A page served without one (an experiment's build) gets
* {@link DEFAULT_MANIFEST}.
*/
export interface BuildManifest {
readonly format: 2;
/** A hash over every file's: changes whenever any file does. */
readonly id: string;
/** The game version the build is of. */
readonly game: string;
readonly release: boolean;
readonly fast?: WasmTarget;
readonly compatible?: WasmTarget;
readonly rust?: RustTarget;
/** The asset pack (build-time data the game mounts read-only), if the build has one. */
readonly pack?: string;
/** Programs for the page's workers, by name (`mesher`). */
readonly programs?: Readonly<Record<string, ProgramTarget>>;
readonly files: readonly BuildFile[];
}
/**
* What an experiment's build (no `build.json`) has: TeaVM's development output as `incari.wasm`. It
* may be either kind; the page gives every module the Fast build's imports where the browser has
* JSPI (boot.ts), so a Fast experiment runs as this entry too.
*/
export const DEFAULT_MANIFEST: BuildManifest = {
format: 2,
id: "development",
game: "unknown",
release: false,
compatible: {
runtime: "incari.wasm-runtime.js",
module: "incari.wasm",
deobfuscator: "incari.wasm-deobfuscator.wasm",
debugInfo: "incari.wasm.teadbg",
},
files: [],
};
/** Checks that `value` is a manifest this loader understands; throws saying what's wrong if not. */
export function parseManifest(value: unknown): BuildManifest {
if (typeof value !== "object" || value === null) {
throw new Error("build.json isn't an object");
}
const manifest = value as Partial<BuildManifest>;
if (manifest.format !== 2) {
throw new Error(`build.json has format ${String(manifest.format)}; this page reads format 2. Reload the page.`);
}
if (typeof manifest.id !== "string" || !Array.isArray(manifest.files)) {
throw new Error("build.json has no id or file list");
}
if (manifest.fast === undefined && manifest.compatible === undefined && manifest.rust === undefined) {
throw new Error("build.json lists no build to run");
}
return manifest as BuildManifest;
}
/** The build to run, or why it can't run. */
export type Choice =
| { readonly kind: "fast" | "compatible"; readonly target: WasmTarget }
| { readonly kind: "rust"; readonly target: RustTarget }
| { readonly kind: "unsupported"; readonly reason: string };
/** Why neither build can run without WebGL 2, the graphics floor for both; null if it's there. */
export function missingWebgl2(features: BrowserFeatures): string | null {
return features.webgl2
? null
: "This browser can't run WebGL 2, which the game needs. Check that hardware acceleration is on.";
}
/** Why neither build can run without WebAssembly GC; null if it's there. */
export function missingWasmGc(features: BrowserFeatures): string | null {
return features.wasmGc
? null
: "This browser is too old to run the game. Use Chrome or Edge 119, Firefox 120, Safari 18.2 or newer.";
}
/** One build on the loading screen's choice: whether it can run here, and why not. */
export interface BuildOption {
readonly kind: BuildKind;
readonly available: boolean;
/** Why it can't run: the browser lacks what it needs, or the build doesn't include it. */
readonly reason?: string;
}
/**
* The builds to offer, Fast first: it's the one to run wherever it works (far quicker, and a smaller
* download). Compatible is for browsers without JSPI. Rust comes last, and only when the copy has it.
*/
export function buildOptions(features: BrowserFeatures, manifest: BuildManifest): readonly BuildOption[] {
const fast: BuildOption =
manifest.fast === undefined
? { kind: "fast", available: false, reason: "This copy of the game doesn't include Fast." }
: features.jspi
? { kind: "fast", available: true }
: {
kind: "fast",
available: false,
reason: "Fast needs Chrome or Edge 137, Firefox 153 or newer.",
};
const compatible: BuildOption =
manifest.compatible === undefined
? { kind: "compatible", available: false, reason: "This copy of the game doesn't include Compatible." }
: { kind: "compatible", available: true };
if (manifest.rust === undefined) {
return [fast, compatible];
}
const rust: BuildOption = features.webgpu
? { kind: "rust", available: true }
: {
kind: "rust",
available: false,
reason: "Rust needs WebGPU: Chrome or Edge 113 or newer, with a graphics card it supports.",
};
return [fast, compatible, rust];
}
/** `?build=fast`, `compatible` or `rust`: a build asked for in the address, skipping the choice. */
export function requestedBuild(value: string | null): BuildKind | null {
return value === "fast" || value === "compatible" || value === "rust" ? value : null;
}
/**
* The option the choice starts on: the player's last pick if it can still run, else Fast if it can,
* else Compatible, and Rust only when nothing else runs.
*/
export function initialBuild(options: readonly BuildOption[], remembered: string | null): BuildKind {
const available = options.filter((option) => option.available).map((option) => option.kind);
const last = requestedBuild(remembered);
if (last !== null && available.includes(last)) {
return last;
}
return available.includes("fast") ? "fast" : available.includes("compatible") ? "compatible" : "rust";
}
/** The manifest's entry for a picked build, or why it can't run. */
export function buildFor(kind: BuildKind, options: readonly BuildOption[], manifest: BuildManifest): Choice {
const option = options.find((o) => o.kind === kind);
const unsupported: Choice = { kind: "unsupported", reason: option?.reason ?? `No ${kind} build to run.` };
if (option?.available !== true) {
return unsupported;
}
if (kind === "rust") {
return manifest.rust === undefined ? unsupported : { kind, target: manifest.rust };
}
const target = kind === "fast" ? manifest.fast : manifest.compatible;
return target === undefined ? unsupported : { kind, target };
}
/** What the player calls a build. */
export function buildName(kind: BuildKind): string {
return kind === "fast" ? "Fast" : kind === "compatible" ? "Compatible" : "Rust";
}
/**
* The Rust build's page with this page's address options, but `?build`: Horizon reads its own
* (`?args=`, its command line), and the rest it ignores.
*/
export function rustPage(target: RustTarget, here: string): string {
const url = new URL(target.page, here);
const search = new URL(here).searchParams;
search.delete("build");
url.search = search.toString();
return url.href;
}
/** A file's URL with its hash as the version, so a cache keeps it exactly until it changes. */
export function versioned(manifest: BuildManifest, path: string): string {
const file = manifest.files.find((f) => f.path === path);
return file === undefined ? path : `${path}?v=${file.sha256.slice(0, 16)}`;
}
/** The size the manifest gives a file, or 0 if it doesn't list it. */
export function sizeOf(manifest: BuildManifest, path: string): number {
return manifest.files.find((f) => f.path === path)?.size ?? 0;
}
/**
* A response whose body reports each chunk as it's read, for a progress bar. Headers and status are
* kept, so `WebAssembly.compileStreaming` still accepts it (it needs `application/wasm`) and still
* compiles while the bytes arrive.
*/
export function countingResponse(response: Response, onBytes: (received: number) => void): Response {
const body = response.body;
if (body === null) {
return response;
}
let received = 0;
const counted = body.pipeThrough(
new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
received += chunk.byteLength;
onBytes(received);
controller.enqueue(chunk);
},
}),
);
return new Response(counted, { status: response.status, statusText: response.statusText, headers: response.headers });
}
/** A byte count for people: "12.3 MB". */
export function formatBytes(bytes: number): string {
if (bytes < 1000) {
return `${String(bytes)} B`;
}
const units = ["kB", "MB", "GB"];
let value = bytes / 1000;
let unit = 0;
while (value >= 1000 && unit < units.length - 1) {
value /= 1000;
unit++;
}
return `${value.toFixed(value < 10 ? 1 : 0)} ${units[unit] ?? "GB"}`;
}
@@ -0,0 +1,456 @@
/**
* The single-file page (`./incari build --html`, ADR 0057): the whole build in one HTML file that
* opens straight from the disk. `tools/webbuild`'s `SingleFile` puts every file of the web folder in
* the page as base64 (gzipped where that helps) and this script in it, inline. It serves those files
* to the page and to every worker by the names they already fetch them by, so the game's code is the
* same as in the folder's build.
*
* A `file://` page can't fetch the files beside it, start a module worker from a Blob URL, or use the
* origin private file system, and its workers can't read the page's Blob URLs. A classic worker from
* a Blob URL works, shares the page's IndexedDB, and can import its own Blob URLs. So:
*
* - The page and every worker get a shim ({@link installFiles}) that answers `fetch`,
* `importScripts` and `new Worker` for the embedded files from their own Blobs.
* - A worker starts as a classic one that installs the shim, then runs its real script (as a module
* if one was asked for).
* - A worker asks the page through a port for a file it doesn't have yet.
* - The storage worker falls back to IndexedDB by itself.
*
* {@link installFiles} and {@link startWorker} are copied into each worker by their source text, so
* they use nothing from this module, only their parameters and the realm's globals.
*/
/** What a realm's shim is set up with. Everything here can be posted to a worker. */
export interface FileSetup {
/** The page's folder: relative URLs resolve against it everywhere, since a worker's own URL is a Blob's. */
readonly base: string;
/** Every embedded file's path, decoded or not. */
readonly paths: readonly string[];
/** The files decoded so far, by path; the scripts always are, since `importScripts` can't wait. */
readonly blobs: Readonly<Record<string, Blob>>;
/** The source of a worker's first script: {@link startWorker} given {@link installFiles}. */
readonly shim: string;
/** In a worker: where to ask for a file it doesn't have. */
readonly port?: MessagePort;
/** In a worker: the script it was started with, and whether to run it as a module. */
readonly script?: WorkerScript;
}
/** A worker's real script: an embedded file (`path`), or a Blob the page made from source. */
export interface WorkerScript {
readonly path: string | null;
readonly blob: Blob;
readonly module: boolean;
}
/** What a realm's shim offers its code. */
export interface FileAccess {
/** The page's folder ({@link FileSetup.base}): resolve page-relative names against it, not `location`. */
readonly base: string;
/** A URL this realm can load an embedded file's script from (a Blob URL), or `href` itself. */
url(href: string): string;
/** A Blob URL of an embedded module whose relative imports point at Blob URLs of their own. */
moduleUrl(path: string): Promise<string>;
/** Runs a worker's real script. */
start(script: WorkerScript): Promise<void>;
}
/** The globals the shim replaces or uses. */
export interface FileScope {
fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
Worker?: new (url: string | URL, options?: WorkerOptions) => Worker;
importScripts?: (...urls: string[]) => void;
incariFiles?: FileAccess;
}
/** A file the page decodes when it's first asked for. */
export type Decoder = (path: string) => Promise<Blob | null>;
/**
* Installs the shim on `scope`. `decode` is the page's; a worker asks `setup.port` instead.
* Self-contained: copied into workers by its source.
*/
export function installFiles(scope: FileScope, setup: FileSetup, decode?: Decoder): FileAccess {
const all = new Set(setup.paths);
const blobs = new Map<string, Blob>(Object.entries(setup.blobs));
const pending = new Map<string, Promise<Blob | null>>();
// Blob URLs made in this realm: by embedded file, and the modules' back to their file, so a worker
// started from `import.meta.url` (game-worker.ts) is one of the files again.
const urls = new Map<string, string>();
const modules = new Map<string, Promise<string>>();
const moduleFiles = new Map<string, string>();
// Script Blobs this realm made URLs of (the storage and program workers' sources), to start
// those workers from.
const scripts = new Map<string, Blob>();
const realFetch = scope.fetch.bind(scope);
const RealWorker = scope.Worker;
const realImportScripts = scope.importScripts?.bind(scope);
const createObjectUrl = URL.createObjectURL.bind(URL);
const revokeObjectUrl = URL.revokeObjectURL.bind(URL);
const asked = new Map<number, (blob: Blob | null) => void>();
let nextAsk = 0;
const port = setup.port;
if (port !== undefined) {
port.onmessage = (event: MessageEvent<{ id: number; blob: Blob | null }>) => {
asked.get(event.data.id)?.(event.data.blob);
asked.delete(event.data.id);
};
}
const fromPage: Decoder =
decode ??
((path) =>
port === undefined
? Promise.resolve(null)
: new Promise((resolve) => {
const id = nextAsk++;
asked.set(id, resolve);
port.postMessage({ id, path });
}));
/** The embedded file `url` names, relative to the page's folder, or null if it names none. */
function fileOf(url: string): string | null {
const module = moduleFiles.get(url);
if (module !== undefined) {
return module;
}
let href: string;
try {
href = new URL(url, setup.base).href;
} catch {
return null;
}
if (!href.startsWith(setup.base)) {
return null;
}
// Versioned URLs (`?v=<hash>`, loader.ts) name the same file.
const path = decodeURIComponent(href.slice(setup.base.length).replace(/[?#].*$/s, ""));
return all.has(path) ? path : null;
}
function blobOf(path: string): Promise<Blob | null> {
const known = blobs.get(path);
if (known !== undefined) {
return Promise.resolve(known);
}
let waiting = pending.get(path);
if (waiting === undefined) {
waiting = fromPage(path).then((blob) => {
if (blob !== null) {
blobs.set(path, blob);
}
return blob;
});
pending.set(path, waiting);
}
return waiting;
}
function urlOf(path: string): string {
let url = urls.get(path);
if (url === undefined) {
const blob = blobs.get(path);
if (blob === undefined) {
throw new Error(`${path} isn't loaded yet`);
}
url = createObjectUrl(blob);
urls.set(path, url);
}
return url;
}
/** The page's scripts import no cycle, so each module's imports are made first. */
function moduleUrl(path: string): Promise<string> {
let made = modules.get(path);
if (made === undefined) {
made = (async () => {
const blob = await blobOf(path);
if (blob === null) {
throw new Error(`No ${path} in this file`);
}
const source = await blob.text();
const imports = /(\b(?:from|import)\s*\(?\s*)(["'])(\.{1,2}\/[^"'\n]+)\2/g;
const targets = new Map<string, string>();
for (const match of source.matchAll(imports)) {
const specifier = match[3] ?? "";
const target = fileOf(new URL(specifier, setup.base + path).href);
if (target !== null && !targets.has(specifier)) {
targets.set(specifier, await moduleUrl(target));
}
}
const rewritten = source.replace(imports, (whole: string, before: string, quote: string, specifier: string) => {
const target = targets.get(specifier);
return target === undefined ? whole : before + quote + target + quote;
});
const url = createObjectUrl(new Blob([rewritten], { type: "text/javascript" }));
moduleFiles.set(url, path);
return url;
})();
modules.set(path, made);
}
return made;
}
scope.fetch = async (input, init) => {
const path = fileOf(input instanceof Request ? input.url : String(input));
if (path === null) {
return realFetch(input, init);
}
const blob = await blobOf(path);
return blob === null ? new Response(null, { status: 404, statusText: "Not Found" }) : new Response(blob);
};
URL.createObjectURL = (object) => {
const url = createObjectUrl(object);
if (object instanceof Blob && object.type.includes("javascript")) {
scripts.set(url, object);
}
return url;
};
URL.revokeObjectURL = (url) => {
scripts.delete(url);
revokeObjectUrl(url);
};
if (realImportScripts !== undefined) {
scope.importScripts = (...requested) => {
realImportScripts(
...requested.map((url) => {
const path = fileOf(url);
return path === null ? url : urlOf(path);
}),
);
};
}
let shimUrl: string | null = null;
if (RealWorker !== undefined) {
// A function, not a class: `new` returns the real worker it makes.
const OfflineWorker = function (url: string | URL, options?: WorkerOptions): Worker {
const href = String(url);
const path = fileOf(href);
const blob = path === null ? scripts.get(href) : blobs.get(path);
if (blob === undefined) {
return new RealWorker(url, options);
}
shimUrl ??= createObjectUrl(new Blob([setup.shim], { type: "text/javascript" }));
const worker = new RealWorker(shimUrl, options?.name === undefined ? {} : { name: options.name });
const channel = new MessageChannel();
channel.port1.onmessage = (event: MessageEvent<{ id: number; path: string }>) => {
void blobOf(event.data.path).then((found) => {
channel.port1.postMessage({ id: event.data.id, blob: found });
});
};
const files: FileSetup = {
base: setup.base,
paths: setup.paths,
blobs: Object.fromEntries(blobs),
shim: setup.shim,
port: channel.port2,
script: { path, blob, module: options?.type === "module" },
};
worker.postMessage({ incariFiles: files }, [channel.port2]);
return worker;
};
scope.Worker = OfflineWorker as unknown as new (url: string | URL, options?: WorkerOptions) => Worker;
}
const access: FileAccess = {
base: setup.base,
url(href) {
const path = fileOf(href);
return path === null ? href : urlOf(path);
},
moduleUrl,
async start(script) {
if (script.module) {
await import(script.path === null ? createObjectUrl(script.blob) : await moduleUrl(script.path));
} else if (realImportScripts !== undefined) {
realImportScripts(createObjectUrl(script.blob));
}
},
};
scope.incariFiles = access;
return access;
}
/** The parts of a worker's scope {@link startWorker} uses. */
export interface StartScope extends FileScope {
addEventListener(type: "message", listener: (event: MessageEvent) => void): void;
removeEventListener(type: "message", listener: (event: MessageEvent) => void): void;
dispatchEvent(event: Event): boolean;
setTimeout(handler: () => void, timeout: number): unknown;
}
/**
* A worker's first script: waits for the page's files, installs the shim, and runs the real script.
* Messages that come before that script listens are held and handed to it in order. Self-contained:
* copied into workers by its source.
*/
export function startWorker(scope: StartScope, install: typeof installFiles): void {
const held: MessageEvent<unknown>[] = [];
const hold = (event: MessageEvent<unknown>): void => {
held.push(event);
};
const first = (event: MessageEvent<{ incariFiles?: FileSetup } | null>): void => {
const setup = event.data?.incariFiles;
if (setup?.script === undefined) {
return;
}
scope.removeEventListener("message", first);
scope.addEventListener("message", hold);
install(scope, setup)
.start(setup.script)
.then(
() => {
scope.removeEventListener("message", hold);
for (const message of held.splice(0)) {
scope.dispatchEvent(new MessageEvent("message", { data: message.data, ports: [...message.ports] }));
}
},
(error: unknown) => {
// An uncaught error, so the worker's `onerror` on the other side hears of it.
scope.setTimeout(() => {
throw error;
}, 0);
},
);
};
scope.addEventListener("message", first);
}
/** The source of a worker's first script. */
export function shimSource(): string {
return `"use strict";\n(${startWorker.toString()})(self, ${installFiles.toString()});\n`;
}
/** How `SingleFile` marks an embedded file: `<script type=...>` with the base64 as its text. */
export const FILE_TYPE = "application/x-incari-file";
/** One embedded file's element, as the page reads it. */
export interface EmbeddedFile {
readonly path: string;
/** The file's media type, for the Blob (`application/wasm` lets the browser compile while reading). */
readonly type: string;
readonly gzip: boolean;
/** The base64; read once, then the element goes. */
text(): string;
}
/** Decodes one embedded file into a Blob of its type. */
export async function decodeFile(file: EmbeddedFile, realFetch: FileScope["fetch"]): Promise<Blob> {
const text = file.text();
const fromBase64 = (Uint8Array as { fromBase64?: (text: string) => Uint8Array<ArrayBuffer> }).fromBase64;
// Browsers before Uint8Array.fromBase64 decode a data: URL natively, which is far quicker than atob.
const bytes =
fromBase64 === undefined
? new Blob([await (await realFetch(`data:application/octet-stream;base64,${text}`)).arrayBuffer()])
: new Blob([fromBase64(text)]);
const body = file.gzip
? await new Response(bytes.stream().pipeThrough(new DecompressionStream("gzip"))).blob()
: bytes;
return new Blob([body], { type: file.type });
}
/**
* The folder for the embedded files' relative names when the page's own URL has none: an
* `about:blank` tab the page was written into, or a `blob:` or `data:` URL (how players open the
* file where `file://` is blocked). Only the shim resolves against it, so it needn't exist.
*/
export const FALLBACK_BASE = "file:///incari/";
/** The folder of the page at `href`, or {@link FALLBACK_BASE} where `href` has none. */
export function pageBase(href: string): string {
try {
return new URL(".", href).href;
} catch {
return FALLBACK_BASE;
}
}
/**
* The page's side: installs the shim over the embedded files and starts `boot.js`. The scripts are
* decoded first (workers and `importScripts` need them at once); the rest when first fetched, so
* the build the player doesn't pick and the languages they don't use are never decoded.
*/
export async function startPage(page: Window & FileScope, files: readonly EmbeddedFile[]): Promise<void> {
const realFetch = page.fetch.bind(page);
const byPath = new Map(files.map((file) => [file.path, file]));
const blobs: Record<string, Blob> = {};
for (const file of files) {
if (file.path.endsWith(".js")) {
blobs[file.path] = await decodeFile(file, realFetch);
byPath.delete(file.path);
}
}
const decodeLater: Decoder = async (path) => {
const file = byPath.get(path);
if (file === undefined) {
return null;
}
byPath.delete(path);
return decodeFile(file, realFetch);
};
const access = installFiles(
page,
{
base: pageBase(page.location.href),
paths: files.map((file) => file.path),
blobs,
shim: shimSource(),
},
decodeLater,
);
const boot = page.document.createElement("script");
boot.type = "module";
boot.src = await access.moduleUrl("boot.js");
page.document.body.append(boot);
}
/** The embedded files in `document`, each element removed once its text is read. */
export function embeddedFiles(document: Document): EmbeddedFile[] {
return Array.from(document.querySelectorAll<HTMLScriptElement>(`script[type="${FILE_TYPE}"]`), (element) => ({
path: element.dataset.path ?? "",
type: element.dataset.type ?? "application/octet-stream",
gzip: element.dataset.encoding === "gzip",
text: () => {
const text = element.text;
element.remove();
return text;
},
}));
}
/**
* Makes `navigator.sendBeacon` say it couldn't queue the beacon (false) instead of throwing, as
* Chromium does on a `file://` page. Scripts that aren't the game's (school monitoring, analytics)
* beacon when the tab is hidden, and their uncaught error would end the game (boot.ts).
*/
export function quietBeacons(navigator: Pick<Navigator, "sendBeacon">): void {
const send = navigator.sendBeacon.bind(navigator);
navigator.sendBeacon = (url, data) => {
try {
return send(url, data);
} catch {
return false;
}
};
}
/** What `SingleFile` calls after this script: starts the page, or says on the loading screen why it couldn't. */
export function start(page: Window & FileScope): void {
if (typeof page.navigator.sendBeacon === "function") {
quietBeacons(page.navigator);
}
startPage(page, embeddedFiles(page.document)).catch((error: unknown) => {
const status = page.document.getElementById("incari-status");
const detail = page.document.getElementById("incari-detail");
if (status !== null && detail !== null) {
status.textContent = "The game couldn't start";
detail.textContent = String(error);
}
console.error(
"[Incari] Crashed: " + (error instanceof Error && error.stack !== undefined ? error.stack : String(error)),
);
});
}
@@ -0,0 +1,106 @@
/**
* The page's service worker: keeps the build and the sounds the game has played, so a returning
* player downloads nothing that hasn't changed and can start offline. The decisions are in
* `cache-policy.ts`; this file only carries them out.
*
* Registered as a module worker by `boot.ts`. It never delays a request it can't help: anything it
* doesn't cache goes straight to the network.
*/
import { CACHES, staleBuildEntries, strategyFor, type Strategy } from "./cache-policy.ts";
/** The parts of a service worker's global scope this file uses (the DOM library doesn't have them). */
interface WorkerScope {
readonly registration: { readonly scope: string };
readonly clients: { claim(): Promise<void> };
skipWaiting(): Promise<void>;
addEventListener(type: "install" | "activate", listener: (event: ExtendableEvent) => void): void;
addEventListener(type: "fetch", listener: (event: FetchEvent) => void): void;
addEventListener(type: "message", listener: (event: MessageEvent<unknown>) => void): void;
}
interface ExtendableEvent {
waitUntil(work: Promise<unknown>): void;
}
interface FetchEvent extends ExtendableEvent {
readonly request: Request;
respondWith(response: Promise<Response>): void;
}
const worker = self as unknown as WorkerScope;
const scope = new URL(worker.registration.scope);
worker.addEventListener("install", (event) => {
// A new worker takes over at once: its caches are keyed by version, so nothing the old one
// stored can be served by mistake.
event.waitUntil(worker.skipWaiting());
});
worker.addEventListener("activate", (event) => {
event.waitUntil(
(async () => {
const known = new Set<string>(Object.values(CACHES));
for (const name of await caches.keys()) {
if (name.startsWith("incari-") && !known.has(name)) {
await caches.delete(name);
}
}
// So the page that registered it loads the build through it on the first visit.
await worker.clients.claim();
})(),
);
});
worker.addEventListener("fetch", (event) => {
const request = event.request;
const strategy = strategyFor(new URL(request.url), scope, request.method);
if (strategy !== "pass") {
event.respondWith(respond(request, strategy));
}
});
/** The page names the files its build loads; older versions of them are dropped. */
worker.addEventListener("message", (event) => {
const data = event.data as { type?: unknown; keep?: unknown } | null;
if (data?.type !== "build" || !Array.isArray(data.keep)) {
return;
}
const keep = data.keep.filter((path): path is string => typeof path === "string");
void (async () => {
const cache = await caches.open(CACHES.build);
const cached = (await cache.keys()).map((r) => r.url);
for (const href of staleBuildEntries(cached, keep, scope)) {
await cache.delete(href);
}
})();
});
async function respond(request: Request, strategy: Exclude<Strategy, "pass">): Promise<Response> {
if (strategy === "page") {
const cache = await caches.open(CACHES.page);
try {
const response = await fetch(request, { cache: "no-cache" });
if (response.ok) {
await cache.put(request, response.clone());
}
return response;
} catch (error) {
const cached = await cache.match(request);
if (cached !== undefined) {
return cached;
}
throw error;
}
}
const cache = await caches.open(strategy === "build" ? CACHES.build : CACHES.immutable);
const cached = await cache.match(request);
if (cached !== undefined) {
return cached;
}
const response = await fetch(request);
if (response.ok) {
// Stored while the page reads its copy: the module still compiles as it downloads.
void cache.put(request, response.clone());
}
return response;
}
@@ -0,0 +1,252 @@
/**
* TeaVM's event queue in the browser (`teavmAsync`), without the browser's timer clamp. TeaVM hands
* every event to `setTimeout`, a woken thread too (a `notify`, a finished wait): due at once, so a
* zero delay. But browsers hold a zero-delay timer set from inside a timer's callback, five deep, to
* at least 4 ms, and one thread waking another is just such a chain. In singleplayer's server worker
* each chunk storage scan (the game's structure check) is a hand-off of that kind between its IO
* thread and the world generation waiting on it, so a new world's ~8,000 scans took 16-22 seconds
* of timers, with the worker idle.
*
* Here an event due now goes on a queue that a `MessageChannel` drains, one event per message: the
* order TeaVM gave them, and no clamp (the background pool's slots use the same, `WorkerSlots`). An
* event due later still waits on `setTimeout`. Ids for queued events are negative, so `kill` knows
* which kind it cancels.
*/
/** The `teavmAsync` import module: `offer` returns an id `kill` takes back. */
export interface AsyncImports {
offer(instance: unknown, fn: (instance: unknown) => void, time: number): number;
kill(id: number): void;
}
/** What the imports need from the global scope, so tests can supply their own. */
export interface WakeupScope {
MessageChannel: new () => MessageChannel;
setTimeout(handler: () => void, delay: number): number;
clearTimeout(id: number): void;
now(): number;
}
const browserScope: WakeupScope = {
MessageChannel,
setTimeout: (handler, delay) => setTimeout(handler, delay) as unknown as number,
clearTimeout: (id) => {
clearTimeout(id);
},
now: () => Date.now(),
};
export function createAsyncImports(scope: WakeupScope = browserScope): AsyncImports {
const channel = new scope.MessageChannel();
// Insertion order is the order events were offered in.
const due = new Map<number, () => void>();
let nextId = 1;
channel.port1.onmessage = () => {
const first = due.entries().next();
if (first.done !== true) {
const [id, run] = first.value;
due.delete(id);
run();
}
};
return {
offer(instance, fn, time) {
const delay = time - scope.now();
if (delay > 0) {
return scope.setTimeout(() => {
fn(instance);
}, delay);
}
const id = -nextId++;
due.set(id, () => {
fn(instance);
});
channel.port2.postMessage(0);
return id;
},
kill(id) {
if (id < 0) {
// Its message still comes; it runs the next event due, or nothing.
due.delete(id);
} else {
scope.clearTimeout(id);
}
},
};
}
/**
* A timer whose callbacks a hidden page still gets on time: browsers hold a hidden page's own timers
* to one wake-up a second, and after five minutes hidden and silent (Chrome) to one a minute, which
* starves a server connection of its keep-alive answers until the server drops it. A worker's timer
* isn't held back that way, and its message wakes the page.
*/
export interface PageTimer {
set(handler: () => void, delay: number): number;
clear(id: number): void;
}
/** The parts of a `Worker` the timer uses, so tests can supply their own. */
export interface TimerWorker {
postMessage(message: unknown): void;
onmessage: ((event: { data: unknown }) => void) | null;
}
/** The timer worker's whole program: a timeout per request, answered with its id. */
const TIMER_WORKER_SOURCE =
"var timers = new Map();" +
"onmessage = function (e) { var m = e.data;" +
" if (m.delay !== undefined) { timers.set(m.id, setTimeout(function () { timers.delete(m.id); postMessage(m.id); }, m.delay)); }" +
" else { var t = timers.get(m.id); if (t !== undefined) { clearTimeout(t); timers.delete(m.id); } } };";
/** Starts the timer worker from a Blob URL; null where the page can't have one. */
export function startTimerWorker(): TimerWorker | null {
try {
const url = URL.createObjectURL(new Blob([TIMER_WORKER_SOURCE], { type: "text/javascript" }));
const worker = new Worker(url, { name: "incari-timer" });
const timerWorker: TimerWorker = {
postMessage: (message) => {
worker.postMessage(message);
},
onmessage: null,
};
worker.onmessage = (event: MessageEvent<unknown>) => {
timerWorker.onmessage?.({ data: event.data });
};
return timerWorker;
} catch {
return null;
}
}
/** A {@link PageTimer} over a timer worker. */
export function createPageTimer(worker: TimerWorker): PageTimer {
const handlers = new Map<number, () => void>();
let nextId = 1;
worker.onmessage = (event) => {
const id = Number(event.data);
const handler = handlers.get(id);
if (handler !== undefined) {
handlers.delete(id);
handler();
}
};
return {
set(handler, delay) {
const id = nextId++;
handlers.set(id, handler);
worker.postMessage({ id, delay: Math.max(0, delay) });
return id;
},
clear(id) {
if (handlers.delete(id)) {
worker.postMessage({ id });
}
},
};
}
/** What the page's imports need: timers, whether the page is hidden, and the worker timer. */
export interface PageWakeupScope extends Omit<WakeupScope, "MessageChannel"> {
hidden(): boolean;
timer: PageTimer | null;
}
/** Ids of events on the {@link PageTimer}: above any id the page's own timers give out. */
const PAGE_TIMER_IDS = 2 ** 30;
/** The page's {@link AsyncImports}, and a way to run the events already due without waiting. */
export interface PageAsyncImports extends AsyncImports {
/**
* Calls `wake` (which resumes a Java thread), then runs the events due now that were offered
* since, oldest first: the threads it woke, and those they wake in turn, at most
* {@link RUN_DUE_LIMIT}. Their timers then have nothing left to do; events offered before stay on
* theirs. Only from the page's own callbacks, with no Java on the stack: platform-web's network
* wake, whose render thread hands a message to the connection's thread.
*/
runWoken(wake: () => void): void;
}
/**
* The most due events one {@link PageAsyncImports.runWoken} runs: two threads that wake each other
* would otherwise keep it going, and the rest still have their timers.
*/
export const RUN_DUE_LIMIT = 32;
/**
* The page's `teavmAsync`: TeaVM's own (every event on `setTimeout`) while the page is visible; while
* it's hidden, every event goes on the {@link PageTimer}, which the browser doesn't hold back. So a
* hidden page's connection threads still answer the server, and its frames still come. Not the
* `MessageChannel` of {@link createAsyncImports}: on the page it once hung singleplayer at spawn (ADR
* 0043), and a spinning wait would busy a hidden tab's core, where a worker's round trip paces it.
*
* A visible page's events due now are also listed for {@link PageAsyncImports.runWoken}. In play,
* Chrome runs a zero-delay timer set from a socket's message ~35 ms late (two frames, measured; a
* channel message later still), while animation frames and socket messages come on time: a
* connection's thread woken to read a message waited that long (ADR 0075).
*/
export function createPageAsyncImports(scope: PageWakeupScope): PageAsyncImports {
// Timer id to its event and when it was offered, in the order offered (a Map keeps insertion order).
const due = new Map<number, { seq: number; run: () => void }>();
let nextSeq = 0;
return {
offer(instance, fn, time) {
const delay = Math.max(0, time - scope.now());
const timer = scope.timer;
if (scope.hidden() && timer !== null) {
return (
PAGE_TIMER_IDS +
timer.set(() => {
fn(instance);
}, delay)
);
}
if (delay > 0) {
return scope.setTimeout(() => {
fn(instance);
}, delay);
}
const id = scope.setTimeout(() => {
if (due.delete(id)) {
fn(instance);
}
}, 0);
due.set(id, {
seq: nextSeq++,
run: () => {
fn(instance);
},
});
return id;
},
kill(id) {
if (id >= PAGE_TIMER_IDS) {
scope.timer?.clear(id - PAGE_TIMER_IDS);
} else {
due.delete(id);
scope.clearTimeout(id);
}
},
runWoken(wake) {
const from = nextSeq;
wake();
let count = 0;
for (const [id, event] of due) {
if (count === RUN_DUE_LIMIT) {
return;
}
if (event.seq >= from) {
count++;
due.delete(id);
scope.clearTimeout(id);
event.run();
}
}
},
};
}
/** The page's {@link PageWakeupScope}: the browser's own channel and timers, and `document.hidden`. */
export function pageWakeupScope(timer: PageTimer | null): PageWakeupScope {
return { ...browserScope, hidden: () => document.hidden, timer };
}
File diff suppressed because one or more lines are too long
@@ -0,0 +1,70 @@
package incari.app.web.memory;
import static org.assertj.core.api.Assertions.assertThat;
import com.mojang.blaze3d.vertex.BufferBuilder;
import incari.platform.api.Platform;
import incari.platform.api.Platforms;
import incari.platform.api.threads.PlatformThreads;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/**
* The memory layer's gate (ADR 0008): the game's vertex and image code writes the same bytes over web-classlib's memory
* as over LWJGL's. {@link MemoryScenario} runs twice, once as the desktop game runs it (LWJGL's
* {@code MemoryUtil}, STB's PNG decoder) and once with the game's classes linked to the browser
* build's stand-ins ({@link SubstitutingClassLoader}), and every result must match to the byte.
*
* <p>This covers the stand-ins' logic and the heap's bookkeeping with its JVM backend; the browser
* probe runs the same scenario over linear memory and prints {@link MemoryScenario#digest}s to compare with these.
*/
class MemoryParityTest {
/**
* What the game's static initializers ask of the platform while these classes load: how many
* background threads {@code Util} may start. Anything else fails loudly.
*/
@BeforeAll
static void installPlatform() {
if (Platforms.isInstalled()) {
return;
}
PlatformThreads inline = suggested -> 0;
Platforms.install((Platform) Proxy.newProxyInstance(
Platform.class.getClassLoader(),
new Class<?>[] {Platform.class},
(proxy, method, args) -> switch (method.getName()) {
case "threads" -> inline;
case "nanoTime" -> System.nanoTime();
case "toString" -> "MemoryParityTest platform";
default -> throw new UnsupportedOperationException(method.getName());
}));
}
@Test
void vertexAndImageBytesMatchVanilla() throws Exception {
Map<String, byte[]> vanilla = new MemoryScenario().get();
SubstitutingClassLoader loader = new SubstitutingClassLoader(
getClass().getClassLoader(), BufferBuilder.class, Set.of(MemoryScenario.class.getName()));
@SuppressWarnings("unchecked") // The scenario's type, loaded again.
Supplier<Map<String, byte[]>> substituted =
(Supplier<Map<String, byte[]>>) loader.loadClass(MemoryScenario.class.getName())
.getConstructor()
.newInstance();
Map<String, byte[]> browser = substituted.get();
assertThat(browser.keySet()).containsExactlyElementsOf(vanilla.keySet());
for (Map.Entry<String, byte[]> result : vanilla.entrySet()) {
assertThat(result.getValue()).as(result.getKey()).isNotEmpty();
assertThat(browser.get(result.getKey())).as(result.getKey()).isEqualTo(result.getValue());
}
System.out.println("Memory parity: " + vanilla.size() + " results match; " + loader.reloadedCount()
+ " game classes linked to the stand-ins");
vanilla.forEach((name, bytes) -> System.out.println(" " + name + " " + MemoryScenario.digest(bytes)));
}
}
@@ -0,0 +1,425 @@
package incari.app.web.memory;
import com.mojang.blaze3d.buffers.Std140Builder;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.vertex.BufferBuilder;
import com.mojang.blaze3d.vertex.ByteBufferBuilder;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.MeshData;
import com.mojang.blaze3d.vertex.VertexSorting;
import com.mojang.renderpearl.api.pipeline.PrimitiveTopology;
import com.mojang.renderpearl.api.vertex.VertexFormat;
import com.mojang.renderpearl.api.vertex.VertexFormatElement;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Supplier;
import java.util.zip.CRC32;
import java.util.zip.Deflater;
import org.lwjgl.system.MemoryStack;
import org.lwjgl.system.MemoryUtil;
/**
* The game's own off-heap memory users, run through whatever {@code MemoryUtil} the class loader
* binds: LWJGL's on the desktop, web-classlib's stand-in in the browser build or under
* {@link SubstitutingClassLoader}. Vertices through {@code BufferBuilder}'s fast and generic paths,
* sorted index buffers, {@code ByteBufferBuilder}'s growth and compaction, {@code NativeImage}
* pixels and PNG decoding, a uniform block on the {@code MemoryStack}, and {@code MemoryUtil}
* directly. Each result is the bytes the game would hand the GPU, by name.
*
* <p>Deterministic: its own generator, not {@code Random}. Bytes the game leaves unwritten (the
* fourth byte of a packed normal) come from {@code malloc} and are garbage, so they're zeroed in
* the copies returned. Also compiled into a browser probe, so it uses nothing TeaVM lacks.
*/
public final class MemoryScenario implements Supplier<Map<String, byte[]>> {
private int seed = 0x1234567;
@Override
public Map<String, byte[]> get() {
Map<String, byte[]> out = new LinkedHashMap<>();
try {
entityQuads(out);
blockQuads(out);
genericFormats(out);
compaction(out);
images(out);
pngs(out);
uniforms(out);
memoryUtil(out);
} catch (IOException e) {
throw new IllegalStateException(e);
}
return out;
}
/** The entity fast path, then the quads sorted back to front, as translucent geometry is. */
private void entityQuads(Map<String, byte[]> out) {
// Small, so the builder grows (reallocates) several times.
try (ByteBufferBuilder vertices = new ByteBufferBuilder(64);
ByteBufferBuilder indices = new ByteBufferBuilder(16)) {
BufferBuilder builder = new BufferBuilder(vertices, PrimitiveTopology.QUADS, DefaultVertexFormat.ENTITY);
for (int i = 0; i < 4 * 700; i++) {
builder.addVertex(
coordinate(),
coordinate(),
coordinate(),
next(),
unit(),
unit(),
next() & 0xFFFF_FFFF,
next(),
signed(),
signed(),
signed());
}
try (MeshData mesh = builder.buildOrThrow()) {
out.put("entity.vertices", vertexBytes(mesh.vertexBuffer(), DefaultVertexFormat.ENTITY));
mesh.sortQuads(indices, VertexSorting.byDistance(3.0F, -2.0F, 5.0F));
ByteBuffer sorted = mesh.indexBuffer();
out.put("entity.indices", bytes(sorted == null ? ByteBuffer.allocate(0) : sorted));
}
}
}
private void blockQuads(Map<String, byte[]> out) {
try (ByteBufferBuilder vertices = new ByteBufferBuilder(256)) {
BufferBuilder builder = new BufferBuilder(vertices, PrimitiveTopology.QUADS, DefaultVertexFormat.BLOCK);
for (int i = 0; i < 4 * 300; i++) {
builder.addVertex(
coordinate(), coordinate(), coordinate(), next(), unit(), unit(), 0, next(), 0.0F, 1.0F, 0.0F);
}
try (MeshData mesh = builder.buildOrThrow()) {
out.put("block.vertices", vertexBytes(mesh.vertexBuffer(), DefaultVertexFormat.BLOCK));
}
}
}
/** Element by element, the path most of the GUI and debug renderers take. */
private void genericFormats(Map<String, byte[]> out) {
try (ByteBufferBuilder vertices = new ByteBufferBuilder(32)) {
BufferBuilder lines = new BufferBuilder(
vertices, PrimitiveTopology.LINES, DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH);
for (int i = 0; i < 4 * 50; i++) {
lines.addVertex(coordinate(), coordinate(), coordinate())
.setColor(next())
.setNormal(signed(), signed(), signed())
.setLineWidth(unit() * 4.0F);
}
try (MeshData mesh = lines.buildOrThrow()) {
out.put(
"lines.vertices",
vertexBytes(mesh.vertexBuffer(), DefaultVertexFormat.POSITION_COLOR_NORMAL_LINE_WIDTH));
}
BufferBuilder gui = new BufferBuilder(
vertices, PrimitiveTopology.TRIANGLES, DefaultVertexFormat.POSITION_TEX_LIGHTMAP_COLOR);
for (int i = 0; i < 3 * 90; i++) {
gui.addVertex(coordinate(), coordinate(), 0.0F)
.setUv(unit(), unit())
.setLight(next())
.setColor(next() & 0xFF, next() & 0xFF, next() & 0xFF, next() & 0xFF);
}
try (MeshData mesh = gui.buildOrThrow()) {
out.put(
"gui.vertices",
vertexBytes(mesh.vertexBuffer(), DefaultVertexFormat.POSITION_TEX_LIGHTMAP_COLOR));
}
}
}
/**
* Two meshes built from one buffer while a third is being written: closing both moves the
* unfinished one to the buffer's start with an overlapping {@code memCopy}.
*/
private void compaction(Map<String, byte[]> out) {
try (ByteBufferBuilder shared = new ByteBufferBuilder(128)) {
MeshData first = quads(shared, 3);
MeshData second = quads(shared, 5);
out.put("compaction.second", vertexBytes(second.vertexBuffer(), DefaultVertexFormat.POSITION_COLOR));
BufferBuilder third =
new BufferBuilder(shared, PrimitiveTopology.QUADS, DefaultVertexFormat.POSITION_COLOR);
for (int i = 0; i < 4 * 7; i++) {
third.addVertex(coordinate(), coordinate(), coordinate()).setColor(next());
}
first.close();
second.close();
try (MeshData mesh = third.buildOrThrow()) {
out.put("compaction.third", vertexBytes(mesh.vertexBuffer(), DefaultVertexFormat.POSITION_COLOR));
}
}
}
private MeshData quads(ByteBufferBuilder buffer, int count) {
BufferBuilder builder = new BufferBuilder(buffer, PrimitiveTopology.QUADS, DefaultVertexFormat.POSITION_COLOR);
for (int i = 0; i < 4 * count; i++) {
builder.addVertex(coordinate(), coordinate(), coordinate()).setColor(next());
}
return builder.buildOrThrow();
}
private void images(Map<String, byte[]> out) {
try (NativeImage image = new NativeImage(37, 23, false);
NativeImage zeroed = new NativeImage(NativeImage.Format.RGBA, 16, 16, true);
NativeImage wide = new NativeImage(41, 23, true)) {
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
image.setPixel(x, y, next());
}
}
image.fillRect(3, 4, 9, 5, 0x80FF4020);
image.copyRect(0, 0, 20, 10, 12, 8, true, false);
image.copyRect(zeroed, 5, 5, 2, 2, 10, 10, false, true);
wide.copyFrom(image);
out.put("image.pixels", bytes(image.getPixelBytes()));
out.put("image.zeroed", bytes(zeroed.getPixelBytes()));
out.put("image.wide", bytes(wide.getPixelBytes()));
try (NativeImage mapped = image.mappedCopy(argb -> argb ^ 0x00FF00FF)) {
out.put("image.mapped", bytes(mapped.getPixelBytes()));
out.put("image.abgr", ints(mapped.getPixelsABGR()));
}
byte[] luminance = new byte[16];
try (NativeImage alpha = new NativeImage(NativeImage.Format.LUMINANCE_ALPHA, 4, 4, true)) {
for (int i = 0; i < luminance.length; i++) {
luminance[i] = alpha.getLuminanceOrAlpha(i % 4, i / 4);
}
}
out.put("image.luminance", luminance);
}
}
/** PNGs of every colour type and row filter, decoded by STB on the desktop and PngDecoder in the browser. */
private void pngs(Map<String, byte[]> out) throws IOException {
int[][] kinds = {{6, 4}, {2, 3}, {0, 1}, {4, 2}, {3, 1}};
for (int[] kind : kinds) {
byte[] png = png(29, 17, kind[0], kind[1]);
// byte[] reads through the MemoryStack; an InputStream through memAlloc and memRealloc.
try (NativeImage fromBytes = NativeImage.read(png);
NativeImage fromStream = NativeImage.read(new ByteArrayInputStream(png))) {
out.put("png.type" + kind[0], bytes(fromBytes.getPixelBytes()));
out.put("png.type" + kind[0] + ".stream", bytes(fromStream.getPixelBytes()));
}
}
// Larger than the stack, so NativeImage.read(byte[]) takes memAlloc instead.
byte[] big = png(300, 120, 6, 4);
try (NativeImage image = NativeImage.read(big)) {
out.put("png.big", bytes(image.getPixelBytes()));
}
}
private void uniforms(Map<String, byte[]> out) {
try (MemoryStack stack = MemoryStack.stackPush()) {
ByteBuffer block = Std140Builder.onStack(stack, 96)
.putVec4(unit(), unit(), unit(), unit())
.putIVec4(next(), next(), next(), next())
.putVec3(unit(), unit(), unit())
.putFloat(unit())
.putVec2(unit(), unit())
.putIVec2(next(), next())
.putInt(next())
.putFloat(unit())
.putVec2(unit(), unit())
.get();
out.put("std140", bytes(block));
java.nio.IntBuffer ints = stack.callocInt(5);
ints.put(2, next());
out.put("stack.ints", bytes(MemoryUtil.memByteBuffer(MemoryUtil.memAddress(ints), 20)));
}
}
private void memoryUtil(Map<String, byte[]> out) {
long address = MemoryUtil.nmemCalloc(8, 8);
MemoryUtil.memPutInt(address, 0x11223344);
MemoryUtil.memPutFloat(address + 4, 1.25F);
MemoryUtil.memPutShort(address + 8, (short) -2);
MemoryUtil.memPutByte(address + 10, (byte) 0x7F);
// Overlapping, to a lower address, as ByteBufferBuilder compacts. (LWJGL's memCopy is
// memcpy: an overlap the other way gives different bytes on different machines.)
MemoryUtil.memCopy(address + 3, address + 1, 11);
ByteBuffer text = MemoryUtil.memUTF8("héllo, wörld");
long copy = MemoryUtil.nmemAlloc(text.remaining() + 1);
MemoryUtil.memCopy(MemoryUtil.memAddress(text), copy, text.remaining() + 1);
String back = MemoryUtil.memUTF8(copy);
ByteBuffer grown = MemoryUtil.memRealloc(MemoryUtil.memAlloc(4).putInt(0, 42), 4096);
ByteArrayOutputStream result = new ByteArrayOutputStream();
append(result, bytes(MemoryUtil.memByteBuffer(address, 64)));
append(result, back.getBytes(StandardCharsets.UTF_8));
result.write(MemoryUtil.memGetInt(address + 3));
result.write(MemoryUtil.memGetByte(address + 13));
result.write(grown.getInt(0));
result.write(grown.capacity() >> 8);
MemoryUtil.memFree(grown);
MemoryUtil.nmemFree(copy);
MemoryUtil.memFree(text);
MemoryUtil.nmemFree(address);
out.put("memoryutil", result.toByteArray());
}
// --- PNG files, written here so the check needs no game assets ------------------------------
/**
* A {@code width}x{@code height} 8-bit PNG of {@code colorType} (0 grey, 2 RGB, 3 palette, 4
* grey and alpha, 6 RGBA), its rows filtered by each of the five filters in turn.
*/
private byte[] png(int width, int height, int colorType, int channels) {
byte[][] rows = new byte[height][width * channels];
for (byte[] row : rows) {
for (int i = 0; i < row.length; i++) {
// Some runs of equal bytes, so the filters have something to predict.
row[i] = (byte) ((next() & 3) == 0 ? next() : i * 7);
}
}
ByteArrayOutputStream raw = new ByteArrayOutputStream();
byte[] previous = new byte[width * channels];
for (int y = 0; y < height; y++) {
int filter = y % 5;
raw.write(filter);
append(raw, filtered(rows[y], previous, channels, filter));
previous = rows[y];
}
ByteArrayOutputStream file = new ByteArrayOutputStream();
append(file, new byte[] {(byte) 0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'});
ByteArrayOutputStream header = new ByteArrayOutputStream();
writeInt(header, width);
writeInt(header, height);
append(header, new byte[] {8, (byte) colorType, 0, 0, 0});
chunk(file, "IHDR", header.toByteArray());
if (colorType == 3) {
byte[] palette = new byte[256 * 3];
byte[] alpha = new byte[256];
for (int i = 0; i < 256; i++) {
palette[i * 3] = (byte) i;
palette[i * 3 + 1] = (byte) (255 - i);
palette[i * 3 + 2] = (byte) (i * 3);
alpha[i] = (byte) (i * 5);
}
chunk(file, "PLTE", palette);
chunk(file, "tRNS", alpha);
}
Deflater deflater = new Deflater();
deflater.setInput(raw.toByteArray());
deflater.finish();
ByteArrayOutputStream packed = new ByteArrayOutputStream();
byte[] chunk = new byte[4096];
while (!deflater.finished()) {
packed.write(chunk, 0, deflater.deflate(chunk));
}
deflater.end();
chunk(file, "IDAT", packed.toByteArray());
chunk(file, "IEND", new byte[0]);
return file.toByteArray();
}
private static byte[] filtered(byte[] row, byte[] above, int stride, int filter) {
byte[] result = new byte[row.length];
for (int i = 0; i < row.length; i++) {
int a = i >= stride ? row[i - stride] & 0xFF : 0;
int b = above[i] & 0xFF;
int c = i >= stride ? above[i - stride] & 0xFF : 0;
int prediction =
switch (filter) {
case 1 -> a;
case 2 -> b;
case 3 -> (a + b) / 2;
case 4 -> paeth(a, b, c);
default -> 0;
};
result[i] = (byte) (row[i] - prediction);
}
return result;
}
private static int paeth(int a, int b, int c) {
int p = a + b - c;
int pa = Math.abs(p - a);
int pb = Math.abs(p - b);
int pc = Math.abs(p - c);
return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
}
private static void chunk(ByteArrayOutputStream file, String type, byte[] data) {
byte[] name = type.getBytes(StandardCharsets.US_ASCII);
writeInt(file, data.length);
append(file, name);
append(file, data);
CRC32 crc = new CRC32();
crc.update(name);
crc.update(data);
writeInt(file, (int) crc.getValue());
}
/** {@code out.writeBytes(bytes)}, which TeaVM's class library lacks. */
private static void append(ByteArrayOutputStream out, byte[] bytes) {
out.write(bytes, 0, bytes.length);
}
private static void writeInt(ByteArrayOutputStream out, int value) {
out.write(value >>> 24);
out.write(value >>> 16);
out.write(value >>> 8);
out.write(value);
}
// --- Values and bytes ---------------------------------------------------------------------
/** xorshift32: the same sequence on every platform. */
private int next() {
seed ^= seed << 13;
seed ^= seed >>> 17;
seed ^= seed << 5;
return seed;
}
private float unit() {
return (next() >>> 8) / (float) (1 << 24);
}
private float signed() {
return unit() * 2.0F - 1.0F;
}
private float coordinate() {
return (unit() - 0.5F) * 64.0F;
}
/**
* A result's fingerprint, to compare a browser run with a desktop one by eye: 64-bit FNV-1a
* (TeaVM has no {@code MessageDigest}).
*/
public static String digest(byte[] bytes) {
long hash = 0xcbf29ce484222325L;
for (byte b : bytes) {
hash = (hash ^ (b & 0xFF)) * 0x100000001b3L;
}
return Long.toHexString(hash) + "/" + bytes.length;
}
/** A buffer's remaining bytes, from its own position; the buffer doesn't move. */
private static byte[] bytes(ByteBuffer buffer) {
byte[] bytes = new byte[buffer.remaining()];
buffer.duplicate().get(bytes);
return bytes;
}
private static byte[] ints(int[] values) {
ByteBuffer buffer = ByteBuffer.allocate(values.length * 4);
buffer.asIntBuffer().put(values);
return buffer.array();
}
/** Vertex bytes with the padding byte after each packed normal cleared (malloc leaves it unset). */
private static byte[] vertexBytes(ByteBuffer vertices, VertexFormat format) {
byte[] bytes = bytes(vertices);
VertexFormatElement normal = format.getElement("Normal");
if (normal != null) {
int stride = format.getVertexSize();
for (int at = normal.offset() + 3; at < bytes.length; at += stride) {
bytes[at] = 0;
}
}
return bytes;
}
}
@@ -0,0 +1,222 @@
package incari.app.web.memory;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.jspecify.annotations.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.ClassRemapper;
import org.objectweb.asm.commons.Remapper;
/**
* Loads the game's classes as the browser build links them, as far as memory goes: every
* reference to an LWJGL class that {@code web-classlib} stands in for ({@code MemoryUtil},
* {@code MemoryStack}, {@code STBImage}...) is renamed to the stand-in, the way TeaVM's
* substitution does it, and the stand-ins run on this JVM.
*
* <p>Only the classes that need it are loaded again here: those that name a stand-in's class, and
* those that name one of them, and so on. Everything else, the stand-ins included, comes from the
* parent, so the game's shared data (vertex formats, enums) is the same objects on both sides.
* The {@code roots} are test classes that drive the game and are loaded here too.
*/
final class SubstitutingClassLoader extends ClassLoader {
private static final String SUBSTITUTES = "incari/classlib/substitutes/";
private final Set<String> reloaded;
private final Remapper remapper;
SubstitutingClassLoader(ClassLoader parent, Class<?> gameClass, Set<String> roots) {
super("substituting", parent);
Map<String, Set<String>> references = references(gameClass);
for (String root : roots) {
references.put(root.replace('.', '/'), referencesOf(readParent(root.replace('.', '/'))));
}
this.reloaded = closure(references);
this.reloaded.addAll(roots.stream().map(root -> root.replace('.', '/')).toList());
this.remapper = new Remapper(Opcodes.ASM9) {
@Override
public String map(String internalName) {
String substitute = substituteFor(internalName);
return substitute != null ? substitute : internalName;
}
};
}
/** How many of the game's classes are loaded again, for the test's report. */
int reloadedCount() {
return reloaded.size();
}
@Override
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
synchronized (getClassLoadingLock(name)) {
if (!reloaded.contains(name.replace('.', '/'))) {
return super.loadClass(name, resolve);
}
Class<?> loaded = findLoadedClass(name);
if (loaded == null) {
ClassWriter writer = new ClassWriter(0);
new ClassReader(readParent(name.replace('.', '/'))).accept(new ClassRemapper(writer, remapper), 0);
byte[] bytes = writer.toByteArray();
loaded = defineClass(name, bytes, 0, bytes.length);
}
if (resolve) {
resolveClass(loaded);
}
return loaded;
}
}
/** {@code org/lwjgl/system/MemoryUtil$MemoryAllocator} to its stand-in's name, if web-classlib has one. */
private @Nullable String substituteFor(String internalName) {
if (!internalName.startsWith("org/lwjgl/")) {
return null;
}
int slash = internalName.lastIndexOf('/');
String candidate = SUBSTITUTES + internalName.substring(0, slash + 1) + "T" + internalName.substring(slash + 1);
return getParent().getResource(candidate + ".class") != null ? candidate : null;
}
private byte[] readParent(String internalName) {
try (InputStream in = getParent().getResourceAsStream(internalName + ".class")) {
if (in == null) {
throw new IllegalStateException("No class file for " + internalName);
}
return in.readAllBytes();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/** The classes each class of the game names, read from the jar or directory {@code gameClass} came from. */
private static Map<String, Set<String>> references(Class<?> gameClass) {
Map<String, Set<String>> references = new HashMap<>();
try {
Path location = Path.of(gameClass
.getProtectionDomain()
.getCodeSource()
.getLocation()
.toURI());
if (Files.isDirectory(location)) {
try (Stream<Path> files = Files.walk(location)) {
for (Path file : (Iterable<Path>) files::iterator) {
String relative = location.relativize(file).toString().replace('\\', '/');
if (relative.endsWith(".class")) {
references.put(
relative.substring(0, relative.length() - 6),
referencesOf(Files.readAllBytes(file)));
}
}
}
} else {
try (ZipInputStream zip = new ZipInputStream(Files.newInputStream(location))) {
for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
String name = entry.getName();
if (name.endsWith(".class") && !name.startsWith("META-INF/")) {
references.put(name.substring(0, name.length() - 6), referencesOf(zip.readAllBytes()));
}
}
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
} catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
return references;
}
/**
* Every class a class file names, loosely: each UTF-8 constant as a name itself (what class
* entries point at) and the {@code Lpkg/Name;} names inside it (descriptors and signatures).
* Names that aren't classes are harmless; they match nothing.
*/
private static Set<String> referencesOf(byte[] classFile) {
Set<String> names = new HashSet<>();
ClassReader reader = new ClassReader(classFile);
for (int i = 1; i < reader.getItemCount(); i++) {
int offset = reader.getItem(i);
// A CONSTANT_Utf8 entry: tag 1, a big-endian length, then the text (ASCII for class names).
if (offset > 0 && classFile[offset - 1] == 1) {
int length = ((classFile[offset] & 0xFF) << 8) | (classFile[offset + 1] & 0xFF);
String text = new String(classFile, offset + 2, length, java.nio.charset.StandardCharsets.ISO_8859_1);
names.add(text.startsWith("[") ? text.substring(text.lastIndexOf('[') + 1) : text);
addDescriptorNames(text, names);
}
}
return names;
}
/** Names in {@code Lpkg/Name;} form inside a descriptor or signature, loosely: false names are harmless. */
private static void addDescriptorNames(String text, Set<String> names) {
int at = text.indexOf('L');
while (at >= 0) {
int end = text.indexOf(';', at);
if (end < 0) {
return;
}
String candidate = text.substring(at + 1, end);
int generic = candidate.indexOf('<');
names.add(generic >= 0 ? candidate.substring(0, generic) : candidate);
at = text.indexOf('L', end);
}
}
/**
* The classes that reach a stand-in's class through the references, and every class in their
* packages: a class loaded here can't use package-private members of one from the parent,
* whose runtime package differs.
*/
private Set<String> closure(Map<String, Set<String>> references) {
Map<String, Set<String>> users = new HashMap<>();
Map<String, Set<String>> packages = new HashMap<>();
ArrayDeque<String> pending = new ArrayDeque<>();
Set<String> result = new HashSet<>();
for (Map.Entry<String, Set<String>> entry : references.entrySet()) {
String name = entry.getKey();
packages.computeIfAbsent(packageOf(name), p -> new HashSet<>()).add(name);
for (String reference : entry.getValue()) {
users.computeIfAbsent(reference, n -> new HashSet<>()).add(name);
if (substituteFor(reference) != null && result.add(name)) {
pending.add(name);
}
}
}
Set<String> expandedPackages = new HashSet<>();
while (!pending.isEmpty()) {
String name = pending.removeFirst();
for (String user : users.getOrDefault(name, Set.of())) {
if (result.add(user)) {
pending.add(user);
}
}
if (expandedPackages.add(packageOf(name))) {
for (String mate : packages.getOrDefault(packageOf(name), Set.of())) {
if (result.add(mate)) {
pending.add(mate);
}
}
}
}
return result;
}
private static String packageOf(String internalName) {
int slash = internalName.lastIndexOf('/');
return slash < 0 ? "" : internalName.substring(0, slash);
}
}
@@ -0,0 +1,47 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { staleBuildEntries, strategyFor } from "../../main/ts/cache-policy.ts";
const scope = new URL("https://example.test/incari/");
const at = (path: string) => new URL(path, scope);
describe("strategyFor", () => {
it("keeps versioned build files until their version changes", () => {
assert.equal(strategyFor(at("incari.wasm?v=0123456789abcdef"), scope), "build");
assert.equal(strategyFor(at("incari.pack?v=0123456789abcdef"), scope), "build");
});
it("keeps game assets named by their content hash", () => {
assert.equal(strategyFor(at("assets/objects/ab/ab" + "0".repeat(38)), scope), "immutable");
assert.equal(strategyFor(at("assets/objects/ab/not-a-hash"), scope), "pass");
});
it("serves the page from the network, with a copy for offline starts", () => {
for (const path of ["", "index.html", "boot.js", "build.json", "asset-index.json"]) {
assert.equal(strategyFor(at(path), scope), "page", path);
}
});
it("leaves the client jar to the storage worker, and anything else alone", () => {
assert.equal(strategyFor(at("client.jar"), scope), "pass");
assert.equal(strategyFor(at("shaders.json"), scope), "pass");
assert.equal(strategyFor(new URL("https://elsewhere.test/incari/boot.js"), scope), "pass");
assert.equal(strategyFor(new URL("https://example.test/other/boot.js"), scope), "pass");
assert.equal(strategyFor(at("build.json"), scope, "POST"), "pass");
});
it("leaves the Rust build to its own worker, versioned files and page included", () => {
assert.equal(strategyFor(at("rust/pkg/horizon-client_bg.wasm?v=0123456789abcdef"), scope), "pass");
assert.equal(strategyFor(at("rust/index.html"), scope), "pass");
});
});
describe("staleBuildEntries", () => {
it("drops every cached build file the running build doesn't load", () => {
const cached = [at("incari.wasm?v=old").href, at("incari.wasm?v=new").href, at("incari.pack?v=new").href];
assert.deepEqual(staleBuildEntries(cached, ["incari.wasm?v=new", "incari.pack?v=new"], scope), [
at("incari.wasm?v=old").href,
]);
});
});
@@ -0,0 +1,71 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { detectFeatures, type FeatureScope } from "../../main/ts/features.ts";
/** JSPI's two members, which TypeScript's WebAssembly types don't have yet. */
function jspiOf(api: object): { Suspending: unknown; promising: unknown } {
const jspi = api as { Suspending: unknown; promising: unknown };
return { Suspending: jspi.Suspending, promising: jspi.promising };
}
describe("detectFeatures", () => {
it("finds WebAssembly GC in an engine that has it", async () => {
// Node 24+ ships the GC proposal, so the real probe must validate here.
assert.equal((await detectFeatures({ WebAssembly })).wasmGc, true);
});
it("finds JSPI in an engine that has it, and none without WebAssembly GC", async () => {
// Node 26 ships JSPI, as Chrome 137+ does.
assert.equal((await detectFeatures({ WebAssembly })).jspi, true);
assert.equal((await detectFeatures({ WebAssembly: { validate: () => true } })).jspi, false);
assert.equal(
(
await detectFeatures({
WebAssembly: { ...jspiOf(WebAssembly), validate: () => false } as unknown as typeof WebAssembly,
})
).jspi,
false,
);
});
it("reports no WebAssembly GC when the engine rejects the probe", async () => {
const withoutGc: FeatureScope = { WebAssembly: { validate: () => false } };
assert.equal((await detectFeatures(withoutGc)).wasmGc, false);
});
it("treats an engine that throws on the probe as unsupported", async () => {
const throwing: FeatureScope = {
WebAssembly: {
validate: () => {
throw new TypeError("unknown type form");
},
},
};
assert.equal((await detectFeatures(throwing)).wasmGc, false);
});
it("needs both isolation and SharedArrayBuffer for shared memory", async () => {
assert.equal((await detectFeatures({ crossOriginIsolated: true, SharedArrayBuffer })).crossOriginIsolated, true);
assert.equal((await detectFeatures({ crossOriginIsolated: false, SharedArrayBuffer })).crossOriginIsolated, false);
assert.equal((await detectFeatures({ crossOriginIsolated: true })).crossOriginIsolated, false);
});
it("reports no WebGL2 without a document, or when no context can be made", async () => {
assert.equal((await detectFeatures({})).webgl2, false);
const noContext = {
createElement: () => ({ getContext: () => null }),
} as unknown as Pick<Document, "createElement">;
assert.equal((await detectFeatures({ document: noContext })).webgl2, false);
});
it("finds WebGPU only when it gives an adapter", async () => {
assert.equal((await detectFeatures({})).webgpu, false);
const gpu = (adapter: unknown) => ({ navigator: { gpu: { requestAdapter: () => Promise.resolve(adapter) } } });
assert.equal((await detectFeatures(gpu({}))).webgpu, true);
// A browser with the API and no GPU it will use.
assert.equal((await detectFeatures(gpu(null))).webgpu, false);
const failing = { navigator: { gpu: { requestAdapter: () => Promise.reject(new Error("no GPU process")) } } };
assert.equal((await detectFeatures(failing)).webgpu, false);
});
});
@@ -0,0 +1,110 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { createInbox, serve, startChild, type WorkerFactory, type WorkerScope } from "../../main/ts/game-worker.ts";
function envelope(kind: number): { kind: number; data: ArrayBuffer } {
return { kind, data: new ArrayBuffer(kind) };
}
describe("game-worker inbox", () => {
it("hands queued messages out in order, then waits for the next", async () => {
const inbox = createInbox();
inbox.push(envelope(1));
inbox.push(envelope(2));
assert.equal(inbox.take()?.kind, 1);
assert.equal((await inbox.next())?.kind, 2);
assert.equal(inbox.take(), null);
const waiting = inbox.next();
inbox.push(envelope(3));
assert.equal((await waiting)?.kind, 3);
});
it("ends with null, and nothing comes after", async () => {
const inbox = createInbox();
inbox.push(envelope(1));
inbox.push(null);
inbox.push(envelope(2));
assert.equal((await inbox.next())?.kind, 1);
assert.equal(await inbox.next(), null);
});
});
describe("game-worker serve", () => {
it("queues the page's messages for the program", async () => {
const posted: unknown[] = [];
const scope: WorkerScope = {
postMessage: (message) => posted.push(message),
onmessage: null,
close: () => undefined,
console,
};
serve(scope);
scope.onmessage?.({ data: envelope(7) });
const parent = scope.__incariParent;
assert.ok(parent !== undefined);
assert.equal((await parent.next())?.kind, 7);
assert.deepEqual(posted, []);
scope.onmessage?.({ data: { kind: -1, data: new ArrayBuffer(0) } });
assert.equal(await parent.next(), null);
});
});
describe("game-worker endings", () => {
it("closes a terrain helper when its server ends the channel", () => {
let closed = false;
const scope: WorkerScope = {
postMessage: () => undefined,
onmessage: null,
close: () => {
closed = true;
},
console,
};
serve(scope);
scope.onmessage?.({
data: { start: { runtime: "data:text/javascript,", module: "m.wasm", jspi: false, role: "terrain" } },
});
scope.onmessage?.({ data: { kind: -1, data: new ArrayBuffer(0) } });
assert.equal(closed, true);
});
});
describe("game-worker startChild", () => {
it("starts the build in the role, and passes messages both ways until the child ends", async () => {
const posted: unknown[] = [];
let made: { url: string; name: string | undefined } | null = null;
let deliver: ((data: unknown) => void) | null = null;
const factory: WorkerFactory = (url, options) => {
made = { url: url.href, name: options.name };
return {
postMessage: (message) => posted.push(message),
listen: (onMessage) => {
deliver = onMessage;
},
terminate: () => undefined,
};
};
const build = { runtime: "r.js", module: "m.wasm", jspi: true, role: "server", query: "?x=1" };
const channel = startChild({ console }, build, "terrain", factory, new URL("https://h/game-worker.js"));
assert.deepEqual(made, { url: "https://h/game-worker.js", name: "incari-terrain" });
assert.deepEqual(posted[0], { start: { ...build, role: "terrain" }, storage: null });
channel.send(4, new ArrayBuffer(4));
assert.equal((posted[1] as { kind: number }).kind, 4);
const toChannel = deliver as ((data: unknown) => void) | null;
assert.ok(toChannel !== null);
toChannel(envelope(5));
assert.equal((await channel.next())?.kind, 5);
toChannel({ kind: -1, data: new ArrayBuffer(0) });
assert.equal(await channel.next(), null);
});
});
@@ -0,0 +1,151 @@
import assert from "node:assert/strict";
import { setImmediate } from "node:timers/promises";
import { describe, it } from "node:test";
import { createJspiImports, supportsJspi, type JspiScope } from "../../main/ts/jspi.ts";
/**
* A module shaped like a JSPI build's fibers: its `teavm.jspi.run(id)` export waits on promise `id`
* through `teavmJspi.await`, then calls `t.done(id)`.
*/
// prettier-ignore
const FIBER_MODULE = new Uint8Array([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, // "\0asm", version 1
0x01, 0x05, 0x01, 0x60, 0x01, 0x7f, 0x00, // types: (func (param i32))
0x02, 0x1c, 0x02, // imports, 28 bytes, two:
0x09, 0x74, 0x65, 0x61, 0x76, 0x6d, 0x4a, 0x73, 0x70, 0x69, // "teavmJspi"
0x05, 0x61, 0x77, 0x61, 0x69, 0x74, 0x00, 0x00, // "await", func type 0
0x01, 0x74, 0x04, 0x64, 0x6f, 0x6e, 0x65, 0x00, 0x00, // "t" "done", func type 0
0x03, 0x02, 0x01, 0x00, // functions: one of type 0
0x07, 0x12, 0x01, 0x0e, // exports, 18 bytes, one, a 14-byte name:
0x74, 0x65, 0x61, 0x76, 0x6d, 0x2e, 0x6a, 0x73, 0x70, 0x69, 0x2e, 0x72, 0x75, 0x6e, // "teavm.jspi.run"
0x00, 0x02, // function 2
0x0a, 0x0c, 0x01, 0x0a, 0x00, // code, one body of 10 bytes, no locals:
0x20, 0x00, 0x10, 0x00, // local.get 0; call await
0x20, 0x00, 0x10, 0x01, // local.get 0; call done
0x0b, // end
]);
/** A scope whose JSPI wrappers record their use, for the bookkeeping alone. */
function fakeScope(promising: (fn: (id: number) => unknown) => (id: number) => Promise<unknown>): JspiScope {
return {
WebAssembly: {
Suspending: class {
readonly fn: (id: number) => unknown;
constructor(fn: (id: number) => unknown) {
this.fn = fn;
}
},
promising,
},
};
}
describe("supportsJspi", () => {
it("finds JSPI in an engine that has it", () => {
// Node 26 ships JSPI, as Chrome 137+ does.
assert.equal(supportsJspi({ WebAssembly }), true);
});
it("reports no JSPI without Suspending and promising", () => {
assert.equal(supportsJspi({ WebAssembly: {} }), false);
assert.equal(supportsJspi({}), false);
});
});
describe("createJspiImports", () => {
it("keeps a fiber's stack until its promise resolves (real JSPI)", async () => {
const done: number[] = [];
const jspi = createJspiImports((error) => {
throw error;
});
const { instance } = await WebAssembly.instantiate(FIBER_MODULE, {
teavmJspi: jspi.module as WebAssembly.ModuleImports,
t: { done: (id: number) => done.push(id) },
});
jspi.attach(instance.exports);
const create = jspi.module.create as () => number;
const run = jspi.module.run as (id: number) => void;
const resolve = jspi.module.resolve as (id: number) => void;
const id = create();
run(id);
// The fiber waits, and run returned to its caller.
assert.deepEqual(done, []);
assert.equal(jspi.pending(), 1);
resolve(id);
await setImmediate();
assert.deepEqual(done, [id]);
assert.equal(jspi.pending(), 0);
});
it("ends every waiting fiber when told to, and reports nothing on the way out", async () => {
const done: number[] = [];
const failures: unknown[] = [];
const jspi = createJspiImports((error) => failures.push(error));
const { instance } = await WebAssembly.instantiate(FIBER_MODULE, {
teavmJspi: jspi.module as WebAssembly.ModuleImports,
t: { done: (id: number) => done.push(id) },
});
jspi.attach(instance.exports);
const create = jspi.module.create as () => number;
const run = jspi.module.run as (id: number) => void;
const first = create();
const second = create();
run(first);
run(second);
assert.equal(jspi.pending(), 2);
jspi.terminate();
await setImmediate();
// Both resumed (a real build's fiber then traps); none is left waiting.
assert.deepEqual(done.sort(), [first, second].sort());
assert.equal(jspi.pending(), 0);
assert.deepEqual(failures, []);
// A fiber that waits after the end resumes at once.
const late = create();
run(late);
await setImmediate();
assert.ok(done.includes(late));
});
it("forgets a promise dropped by a call that completed before waiting", () => {
const jspi = createJspiImports(
() => undefined,
fakeScope(() => () => Promise.resolve()),
);
const create = jspi.module.create as () => number;
const drop = jspi.module.drop as (id: number) => void;
const first = create();
const second = create();
assert.notEqual(first, second);
drop(first);
assert.equal(jspi.pending(), 1);
});
it("reports an error that escapes a fiber", async () => {
const failures: unknown[] = [];
const jspi = createJspiImports(
(error) => failures.push(error),
fakeScope(() => () => Promise.reject(new Error("escaped"))),
);
jspi.attach({ "teavm.jspi.run": () => undefined });
(jspi.module.run as (id: number) => void)(1);
await setImmediate();
assert.equal(failures.length, 1);
assert.match(String(failures[0]), /escaped/);
});
it("refuses to start a fiber before the exports are attached", () => {
const jspi = createJspiImports(
() => undefined,
fakeScope(() => () => Promise.resolve()),
);
assert.throws(() => {
(jspi.module.run as (id: number) => void)(1);
}, /before the module's exports/);
});
});
@@ -0,0 +1,212 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import type { BrowserFeatures } from "../../main/ts/features.ts";
import {
buildFor,
buildName,
buildOptions,
countingResponse,
DEFAULT_MANIFEST,
formatBytes,
initialBuild,
missingWasmGc,
missingWebgl2,
parseManifest,
requestedBuild,
rustPage,
sizeOf,
versioned,
type BuildManifest,
} from "../../main/ts/loader.ts";
const everything: BrowserFeatures = {
wasmGc: true,
jspi: true,
crossOriginIsolated: true,
webgl2: true,
webgpu: true,
};
/** Safari 18.2+ and Chrome 119-136: WebAssembly GC, no JSPI. */
const noJspi: BrowserFeatures = { ...everything, jspi: false };
const manifest: BuildManifest = {
format: 2,
id: "abc",
game: "26.3",
release: true,
fast: { runtime: "incari.wasm-runtime.js", module: "incari-fast.wasm" },
compatible: { runtime: "incari.wasm-runtime.js", module: "incari.wasm" },
files: [
{ path: "incari.wasm", size: 1000, sha256: "0123456789abcdef0123456789abcdef" },
{ path: "incari-fast.wasm", size: 2000, sha256: "fedcba9876543210fedcba9876543210" },
],
};
describe("buildOptions", () => {
it("offers both builds, Fast first, where both can run", () => {
assert.deepEqual(buildOptions(everything, manifest), [
{ kind: "fast", available: true },
{ kind: "compatible", available: true },
]);
});
it("explains why Fast can't run in a browser without JSPI", () => {
assert.deepEqual(buildOptions(noJspi, manifest), [
{
kind: "fast",
available: false,
reason: "Fast needs Chrome or Edge 137, Firefox 153 or newer.",
},
{ kind: "compatible", available: true },
]);
});
it("offers Rust last, only when the copy has it, and says when WebGPU is missing", () => {
const withRust: BuildManifest = { ...manifest, rust: { page: "rust/index.html" } };
assert.deepEqual(buildOptions(everything, withRust)[2], { kind: "rust", available: true });
const noWebgpu = buildOptions({ ...everything, webgpu: false }, withRust).find((o) => o.kind === "rust");
assert.equal(noWebgpu?.available, false);
assert.match(noWebgpu.reason ?? "", /WebGPU/);
});
it("marks a build this copy doesn't include", () => {
const fastOnly = { ...manifest, compatible: undefined } as unknown as BuildManifest;
assert.deepEqual(buildOptions(everything, fastOnly), [
{ kind: "fast", available: true },
{ kind: "compatible", available: false, reason: "This copy of the game doesn't include Compatible." },
]);
});
});
describe("requestedBuild", () => {
it("reads ?build=fast and ?build=compatible, and nothing else", () => {
assert.equal(requestedBuild("fast"), "fast");
assert.equal(requestedBuild("compatible"), "compatible");
assert.equal(requestedBuild("rust"), "rust");
assert.equal(requestedBuild("wasm"), null);
assert.equal(requestedBuild(null), null);
});
});
describe("initialBuild", () => {
const both = buildOptions(everything, manifest);
it("starts on Fast, the recommended build", () => {
assert.equal(initialBuild(both, null), "fast");
});
it("never starts on Rust unless it was the last pick or nothing else runs", () => {
const withRust = buildOptions(everything, { ...manifest, rust: { page: "rust/index.html" } });
assert.equal(initialBuild(withRust, null), "fast");
assert.equal(initialBuild(withRust, "rust"), "rust");
const rustOnly = withRust.map((option) => (option.kind === "rust" ? option : { ...option, available: false }));
assert.equal(initialBuild(rustOnly, null), "rust");
});
it("starts on the player's last pick while it can still run", () => {
assert.equal(initialBuild(both, "compatible"), "compatible");
assert.equal(initialBuild(buildOptions(noJspi, manifest), "fast"), "compatible");
});
});
describe("buildFor", () => {
it("gives the manifest's entry for a build that can run", () => {
assert.deepEqual(buildFor("fast", buildOptions(everything, manifest), manifest), {
kind: "fast",
target: manifest.fast,
});
});
it("gives the Rust build's page", () => {
const withRust: BuildManifest = { ...manifest, rust: { page: "rust/index.html" } };
assert.deepEqual(buildFor("rust", buildOptions(everything, withRust), withRust), {
kind: "rust",
target: { page: "rust/index.html" },
});
});
it("refuses a build that can't run here, with the reason", () => {
const choice = buildFor("fast", buildOptions(noJspi, manifest), manifest);
assert.ok(choice.kind === "unsupported");
assert.match(choice.reason, /Fast needs/);
});
});
describe("buildName", () => {
it("names the builds as the player sees them", () => {
assert.equal(buildName("fast"), "Fast");
assert.equal(buildName("compatible"), "Compatible");
assert.equal(buildName("rust"), "Rust");
});
});
describe("rustPage", () => {
it("opens Rust's page beside this one, keeping the address options but ?build", () => {
assert.equal(
rustPage({ page: "rust/index.html" }, "https://example.test/incari/?build=rust&args=--world%20T"),
"https://example.test/incari/rust/index.html?args=--world+T",
);
assert.equal(
rustPage({ page: "rust/index.html" }, "https://example.test/"),
"https://example.test/rust/index.html",
);
});
});
describe("missingWebgl2 and missingWasmGc", () => {
it("need WebGL 2 and WebAssembly GC for either build", () => {
assert.equal(missingWebgl2(everything), null);
assert.match(missingWebgl2({ ...everything, webgl2: false }) ?? "", /WebGL 2/);
assert.equal(missingWasmGc(everything), null);
assert.match(missingWasmGc({ ...everything, wasmGc: false }) ?? "", /too old to run the game/);
});
});
describe("parseManifest", () => {
it("accepts a manifest the build tool writes", () => {
assert.deepEqual(parseManifest(JSON.parse(JSON.stringify(manifest))), manifest);
});
it("refuses another format, a missing file list, and a manifest with nothing to run", () => {
assert.throws(() => parseManifest({ ...manifest, format: 1 }), /format 1/);
assert.throws(() => parseManifest({ format: 2, id: "x" }), /file list/);
assert.throws(() => parseManifest({ format: 2, id: "x", files: [] }), /no build/);
assert.throws(() => parseManifest(null), /isn't an object/);
});
});
describe("versioned", () => {
it("adds the file's hash as its version", () => {
assert.equal(versioned(manifest, "incari.wasm"), "incari.wasm?v=0123456789abcdef");
});
it("leaves a file the manifest doesn't list as it is", () => {
assert.equal(versioned(DEFAULT_MANIFEST, "incari.wasm"), "incari.wasm");
assert.equal(sizeOf(DEFAULT_MANIFEST, "incari.wasm"), 0);
assert.equal(sizeOf(manifest, "incari-fast.wasm"), 2000);
});
});
describe("countingResponse", () => {
it("reports the bytes read so far and keeps the body and headers", async () => {
const original = new Response(new Blob([new Uint8Array(10), new Uint8Array(5)]), {
headers: { "Content-Type": "application/wasm" },
});
const seen: number[] = [];
const counted = countingResponse(original, (received) => seen.push(received));
assert.equal(counted.headers.get("Content-Type"), "application/wasm");
const body = new Uint8Array(await counted.arrayBuffer());
assert.equal(body.byteLength, 15);
assert.equal(seen.at(-1), 15);
});
});
describe("formatBytes", () => {
it("prints sizes as people read them", () => {
assert.equal(formatBytes(512), "512 B");
assert.equal(formatBytes(1_500), "1.5 kB");
assert.equal(formatBytes(29_390_000), "29 MB");
assert.equal(formatBytes(156_500_000), "157 MB");
});
});
@@ -0,0 +1,325 @@
import assert from "node:assert/strict";
import { resolveObjectURL } from "node:buffer";
import { afterEach, beforeEach, describe, it } from "node:test";
import {
installFiles,
quietBeacons,
shimSource,
startWorker,
type FileScope,
type FileSetup,
type StartScope,
} from "../../main/ts/offline.ts";
const BASE = "file:///home/player/";
/** The shim replaces URL's Blob URL functions in its realm; each test gets the originals back. */
const createObjectURL = URL.createObjectURL.bind(URL);
const revokeObjectURL = URL.revokeObjectURL.bind(URL);
afterEach(() => {
URL.createObjectURL = createObjectURL;
URL.revokeObjectURL = revokeObjectURL;
});
async function textAt(url: string): Promise<string> {
const blob = resolveObjectURL(url);
assert.ok(blob !== undefined, `${url} is a Blob URL`);
return blob.text();
}
function script(source: string): Blob {
return new Blob([source], { type: "text/javascript" });
}
function setup(blobs: Record<string, Blob>, paths: string[] = Object.keys(blobs)): FileSetup {
return { base: BASE, paths, blobs, shim: "/* shim */" };
}
/** A realm whose fetch records what reached the network. */
function scope(): FileScope & { fetched: string[] } {
const fetched: string[] = [];
return {
fetched,
fetch: (input) => {
fetched.push(input instanceof Request ? input.url : String(input));
return Promise.resolve(new Response("from the network"));
},
};
}
describe("offline files: fetch", () => {
it("serves embedded files by relative, absolute and versioned URLs", async () => {
const realm = scope();
installFiles(realm, setup({ "build.json": new Blob(["{}"], { type: "application/json" }) }));
for (const url of ["build.json", `${BASE}build.json`, "build.json?v=0123456789abcdef", "./build.json#x"]) {
const response = await realm.fetch(url);
assert.equal(response.status, 200);
assert.equal(response.headers.get("content-type"), "application/json");
assert.equal(await response.text(), "{}");
}
assert.deepEqual(realm.fetched, []);
});
it("leaves every other URL to the real fetch", async () => {
const realm = scope();
installFiles(realm, setup({ "build.json": new Blob(["{}"]) }));
await realm.fetch("assets/objects/ab/abcdef");
await realm.fetch("https://example.com/build.json");
await realm.fetch("data:text/plain,hi");
assert.deepEqual(realm.fetched, [
"assets/objects/ab/abcdef",
"https://example.com/build.json",
"data:text/plain,hi",
]);
});
it("decodes a file once, when it's first fetched", async () => {
const realm = scope();
const decoded: string[] = [];
installFiles(realm, setup({}, ["client.jar", "missing.bin"]), (path) => {
decoded.push(path);
return Promise.resolve(path === "client.jar" ? new Blob(["jar"]) : null);
});
const [first, second] = await Promise.all([realm.fetch("client.jar"), realm.fetch("client.jar?v=1")]);
assert.equal(await first.text(), "jar");
assert.equal(await second.text(), "jar");
assert.equal((await realm.fetch("missing.bin")).status, 404);
assert.deepEqual(decoded, ["client.jar", "missing.bin"]);
});
});
describe("offline files: scripts", () => {
it("points a module's relative imports at Blob URLs of the imported files", async () => {
const realm = scope();
const files = installFiles(
realm,
setup({
"boot.js": script('import { a } from "./loader.js";\nimport "./jspi.js";\nconst b = import("./other.js");'),
"loader.js": script('import { c } from "./jspi.js";\nexport const a = c;'),
"jspi.js": script("export const c = 1;"),
}),
);
const boot = await textAt(await files.moduleUrl("boot.js"));
const imported = [...boot.matchAll(/"(blob:[^"]+)"/g)].map((match) => match[1] ?? "");
assert.equal(imported.length, 2);
assert.match(await textAt(imported[0] ?? ""), /^import \{ c \} from "blob:/);
assert.equal(await textAt(imported[1] ?? ""), "export const c = 1;");
// Not an embedded file: left as it was.
assert.match(boot, /import\("\.\/other\.js"\)/);
// One Blob URL per module, however many import it.
assert.equal(await files.moduleUrl("jspi.js"), imported[1]);
});
it("gives an embedded script's Blob URL for loading, and any other URL back", () => {
const realm = scope();
const files = installFiles(realm, setup({ "incari.wasm-runtime.js": script("var TeaVM = {};") }));
assert.match(files.url(`${BASE}incari.wasm-runtime.js?v=1`), /^blob:/);
assert.equal(files.url("https://example.com/x.js"), "https://example.com/x.js");
assert.equal(realm.incariFiles, files);
});
it("loads embedded scripts through importScripts from Blob URLs", () => {
const loaded: string[] = [];
const realm: FileScope = {
...scope(),
importScripts: (...urls) => {
loaded.push(...urls);
},
};
installFiles(realm, setup({ "mesher.wasm-runtime.js": script("") }));
realm.importScripts?.(`${BASE}mesher.wasm-runtime.js?v=2`, "https://example.com/other.js");
assert.equal(loaded.length, 2);
assert.match(loaded[0] ?? "", /^blob:/);
assert.equal(loaded[1], "https://example.com/other.js");
});
});
/** The shim's `Worker`, which a realm with workers always gets. */
function workerClass(realm: FileScope): NonNullable<FileScope["Worker"]> {
const Worker = realm.Worker;
assert.ok(Worker !== undefined);
return Worker;
}
/** A worker as the shim starts it: what it was made with and the messages posted to it. */
interface MadeWorker {
url: string;
options: WorkerOptions | undefined;
posted: { message: unknown; transfer: Transferable[] | undefined }[];
}
describe("offline files: workers", () => {
let made: MadeWorker[];
let realm: FileScope & { fetched: string[] };
afterEach(() => {
// Open ports keep Node running.
for (const worker of made) {
(worker.posted[0]?.message as { incariFiles?: FileSetup } | undefined)?.incariFiles?.port?.close();
}
});
beforeEach(() => {
made = [];
realm = scope();
realm.Worker = function (url: string | URL, options?: WorkerOptions) {
const worker: MadeWorker = { url: String(url), options, posted: [] };
made.push(worker);
return {
postMessage: (message: unknown, transfer?: Transferable[]) => worker.posted.push({ message, transfer }),
} as unknown as Worker;
} as unknown as NonNullable<FileScope["Worker"]>;
});
function setupPosted(worker: MadeWorker | undefined): FileSetup {
const message = worker?.posted[0]?.message as { incariFiles?: FileSetup } | undefined;
assert.ok(message?.incariFiles !== undefined, "the shim's files are the first message");
return message.incariFiles;
}
it("starts an embedded module worker as a classic one that runs the shim, then the module", () => {
installFiles(realm, setup({ "game-worker.js": script("export {};"), "client.jar": new Blob(["jar"]) }));
new (workerClass(realm))(new URL("game-worker.js", BASE), { type: "module", name: "incari-server" });
const worker = made[0];
assert.match(worker?.url ?? "", /^blob:/);
assert.deepEqual(worker?.options, { name: "incari-server" });
const files = setupPosted(worker);
assert.deepEqual(files.script === undefined ? null : { path: files.script.path, module: files.script.module }, {
path: "game-worker.js",
module: true,
});
assert.deepEqual(Object.keys(files.blobs).sort(), ["client.jar", "game-worker.js"]);
assert.equal(files.base, BASE);
});
it("starts a worker from a script Blob this realm made with the shim, as a classic worker", async () => {
installFiles(realm, setup({}));
const source = script("onmessage = () => {};");
const url = URL.createObjectURL(source);
new (workerClass(realm))(url, { name: "incari-storage" });
const files = setupPosted(made[0]);
assert.equal(files.script?.path, null);
assert.equal(files.script.module, false);
assert.equal(await files.script.blob.text(), "onmessage = () => {};");
});
it("leaves any other worker alone", () => {
installFiles(realm, setup({}));
new (workerClass(realm))("https://example.com/worker.js", { type: "module" });
assert.deepEqual(made[0], { url: "https://example.com/worker.js", options: { type: "module" }, posted: [] });
});
it("answers a worker's request for a file it doesn't have yet", async () => {
installFiles(realm, setup({}, ["incari-fast.wasm", "program.js"]), (path) =>
Promise.resolve(path === "incari-fast.wasm" ? new Blob(["module"]) : script("")),
);
await realm.fetch("program.js");
new (workerClass(realm))("program.js");
const port = setupPosted(made[0]).port;
assert.ok(port !== undefined);
const reply = new Promise<{ id: number; blob: Blob | null }>((resolve) => {
port.onmessage = (event: MessageEvent<{ id: number; blob: Blob | null }>) => {
resolve(event.data);
};
});
port.postMessage({ id: 7, path: "incari-fast.wasm" });
const answer = await reply;
assert.equal(answer.id, 7);
assert.equal(await answer.blob?.text(), "module");
});
});
/** A worker's global scope, enough for startWorker. */
class FakeWorkerScope extends EventTarget {
readonly imported: string[] = [];
readonly heard: unknown[] = [];
fetch: FileScope["fetch"] = () => Promise.resolve(new Response(null));
importScripts = (...urls: string[]): void => {
this.imported.push(...urls);
// The real script listens once it runs.
this.addEventListener("message", (event) => {
this.heard.push((event as MessageEvent).data);
});
};
setTimeout = (handler: () => void, timeout: number): unknown => setTimeout(handler, timeout);
}
function init(files: Partial<FileSetup>): MessageEvent {
return new MessageEvent("message", {
data: { incariFiles: { base: BASE, paths: [], blobs: {}, shim: "", ...files } },
});
}
describe("offline files: a worker's start", () => {
it("runs the real script, which then hears the page's messages", async () => {
const worker = new FakeWorkerScope();
startWorker(worker as unknown as StartScope, installFiles);
worker.dispatchEvent(init({ script: { path: null, blob: script(""), module: false } }));
// A message is a task of its own: the start's promise has settled before the next one comes.
// (A module's import takes longer; messages before it are held, which the browser checks see.)
await new Promise((resolve) => setTimeout(resolve, 0));
worker.dispatchEvent(new MessageEvent("message", { data: "first" }));
worker.dispatchEvent(new MessageEvent("message", { data: "second" }));
assert.equal(worker.imported.length, 1);
assert.match(worker.imported[0] ?? "", /^blob:/);
assert.deepEqual(worker.heard, ["first", "second"]);
});
it("works from its own source alone, as a worker gets it", async () => {
const worker = new FakeWorkerScope();
// eslint-disable-next-line @typescript-eslint/no-implied-eval -- the worker's shim is source text by design
(new Function("self", shimSource()) as (self: unknown) => void)(worker);
worker.dispatchEvent(
init({
paths: ["runtime.js"],
blobs: { "runtime.js": script("") },
script: { path: null, blob: script(""), module: false },
}),
);
await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal(worker.imported.length, 1);
assert.equal(typeof (worker as unknown as FileScope).incariFiles?.url, "function");
const response = await worker.fetch("runtime.js");
assert.equal(response.headers.get("content-type"), "text/javascript");
});
});
describe("quietBeacons", () => {
it("answers false where the browser throws, and passes the rest through", () => {
const sent: string[] = [];
const navigator = {
sendBeacon(url: string | URL): boolean {
if (String(url).startsWith("file:")) {
throw new TypeError("Beacons are only supported over HTTP(S).");
}
sent.push(String(url));
return true;
},
};
quietBeacons(navigator);
assert.equal(navigator.sendBeacon("file:///home/player/log"), false);
assert.equal(navigator.sendBeacon("https://example.com/log"), true);
assert.deepEqual(sent, ["https://example.com/log"]);
});
});
@@ -0,0 +1,217 @@
import assert from "node:assert/strict";
import { setTimeout as sleep } from "node:timers/promises";
import { afterEach, describe, it } from "node:test";
import {
createAsyncImports,
createPageAsyncImports,
createPageTimer,
RUN_DUE_LIMIT,
type PageTimer,
type TimerWorker,
type WakeupScope,
} from "../../main/ts/wakeups.ts";
/** Channels the tests made: an open port keeps Node running, so each test closes them. */
const channels: MessageChannel[] = [];
class ClosableChannel extends MessageChannel {
constructor() {
super();
channels.push(this);
}
}
/** Node's own channel and timers, with a clock the test sets. */
function scope(now: () => number): WakeupScope & { timers: number } {
const result = {
MessageChannel: ClosableChannel,
timers: 0,
setTimeout(handler: () => void, delay: number): number {
result.timers++;
return setTimeout(handler, delay) as unknown as number;
},
clearTimeout(id: number): void {
clearTimeout(id);
},
now,
};
return result;
}
/** Waits until the channel's messages have been handled. */
async function drain(): Promise<void> {
await sleep(20);
}
describe("wakeups", () => {
afterEach(() => {
for (const channel of channels.splice(0)) {
channel.port1.close();
channel.port2.close();
}
});
it("runs events due now in the order offered, without timers", async () => {
const s = scope(() => 1000);
const imports = createAsyncImports(s);
const ran: string[] = [];
for (const name of ["a", "b", "c"]) {
imports.offer(name, (instance) => ran.push(instance as string), 1000);
}
assert.deepEqual(ran, []);
await drain();
assert.deepEqual(ran, ["a", "b", "c"]);
assert.equal(s.timers, 0);
});
it("runs an event due later on a timer", async () => {
const s = scope(() => 1000);
const imports = createAsyncImports(s);
const ran: string[] = [];
const id = imports.offer("later", (instance) => ran.push(instance as string), 1005);
assert.ok(id > 0);
assert.equal(s.timers, 1);
await sleep(30);
assert.deepEqual(ran, ["later"]);
});
it("cancels either kind", async () => {
const s = scope(() => 1000);
const imports = createAsyncImports(s);
const ran: string[] = [];
const now = imports.offer("now", (instance) => ran.push(instance as string), 900);
const kept = imports.offer("kept", (instance) => ran.push(instance as string), 1000);
const later = imports.offer("later", (instance) => ran.push(instance as string), 1010);
assert.ok(now < 0 && kept < 0);
imports.kill(now);
imports.kill(later);
await sleep(40);
assert.deepEqual(ran, ["kept"]);
// The cancelled event's message ran nothing extra.
imports.offer("after", (instance) => ran.push(instance as string), 1000);
await drain();
assert.deepEqual(ran, ["kept", "after"]);
});
it("keeps up with a chain of events each offering the next", async () => {
const imports = createAsyncImports(scope(() => 0));
let count = 0;
const started = performance.now();
await new Promise<void>((resolve) => {
const step = (): void => {
if (++count === 500) {
resolve();
} else {
imports.offer(null, step, 0);
}
};
imports.offer(null, step, 0);
});
// Timers clamped to 1 ms or more would take half a second at least.
const elapsed = performance.now() - started;
assert.ok(elapsed < 400, `${elapsed.toFixed(0)} ms`);
});
it("leaves a visible page on plain timers, and times a hidden one in the worker", async () => {
const s = scope(() => 1000);
let hidden = false;
const set: number[] = [];
const cleared: number[] = [];
const timer: PageTimer = {
set(handler, delay) {
set.push(delay);
setTimeout(handler, 1);
return set.length;
},
clear(id) {
cleared.push(id);
},
};
const imports = createPageAsyncImports({ ...s, hidden: () => hidden, timer });
const ran: string[] = [];
const visible = imports.offer("visible", (instance) => ran.push(instance as string), 1000);
assert.ok(visible > 0 && visible < 2 ** 30);
assert.equal(s.timers, 1);
hidden = true;
const now = imports.offer("now", (instance) => ran.push(instance as string), 900);
const later = imports.offer("later", (instance) => ran.push(instance as string), 1500);
assert.ok(now >= 2 ** 30 && later >= 2 ** 30);
assert.deepEqual(set, [0, 500]);
assert.equal(s.timers, 1);
imports.kill(later);
assert.deepEqual(cleared, [2]);
await sleep(30);
assert.deepEqual([...ran].sort(), ["later", "now", "visible"]);
});
it("runs the events a wake offers at once, each only once, and leaves the rest to their timers", async () => {
const s = scope(() => 1000);
const imports = createPageAsyncImports({ ...s, hidden: () => false, timer: null });
const ran: string[] = [];
const offer = (name: string, time: number): number =>
imports.offer(name, (instance) => ran.push(instance as string), time);
offer("older", 1000);
imports.runWoken(() => {
offer("woken", 1000);
const killed = offer("killed", 990);
offer("later", 1010);
imports.kill(killed);
imports.offer(
"chained",
(instance) => {
ran.push(instance as string);
offer("chain's own", 1000);
},
1000,
);
});
assert.deepEqual(ran, ["woken", "chained", "chain's own"]);
await sleep(40);
// The older event and the later one come on their own timers; the woken ones' find nothing.
assert.deepEqual(ran, ["woken", "chained", "chain's own", "older", "later"]);
});
it("stops after its limit when the woken events keep offering more", async () => {
const s = scope(() => 0);
const imports = createPageAsyncImports({ ...s, hidden: () => false, timer: null });
const count = { runs: 0 };
let stopped = false;
const again = (): void => {
count.runs++;
if (!stopped) {
imports.offer(null, again, 0);
}
};
imports.runWoken(() => {
imports.offer(null, again, 0);
});
assert.equal(count.runs, RUN_DUE_LIMIT);
// The rest are still on their timers.
const runsSoFar = (): number => count.runs;
const stop = runsSoFar();
await sleep(5);
stopped = true;
assert.ok(runsSoFar() > stop);
await sleep(5);
});
it("times a page timer in its worker and cancels it there", () => {
const posted: unknown[] = [];
const worker: TimerWorker = {
postMessage(message) {
posted.push(message);
},
onmessage: null,
};
const timer = createPageTimer(worker);
const ran: number[] = [];
const first = timer.set(() => ran.push(1), 250);
const second = timer.set(() => ran.push(2), -5);
timer.clear(second);
assert.deepEqual(posted, [{ id: first, delay: 250 }, { id: second, delay: 0 }, { id: second }]);
worker.onmessage?.({ data: second });
worker.onmessage?.({ data: first });
assert.deepEqual(ran, [1]);
});
});