Archive incari-client (client, 26.3, clean)
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
+222
@@ -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]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user