Archive incari-client (client, 26.3, clean)
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
# tools/webbuild
|
||||
|
||||
- Change what's removed through `tools/survey/rules.txt`, not code here.
|
||||
- A link error in a stub or shim symbol is fixed in `web-classlib`, never by removing it.
|
||||
- Test: `./gradlew :tools:webbuild:check`; run for real with `./gradlew :app-web:teavm`.
|
||||
@@ -0,0 +1,51 @@
|
||||
# tools/webbuild: the browser build's compiler
|
||||
|
||||
Compiles the game for the browser with TeaVM (WebAssembly GC): the game as `:client` built it, the
|
||||
web platform, `web-classlib`, and the libraries `tools/survey/rules.txt` keeps. Output goes to
|
||||
`app-web/build/teavm/` (Compatible) or `teavm-fast/` (Fast), never committed or published. It also
|
||||
holds the dev server, browser checks, screenshot diffs, benchmark and packaging. You run it through
|
||||
`app-web`'s Gradle tasks.
|
||||
|
||||
```sh
|
||||
./gradlew :app-web:teavm -Pteavm.verbose # with TeaVM's call chains for link errors
|
||||
```
|
||||
|
||||
## What changes what TeaVM sees
|
||||
|
||||
`Main` first checks that `tools/teavm-patches`' classes, not TeaVM's, are loaded. Then:
|
||||
|
||||
| Class | Does |
|
||||
| --- | --- |
|
||||
| `ClasslibPolicy`, `ClasslibRenamer` | Map `web-classlib`'s `T<Name>` substitutes over JDK classes |
|
||||
| `AdditionsTransformer` | Add `web-classlib`'s additions to TeaVM's classes, or replace methods |
|
||||
| `RemovalTransformer`, `Removals` | Remove references to missing symbols the survey files under *delete* or *rewrite* |
|
||||
| `MonitorElision` | Drop monitors from methods that can't suspend, so they don't become coroutines (ADR 0006) |
|
||||
| `TypeCaptures` | Keep generic superclasses that `TypeToken`s and Netty handlers read at run time |
|
||||
| `JspiTransformer` | Route fibers through JSPI in the Fast build (ADR 0036) |
|
||||
| `JsoIntrinsics`, `MathIntrinsics` | Cheaper JavaScript calls; `Math.floor`/`ceil`/`sqrt` as wasm instructions |
|
||||
| `ThrowCensus` | Count throws (`-Pteavm.throwCensus`, ADR 0033) |
|
||||
| `WasmOpt` | Run Binaryen's wasm-opt on the Fast release build (ADR 0043) |
|
||||
|
||||
## Tools
|
||||
|
||||
| Class | Task | Does |
|
||||
| --- | --- | --- |
|
||||
| `Serve` | `serve` | Localhost-only static server with the right `.wasm` type and isolation headers |
|
||||
| `BrowserCheck`, `DevTools`, `Chromium` | `browserCheck` | Runs the page in headless Chromium; passes on the game loop's heartbeat, fails on a crash. Runs step scripts |
|
||||
| `DownloadSize`, `DownloadBudget` | `checkDownloadSize` | Sizes (raw, gzip 9, brotli via the `brotli` command) against the budget |
|
||||
| `ScreenshotDiff`, `ImageDiff` | `screenshotDiff` | Desktop vs browser renders by SSIM (ADR 0012) |
|
||||
| `Benchmark`, `BenchmarkReport`, `PerfBaseline`, `PerfBudget` | `benchmark` | Scenario runs against a baseline ([`docs/benchmark.md`](../../docs/benchmark.md)) |
|
||||
| `BuildManifest`, `WebFolder`, `SingleFile`, `SmallSounds` | `buildManifest`, `webFolder`, `singleFile` | The manifest, the self-hosted folder, the one-file build |
|
||||
|
||||
## Outputs beside the build
|
||||
|
||||
- `problems.txt`: every link error, by missing symbol, with call sites.
|
||||
- `async.txt`: why methods are coroutines, and hot virtual calls still compiled as suspension points.
|
||||
- `removed.txt`: every reference removed, by the rule that removed it.
|
||||
|
||||
## Invariants
|
||||
|
||||
- Removal decisions belong to the survey: change `tools/survey/rules.txt`, never special-case a
|
||||
symbol here. Only missing symbols are removed.
|
||||
- A missing stub or shim stays a link error until `web-classlib` provides it.
|
||||
- Runs on exactly JDK 25, like the survey.
|
||||
@@ -0,0 +1,38 @@
|
||||
plugins {
|
||||
application
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// Fixes to TeaVM classes; first on the class path so they replace TeaVM's (see its README).
|
||||
implementation(project(":tools:teavm-patches"))
|
||||
// The workspace, the version pin, and the survey's library rules and JDK hiding.
|
||||
implementation(project(":tools:build"))
|
||||
implementation(project(":tools:survey"))
|
||||
implementation(libs.teavm.tooling)
|
||||
implementation(libs.teavm.core)
|
||||
implementation(libs.teavm.classlib)
|
||||
// The class substitution SPI (ClasslibPolicy).
|
||||
implementation(libs.teavm.extension.spi)
|
||||
// The JavaScript interop the web platform is written against.
|
||||
implementation(libs.teavm.jso)
|
||||
implementation(libs.teavm.jso.apis)
|
||||
runtimeOnly(libs.teavm.jso.impl)
|
||||
// The browser check's DevTools protocol messages.
|
||||
implementation(libs.gson)
|
||||
// The screenshot-diff harness bridges the browser to its game server in-process.
|
||||
implementation(project(":tools:wsbridge"))
|
||||
// Turns WebAssembly stack traces back into Java names in development builds.
|
||||
runtimeOnly(libs.teavm.wasm.gc.deobfuscator)
|
||||
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testImplementation(libs.assertj)
|
||||
testRuntimeOnly(libs.junit.launcher)
|
||||
}
|
||||
|
||||
application {
|
||||
applicationName = "incari-webbuild"
|
||||
mainClass = "incari.tools.webbuild.Main"
|
||||
// TeaVM's dependency analysis over the game is memory-hungry.
|
||||
applicationDefaultJvmArgs = listOf("-Xmx16g")
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import org.teavm.model.AccessLevel;
|
||||
import org.teavm.model.ClassHierarchy;
|
||||
import org.teavm.model.ClassHolder;
|
||||
import org.teavm.model.ClassHolderTransformer;
|
||||
import org.teavm.model.ClassHolderTransformerContext;
|
||||
import org.teavm.model.ClassReader;
|
||||
import org.teavm.model.ElementModifier;
|
||||
import org.teavm.model.MethodDescriptor;
|
||||
import org.teavm.model.MethodHolder;
|
||||
import org.teavm.model.MethodReader;
|
||||
import org.teavm.model.MethodReference;
|
||||
import org.teavm.model.ValueType;
|
||||
import org.teavm.model.emit.ProgramEmitter;
|
||||
import org.teavm.model.emit.ValueEmitter;
|
||||
|
||||
/**
|
||||
* Adds methods a class TeaVM has lacks, from {@code web-classlib}'s additions classes: the
|
||||
* public static methods of {@code incari.classlib.additions.<package>.<Name>Additions} become
|
||||
* methods of {@code <package>.<Name>}, each forwarding to its addition.
|
||||
*
|
||||
* <p>An addition annotated {@code @incari.classlib.InstanceMethod} becomes an instance method:
|
||||
* its first parameter is the receiver ({@code static long threadId(Thread self)} adds
|
||||
* {@code Thread.threadId()}). Others are added as static methods. A method the class already has
|
||||
* is left alone, so an addition goes quiet once TeaVM catches up, unless TeaVM marks it
|
||||
* {@code @UnsupportedOn} a platform or the addition is marked {@code @incari.classlib.Replaces}:
|
||||
* then the addition replaces it. An addition marked {@code @incari.classlib.Constructor} becomes a
|
||||
* constructor with its parameters that hands its result to the class's own constructor for that
|
||||
* type.
|
||||
*/
|
||||
public final class AdditionsTransformer implements ClassHolderTransformer {
|
||||
|
||||
static final String PACKAGE = "incari.classlib.additions";
|
||||
static final String INSTANCE_METHOD = "incari.classlib.InstanceMethod";
|
||||
static final String REPLACES = "incari.classlib.Replaces";
|
||||
static final String CONSTRUCTOR = "incari.classlib.Constructor";
|
||||
private static final String UNSUPPORTED_ON = "org.teavm.interop.UnsupportedOn";
|
||||
|
||||
@Override
|
||||
public void transformClass(ClassHolder cls, ClassHolderTransformerContext context) {
|
||||
if (cls.getName().startsWith("incari.")) {
|
||||
return;
|
||||
}
|
||||
ClassHierarchy hierarchy = context.getHierarchy();
|
||||
ClassReader additions = hierarchy.getClassSource().get(PACKAGE + "." + cls.getName() + "Additions");
|
||||
if (additions == null) {
|
||||
return;
|
||||
}
|
||||
for (MethodReader addition : additions.getMethods()) {
|
||||
if (!addition.hasModifier(ElementModifier.STATIC)
|
||||
|| addition.getLevel() != AccessLevel.PUBLIC
|
||||
|| addition.hasModifier(ElementModifier.SYNTHETIC)) {
|
||||
continue;
|
||||
}
|
||||
boolean instance = addition.getAnnotations().get(INSTANCE_METHOD) != null;
|
||||
// The hierarchy reads classes as they were before this compile's transformers ran, so
|
||||
// substitute names in an addition's signature are mapped here, as ClasslibRenamer maps
|
||||
// them in the additions class itself.
|
||||
MethodDescriptor original = originalNames(addition.getDescriptor());
|
||||
MethodReference target = new MethodReference(addition.getOwnerName(), original);
|
||||
if (addition.getAnnotations().get(CONSTRUCTOR) != null) {
|
||||
MethodDescriptor constructor = asConstructor(original);
|
||||
if (cls.getMethod(constructor) == null) {
|
||||
cls.addMethod(delegatingConstructor(cls, constructor, original.getResultType(), target, hierarchy));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
MethodDescriptor descriptor = instance ? dropReceiver(original) : original;
|
||||
MethodHolder existing = cls.getMethod(descriptor);
|
||||
if (existing != null) {
|
||||
// TeaVM marks methods it can't provide on a target; an addition stands in for those,
|
||||
// and an addition marked @Replaces takes the place of TeaVM's version.
|
||||
if (existing.getAnnotations().get(UNSUPPORTED_ON) == null
|
||||
&& addition.getAnnotations().get(REPLACES) == null) {
|
||||
continue;
|
||||
}
|
||||
cls.removeMethod(existing);
|
||||
}
|
||||
cls.addMethod(forwarder(cls, descriptor, instance, target, hierarchy));
|
||||
}
|
||||
}
|
||||
|
||||
/** {@code descriptor} with substitute ({@code T}) class names read as the JDK names they stand for. */
|
||||
static MethodDescriptor originalNames(MethodDescriptor descriptor) {
|
||||
ValueType[] signature = descriptor.getSignature();
|
||||
for (int i = 0; i < signature.length; i++) {
|
||||
signature[i] = originalName(signature[i]);
|
||||
}
|
||||
return new MethodDescriptor(descriptor.getName(), signature);
|
||||
}
|
||||
|
||||
private static ValueType originalName(ValueType type) {
|
||||
if (type instanceof ValueType.Array array) {
|
||||
return ValueType.arrayOf(originalName(array.getItemType()));
|
||||
}
|
||||
if (type instanceof ValueType.Object object) {
|
||||
return ValueType.object(ClasslibRenamer.original(object.getClassName()));
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
/** The constructor an addition marked {@code @Constructor} adds: its parameters, returning nothing. */
|
||||
static MethodDescriptor asConstructor(MethodDescriptor descriptor) {
|
||||
ValueType[] constructor = new ValueType[descriptor.parameterCount() + 1];
|
||||
for (int i = 0; i < descriptor.parameterCount(); i++) {
|
||||
constructor[i] = descriptor.parameterType(i);
|
||||
}
|
||||
constructor[constructor.length - 1] = ValueType.VOID;
|
||||
return new MethodDescriptor("<init>", constructor);
|
||||
}
|
||||
|
||||
static MethodDescriptor dropReceiver(MethodDescriptor descriptor) {
|
||||
ValueType[] signature = descriptor.getSignature();
|
||||
ValueType[] rest = new ValueType[signature.length - 1];
|
||||
System.arraycopy(signature, 1, rest, 0, rest.length);
|
||||
return new MethodDescriptor(descriptor.getName(), rest);
|
||||
}
|
||||
|
||||
/** {@code Name(parameters) { this(addition(parameters)); }} */
|
||||
private static MethodHolder delegatingConstructor(
|
||||
ClassHolder cls,
|
||||
MethodDescriptor descriptor,
|
||||
ValueType argument,
|
||||
MethodReference target,
|
||||
ClassHierarchy hierarchy) {
|
||||
MethodHolder method = new MethodHolder(descriptor);
|
||||
method.setLevel(AccessLevel.PUBLIC);
|
||||
ProgramEmitter pe = ProgramEmitter.create(method, hierarchy);
|
||||
ValueEmitter self = pe.var(0, ValueType.object(cls.getName()));
|
||||
ValueEmitter[] arguments = new ValueEmitter[descriptor.parameterCount()];
|
||||
for (int i = 0; i < arguments.length; i++) {
|
||||
arguments[i] = pe.var(i + 1, descriptor.parameterType(i));
|
||||
}
|
||||
ValueEmitter value = pe.invoke(target, arguments);
|
||||
self.invokeSpecial(new MethodReference(cls.getName(), "<init>", argument, ValueType.VOID), value);
|
||||
pe.exit();
|
||||
return method;
|
||||
}
|
||||
|
||||
private static MethodHolder forwarder(
|
||||
ClassHolder cls,
|
||||
MethodDescriptor descriptor,
|
||||
boolean instance,
|
||||
MethodReference target,
|
||||
ClassHierarchy hierarchy) {
|
||||
MethodHolder method = new MethodHolder(descriptor);
|
||||
method.setLevel(AccessLevel.PUBLIC);
|
||||
if (!instance) {
|
||||
method.getModifiers().add(ElementModifier.STATIC);
|
||||
}
|
||||
ProgramEmitter pe = ProgramEmitter.create(method, hierarchy);
|
||||
int offset = instance ? 1 : 0;
|
||||
ValueEmitter[] arguments = new ValueEmitter[descriptor.parameterCount() + offset];
|
||||
if (instance) {
|
||||
arguments[0] = pe.var(0, ValueType.object(cls.getName()));
|
||||
}
|
||||
for (int i = 0; i < descriptor.parameterCount(); i++) {
|
||||
arguments[i + offset] = pe.var(i + 1, descriptor.parameterType(i));
|
||||
}
|
||||
ValueEmitter result = pe.invoke(target, arguments);
|
||||
if (descriptor.getResultType() == ValueType.VOID) {
|
||||
pe.exit();
|
||||
} else {
|
||||
result.returnValue();
|
||||
}
|
||||
return method;
|
||||
}
|
||||
}
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Deque;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.callgraph.CallGraph;
|
||||
import org.teavm.callgraph.CallGraphNode;
|
||||
import org.teavm.callgraph.CallSite;
|
||||
import org.teavm.dependency.DependencyInfo;
|
||||
import org.teavm.model.ClassReader;
|
||||
import org.teavm.model.ElementModifier;
|
||||
import org.teavm.model.MethodReader;
|
||||
import org.teavm.model.MethodReference;
|
||||
import org.teavm.model.ProgramReader;
|
||||
import org.teavm.model.VariableReader;
|
||||
import org.teavm.model.instructions.AbstractInstructionReader;
|
||||
|
||||
/**
|
||||
* Explains why TeaVM treats a method as one that can suspend: the shortest call chain from it to a
|
||||
* method that holds a monitor ({@code synchronized}) or is {@code @Async}. TeaVM compiles every
|
||||
* such method as a coroutine, and follows virtual calls to every override, so one blocking
|
||||
* {@code toString} makes every {@code toString} call a suspension point. Written to
|
||||
* {@code async.txt} for methods TeaVM failed to compile, and on request.
|
||||
*/
|
||||
final class AsyncExplainer {
|
||||
|
||||
private static final String ASYNC = "org.teavm.interop.Async";
|
||||
|
||||
private final CallGraph callGraph;
|
||||
private final DependencyInfo dependencies;
|
||||
|
||||
AsyncExplainer(DependencyInfo dependencies) {
|
||||
this.dependencies = dependencies;
|
||||
this.callGraph = dependencies.getCallGraph();
|
||||
}
|
||||
|
||||
/**
|
||||
* Virtual methods the game calls everywhere. If any implementation of one can suspend, TeaVM
|
||||
* compiles every call to it as a suspension point, so none should.
|
||||
*/
|
||||
private static final List<String> HOT = List.of(
|
||||
"java.lang.Object.toString()Ljava/lang/String;",
|
||||
"java.lang.Object.hashCode()I",
|
||||
"java.lang.Object.equals(Ljava/lang/Object;)Z",
|
||||
"java.lang.CharSequence.charAt(I)C",
|
||||
"java.lang.CharSequence.length()I",
|
||||
"java.lang.Comparable.compareTo(Ljava/lang/Object;)I",
|
||||
"java.lang.Iterable.iterator()Ljava/util/Iterator;",
|
||||
"java.util.Iterator.hasNext()Z",
|
||||
"java.util.Iterator.next()Ljava/lang/Object;",
|
||||
"java.util.Collection.size()I",
|
||||
"java.util.Collection.add(Ljava/lang/Object;)Z",
|
||||
"java.util.Collection.contains(Ljava/lang/Object;)Z",
|
||||
"java.util.Collection.isEmpty()Z",
|
||||
"java.util.List.get(I)Ljava/lang/Object;",
|
||||
"java.util.Map.get(Ljava/lang/Object;)Ljava/lang/Object;",
|
||||
"java.util.Map.put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;",
|
||||
"java.util.Map.containsKey(Ljava/lang/Object;)Z",
|
||||
"java.util.Queue.offer(Ljava/lang/Object;)Z",
|
||||
"java.util.Queue.poll()Ljava/lang/Object;",
|
||||
"java.util.Comparator.compare(Ljava/lang/Object;Ljava/lang/Object;)I",
|
||||
"java.util.function.Function.apply(Ljava/lang/Object;)Ljava/lang/Object;",
|
||||
"java.util.function.Predicate.test(Ljava/lang/Object;)Z",
|
||||
"java.util.function.Consumer.accept(Ljava/lang/Object;)V");
|
||||
|
||||
/**
|
||||
* Lines for {@code async.txt}: each hot method that TeaVM will compile as a suspension point,
|
||||
* with up to three implementations that make it one and why.
|
||||
*/
|
||||
List<String> hotReport() {
|
||||
// Reachable names include arrays and generated classes with no class reader behind them.
|
||||
java.util.Set<String> reachable = new java.util.HashSet<>();
|
||||
for (String name : dependencies.getReachableClasses()) {
|
||||
if (dependencies.getClassSource().get(name) != null) {
|
||||
reachable.add(name);
|
||||
}
|
||||
}
|
||||
org.teavm.model.ListableClassReaderSource source = new org.teavm.model.ListableClassReaderSource() {
|
||||
@Override
|
||||
public java.util.Set<String> getClassNames() {
|
||||
return reachable;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable ClassReader get(String name) {
|
||||
return dependencies.getClassSource().get(name);
|
||||
}
|
||||
};
|
||||
org.teavm.model.util.AsyncMethodFinder finder =
|
||||
new org.teavm.model.util.AsyncMethodFinder(callGraph, dependencies);
|
||||
finder.find(source);
|
||||
org.teavm.model.ClassHierarchy hierarchy = new org.teavm.model.ClassHierarchy(dependencies.getClassSource());
|
||||
List<String> lines = new ArrayList<>();
|
||||
// How much of the program is compiled as coroutines at all (ADR 0027): each of these pays
|
||||
// suspend and resume bookkeeping around its calls that may suspend, and inlines less.
|
||||
int reachableMethods = dependencies.getReachableMethods().size();
|
||||
java.util.Map<String, Integer> byPackage = new java.util.TreeMap<>();
|
||||
for (MethodReference method : finder.getAsyncMethods()) {
|
||||
String className = method.getClassName();
|
||||
int lastDot = className.lastIndexOf('.');
|
||||
byPackage.merge(lastDot < 0 ? "" : className.substring(0, lastDot), 1, Integer::sum);
|
||||
}
|
||||
lines.add(
|
||||
"# Methods compiled as coroutines: " + finder.getAsyncMethods().size() + " of " + reachableMethods
|
||||
+ " reachable. The packages with the most:");
|
||||
byPackage.entrySet().stream()
|
||||
.sorted(java.util.Map.Entry.<String, Integer>comparingByValue().reversed())
|
||||
.limit(25)
|
||||
.forEach(entry -> lines.add("# " + entry.getValue() + " " + entry.getKey()));
|
||||
for (String hot : HOT) {
|
||||
int paren = hot.indexOf('(');
|
||||
int dot = hot.lastIndexOf('.', paren);
|
||||
String owner = hot.substring(0, dot);
|
||||
org.teavm.model.MethodDescriptor descriptor =
|
||||
org.teavm.model.MethodDescriptor.parse(hot.substring(dot + 1));
|
||||
List<MethodReference> offenders = new ArrayList<>();
|
||||
for (MethodReference method : finder.getAsyncMethods()) {
|
||||
if (method.getDescriptor().equals(descriptor)
|
||||
&& hierarchy.isSuperType(owner, method.getClassName(), false)) {
|
||||
offenders.add(method);
|
||||
}
|
||||
}
|
||||
if (offenders.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
lines.add("SUSPENDS " + hot + " (" + offenders.size() + " implementations)");
|
||||
for (MethodReference offender : offenders.subList(0, Math.min(3, offenders.size()))) {
|
||||
lines.add(" " + offender);
|
||||
for (MethodReference step : explain(offender)) {
|
||||
lines.add(" -> " + step);
|
||||
}
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/** The chain from {@code start} to a suspension source, start first; empty if there's none. */
|
||||
List<MethodReference> explain(MethodReference start) {
|
||||
Map<MethodReference, @Nullable MethodReference> cameFrom = new HashMap<>();
|
||||
Deque<MethodReference> queue = new ArrayDeque<>();
|
||||
cameFrom.put(start, null);
|
||||
queue.add(start);
|
||||
while (!queue.isEmpty()) {
|
||||
MethodReference method = queue.removeFirst();
|
||||
if (suspends(method)) {
|
||||
List<MethodReference> chain = new ArrayList<>();
|
||||
for (MethodReference at = method; at != null; at = cameFrom.get(at)) {
|
||||
chain.addFirst(at);
|
||||
}
|
||||
return chain;
|
||||
}
|
||||
CallGraphNode node = callGraph.getNode(method);
|
||||
if (node == null) {
|
||||
continue;
|
||||
}
|
||||
for (CallSite site : node.getCallSites()) {
|
||||
for (CallGraphNode callee : site.getCalledMethods()) {
|
||||
if (!cameFrom.containsKey(callee.getMethod())) {
|
||||
cameFrom.put(callee.getMethod(), method);
|
||||
queue.addLast(callee.getMethod());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private boolean suspends(MethodReference reference) {
|
||||
ClassReader cls = dependencies.getClassSource().get(reference.getClassName());
|
||||
MethodReader method = cls == null ? null : cls.getMethod(reference.getDescriptor());
|
||||
if (method == null) {
|
||||
return false;
|
||||
}
|
||||
if (method.getAnnotations().get(ASYNC) != null || method.hasModifier(ElementModifier.SYNCHRONIZED)) {
|
||||
return true;
|
||||
}
|
||||
ProgramReader program = method.getProgram();
|
||||
if (program == null) {
|
||||
return false;
|
||||
}
|
||||
MonitorFinder finder = new MonitorFinder();
|
||||
for (int i = 0; i < program.basicBlockCount() && !finder.found; i++) {
|
||||
program.basicBlockAt(i).readAllInstructions(finder);
|
||||
}
|
||||
return finder.found;
|
||||
}
|
||||
|
||||
private static final class MonitorFinder extends AbstractInstructionReader {
|
||||
boolean found;
|
||||
|
||||
@Override
|
||||
public void monitorEnter(VariableReader objectRef) {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
+1263
File diff suppressed because it is too large
Load Diff
+286
@@ -0,0 +1,286 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The benchmark's report as Markdown: a table of each scenario's figures, the load times
|
||||
* and download size, the figures against the machine's baseline, and a trend of the frame rates
|
||||
* over the runs this machine kept (GitHub renders the Mermaid chart in a job summary, which is
|
||||
* where CI puts the report). Pure text, from figures keyed as the runner keys them.
|
||||
*/
|
||||
final class BenchmarkReport {
|
||||
|
||||
/** Runs the trend charts show. */
|
||||
private static final int TREND_RUNS = 20;
|
||||
|
||||
private record Row(String label, Function<Map<String, Double>, String> cell) {}
|
||||
|
||||
private static final List<Row> ROWS = List.of(
|
||||
new Row("Frame rate, median (fps)", f -> number(f.get("fpsMedian"))),
|
||||
new Row("1% low (fps)", f -> number(f.get("fpsLow1"))),
|
||||
new Row("Frame time, 99th percentile (ms)", f -> number(f.get("frameP99Millis"))),
|
||||
new Row("CPU: tick (ms)", f -> number(f.get("tickMillis"))),
|
||||
new Row("CPU: extract (ms)", f -> number(f.get("extractMillis"))),
|
||||
new Row("CPU: render submit (ms)", f -> number(f.get("renderMillis"))),
|
||||
new Row("GPU (ms)", f -> number(f.get("gpuMillis"))),
|
||||
new Row("Draw calls", f -> number(f.get("drawCalls"))),
|
||||
new Row("Terrain draw calls", f -> number(f.get("terrainDrawCalls"))),
|
||||
new Row("Terrain sections drawn", f -> number(f.get("terrainSections"))),
|
||||
new Row(
|
||||
"Mesh queue, mean / max",
|
||||
f -> number(f.get("meshQueueMean")) + " / " + number(f.get("meshQueueMax"))),
|
||||
new Row("JavaScript heap, max (MB)", f -> number(f.get("heapMaxMB"))),
|
||||
new Row("JavaScript heap, live after a collection (MB)", f -> number(f.get("heapLiveMB"))),
|
||||
new Row("Linear memory, max (MB)", f -> number(f.get("nativeMaxMB"))),
|
||||
new Row("Linear memory, in use after (MB)", f -> number(f.get("nativeLiveMB"))),
|
||||
new Row(
|
||||
"GC pauses: count, longest (ms)",
|
||||
f -> number(f.get("gcCount")) + ", " + number(f.get("gcMaxPauseMillis"))),
|
||||
new Row("Frames measured", f -> number(f.get("frames"))));
|
||||
|
||||
/** Singleplayer's server worker (ADR 0039), from its tick table and heap. */
|
||||
private static final List<Row> SERVER_ROWS = List.of(
|
||||
new Row("Server: ticks a second (of 20)", f -> number(f.get("serverTicksPerSecond"))),
|
||||
new Row(
|
||||
"Server: tick, mean / 95th percentile / longest (ms)",
|
||||
f -> number(f.get("serverTickMillis")) + " / " + number(f.get("serverTickP95Millis")) + " / "
|
||||
+ number(f.get("serverTickMaxMillis"))),
|
||||
new Row("Server: loaded chunks at the end", f -> number(f.get("serverChunks"))),
|
||||
new Row("Server worker's heap, live after a collection (MB)", f -> number(f.get("workerHeapLiveMB"))));
|
||||
|
||||
private BenchmarkReport() {}
|
||||
|
||||
static String markdown(
|
||||
Map<String, String> about,
|
||||
Map<String, Double> figures,
|
||||
List<PerfBudget.Check> budgets,
|
||||
List<PerfBaseline.Comparison> comparisons,
|
||||
Map<String, Double> baseline,
|
||||
List<Map<String, Double>> history) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
out.append("## Incari benchmark: ").append(about.get("machine")).append("\n\n");
|
||||
String commit = about.getOrDefault("commit", "unknown");
|
||||
out.append(about.getOrDefault("renderer", "unknown GPU"))
|
||||
.append(", ")
|
||||
.append(about.getOrDefault("browser", "unknown browser"))
|
||||
.append(", commit `")
|
||||
.append(commit.length() > 12 ? commit.substring(0, 12) : commit)
|
||||
.append('`');
|
||||
String query = about.getOrDefault("query", "");
|
||||
if (!query.isEmpty()) {
|
||||
out.append(", page options `").append(query).append('`');
|
||||
}
|
||||
out.append(".\n\n");
|
||||
|
||||
List<String> scenarios = scenarios(figures);
|
||||
out.append("| |");
|
||||
scenarios.forEach(name -> out.append(' ').append(name).append(" |"));
|
||||
out.append("\n|---|");
|
||||
scenarios.forEach(name -> out.append("---:|"));
|
||||
out.append('\n');
|
||||
boolean singleplayer = "singleplayer".equals(about.get("mode"));
|
||||
List<Row> rows = new ArrayList<>(ROWS);
|
||||
if (singleplayer) {
|
||||
rows.addAll(SERVER_ROWS);
|
||||
}
|
||||
for (Row row : rows) {
|
||||
out.append("| ").append(row.label()).append(" |");
|
||||
for (String scenario : scenarios) {
|
||||
out.append(' ')
|
||||
.append(row.cell().apply(scenarioFigures(figures, scenario)))
|
||||
.append(" |");
|
||||
}
|
||||
out.append('\n');
|
||||
}
|
||||
out.append('\n');
|
||||
|
||||
if (singleplayer) {
|
||||
out.append("Load: cold start to the title screen ")
|
||||
.append(seconds(figures.get("load.coldTitleMillis")))
|
||||
.append(", creating the world from there ")
|
||||
.append(seconds(figures.get("load.createMillis")))
|
||||
.append(", Save and Quit to the title screen with the world stored ")
|
||||
.append(seconds(figures.get("load.saveQuitMillis")))
|
||||
.append(", opening it again from a reload ")
|
||||
.append(seconds(figures.get("load.openMillis")))
|
||||
.append(". At the title screen after leaving, after a collection: JavaScript heap ")
|
||||
.append(number(figures.get("load.leftHeapLiveMB")))
|
||||
.append(" MB, linear memory in use ")
|
||||
.append(number(figures.get("load.leftNativeLiveMB")))
|
||||
.append(" MB.");
|
||||
} else {
|
||||
serverLoads(out, figures);
|
||||
}
|
||||
Double download = figures.get("download.gzipBytes");
|
||||
if (download != null && !download.isNaN()) {
|
||||
out.append(" Download: ")
|
||||
.append(String.format(Locale.ROOT, "%.1f", download / 1_000_000))
|
||||
.append(" MB gzip.");
|
||||
}
|
||||
out.append("\n\n");
|
||||
|
||||
if (!budgets.isEmpty()) {
|
||||
long over = budgets.stream().filter(PerfBudget.Check::over).count();
|
||||
out.append("### Budgets\n\n")
|
||||
.append(over == 0 ? "Every figure is within its budget" : over + " figures are over their budgets")
|
||||
.append(" (`app-web/benchmark/budgets.properties`).\n\n")
|
||||
.append("| Figure | Now | Budget | |\n|---|---:|---:|---|\n");
|
||||
for (PerfBudget.Check check : budgets) {
|
||||
out.append("| ")
|
||||
.append(check.figure())
|
||||
.append(" | ")
|
||||
.append(number(check.value()))
|
||||
.append(" | ")
|
||||
.append(number(check.limit().max()))
|
||||
.append(check.limit().machineOnly() ? " (this machine)" : "")
|
||||
.append(" | ")
|
||||
.append(check.over() ? "**over**" : "within")
|
||||
.append(" |\n");
|
||||
}
|
||||
out.append('\n');
|
||||
}
|
||||
|
||||
out.append("### Against the baseline\n\n");
|
||||
if (baseline.isEmpty()) {
|
||||
out.append("No baseline recorded for this machine yet.\n\n");
|
||||
} else {
|
||||
List<PerfBaseline.Comparison> shown = comparisons.stream()
|
||||
.filter(c -> c.regressed()
|
||||
|| Math.abs(c.rule().worsening(c.baseline(), c.current()))
|
||||
> Math.abs(c.baseline()) * c.rule().percent() / 200)
|
||||
.toList();
|
||||
long regressed = comparisons.stream()
|
||||
.filter(PerfBaseline.Comparison::regressed)
|
||||
.count();
|
||||
out.append(
|
||||
regressed == 0
|
||||
? "No figure regressed past its rule"
|
||||
: regressed + " figures regressed past their rules")
|
||||
.append(" (")
|
||||
.append(comparisons.size())
|
||||
.append(" compared).");
|
||||
if (shown.isEmpty()) {
|
||||
out.append(" Nothing moved by more than half its allowance.\n\n");
|
||||
} else {
|
||||
out.append(" The ones that moved by more than half their allowance:\n\n");
|
||||
out.append("| Figure | Baseline | Now | Change | |\n|---|---:|---:|---:|---|\n");
|
||||
for (PerfBaseline.Comparison c : shown) {
|
||||
double change = c.baseline() == 0
|
||||
? Double.NaN
|
||||
: (c.current() - c.baseline()) / Math.abs(c.baseline()) * 100;
|
||||
out.append("| ")
|
||||
.append(c.key())
|
||||
.append(" | ")
|
||||
.append(number(c.baseline()))
|
||||
.append(" | ")
|
||||
.append(number(c.current()))
|
||||
.append(" | ")
|
||||
.append(Double.isNaN(change) ? "n/a" : String.format(Locale.ROOT, "%+.1f%%", change))
|
||||
.append(" | ")
|
||||
.append(
|
||||
c.regressed()
|
||||
? "**regressed**"
|
||||
: c.rule().worsening(c.baseline(), c.current()) < 0
|
||||
? "better"
|
||||
: "worse, within the rule")
|
||||
.append(" |\n");
|
||||
}
|
||||
out.append('\n');
|
||||
}
|
||||
}
|
||||
|
||||
if (history.size() >= 2) {
|
||||
List<Map<String, Double>> runs = history.subList(Math.max(0, history.size() - TREND_RUNS), history.size());
|
||||
out.append("### Trend (this machine's last ").append(runs.size()).append(" runs)\n\n");
|
||||
for (String scenario : scenarios) {
|
||||
out.append("```mermaid\nxychart-beta\n title \"")
|
||||
.append(scenario)
|
||||
.append(": median and 1% low frame rate\"\n x-axis [");
|
||||
for (int i = 1; i <= runs.size(); i++) {
|
||||
out.append(i == 1 ? "" : ", ").append(i);
|
||||
}
|
||||
out.append("]\n y-axis \"fps\"\n");
|
||||
for (String figure : List.of("fpsMedian", "fpsLow1")) {
|
||||
out.append(" line [");
|
||||
for (int i = 0; i < runs.size(); i++) {
|
||||
Double value = runs.get(i).get(scenario + "." + figure);
|
||||
out.append(i == 0 ? "" : ", ").append(value == null || value.isNaN() ? "0" : number(value));
|
||||
}
|
||||
out.append("]\n");
|
||||
}
|
||||
out.append("```\n\n");
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/** The server benchmark's loads: start-ups, the join and the rejoin, and the title screen's memory. */
|
||||
private static void serverLoads(StringBuilder out, Map<String, Double> figures) {
|
||||
out.append("Load: cold start to the title screen ")
|
||||
.append(seconds(figures.get("load.coldTitleMillis")))
|
||||
.append(" (first frame ")
|
||||
.append(seconds(figures.get("load.coldFirstFrameMillis")))
|
||||
.append("), warm start ")
|
||||
.append(seconds(figures.get("load.warmTitleMillis")))
|
||||
.append(" (first frame ")
|
||||
.append(seconds(figures.get("load.warmFirstFrameMillis")))
|
||||
.append(", resources loaded ")
|
||||
.append(seconds(figures.get("load.warmReloadedMillis")))
|
||||
.append(')')
|
||||
.append(", joining the server ")
|
||||
.append(seconds(figures.get("load.joinMillis")))
|
||||
.append(" (again, from a reload: ")
|
||||
.append(seconds(figures.get("load.rejoinMillis")))
|
||||
.append(')')
|
||||
.append(". At the title screen, after a collection: JavaScript heap ")
|
||||
.append(number(figures.get("load.titleHeapLiveMB")))
|
||||
.append(" MB, linear memory in use ")
|
||||
.append(number(figures.get("load.titleNativeLiveMB")))
|
||||
.append(" MB.");
|
||||
}
|
||||
|
||||
/** The scenarios in the figures, in the order they ran. */
|
||||
private static List<String> scenarios(Map<String, Double> figures) {
|
||||
Set<String> names = new LinkedHashSet<>();
|
||||
for (String key : figures.keySet()) {
|
||||
int dot = key.indexOf('.');
|
||||
String group = key.substring(0, dot);
|
||||
if (!group.equals("load") && !group.equals("download")) {
|
||||
names.add(group);
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(names);
|
||||
}
|
||||
|
||||
private static Map<String, Double> scenarioFigures(Map<String, Double> figures, String scenario) {
|
||||
Map<String, Double> out = new HashMap<>();
|
||||
String prefix = scenario + ".";
|
||||
figures.forEach((key, value) -> {
|
||||
if (key.startsWith(prefix)) {
|
||||
out.put(key.substring(prefix.length()), value);
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
private static String number(@Nullable Double value) {
|
||||
if (value == null || value.isNaN() || value.isInfinite()) {
|
||||
return "n/a";
|
||||
}
|
||||
return Math.abs(value) >= 100 || value == Math.rint(value)
|
||||
? Long.toString(Math.round(value))
|
||||
: String.format(Locale.ROOT, "%.1f", value);
|
||||
}
|
||||
|
||||
private static String seconds(@Nullable Double millis) {
|
||||
return millis == null || millis.isNaN() ? "n/a" : String.format(Locale.ROOT, "%.1f s", millis / 1000);
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The benchmark's script, as {@code app-web/benchmark/benchmark.txt} writes it: steps for
|
||||
* the server before anyone joins, steps once the page has joined, and named scenarios, each a
|
||||
* list of steps with measured stretches in it.
|
||||
*
|
||||
* <pre>
|
||||
* server
|
||||
* rcon:gamerule advance_time false
|
||||
* setup
|
||||
* rcon:gamemode spectator IncariBench
|
||||
* scenario flythrough A straight flight over fresh terrain
|
||||
* rcon:spectate @e[tag=incari_camera,limit=1] IncariBench
|
||||
* measure:60
|
||||
* </pre>
|
||||
*
|
||||
* Steps: {@code rcon:<command>} (a server command; {@code rcon*<n>:<command>} runs it {@code n}
|
||||
* times, to summon a crowd), {@code rconwait:<command> => <text>} (repeat a
|
||||
* command until its reply contains the text, for up to five minutes), {@code sleep:<ms>},
|
||||
* {@code key:<chord>}, {@code move:<x>,<y>} (fractions of the window), {@code shot:<name>} (a
|
||||
* screenshot in {@code build/benchmark}) and, in a scenario only,
|
||||
* {@code measure:<seconds>}: a stretch whose frames count towards the scenario's figures. A
|
||||
* scenario's figures cover all its measured stretches together. A {@code #} starts a comment line.
|
||||
* In singleplayer ({@code app-web/benchmark/singleplayer.txt}) there's no server to reach: the
|
||||
* runner types each command into the game's chat, and a {@code rconwait} reads its answer from the
|
||||
* page's console.
|
||||
*/
|
||||
record BenchmarkScript(List<Step> server, List<Step> setup, List<Scenario> scenarios) {
|
||||
|
||||
/** One step: its kind (the part before the colon), its value, and its line, for messages. */
|
||||
record Step(String kind, String value, int line) {}
|
||||
|
||||
record Scenario(String name, String description, List<Step> steps) {}
|
||||
|
||||
private static final Set<String> KINDS = Set.of("rcon", "rconwait", "sleep", "key", "move", "shot", "measure");
|
||||
|
||||
static BenchmarkScript read(Path file) throws IOException {
|
||||
return parse(Files.readAllLines(file), file.toString());
|
||||
}
|
||||
|
||||
static BenchmarkScript parse(List<String> lines, String source) {
|
||||
List<Step> server = new ArrayList<>();
|
||||
List<Step> setup = new ArrayList<>();
|
||||
List<Scenario> scenarios = new ArrayList<>();
|
||||
@Nullable List<Step> current = null;
|
||||
String section = "";
|
||||
String name = "";
|
||||
String description = "";
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String raw = lines.get(i);
|
||||
String line = raw.strip();
|
||||
int number = i + 1;
|
||||
if (line.isEmpty() || line.startsWith("#")) {
|
||||
continue;
|
||||
}
|
||||
if (!Character.isWhitespace(raw.charAt(0))) {
|
||||
if (section.equals("scenario") && current != null) {
|
||||
scenarios.add(scenario(name, description, current, source));
|
||||
}
|
||||
String[] words = line.split("\\s+", 3);
|
||||
section = words[0];
|
||||
switch (section) {
|
||||
case "server" -> current = server;
|
||||
case "setup" -> current = setup;
|
||||
case "scenario" -> {
|
||||
if (words.length < 2) {
|
||||
throw error(source, number, "a scenario needs a name");
|
||||
}
|
||||
name = words[1];
|
||||
description = words.length > 2 ? words[2] : "";
|
||||
if (!name.matches("[a-z0-9_]+")) {
|
||||
throw error(source, number, "scenario names are [a-z0-9_]+: '" + name + "'");
|
||||
}
|
||||
String taken = name;
|
||||
if (scenarios.stream()
|
||||
.anyMatch(scenario -> scenario.name().equals(taken))) {
|
||||
throw error(source, number, "scenario " + name + " is named twice");
|
||||
}
|
||||
current = new ArrayList<>();
|
||||
}
|
||||
default -> throw error(source, number, "expected server, setup or scenario, not '" + line + "'");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (current == null) {
|
||||
throw error(source, number, "a step outside a section");
|
||||
}
|
||||
int colon = line.indexOf(':');
|
||||
String kind = colon < 0 ? line : line.substring(0, colon);
|
||||
String value = colon < 0 ? "" : line.substring(colon + 1);
|
||||
int times = 1;
|
||||
if (kind.matches("rcon\\*\\d+")) {
|
||||
times = Integer.parseInt(kind.substring("rcon*".length()));
|
||||
kind = "rcon";
|
||||
}
|
||||
if (!KINDS.contains(kind)) {
|
||||
throw error(source, number, "unknown step '" + kind + "'");
|
||||
}
|
||||
if (kind.equals("measure") && !section.equals("scenario")) {
|
||||
throw error(source, number, "only scenarios measure");
|
||||
}
|
||||
if (kind.equals("measure") && !value.matches("\\d+")) {
|
||||
throw error(source, number, "measure takes whole seconds: '" + value + "'");
|
||||
}
|
||||
if (kind.equals("rconwait") && !value.contains(" => ")) {
|
||||
throw error(source, number, "rconwait needs '<command> => <text>'");
|
||||
}
|
||||
if (!section.equals("scenario")
|
||||
&& !section.equals("setup")
|
||||
&& !kind.startsWith("rcon")
|
||||
&& !kind.equals("sleep")) {
|
||||
throw error(source, number, "the server section only runs server commands and sleeps");
|
||||
}
|
||||
for (int n = 0; n < times; n++) {
|
||||
current.add(new Step(kind, value, number));
|
||||
}
|
||||
}
|
||||
if (section.equals("scenario") && current != null) {
|
||||
scenarios.add(scenario(name, description, current, source));
|
||||
}
|
||||
if (scenarios.isEmpty()) {
|
||||
throw new CliException(source + ": no scenarios");
|
||||
}
|
||||
return new BenchmarkScript(List.copyOf(server), List.copyOf(setup), List.copyOf(scenarios));
|
||||
}
|
||||
|
||||
private static Scenario scenario(String name, String description, List<Step> steps, String source) {
|
||||
if (steps.stream().noneMatch(step -> step.kind().equals("measure"))) {
|
||||
throw new CliException(source + ": scenario " + name + " measures nothing");
|
||||
}
|
||||
return new Scenario(name, description, List.copyOf(steps));
|
||||
}
|
||||
|
||||
private static CliException error(String source, int line, String message) {
|
||||
return new CliException(source + ":" + line + ": " + message);
|
||||
}
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.TreeSet;
|
||||
import org.teavm.dependency.DependencyInfo;
|
||||
import org.teavm.model.ClassHierarchy;
|
||||
import org.teavm.model.ClassReader;
|
||||
import org.teavm.model.MethodReader;
|
||||
import org.teavm.model.MethodReference;
|
||||
import org.teavm.model.ProgramReader;
|
||||
import org.teavm.model.TextLocation;
|
||||
import org.teavm.model.ValueType;
|
||||
import org.teavm.model.VariableReader;
|
||||
import org.teavm.model.instructions.AbstractInstructionReader;
|
||||
import org.teavm.model.instructions.InvocationType;
|
||||
|
||||
/**
|
||||
* Lists every call to a blocking API in the code the browser build links (the game, its libraries
|
||||
* and Incari's modules, not the class library that implements the APIs): {@code blocking.txt}, the
|
||||
* input to the threading audit ({@code docs/threading.md}).
|
||||
*
|
||||
* <p>In the page, threads are coroutines on one thread, so a blocking call suspends the calling
|
||||
* coroutine and runs the others. On a background thread that's harmless. On the render thread the
|
||||
* frame waits with it, and it deadlocks if what it waits for can only happen on the render thread
|
||||
* (a task queued for the game's own loop, which only runs between frames).
|
||||
*/
|
||||
final class BlockingCalls {
|
||||
|
||||
/** A blocking method, by the type that declares it and its name. */
|
||||
private record Api(String owner, String name) {}
|
||||
|
||||
private static final List<Api> APIS = List.of(
|
||||
new Api("java.lang.Object", "wait"),
|
||||
new Api("java.lang.Thread", "sleep"),
|
||||
new Api("java.lang.Thread", "join"),
|
||||
new Api("java.lang.Thread", "yield"),
|
||||
new Api("java.lang.Thread", "onSpinWait"),
|
||||
new Api("java.util.concurrent.Future", "get"),
|
||||
new Api("java.util.concurrent.CompletableFuture", "join"),
|
||||
new Api("java.util.concurrent.ForkJoinTask", "join"),
|
||||
new Api("java.util.concurrent.ForkJoinTask", "invoke"),
|
||||
new Api("java.util.concurrent.locks.LockSupport", "park"),
|
||||
new Api("java.util.concurrent.locks.LockSupport", "parkNanos"),
|
||||
new Api("java.util.concurrent.locks.LockSupport", "parkUntil"),
|
||||
new Api("java.util.concurrent.locks.Lock", "lock"),
|
||||
new Api("java.util.concurrent.locks.Lock", "lockInterruptibly"),
|
||||
new Api("java.util.concurrent.locks.Condition", "await"),
|
||||
new Api("java.util.concurrent.locks.Condition", "awaitNanos"),
|
||||
new Api("java.util.concurrent.locks.Condition", "awaitUninterruptibly"),
|
||||
new Api("java.util.concurrent.CountDownLatch", "await"),
|
||||
new Api("java.util.concurrent.CyclicBarrier", "await"),
|
||||
new Api("java.util.concurrent.Semaphore", "acquire"),
|
||||
new Api("java.util.concurrent.Semaphore", "acquireUninterruptibly"),
|
||||
new Api("java.util.concurrent.BlockingQueue", "take"),
|
||||
new Api("java.util.concurrent.BlockingQueue", "put"),
|
||||
new Api("java.util.concurrent.ExecutorService", "awaitTermination"),
|
||||
new Api("java.util.concurrent.ExecutorService", "invokeAll"),
|
||||
new Api("java.util.concurrent.ExecutorService", "invokeAny"),
|
||||
new Api("java.util.concurrent.ExecutorService", "close"),
|
||||
new Api("net.minecraft.util.thread.BlockableEventLoop", "managedBlock"),
|
||||
new Api("net.minecraft.util.thread.BlockableEventLoop", "waitForTasks"));
|
||||
|
||||
/**
|
||||
* {@code Object.wait}'s own signatures. Every class is an {@code Object}, and a method of another
|
||||
* class that happens to be called {@code wait} (the game's reload barrier) doesn't block.
|
||||
*/
|
||||
private static final Set<String> OBJECT_WAITS = Set.of("wait()V", "wait(J)V", "wait(JI)V");
|
||||
|
||||
/** Packages of the class library and TeaVM, which implement the APIs rather than call them. */
|
||||
private static final List<String> IMPLEMENTATIONS =
|
||||
List.of("java.", "javax.", "jdk.", "sun.", "org.teavm.", "incari.classlib.");
|
||||
|
||||
private BlockingCalls() {}
|
||||
|
||||
static void write(DependencyInfo dependencies, Path file) throws IOException {
|
||||
ClassHierarchy hierarchy = new ClassHierarchy(dependencies.getClassSource());
|
||||
// API -> "caller (Source.java:line)"
|
||||
Map<String, Set<String>> byApi = new TreeMap<>();
|
||||
for (MethodReference reference : dependencies.getReachableMethods()) {
|
||||
String owner = reference.getClassName();
|
||||
if (IMPLEMENTATIONS.stream().anyMatch(owner::startsWith)) {
|
||||
continue;
|
||||
}
|
||||
ClassReader cls = dependencies.getClassSource().get(owner);
|
||||
MethodReader method = cls == null ? null : cls.getMethod(reference.getDescriptor());
|
||||
ProgramReader program = method == null ? null : method.getProgram();
|
||||
if (program == null) {
|
||||
continue;
|
||||
}
|
||||
Finder finder = new Finder(hierarchy, reference, byApi);
|
||||
for (int i = 0; i < program.basicBlockCount(); i++) {
|
||||
program.basicBlockAt(i).readAllInstructions(finder);
|
||||
}
|
||||
}
|
||||
List<String> lines = new ArrayList<>();
|
||||
lines.add("# Calls to blocking APIs in the linked program (docs/threading.md classifies them).");
|
||||
lines.add("# Each API, then its callers: method (source:line).");
|
||||
int total = 0;
|
||||
for (Map.Entry<String, Set<String>> entry : byApi.entrySet()) {
|
||||
lines.add("");
|
||||
lines.add(entry.getKey() + " (" + entry.getValue().size() + ")");
|
||||
for (String caller : entry.getValue()) {
|
||||
lines.add(" " + caller);
|
||||
}
|
||||
total += entry.getValue().size();
|
||||
}
|
||||
lines.add(1, "# " + total + " call sites.");
|
||||
Files.write(file, lines);
|
||||
}
|
||||
|
||||
private static final class Finder extends AbstractInstructionReader {
|
||||
private final ClassHierarchy hierarchy;
|
||||
private final MethodReference caller;
|
||||
private final Map<String, Set<String>> byApi;
|
||||
private TextLocation location = TextLocation.EMPTY;
|
||||
|
||||
Finder(ClassHierarchy hierarchy, MethodReference caller, Map<String, Set<String>> byApi) {
|
||||
this.hierarchy = hierarchy;
|
||||
this.caller = caller;
|
||||
this.byApi = byApi;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void location(TextLocation location) {
|
||||
this.location = location == null ? TextLocation.EMPTY : location;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void invoke(
|
||||
VariableReader receiver,
|
||||
VariableReader instance,
|
||||
MethodReference method,
|
||||
List<? extends VariableReader> arguments,
|
||||
InvocationType type) {
|
||||
for (Api api : APIS) {
|
||||
if (api.name().equals(method.getName())
|
||||
&& (method.getClassName().equals(api.owner())
|
||||
|| hierarchy.isSuperType(api.owner(), method.getClassName(), false))
|
||||
&& (!api.owner().equals("java.lang.Object")
|
||||
|| OBJECT_WAITS.contains(method.getDescriptor().toString()))) {
|
||||
String where = location.isEmpty()
|
||||
? ""
|
||||
: " (" + fileName(location.getFileName()) + ":" + location.getLine() + ")";
|
||||
byApi.computeIfAbsent(api.owner() + "." + api.name() + signature(method), k -> new TreeSet<>())
|
||||
.add(caller.getClassName() + "." + caller.getName() + where);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String signature(MethodReference method) {
|
||||
StringBuilder text = new StringBuilder("(");
|
||||
ValueType[] parameters = method.getParameterTypes();
|
||||
for (int i = 0; i < parameters.length; i++) {
|
||||
if (i > 0) {
|
||||
text.append(", ");
|
||||
}
|
||||
text.append(typeName(parameters[i]));
|
||||
}
|
||||
return text.append(")").toString();
|
||||
}
|
||||
|
||||
private static String typeName(ValueType type) {
|
||||
if (type instanceof ValueType.Object object) {
|
||||
String name = object.getClassName();
|
||||
return name.substring(name.lastIndexOf('.') + 1);
|
||||
} else if (type instanceof ValueType.Array array) {
|
||||
return typeName(array.getItemType()) + "[]";
|
||||
} else if (type instanceof ValueType.Primitive primitive) {
|
||||
return primitive.getKind().name().toLowerCase(java.util.Locale.ROOT);
|
||||
}
|
||||
return type.toString();
|
||||
}
|
||||
|
||||
private static String fileName(String path) {
|
||||
return path.substring(path.lastIndexOf('/') + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
+486
@@ -0,0 +1,486 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import incari.tools.build.CliException;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Pattern;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Checks that the browser build's game loop runs: serves the output directory on a free loopback
|
||||
* port, opens it in headless Chromium, echoes the console, and succeeds once the expected message
|
||||
* has appeared often enough.
|
||||
*
|
||||
* <p>{@link Chromium} says where the browser comes from. WebGL runs on SwiftShader unless
|
||||
* {@code --gpu gl} or {@code --gpu vulkan} asks for the machine's GPU; {@code --gpu webgpu} also
|
||||
* gives WebGPU the machine's GPU.
|
||||
*/
|
||||
public final class BrowserCheck {
|
||||
|
||||
private BrowserCheck() {}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
System.exit(run(args));
|
||||
} catch (CliException e) {
|
||||
System.err.println("error: " + e.getMessage());
|
||||
System.exit(1);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
static int run(String[] args) throws IOException, InterruptedException {
|
||||
if (args.length < 1) {
|
||||
throw new CliException(
|
||||
"Usage: browser-check <dir>|<page.html> [--file <name>=<path>]... [--dir <prefix>=<path>]..."
|
||||
+ " [--chrome <path>]"
|
||||
+ " [--seconds <n>] [--expect <regex>] [--count <n>] [--query <page query>] [--step <step>]..."
|
||||
+ " [--steps-file <file>] [--rcon <host:port>] [--gpu swiftshader|gl|vulkan|webgpu]");
|
||||
}
|
||||
Path directory = Path.of(args[0]);
|
||||
@Nullable String chrome = null;
|
||||
Chromium.Gpu gpu = Chromium.Gpu.SWIFTSHADER;
|
||||
Map<String, Path> files = new LinkedHashMap<>();
|
||||
String query = "";
|
||||
int seconds = 180;
|
||||
Pattern expect = Pattern.compile("\\[Incari\\] Main loop running.*");
|
||||
int count = 2;
|
||||
List<String> steps = new ArrayList<>();
|
||||
@Nullable String rcon = null;
|
||||
for (int i = 1; i < args.length; i++) {
|
||||
switch (args[i]) {
|
||||
case "--chrome" -> chrome = args[++i];
|
||||
case "--gpu" -> gpu = Chromium.Gpu.parse(args[++i]);
|
||||
case "--file" -> Serve.addFile(files, args[++i]);
|
||||
case "--dir" -> Serve.addDirectory(files, args[++i]);
|
||||
case "--query" -> query = args[++i];
|
||||
case "--seconds" -> seconds = Integer.parseInt(args[++i]);
|
||||
case "--expect" -> expect = Pattern.compile(args[++i]);
|
||||
case "--count" -> count = Integer.parseInt(args[++i]);
|
||||
case "--step" -> steps.add(args[++i]);
|
||||
case "--steps-file" -> steps.addAll(readSteps(Path.of(args[++i])));
|
||||
case "--rcon" -> rcon = args[++i];
|
||||
default -> throw new CliException("Unknown option '" + args[i] + "'");
|
||||
}
|
||||
}
|
||||
// A single-file build (SingleFile, ADR 0057) opens from the disk, as a player opens it.
|
||||
boolean singleFile =
|
||||
Files.isRegularFile(directory) && directory.toString().endsWith(".html");
|
||||
if (!singleFile && !Files.isRegularFile(directory.resolve("index.html"))) {
|
||||
throw new CliException(directory + " has no index.html; run ./gradlew :app-web:teavm first");
|
||||
}
|
||||
@Nullable HttpServer server = singleFile ? null : Serve.start(directory, 0, files);
|
||||
// The page names the player (Player), so Edit Profile doesn't open before the title screen
|
||||
// the steps expect; --query name= (empty) leaves it to the player, to check that screen.
|
||||
String page = query.matches("(^|.*&)name=.*") ? query : "name=Player" + (query.isEmpty() ? "" : "&" + query);
|
||||
String url = (server == null
|
||||
? directory.toAbsolutePath().toUri().toString()
|
||||
: "http://localhost:" + server.getAddress().getPort() + "/")
|
||||
+ "?" + PageQuery.withBuild(page);
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(seconds);
|
||||
// Steps drive the page through the DevTools protocol, at a player's window size.
|
||||
try (Chromium chromium =
|
||||
Chromium.open(chrome, url, gpu, steps.isEmpty() ? -1 : 0, steps.isEmpty() ? null : "1280,720")) {
|
||||
PageConsole console = chromium.console();
|
||||
if (!console.await(expect, count, deadline)) {
|
||||
return 1;
|
||||
}
|
||||
System.out.println("==> Passed: saw " + count + " messages matching " + expect.pattern());
|
||||
if (steps.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
String devToolsUrl = console.devToolsUrl(deadline);
|
||||
try (DevTools devTools = DevTools.connect(devToolsUrl);
|
||||
StepState state = new StepState(url, rcon)) {
|
||||
state.clientJar = files.get("/client.jar");
|
||||
for (String step : steps) {
|
||||
if (!runStep(step, devTools, console, deadline, state)) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("==> Passed: ran " + steps.size() + " steps");
|
||||
return 0;
|
||||
} finally {
|
||||
if (server != null) {
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs one step; false if it failed. Positions are fractions of the viewport, so a step list
|
||||
* works at any window size:
|
||||
* <ul>
|
||||
* <li>{@code sleep:<ms>}: let the page run
|
||||
* <li>{@code wait:<regex>}: wait for a console message
|
||||
* <li>{@code shot:<path>}: save a screenshot (PNG)
|
||||
* <li>{@code move:<x>,<y>} and {@code click:<x>,<y>}: the mouse, as a player moves and clicks it
|
||||
* <li>{@code type:<text>}: type text
|
||||
* <li>{@code eval:<expression>}: print a JavaScript expression's value
|
||||
* <li>{@code init:<script>}: run a script before the page's own on every load, and reload
|
||||
* (to watch what the game does while it starts; follow it with a {@code wait:})
|
||||
* <li>{@code reload}: reload the page, as a player would (follow it with a {@code wait:})
|
||||
* <li>{@code key:<chord>}: press keys by {@code KeyboardEvent.code} and release them in
|
||||
* reverse: {@code key:F3}, {@code key:Control+KeyV}, {@code key:F3+KeyB} ({@link Keys})
|
||||
* <li>{@code down:<code>} and {@code up:<code>}: hold a key, and let it go
|
||||
* <li>{@code assert:<expression>}: fail unless a JavaScript expression is true (a promise's
|
||||
* value counts)
|
||||
* <li>{@code waitfor:<expression>}: wait up to ten seconds for an expression to be true
|
||||
* <li>{@code holds:<expression>} and {@code until:<expression>}: {@code assert} and
|
||||
* {@code waitfor} without counting as a click, so the page stays without user
|
||||
* activation (the audio unlock); every other step that evaluates counts as one
|
||||
* <li>{@code resize:<width>,<height>[,<density>]}: the viewport in CSS pixels, and the device
|
||||
* pixels per CSS pixel (1 unless given)
|
||||
* <li>{@code clipboard:<text>}: allow the page the clipboard, and put text on it
|
||||
* <li>{@code compose:<text>} and {@code insert:<text>}: an input method's composition, and
|
||||
* committed text without key events
|
||||
* <li>{@code drop:<x>,<y>,<file>[,<file>]...}: drop files from this machine on the page
|
||||
* <li>{@code choose:<x>,<y>,<file>[,<file>]...}: click where the page opens a file chooser, and
|
||||
* pick files from this machine in it
|
||||
* <li>{@code downloads:<dir>}: let the page download files, into this (emptied) folder
|
||||
* <li>{@code download:<regex>}: wait up to 20 seconds for a download whose file name matches
|
||||
* to finish; a {@code .png} must be a PNG
|
||||
* <li>{@code pack:<zip>}: write a small resource pack for the check, made here from scratch
|
||||
* (for {@code drop:} or {@code choose:}): it renames the title screen's Singleplayer
|
||||
* button to "Singleplayer (Incari check pack)", in the pack format of the client jar the
|
||||
* page is given
|
||||
* <li>{@code profile:start} and {@code profile:<file>}: start the CPU profiler, and stop it,
|
||||
* writing the profile ({@code .cpuprofile}, which Chrome's DevTools opens) to the file
|
||||
* <li>{@code rcon:<command>}: run a command on the game server through its remote console
|
||||
* ({@code --rcon <host:port>}, password in {@code INCARI_RCON_PASSWORD}), and print the reply
|
||||
* <li>{@code rconwait:<command> => <regex>}: run a server command every half second until its
|
||||
* reply contains a match, for up to a minute ({@code rconwait:list => IncariWeb})
|
||||
* </ul>
|
||||
*/
|
||||
private static boolean runStep(String step, DevTools devTools, PageConsole console, long deadline, StepState state)
|
||||
throws IOException, InterruptedException {
|
||||
int colon = step.indexOf(':');
|
||||
String kind = colon < 0 ? step : step.substring(0, colon);
|
||||
String value = colon < 0 ? "" : step.substring(colon + 1);
|
||||
System.out.println("==> Step " + step);
|
||||
return switch (kind) {
|
||||
case "sleep" -> console.idle(Long.parseLong(value), deadline);
|
||||
case "wait" -> console.await(Pattern.compile(value), 1, deadline);
|
||||
case "shot" -> {
|
||||
Path file = Path.of(value);
|
||||
Path parent = file.toAbsolutePath().getParent();
|
||||
if (parent != null) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
Files.write(file, devTools.screenshot());
|
||||
System.out.println("==> Saved " + file.toAbsolutePath());
|
||||
yield true;
|
||||
}
|
||||
case "move", "click" -> {
|
||||
String[] parts = value.split(",", -1);
|
||||
double[] viewport = devTools.viewport();
|
||||
double x = Double.parseDouble(parts[0]) * viewport[0];
|
||||
double y = Double.parseDouble(parts[1]) * viewport[1];
|
||||
if (kind.equals("click")) {
|
||||
devTools.click(x, y);
|
||||
} else {
|
||||
devTools.move(x, y);
|
||||
}
|
||||
yield true;
|
||||
}
|
||||
case "drag" -> {
|
||||
// drag:x1,y1,x2,y2 in fractions of the viewport, the left button held between.
|
||||
String[] parts = value.split(",", -1);
|
||||
double[] viewport = devTools.viewport();
|
||||
devTools.drag(
|
||||
Double.parseDouble(parts[0]) * viewport[0],
|
||||
Double.parseDouble(parts[1]) * viewport[1],
|
||||
Double.parseDouble(parts[2]) * viewport[0],
|
||||
Double.parseDouble(parts[3]) * viewport[1],
|
||||
12,
|
||||
30);
|
||||
yield true;
|
||||
}
|
||||
case "hold" -> {
|
||||
// hold:x,y,millis: the left button held down at one point (breaking a block).
|
||||
String[] parts = value.split(",", -1);
|
||||
double[] viewport = devTools.viewport();
|
||||
double x = Double.parseDouble(parts[0]) * viewport[0];
|
||||
double y = Double.parseDouble(parts[1]) * viewport[1];
|
||||
long millis = Long.parseLong(parts[2]);
|
||||
devTools.drag(x, y, x, y, (int) Math.max(1, millis / 50), 50);
|
||||
yield true;
|
||||
}
|
||||
case "type" -> {
|
||||
devTools.type(value);
|
||||
yield true;
|
||||
}
|
||||
case "init" -> {
|
||||
devTools.reloadWith(value);
|
||||
yield true;
|
||||
}
|
||||
case "reload" -> {
|
||||
devTools.reload();
|
||||
yield true;
|
||||
}
|
||||
case "eval" -> {
|
||||
System.out.println("==> " + value + " = " + devTools.evaluate(value));
|
||||
yield true;
|
||||
}
|
||||
case "key" -> {
|
||||
List<String> chord = Keys.chord(value);
|
||||
for (String code : chord) {
|
||||
state.press(devTools, code);
|
||||
}
|
||||
for (String code : chord.reversed()) {
|
||||
state.release(devTools, code);
|
||||
}
|
||||
yield true;
|
||||
}
|
||||
case "down" -> {
|
||||
state.press(devTools, Keys.chord(value).getFirst());
|
||||
yield true;
|
||||
}
|
||||
case "up" -> {
|
||||
state.release(devTools, Keys.chord(value).getFirst());
|
||||
yield true;
|
||||
}
|
||||
case "assert", "holds" -> {
|
||||
String result = devTools.evaluate(value, kind.equals("assert"));
|
||||
if (!result.equals("true")) {
|
||||
System.out.println("==> Failed: " + value + " is " + result);
|
||||
yield false;
|
||||
}
|
||||
System.out.println("==> Holds: " + value);
|
||||
yield true;
|
||||
}
|
||||
case "waitfor", "until" -> {
|
||||
boolean gesture = kind.equals("waitfor");
|
||||
long until = Math.min(deadline, System.nanoTime() + TimeUnit.SECONDS.toNanos(10));
|
||||
String result = devTools.evaluate(value, gesture);
|
||||
while (!result.equals("true") && System.nanoTime() < until) {
|
||||
if (!console.idle(100, deadline)) {
|
||||
yield false;
|
||||
}
|
||||
result = devTools.evaluate(value, gesture);
|
||||
}
|
||||
if (!result.equals("true")) {
|
||||
System.out.println("==> Failed: " + value + " is still " + result);
|
||||
yield false;
|
||||
}
|
||||
System.out.println("==> Holds: " + value);
|
||||
yield true;
|
||||
}
|
||||
case "resize" -> {
|
||||
String[] parts = value.split(",", -1);
|
||||
devTools.resize(
|
||||
Integer.parseInt(parts[0].trim()),
|
||||
Integer.parseInt(parts[1].trim()),
|
||||
parts.length > 2 ? Double.parseDouble(parts[2].trim()) : 1);
|
||||
yield true;
|
||||
}
|
||||
case "clipboard" -> {
|
||||
devTools.grantClipboard(state.origin);
|
||||
devTools.evaluate("navigator.clipboard.writeText(" + new JsonPrimitive(value) + ")");
|
||||
yield true;
|
||||
}
|
||||
case "compose" -> {
|
||||
devTools.compose(value);
|
||||
yield true;
|
||||
}
|
||||
case "insert" -> {
|
||||
devTools.insertText(value);
|
||||
yield true;
|
||||
}
|
||||
case "drop" -> {
|
||||
String[] parts = value.split(",", -1);
|
||||
double[] viewport = devTools.viewport();
|
||||
List<String> files = new ArrayList<>();
|
||||
for (int i = 2; i < parts.length; i++) {
|
||||
files.add(Path.of(parts[i].trim()).toAbsolutePath().toString());
|
||||
}
|
||||
devTools.dropFiles(
|
||||
Double.parseDouble(parts[0]) * viewport[0], Double.parseDouble(parts[1]) * viewport[1], files);
|
||||
yield true;
|
||||
}
|
||||
case "choose" -> {
|
||||
String[] parts = value.split(",", -1);
|
||||
double[] viewport = devTools.viewport();
|
||||
List<String> files = new ArrayList<>();
|
||||
for (int i = 2; i < parts.length; i++) {
|
||||
files.add(Path.of(parts[i].trim()).toAbsolutePath().toString());
|
||||
}
|
||||
devTools.chooseFiles(
|
||||
Double.parseDouble(parts[0]) * viewport[0], Double.parseDouble(parts[1]) * viewport[1], files);
|
||||
yield true;
|
||||
}
|
||||
case "downloads" -> {
|
||||
Path directory = Path.of(value).toAbsolutePath();
|
||||
if (Files.exists(directory)) {
|
||||
Chromium.deleteRecursively(directory);
|
||||
}
|
||||
Files.createDirectories(directory);
|
||||
devTools.allowDownloads(directory.toString());
|
||||
state.downloads = directory;
|
||||
yield true;
|
||||
}
|
||||
case "download" -> {
|
||||
Path directory = state.downloads;
|
||||
if (directory == null) {
|
||||
throw new CliException("A download: step needs a downloads: step first");
|
||||
}
|
||||
Pattern name = Pattern.compile(value);
|
||||
String file = devTools.awaitDownload(n -> name.matcher(n).matches(), 20);
|
||||
if (file == null) {
|
||||
System.out.println("==> Failed: no download matching " + value + " finished");
|
||||
yield false;
|
||||
}
|
||||
byte[] bytes = Files.readAllBytes(directory.resolve(file));
|
||||
if (file.endsWith(".png") && !isPng(bytes)) {
|
||||
System.out.println("==> Failed: " + file + " isn't a PNG");
|
||||
yield false;
|
||||
}
|
||||
System.out.println("==> Downloaded " + directory.resolve(file) + " (" + bytes.length + " bytes)");
|
||||
yield true;
|
||||
}
|
||||
case "profile" -> {
|
||||
if (value.equals("start")) {
|
||||
devTools.startProfile();
|
||||
} else {
|
||||
Path file = Path.of(value).toAbsolutePath();
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, devTools.stopProfile());
|
||||
System.out.println("==> Saved " + file);
|
||||
}
|
||||
yield true;
|
||||
}
|
||||
case "pack" -> {
|
||||
Path jar = state.clientJar;
|
||||
if (jar == null) {
|
||||
throw new CliException("A pack: step needs the client jar (--file client.jar=<path>)");
|
||||
}
|
||||
Path zip = Path.of(value).toAbsolutePath();
|
||||
CheckPack.write(zip, CheckPack.resourceFormat(jar));
|
||||
System.out.println("==> Wrote " + zip);
|
||||
yield true;
|
||||
}
|
||||
case "rcon" -> {
|
||||
System.out.println("==> " + state.rcon().command(value).strip());
|
||||
yield true;
|
||||
}
|
||||
case "rconwait" -> {
|
||||
int arrow = value.indexOf(" => ");
|
||||
if (arrow < 0) {
|
||||
throw new CliException("rconwait needs '<command> => <regex>': " + step);
|
||||
}
|
||||
String command = value.substring(0, arrow);
|
||||
Pattern expected = Pattern.compile(value.substring(arrow + " => ".length()));
|
||||
long until = Math.min(deadline, System.nanoTime() + TimeUnit.SECONDS.toNanos(60));
|
||||
String reply = state.rcon().command(command).strip();
|
||||
while (!expected.matcher(reply).find() && System.nanoTime() < until) {
|
||||
if (!console.idle(500, deadline)) {
|
||||
yield false;
|
||||
}
|
||||
reply = state.rcon().command(command).strip();
|
||||
}
|
||||
if (!expected.matcher(reply).find()) {
|
||||
System.out.println("==> Failed: the server still answers '" + reply + "'");
|
||||
yield false;
|
||||
}
|
||||
System.out.println("==> Holds: " + reply);
|
||||
yield true;
|
||||
}
|
||||
default -> throw new CliException("Unknown step '" + step + "'");
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean isPng(byte[] bytes) {
|
||||
byte[] signature = {(byte) 0x89, 'P', 'N', 'G', '\r', '\n', 0x1A, '\n'};
|
||||
return bytes.length > signature.length
|
||||
&& Arrays.equals(bytes, 0, signature.length, signature, 0, signature.length);
|
||||
}
|
||||
|
||||
/** What steps leave behind for later steps: the keys held, the page's origin, the server's console. */
|
||||
private static final class StepState implements AutoCloseable {
|
||||
final String origin;
|
||||
|
||||
@Nullable
|
||||
Path downloads;
|
||||
|
||||
@Nullable
|
||||
Path clientJar;
|
||||
|
||||
private final List<String> held = new ArrayList<>();
|
||||
private final @Nullable String rconAddress;
|
||||
private @Nullable Rcon rcon;
|
||||
|
||||
StepState(String url, @Nullable String rconAddress) {
|
||||
URI uri = URI.create(url);
|
||||
this.origin = uri.getScheme() + "://" + uri.getAuthority();
|
||||
this.rconAddress = rconAddress;
|
||||
}
|
||||
|
||||
/** The server's remote console, logged in on first use. */
|
||||
Rcon rcon() throws IOException {
|
||||
Rcon open = rcon;
|
||||
if (open == null) {
|
||||
if (rconAddress == null) {
|
||||
throw new CliException("An rcon: step needs --rcon <host:port> (-Pbrowser.rcon=...)");
|
||||
}
|
||||
String password = System.getenv("INCARI_RCON_PASSWORD");
|
||||
if (password == null || password.isEmpty()) {
|
||||
throw new CliException("An rcon: step needs the server's rcon.password in INCARI_RCON_PASSWORD");
|
||||
}
|
||||
open = Rcon.connect(rconAddress, password);
|
||||
rcon = open;
|
||||
}
|
||||
return open;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
Rcon open = rcon;
|
||||
if (open != null) {
|
||||
open.close();
|
||||
}
|
||||
}
|
||||
|
||||
void press(DevTools devTools, String code) throws IOException, InterruptedException {
|
||||
held.add(code);
|
||||
devTools.key(code, true, modifiers());
|
||||
}
|
||||
|
||||
void release(DevTools devTools, String code) throws IOException, InterruptedException {
|
||||
held.remove(code);
|
||||
devTools.key(code, false, modifiers());
|
||||
}
|
||||
|
||||
private int modifiers() {
|
||||
int bits = 0;
|
||||
for (String code : held) {
|
||||
bits |= Keys.modifierBit(code);
|
||||
}
|
||||
return bits;
|
||||
}
|
||||
}
|
||||
|
||||
/** A steps file: one step per line; blank lines and lines starting with # are skipped. */
|
||||
private static List<String> readSteps(Path file) throws IOException {
|
||||
List<String> steps = new ArrayList<>();
|
||||
for (String line : Files.readAllLines(file)) {
|
||||
String step = line.strip();
|
||||
if (!step.isEmpty() && !step.startsWith("#")) {
|
||||
steps.add(step);
|
||||
}
|
||||
}
|
||||
return steps;
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.imageio.ImageIO;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The browser build over WebGL2 in headless Chromium, driven through the DevTools protocol: served
|
||||
* like {@code browserCheck} serves it, with the pinned options handed to the page
|
||||
* ({@code ?options=}), straight into the harness's server over the WebSocket bridge, in a viewport
|
||||
* of exactly the harness's size at one device pixel per CSS pixel, so the canvas matches the
|
||||
* desktop window pixel for pixel.
|
||||
*/
|
||||
final class BrowserSceneClient implements SceneClient {
|
||||
|
||||
private final HttpServer server;
|
||||
private final Chromium chromium;
|
||||
private final DevTools devTools;
|
||||
private final List<String> held = new ArrayList<>();
|
||||
private final long deadline;
|
||||
|
||||
private BrowserSceneClient(HttpServer server, Chromium chromium, DevTools devTools, long deadline) {
|
||||
this.server = server;
|
||||
this.chromium = chromium;
|
||||
this.devTools = devTools;
|
||||
this.deadline = deadline;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the page.
|
||||
*
|
||||
* @param files what the page fetches from beside it: the client jar, the shaders, the options
|
||||
* @param query the page's options ({@code server=...&name=...&options=...})
|
||||
*/
|
||||
static BrowserSceneClient start(
|
||||
Path build,
|
||||
Map<String, Path> files,
|
||||
String query,
|
||||
@Nullable String chrome,
|
||||
Chromium.Gpu gpu,
|
||||
int httpPort,
|
||||
int devToolsPort,
|
||||
int width,
|
||||
int height)
|
||||
throws IOException, InterruptedException {
|
||||
HttpServer server = Serve.start(build, httpPort, files);
|
||||
String url = "http://localhost:" + server.getAddress().getPort() + "/?" + PageQuery.withBuild(query);
|
||||
Chromium chromium = Chromium.open(chrome, url, gpu, devToolsPort, width + "," + height);
|
||||
long deadline = System.nanoTime() + TimeUnit.HOURS.toNanos(2);
|
||||
try {
|
||||
PageConsole console = chromium.console();
|
||||
if (!console.await(Pattern.compile("\\[Incari\\] Main loop running.*"), 1, deadline)) {
|
||||
throw new IOException("The browser build didn't start");
|
||||
}
|
||||
DevTools devTools = DevTools.connect(console.devToolsUrl(deadline));
|
||||
devTools.resize(width, height, 1);
|
||||
// The development page's status line would sit on top of the canvas in every screenshot.
|
||||
devTools.evaluate("document.getElementById('incari-status')?.remove(), true");
|
||||
return new BrowserSceneClient(server, chromium, devTools, deadline);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
chromium.close();
|
||||
server.stop(0);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return "browser";
|
||||
}
|
||||
|
||||
/** The page's console so far, to check for WebGL errors and skipped pipelines. */
|
||||
PageConsole console() {
|
||||
return chromium.console();
|
||||
}
|
||||
|
||||
/** A JavaScript expression's value in the page, as JSON. */
|
||||
String evaluate(String expression) throws IOException, InterruptedException {
|
||||
return devTools.evaluate(expression);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void awaitWorld() throws IOException, InterruptedException {
|
||||
// The server lists the player once the login finishes; the world's first frames follow.
|
||||
if (!chromium.console().idle(12_000, deadline)) {
|
||||
throw new IOException("The browser build stopped");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void key(List<String> chord) throws IOException, InterruptedException {
|
||||
for (String code : chord) {
|
||||
held.add(code);
|
||||
devTools.key(code, true, modifiers());
|
||||
}
|
||||
for (String code : chord.reversed()) {
|
||||
held.remove(code);
|
||||
devTools.key(code, false, modifiers());
|
||||
}
|
||||
}
|
||||
|
||||
private int modifiers() {
|
||||
int bits = 0;
|
||||
for (String code : held) {
|
||||
bits |= Keys.modifierBit(code);
|
||||
}
|
||||
return bits;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void move(double x, double y) throws IOException, InterruptedException {
|
||||
double[] viewport = devTools.viewport();
|
||||
devTools.move(x * viewport[0], y * viewport[1]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void click(double x, double y) throws IOException, InterruptedException {
|
||||
double[] viewport = devTools.viewport();
|
||||
devTools.click(x * viewport[0], y * viewport[1]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BufferedImage shot(Path file) throws IOException, InterruptedException {
|
||||
byte[] png = devTools.screenshot();
|
||||
Path parent = file.toAbsolutePath().getParent();
|
||||
if (parent != null) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
Files.write(file, png);
|
||||
BufferedImage image = ImageIO.read(new ByteArrayInputStream(png));
|
||||
if (image == null) {
|
||||
throw new IOException("The browser's screenshot isn't a PNG");
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
devTools.close();
|
||||
chromium.close();
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import incari.tools.build.CliException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Collections;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.SequencedMap;
|
||||
|
||||
/**
|
||||
* Writes {@code build.json}, the build manifest the page's loader reads (ADR 0014): which builds
|
||||
* there are (Fast and Compatible, ADR 0036: each a WebAssembly GC module, with TeaVM's loader beside
|
||||
* them), the asset pack, and every file's size and SHA-256. The loader asks for each file with its hash as the version
|
||||
* ({@code incari.wasm?v=...}), so the service worker keeps it exactly until a build changes it.
|
||||
*
|
||||
* <p>Run by {@code ./gradlew :app-web:buildManifest}:
|
||||
* {@code --out build.json --game 26.3 [--rust <folder>] --file <name>=<path>...}, where each name is
|
||||
* where the page finds the file (the dev server serves it there), and {@code --rust} is the Rust
|
||||
* build's folder, listed when it has a page.
|
||||
*/
|
||||
public final class BuildManifest {
|
||||
|
||||
/**
|
||||
* The game's builds by the manifest's name for them (ADR 0036), each by the name the page fetches
|
||||
* its module by: Fast (JSPI) and Compatible (coroutines). Compatible keeps the name every build
|
||||
* had before, which an experiment's build (no manifest) still has.
|
||||
*/
|
||||
static final SequencedMap<String, String> BUILDS = builds();
|
||||
|
||||
/** TeaVM's loader, one file for both builds. */
|
||||
static final String RUNTIME = "incari.wasm-runtime.js";
|
||||
|
||||
/**
|
||||
* The experimental Rust build's page (ADR 0068): Horizon's own page and files in {@code rust/},
|
||||
* which the loader opens instead of loading a module. Horizon's service worker keeps those files,
|
||||
* so they aren't in the file list.
|
||||
*/
|
||||
static final String RUST_PAGE = "rust/index.html";
|
||||
|
||||
static final String DEOBFUSCATOR = "-deobfuscator.wasm";
|
||||
static final String DEBUG_INFO = ".teadbg";
|
||||
|
||||
private BuildManifest() {}
|
||||
|
||||
private static SequencedMap<String, String> builds() {
|
||||
SequencedMap<String, String> builds = new LinkedHashMap<>();
|
||||
builds.put("fast", "incari-fast.wasm");
|
||||
builds.put("compatible", "incari.wasm");
|
||||
return Collections.unmodifiableSequencedMap(builds);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
Path out = null;
|
||||
String game = null;
|
||||
boolean rust = false;
|
||||
Map<String, Path> files = new LinkedHashMap<>();
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
switch (args[i]) {
|
||||
case "--out" -> out = Path.of(args[++i]);
|
||||
case "--game" -> game = args[++i];
|
||||
case "--rust" -> rust = Files.isRegularFile(Path.of(args[++i]).resolve("index.html"));
|
||||
case "--file" -> {
|
||||
String option = args[++i];
|
||||
int equals = option.indexOf('=');
|
||||
if (equals <= 0) {
|
||||
throw new CliException("Expected <name>=<path>, got '" + option + "'");
|
||||
}
|
||||
Path path = Path.of(option.substring(equals + 1));
|
||||
// Optional files (a build not compiled, a debug build's deobfuscator) may be missing.
|
||||
if (Files.isRegularFile(path)) {
|
||||
files.put(option.substring(0, equals), path);
|
||||
}
|
||||
}
|
||||
default -> throw new CliException("Unknown option '" + args[i] + "'");
|
||||
}
|
||||
}
|
||||
if (out == null || game == null) {
|
||||
throw new CliException(
|
||||
"Usage: BuildManifest --out <file> --game <version> [--rust <folder>] [--file <name>=<path>]...");
|
||||
}
|
||||
JsonObject manifest = manifest(game, files, rust);
|
||||
Files.createDirectories(out.toAbsolutePath().getParent());
|
||||
Files.writeString(out, new GsonBuilder().setPrettyPrinting().create().toJson(manifest) + "\n");
|
||||
System.out.println("==> Wrote " + out + " (build "
|
||||
+ manifest.get("id").getAsString().substring(0, 12) + ")");
|
||||
}
|
||||
|
||||
static JsonObject manifest(String game, Map<String, Path> files, boolean rust) throws IOException {
|
||||
JsonArray list = new JsonArray();
|
||||
MessageDigest id = sha256();
|
||||
for (Map.Entry<String, Path> entry : files.entrySet()) {
|
||||
String hash = hash(entry.getValue());
|
||||
JsonObject file = new JsonObject();
|
||||
file.addProperty("path", entry.getKey());
|
||||
file.addProperty("size", Files.size(entry.getValue()));
|
||||
file.addProperty("sha256", hash);
|
||||
list.add(file);
|
||||
id.update((entry.getKey() + "=" + hash + "\n").getBytes(java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
JsonObject manifest = new JsonObject();
|
||||
manifest.addProperty("format", 2);
|
||||
manifest.addProperty("id", HexFormat.of().formatHex(id.digest()));
|
||||
manifest.addProperty("game", game);
|
||||
// A development build has TeaVM's stack deobfuscator beside it; a release build doesn't.
|
||||
boolean release = BUILDS.values().stream().noneMatch(module -> files.containsKey(module + DEOBFUSCATOR));
|
||||
manifest.addProperty("release", release);
|
||||
for (Map.Entry<String, String> build : BUILDS.entrySet()) {
|
||||
String module = build.getValue();
|
||||
if (!files.containsKey(module)) {
|
||||
continue;
|
||||
}
|
||||
JsonObject entry = new JsonObject();
|
||||
entry.addProperty("runtime", RUNTIME);
|
||||
entry.addProperty("module", module);
|
||||
if (!release && files.containsKey(module + DEBUG_INFO)) {
|
||||
entry.addProperty("deobfuscator", module + DEOBFUSCATOR);
|
||||
entry.addProperty("debugInfo", module + DEBUG_INFO);
|
||||
}
|
||||
manifest.add(build.getKey(), entry);
|
||||
}
|
||||
if (rust) {
|
||||
JsonObject entry = new JsonObject();
|
||||
entry.addProperty("page", RUST_PAGE);
|
||||
manifest.add("rust", entry);
|
||||
}
|
||||
// Programs the page's workers run beside the game: each its own module and loader.
|
||||
JsonObject programs = new JsonObject();
|
||||
for (String name : files.keySet()) {
|
||||
if (name.endsWith(".wasm") && !BUILDS.containsValue(name) && !name.endsWith(DEOBFUSCATOR)) {
|
||||
String program = name.substring(0, name.length() - ".wasm".length());
|
||||
if (files.containsKey(program + ".wasm-runtime.js")) {
|
||||
JsonObject entry = new JsonObject();
|
||||
entry.addProperty("runtime", program + ".wasm-runtime.js");
|
||||
entry.addProperty("module", name);
|
||||
programs.add(program, entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!programs.isEmpty()) {
|
||||
manifest.add("programs", programs);
|
||||
}
|
||||
if (files.containsKey("incari.pack")) {
|
||||
manifest.addProperty("pack", "incari.pack");
|
||||
}
|
||||
manifest.add("files", list);
|
||||
return manifest;
|
||||
}
|
||||
|
||||
private static String hash(Path file) throws IOException {
|
||||
MessageDigest digest = sha256();
|
||||
byte[] buffer = new byte[1 << 20];
|
||||
try (InputStream in = Files.newInputStream(file)) {
|
||||
int read;
|
||||
while ((read = in.read(buffer)) > 0) {
|
||||
digest.update(buffer, 0, read);
|
||||
}
|
||||
}
|
||||
return HexFormat.of().formatHex(digest.digest());
|
||||
}
|
||||
|
||||
private static MessageDigest sha256() {
|
||||
try {
|
||||
return MessageDigest.getInstance("SHA-256");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("Every JDK has SHA-256", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import incari.tools.build.CliException;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import javax.imageio.ImageIO;
|
||||
|
||||
/**
|
||||
* A resource pack the browser checks import, made from scratch when the check runs: the
|
||||
* repository holds no pack files (the content check rejects game-asset paths, and a pack of our
|
||||
* own is a few lines anyway). It renames the title screen's Singleplayer button, so a screenshot
|
||||
* shows whether the game loaded it, and has a plain icon.
|
||||
*/
|
||||
final class CheckPack {
|
||||
|
||||
/** What the pack calls the title screen's Singleplayer button. */
|
||||
static final String BUTTON = "Singleplayer (Incari check pack)";
|
||||
|
||||
private CheckPack() {}
|
||||
|
||||
/** The resource pack format of the game in {@code clientJar}, from its {@code version.json}. */
|
||||
static int resourceFormat(Path clientJar) throws IOException {
|
||||
try (ZipFile jar = new ZipFile(clientJar.toFile())) {
|
||||
ZipEntry version = jar.getEntry("version.json");
|
||||
if (version == null) {
|
||||
throw new CliException(clientJar + " has no version.json");
|
||||
}
|
||||
try (InputStream in = jar.getInputStream(version)) {
|
||||
JsonObject json = JsonParser.parseReader(new InputStreamReader(in, StandardCharsets.UTF_8))
|
||||
.getAsJsonObject();
|
||||
return json.getAsJsonObject("pack_version")
|
||||
.get("resource_major")
|
||||
.getAsInt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes the pack, for resource pack format {@code format}, as a zip at {@code zip}. */
|
||||
static void write(Path zip, int format) throws IOException {
|
||||
Path parent = zip.getParent();
|
||||
if (parent != null) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
String meta = "{\"pack\": {\"description\": \"Incari storage check\", \"min_format\": " + format
|
||||
+ ", \"max_format\": " + format + "}}\n";
|
||||
String language = "{\"menu.singleplayer\": \"" + BUTTON + "\"}\n";
|
||||
try (OutputStream out = Files.newOutputStream(zip);
|
||||
ZipOutputStream pack = new ZipOutputStream(out)) {
|
||||
entry(pack, "pack.mcmeta", meta.getBytes(StandardCharsets.UTF_8));
|
||||
entry(pack, "pack.png", icon());
|
||||
entry(pack, "assets/minecraft/lang/en_us.json", language.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
|
||||
private static void entry(ZipOutputStream pack, String name, byte[] data) throws IOException {
|
||||
pack.putNextEntry(new ZipEntry(name));
|
||||
pack.write(data);
|
||||
pack.closeEntry();
|
||||
}
|
||||
|
||||
/** A 16x16 icon in two colors, diagonally split. */
|
||||
private static byte[] icon() throws IOException {
|
||||
BufferedImage image = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
|
||||
for (int y = 0; y < 16; y++) {
|
||||
for (int x = 0; x < 16; x++) {
|
||||
image.setRGB(x, y, x > y ? 0xFF3B82F6 : 0xFFF59E0B);
|
||||
}
|
||||
}
|
||||
ByteArrayOutputStream png = new ByteArrayOutputStream();
|
||||
ImageIO.write(image, "png", png);
|
||||
return png.toByteArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Stream;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Headless Chromium for the browser checks: found, started on a page with a profile of its own,
|
||||
* its console read ({@link PageConsole}), and cleaned up.
|
||||
*
|
||||
* <p>Chromium comes from {@code --chrome}, else {@code INCARI_CHROME}, else Playwright's download
|
||||
* cache, else {@code chromium} or {@code google-chrome} on the path.
|
||||
*/
|
||||
final class Chromium implements AutoCloseable {
|
||||
|
||||
/**
|
||||
* Which GPU WebGL runs on. Headless Chromium picks SwiftShader, its software renderer, unless
|
||||
* told to use the machine's GPU through ANGLE.
|
||||
*/
|
||||
enum Gpu {
|
||||
/** SwiftShader: works anywhere (CI, machines without a GPU), slowly, and differs from any real GPU. */
|
||||
SWIFTSHADER("--enable-unsafe-swiftshader", "--ignore-gpu-blocklist"),
|
||||
/** The machine's GPU through ANGLE's OpenGL backend: the same driver the desktop game uses. */
|
||||
GL("--use-angle=gl", "--ignore-gpu-blocklist"),
|
||||
/** The machine's GPU through ANGLE's Vulkan backend, which Chrome prefers on some systems. */
|
||||
VULKAN("--use-angle=vulkan", "--enable-features=Vulkan", "--ignore-gpu-blocklist"),
|
||||
/**
|
||||
* As {@link #VULKAN}, with WebGPU on the machine's GPU: on Linux, Chrome's WebGPU needs Vulkan,
|
||||
* and headless Chromium offers only SwiftShader's adapter without {@code --enable-unsafe-webgpu}
|
||||
* (docs/webgpu-backend.md).
|
||||
*/
|
||||
WEBGPU("--use-angle=vulkan", "--enable-features=Vulkan", "--enable-unsafe-webgpu", "--ignore-gpu-blocklist");
|
||||
|
||||
/** Chromium flags, separated by spaces (an enum holds no mutable list). */
|
||||
private final String flags;
|
||||
|
||||
Gpu(String... flags) {
|
||||
this.flags = String.join(" ", flags);
|
||||
}
|
||||
|
||||
static Gpu parse(String name) {
|
||||
return switch (name) {
|
||||
case "swiftshader" -> SWIFTSHADER;
|
||||
case "gl" -> GL;
|
||||
case "vulkan" -> VULKAN;
|
||||
case "webgpu" -> WEBGPU;
|
||||
default -> throw new CliException("Unknown GPU '" + name + "' (swiftshader, gl, vulkan or webgpu)");
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private final Process process;
|
||||
private final Path profile;
|
||||
private final PageConsole console;
|
||||
|
||||
private Chromium(Process process, Path profile) {
|
||||
this.process = process;
|
||||
this.profile = profile;
|
||||
this.console = new PageConsole(process);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens {@code url} in headless Chromium.
|
||||
*
|
||||
* @param devToolsPort where to listen for the DevTools protocol (steps, screenshots): 0 for any
|
||||
* free port, -1 not at all
|
||||
* @param windowSize the window's size, {@code 1280,720} say, or null for Chromium's default
|
||||
*/
|
||||
static Chromium open(@Nullable String chrome, String url, Gpu gpu, int devToolsPort, @Nullable String windowSize)
|
||||
throws IOException {
|
||||
return open(chrome, url, gpu, devToolsPort, windowSize, true, List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens {@code url} in Chromium, headless or in a window of its own (the benchmark runner's
|
||||
* {@code --headed}: frame pacing in a real window is what players get), with
|
||||
* {@code extraFlags} added to the usual ones.
|
||||
*/
|
||||
static Chromium open(
|
||||
@Nullable String chrome,
|
||||
String url,
|
||||
Gpu gpu,
|
||||
int devToolsPort,
|
||||
@Nullable String windowSize,
|
||||
boolean headless,
|
||||
List<String> extraFlags)
|
||||
throws IOException {
|
||||
Path browser = chrome != null ? Path.of(chrome) : find();
|
||||
Path profile = Files.createTempDirectory("incari-browser-check");
|
||||
System.out.println("==> Opening " + url + " in " + browser);
|
||||
List<String> command = new ArrayList<>(List.of(browser.toString()));
|
||||
if (headless) {
|
||||
command.add("--headless=new");
|
||||
}
|
||||
command.addAll(List.of(
|
||||
"--no-first-run",
|
||||
"--no-default-browser-check",
|
||||
// As a player's browser does: sound waits for a click or a key press (the
|
||||
// unlock prompt). Headless Chromium would otherwise let the page play at once, and
|
||||
// does even with user-gesture-required.
|
||||
"--autoplay-policy=document-user-activation-required",
|
||||
// Silent on this machine's speakers; the page's audio graph still runs, and checks
|
||||
// measure it there (browser-checks/audio*.steps).
|
||||
"--mute-audio",
|
||||
// Voice chat: a fake microphone (a steady tone), and the permission prompt
|
||||
// answered yes, as a player would.
|
||||
"--use-fake-device-for-media-stream",
|
||||
"--use-fake-ui-for-media-stream",
|
||||
"--user-data-dir=" + profile,
|
||||
"--enable-logging=stderr",
|
||||
"--v=0"));
|
||||
command.addAll(List.of(gpu.flags.split(" ")));
|
||||
if (devToolsPort >= 0) {
|
||||
command.add("--remote-debugging-port=" + devToolsPort);
|
||||
}
|
||||
if (windowSize != null) {
|
||||
command.add("--window-size=" + windowSize);
|
||||
}
|
||||
command.addAll(extraFlags);
|
||||
command.add(url);
|
||||
Process process = new ProcessBuilder(command)
|
||||
.redirectOutput(ProcessBuilder.Redirect.DISCARD)
|
||||
.start();
|
||||
return new Chromium(process, profile);
|
||||
}
|
||||
|
||||
PageConsole console() {
|
||||
return console;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
process.descendants().forEach(ProcessHandle::destroyForcibly);
|
||||
process.destroyForcibly();
|
||||
try {
|
||||
process.waitFor(10, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
deleteRecursively(profile);
|
||||
}
|
||||
|
||||
private static Path find() throws IOException {
|
||||
String fromEnvironment = System.getenv("INCARI_CHROME");
|
||||
if (fromEnvironment != null && !fromEnvironment.isBlank()) {
|
||||
return Path.of(fromEnvironment);
|
||||
}
|
||||
Path playwright = Path.of(System.getProperty("user.home"), ".cache", "ms-playwright");
|
||||
if (Files.isDirectory(playwright)) {
|
||||
try (Stream<Path> found = Files.walk(playwright, 3)) {
|
||||
List<Path> candidates = new ArrayList<>(
|
||||
found.filter(p -> p.getFileName().toString().equals("chrome") && Files.isExecutable(p))
|
||||
.sorted()
|
||||
.toList());
|
||||
if (!candidates.isEmpty()) {
|
||||
return candidates.getLast();
|
||||
}
|
||||
}
|
||||
}
|
||||
for (String name : List.of("chromium", "chromium-browser", "google-chrome")) {
|
||||
for (String dir : System.getenv().getOrDefault("PATH", "").split(File.pathSeparator, -1)) {
|
||||
Path candidate = Path.of(dir, name);
|
||||
if (Files.isExecutable(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new CliException("No Chromium found; pass --chrome <path> or set INCARI_CHROME");
|
||||
}
|
||||
|
||||
static void deleteRecursively(Path directory) throws IOException {
|
||||
if (!Files.exists(directory)) {
|
||||
return;
|
||||
}
|
||||
try (Stream<Path> paths = Files.walk(directory)) {
|
||||
for (Path path : paths.sorted(Comparator.reverseOrder()).toList()) {
|
||||
Files.deleteIfExists(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import org.teavm.extension.spi.substitution.SimpleSubstitutionPolicy;
|
||||
import org.teavm.extension.spi.substitution.SubstitutionSink;
|
||||
|
||||
/**
|
||||
* Lets {@code web-classlib} stand in for classes: a class
|
||||
* {@code incari.classlib.substitutes.<package>.T<Name>} replaces {@code <package>.<Name>} everywhere
|
||||
* in the browser build, the way TeaVM's own class library maps {@code java.util.Foo} to
|
||||
* {@code org.teavm.classlib.java.util.TFoo}.
|
||||
*
|
||||
* <p>TeaVM tries each policy's rule in turn and takes the first substitute that exists, so a class
|
||||
* this rule finds wins over TeaVM's. {@code web-classlib} only defines what TeaVM lacks, or
|
||||
* replaces a class TeaVM has in part (named in that class's comment).
|
||||
*
|
||||
* <p>The mapping also runs backwards over everything under the package: any top-level class there
|
||||
* whose name starts with {@code T} is taken for a substitute. Helpers go elsewhere in
|
||||
* {@code incari.classlib}.
|
||||
*
|
||||
* <p>Registered in {@code META-INF/services}; TeaVM loads it from the compile's class loader.
|
||||
*/
|
||||
public final class ClasslibPolicy extends SimpleSubstitutionPolicy {
|
||||
|
||||
/** The package the substitutes live under. */
|
||||
public static final String PACKAGE = "incari.classlib.substitutes";
|
||||
|
||||
@Override
|
||||
public void contribute(SubstitutionSink sink) {
|
||||
sink.selectClasses(name -> !name.startsWith(PACKAGE + "."))
|
||||
.packagePrefix(PACKAGE)
|
||||
.simpleNamePrefix("T");
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import org.teavm.model.ClassHolder;
|
||||
import org.teavm.model.ClassHolderTransformer;
|
||||
import org.teavm.model.ClassHolderTransformerContext;
|
||||
import org.teavm.model.ReferenceCache;
|
||||
import org.teavm.parsing.ClassRefsRenamer;
|
||||
|
||||
/**
|
||||
* Gives {@code web-classlib}'s helpers the same view of names the substitutes have. TeaVM rewrites
|
||||
* the references inside a substitute ({@code TFileChannel} becomes {@code FileChannel}
|
||||
* everywhere in it), but not inside other classes, so a helper that names a substitute directly
|
||||
* would keep the {@code T} name and miss the renamed class. This rewrites those references in
|
||||
* every other {@code incari.classlib} class, in place.
|
||||
*/
|
||||
public final class ClasslibRenamer implements ClassHolderTransformer {
|
||||
|
||||
private static final String PREFIX = ClasslibPolicy.PACKAGE + ".";
|
||||
|
||||
private final ClassRefsRenamer renamer = new ClassRefsRenamer(new ReferenceCache(), ClasslibRenamer::original);
|
||||
|
||||
@Override
|
||||
public void transformClass(ClassHolder cls, ClassHolderTransformerContext context) {
|
||||
if (cls.getName().startsWith("incari.classlib.")) {
|
||||
// The name stays the same, so the renamer updates the class itself.
|
||||
renamer.rename(cls);
|
||||
}
|
||||
}
|
||||
|
||||
/** {@code incari.classlib.substitutes.java.nio.channels.TFileChannel} to {@code java.nio.channels.FileChannel}. */
|
||||
static String original(String name) {
|
||||
if (!name.startsWith(PREFIX)) {
|
||||
return name;
|
||||
}
|
||||
int dot = name.lastIndexOf('.');
|
||||
if (dot < PREFIX.length() || name.charAt(dot + 1) != 'T') {
|
||||
return name;
|
||||
}
|
||||
return name.substring(PREFIX.length(), dot + 1) + name.substring(dot + 2);
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import org.teavm.tooling.TeaVMToolLog;
|
||||
|
||||
/** TeaVM's progress on the console: warnings and errors always, the rest with --verbose. */
|
||||
final class ConsoleLog implements TeaVMToolLog {
|
||||
|
||||
private final boolean verbose;
|
||||
|
||||
ConsoleLog(boolean verbose) {
|
||||
this.verbose = verbose;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void info(String text) {
|
||||
if (verbose) {
|
||||
System.out.println(" " + text);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void debug(String text) {
|
||||
if (verbose) {
|
||||
System.out.println(" " + text);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warning(String text) {
|
||||
if (verbose) {
|
||||
System.err.println("warning: " + text);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String text) {
|
||||
System.err.println("error: " + text);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void info(String text, Throwable e) {
|
||||
info(text + ": " + e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void debug(String text, Throwable e) {
|
||||
debug(text + ": " + e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void warning(String text, Throwable e) {
|
||||
warning(text + ": " + e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String text, Throwable e) {
|
||||
error(text + ": " + e);
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* The sounds the single HTML file carries where ffmpeg isn't there to make them smaller
|
||||
* ({@link SmallSounds}; ADR 0057, ADR 0062): every sound is 377 MB, music and records 293 of it,
|
||||
* more than a file a 4 GB device opens should hold. These are about 10 MB, as they are: digging and footsteps of the classic materials, the interface, items, players,
|
||||
* damage, liquids, fire, explosions, everyday blocks (chests, doors, furnaces) and the hostile mobs a
|
||||
* fight depends on hearing. No music, records, ambience, or the newer blocks' and other mobs' own
|
||||
* sounds.
|
||||
*
|
||||
* <p>The sound list ({@code sounds.json}) is trimmed to match ({@link #trim}), so the game lists only
|
||||
* sounds the file has: no warning for a missing file at start, and no event that plays nothing.
|
||||
*/
|
||||
final class CoreSounds {
|
||||
|
||||
/** Folders under {@code minecraft/sounds/} whose files are kept. */
|
||||
private static final List<String> FOLDERS = List.of(
|
||||
"damage/",
|
||||
"dig/",
|
||||
"enchant/",
|
||||
"entity/",
|
||||
"event/",
|
||||
"fire/",
|
||||
"fireworks/",
|
||||
"item/",
|
||||
"liquid/",
|
||||
"minecart/",
|
||||
"note/",
|
||||
"portal/",
|
||||
"random/",
|
||||
"step/",
|
||||
"tile/",
|
||||
"ui/",
|
||||
"block/barrel/",
|
||||
"block/beacon/",
|
||||
"block/brewing_stand/",
|
||||
"block/chest/",
|
||||
"block/enchantment_table/",
|
||||
"block/fence_gate/",
|
||||
"block/furnace/",
|
||||
"block/grindstone/",
|
||||
"block/iron_door/",
|
||||
"block/iron_trapdoor/",
|
||||
"block/lantern/",
|
||||
"block/smithing_table/",
|
||||
"block/wooden_door/",
|
||||
"block/wooden_trapdoor/",
|
||||
"mob/creeper/",
|
||||
"mob/endermen/",
|
||||
"mob/skeleton/",
|
||||
"mob/spider/",
|
||||
"mob/zombie/");
|
||||
|
||||
private static final String SOUNDS = "minecraft/sounds/";
|
||||
|
||||
private CoreSounds() {}
|
||||
|
||||
/** Whether the asset index's {@code name} is a sound file the single file carries. */
|
||||
static boolean keeps(String name) {
|
||||
if (!name.startsWith(SOUNDS) || !name.endsWith(".ogg")) {
|
||||
return false;
|
||||
}
|
||||
String path = name.substring(SOUNDS.length());
|
||||
for (String folder : FOLDERS) {
|
||||
if (path.startsWith(folder)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code soundList} (the game's {@code sounds.json}) with only the sounds whose files {@code
|
||||
* kept} names (by asset name) and the events those leave something to play. An event entry
|
||||
* ({@code "type": "event"}) stays while the event it names does; repeated until nothing changes.
|
||||
*/
|
||||
static JsonObject trim(JsonObject soundList, Predicate<String> kept) {
|
||||
JsonObject events = soundList.deepCopy();
|
||||
boolean changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (Map.Entry<String, JsonElement> event : List.copyOf(events.entrySet())) {
|
||||
JsonObject definition = event.getValue().getAsJsonObject();
|
||||
JsonArray sounds = definition.getAsJsonArray("sounds");
|
||||
if (sounds == null) {
|
||||
continue;
|
||||
}
|
||||
JsonArray left = new JsonArray();
|
||||
for (JsonElement sound : sounds) {
|
||||
if (plays(sound, events, kept)) {
|
||||
left.add(sound);
|
||||
}
|
||||
}
|
||||
if (left.isEmpty()) {
|
||||
events.remove(event.getKey());
|
||||
changed = true;
|
||||
} else if (left.size() != sounds.size()) {
|
||||
definition.add("sounds", left);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
private static boolean plays(JsonElement sound, JsonObject events, Predicate<String> kept) {
|
||||
String name;
|
||||
boolean event = false;
|
||||
if (sound.isJsonPrimitive()) {
|
||||
name = sound.getAsString();
|
||||
} else {
|
||||
JsonObject entry = sound.getAsJsonObject();
|
||||
name = entry.get("name").getAsString();
|
||||
JsonElement type = entry.get("type");
|
||||
event = type != null && type.getAsString().equals("event");
|
||||
}
|
||||
String namespace = "minecraft";
|
||||
int colon = name.indexOf(':');
|
||||
if (colon >= 0) {
|
||||
namespace = name.substring(0, colon);
|
||||
name = name.substring(colon + 1);
|
||||
}
|
||||
if (event) {
|
||||
// Another event of this list, which plays while it's still here.
|
||||
return namespace.equals("minecraft") && events.has(name);
|
||||
}
|
||||
return kept.test(namespace + "/sounds/" + name + ".ogg");
|
||||
}
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.PrintWriter;
|
||||
import java.net.InetAddress;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.imageio.ImageIO;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The desktop game (Mojang's OpenGL backend) as the harness's reference: started from the launch
|
||||
* file {@code :app-desktop:sceneLaunch} writes, with a fresh game directory holding the pinned
|
||||
* options, straight into the harness's server (quick play), and driven through app-desktop's
|
||||
* {@code SceneAgent} on a loopback port.
|
||||
*/
|
||||
final class DesktopSceneClient implements SceneClient {
|
||||
|
||||
private final Process process;
|
||||
private final Path java;
|
||||
private final Socket socket;
|
||||
private final BufferedReader in;
|
||||
private final PrintWriter out;
|
||||
|
||||
private DesktopSceneClient(Process process, Path java, Socket socket) throws IOException {
|
||||
this.process = process;
|
||||
this.java = java;
|
||||
this.socket = socket;
|
||||
this.in = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
|
||||
this.out = new PrintWriter(socket.getOutputStream(), true, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the game.
|
||||
*
|
||||
* @param launch {@code :app-desktop:sceneLaunch}'s file
|
||||
* @param gameDirectory a fresh directory, already holding {@code options.txt}
|
||||
* @param server the server, as {@code host:port}
|
||||
*/
|
||||
static DesktopSceneClient start(
|
||||
Path launch, Path gameDirectory, String player, String server, int agentPort, int width, int height)
|
||||
throws IOException, InterruptedException {
|
||||
return start(launch, gameDirectory, player, server, agentPort, width, height, List.of());
|
||||
}
|
||||
|
||||
/** As {@link #start(Path, Path, String, String, int, int, int)}, with {@code extraJvm} options for the game's JVM. */
|
||||
static DesktopSceneClient start(
|
||||
Path launch,
|
||||
Path gameDirectory,
|
||||
String player,
|
||||
String server,
|
||||
int agentPort,
|
||||
int width,
|
||||
int height,
|
||||
List<String> extraJvm)
|
||||
throws IOException, InterruptedException {
|
||||
@Nullable String java = null;
|
||||
@Nullable String main = null;
|
||||
List<String> jvm = new ArrayList<>();
|
||||
List<String> classpath = new ArrayList<>();
|
||||
List<String> arguments = new ArrayList<>();
|
||||
for (String line : Files.readAllLines(launch)) {
|
||||
int space = line.indexOf(' ');
|
||||
if (space < 0) {
|
||||
continue;
|
||||
}
|
||||
String value = line.substring(space + 1);
|
||||
switch (line.substring(0, space)) {
|
||||
case "java" -> java = value;
|
||||
case "jvm" -> jvm.add(value);
|
||||
case "classpath" -> classpath.add(value);
|
||||
case "main" -> main = value;
|
||||
case "arg" -> arguments.add(value);
|
||||
default -> throw new CliException(launch + ": unknown line '" + line + "'");
|
||||
}
|
||||
}
|
||||
if (java == null || main == null) {
|
||||
throw new CliException(launch + " names no java or main class; run ./gradlew :app-desktop:sceneLaunch");
|
||||
}
|
||||
List<String> command = new ArrayList<>();
|
||||
command.add(java);
|
||||
command.addAll(jvm);
|
||||
command.addAll(extraJvm);
|
||||
command.add("-Dincari.sceneAgent=" + agentPort);
|
||||
command.add("-cp");
|
||||
command.add(String.join(File.pathSeparator, classpath));
|
||||
command.add(main);
|
||||
command.addAll(arguments);
|
||||
command.addAll(List.of(
|
||||
"--gameDir", gameDirectory.toAbsolutePath().toString(),
|
||||
"--username", player,
|
||||
"--width", Integer.toString(width),
|
||||
"--height", Integer.toString(height),
|
||||
"--quickPlayMultiplayer", server));
|
||||
System.out.println("==> Starting the desktop game (Mojang's OpenGL backend)");
|
||||
Process process = new ProcessBuilder(command)
|
||||
.directory(gameDirectory.toFile())
|
||||
.redirectErrorStream(true)
|
||||
.redirectOutput(gameDirectory.resolve("game-output.txt").toFile())
|
||||
.start();
|
||||
long until = System.nanoTime() + TimeUnit.MINUTES.toNanos(3);
|
||||
while (true) {
|
||||
try {
|
||||
return new DesktopSceneClient(
|
||||
process, Path.of(java), new Socket(InetAddress.getLoopbackAddress(), agentPort));
|
||||
} catch (IOException e) {
|
||||
if (!process.isAlive() || System.nanoTime() > until) {
|
||||
process.destroyForcibly();
|
||||
throw new IOException(
|
||||
"The desktop game's scene agent didn't answer; see "
|
||||
+ gameDirectory.resolve("game-output.txt"),
|
||||
e);
|
||||
}
|
||||
Thread.sleep(500);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return "desktop";
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs {@code jcmd} against the game's JVM with {@code command} (a Flight Recorder recording's
|
||||
* start and stop, for the benchmark's allocation profile, ADR 0025); its output.
|
||||
*/
|
||||
String jcmd(String... command) throws IOException, InterruptedException {
|
||||
List<String> line = new ArrayList<>();
|
||||
Path parent = java.getParent();
|
||||
line.add(parent == null ? "jcmd" : parent.resolve("jcmd").toString());
|
||||
line.add(Long.toString(process.pid()));
|
||||
line.addAll(List.of(command));
|
||||
Process jcmd = new ProcessBuilder(line).redirectErrorStream(true).start();
|
||||
String output = new String(jcmd.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
if (jcmd.waitFor() != 0) {
|
||||
throw new IOException("jcmd " + String.join(" ", command) + " failed: " + output);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void awaitWorld() throws IOException, InterruptedException {
|
||||
long until = System.nanoTime() + TimeUnit.MINUTES.toNanos(3);
|
||||
String state = "";
|
||||
while (System.nanoTime() < until) {
|
||||
state = send("state");
|
||||
if (state.equals("world")) {
|
||||
return;
|
||||
}
|
||||
Thread.sleep(500);
|
||||
}
|
||||
throw new IOException("The desktop game isn't in the world (it's at '" + state + "')");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void key(List<String> chord) throws IOException {
|
||||
for (String code : chord) {
|
||||
Keys.SdlKey key = Keys.sdl(code);
|
||||
send("key " + key.scancode() + " " + key.keycode() + " down");
|
||||
}
|
||||
for (String code : chord.reversed()) {
|
||||
Keys.SdlKey key = Keys.sdl(code);
|
||||
send("key " + key.scancode() + " " + key.keycode() + " up");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void move(double x, double y) throws IOException {
|
||||
send("move " + x + " " + y);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void click(double x, double y) throws IOException {
|
||||
send("click " + x + " " + y);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BufferedImage shot(Path file) throws IOException {
|
||||
send("shot " + file.toAbsolutePath());
|
||||
BufferedImage image = ImageIO.read(file.toFile());
|
||||
if (image == null) {
|
||||
throw new IOException("The desktop game wrote no readable PNG at " + file);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
private String send(String command) throws IOException {
|
||||
out.println(command);
|
||||
String answer = in.readLine();
|
||||
if (answer == null) {
|
||||
throw new IOException("The desktop game closed its scene agent (did it crash?)");
|
||||
}
|
||||
if (!answer.startsWith("ok")) {
|
||||
throw new IOException("The desktop game's scene agent: " + command + ": " + answer);
|
||||
}
|
||||
return answer.substring(2).strip();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
socket.close();
|
||||
process.descendants().forEach(ProcessHandle::destroyForcibly);
|
||||
process.destroyForcibly();
|
||||
try {
|
||||
process.waitFor(20, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,784 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.io.Writer;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.WebSocket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.Predicate;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Just enough of the Chrome DevTools Protocol to look at the page and use it like a player:
|
||||
* screenshots, and mouse and keyboard input the page receives as real, trusted events. Connects to
|
||||
* the browser endpoint Chromium prints ({@code --remote-debugging-port}) and attaches to the page.
|
||||
*/
|
||||
final class DevTools implements AutoCloseable {
|
||||
|
||||
private static final long TIMEOUT_SECONDS = 30;
|
||||
|
||||
private final WebSocket socket;
|
||||
private final Map<Integer, CompletableFuture<JsonObject>> pending = new ConcurrentHashMap<>();
|
||||
// Events (messages without an id) that a step waits for: file choosers, downloads.
|
||||
private final BlockingQueue<JsonObject> events = new LinkedBlockingQueue<>();
|
||||
// A trace's events as they arrive (Tracing.dataCollected), until the trace ends.
|
||||
private final Queue<JsonObject> traceEvents = new ConcurrentLinkedQueue<>();
|
||||
// Where a heap snapshot's chunks go as they arrive (HeapProfiler.addHeapSnapshotChunk), while one is taken.
|
||||
private volatile @Nullable Writer snapshotSink;
|
||||
// The page's console, when collected over the protocol (collectConsole): for a browser this tool
|
||||
// didn't start, whose log it can't read.
|
||||
private final Queue<String> console = new ConcurrentLinkedQueue<>();
|
||||
/** The page's workers attached so far ({@link #attachWorkers}), by session: their names and addresses. */
|
||||
private final Map<String, String> workers = new ConcurrentHashMap<>();
|
||||
/** The workers' sessions in the order they attached, the latest last. */
|
||||
private final Queue<String> workerOrder = new ConcurrentLinkedQueue<>();
|
||||
|
||||
private final AtomicInteger ids = new AtomicInteger();
|
||||
private @Nullable String session;
|
||||
/** The tab this connection opened ({@link #openTab}), closed with it; null for a page it found. */
|
||||
private @Nullable String openedTab;
|
||||
|
||||
private DevTools(WebSocket socket) {
|
||||
this.socket = socket;
|
||||
}
|
||||
|
||||
/** Connects to {@code browserUrl} ({@code ws://127.0.0.1:<port>/devtools/browser/<id>}) and attaches to its page. */
|
||||
static DevTools connect(String browserUrl) throws IOException, InterruptedException {
|
||||
return connect(browserUrl, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects to {@code browserUrl} and attaches to a new tab it opens on {@code url}, leaving the
|
||||
* browser's other tabs alone: for a browser this tool didn't start (a Chromebook's, which the
|
||||
* benchmark runner drives over the network).
|
||||
*/
|
||||
static DevTools openTab(String browserUrl, String url) throws IOException, InterruptedException {
|
||||
return connect(browserUrl, url);
|
||||
}
|
||||
|
||||
private static DevTools connect(String browserUrl, @Nullable String newTab)
|
||||
throws IOException, InterruptedException {
|
||||
Listener listener = new Listener();
|
||||
WebSocket socket;
|
||||
try {
|
||||
socket = HttpClient.newHttpClient()
|
||||
.newWebSocketBuilder()
|
||||
.buildAsync(URI.create(browserUrl), listener)
|
||||
.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
} catch (ExecutionException | TimeoutException e) {
|
||||
throw new IOException("Couldn't connect to the browser's DevTools at " + browserUrl, e);
|
||||
}
|
||||
DevTools devTools = new DevTools(socket);
|
||||
listener.devTools = devTools;
|
||||
String page = newTab != null ? devTools.createTab(newTab) : devTools.firstPage();
|
||||
if (page == null) {
|
||||
throw new IOException("The browser has no page to attach to");
|
||||
}
|
||||
if (newTab != null) {
|
||||
devTools.openedTab = page;
|
||||
}
|
||||
JsonObject attach = new JsonObject();
|
||||
attach.addProperty("targetId", page);
|
||||
attach.addProperty("flatten", true);
|
||||
devTools.session =
|
||||
devTools.call("Target.attachToTarget", attach).get("sessionId").getAsString();
|
||||
return devTools;
|
||||
}
|
||||
|
||||
private String createTab(String url) throws IOException, InterruptedException {
|
||||
JsonObject create = new JsonObject();
|
||||
create.addProperty("url", url);
|
||||
return call("Target.createTarget", create).get("targetId").getAsString();
|
||||
}
|
||||
|
||||
private @Nullable String firstPage() throws IOException, InterruptedException {
|
||||
JsonArray targets = call("Target.getTargets", new JsonObject()).getAsJsonArray("targetInfos");
|
||||
String page = null;
|
||||
for (JsonElement target : targets) {
|
||||
JsonObject info = target.getAsJsonObject();
|
||||
if (info.get("type").getAsString().equals("page")) {
|
||||
page = info.get("targetId").getAsString();
|
||||
break;
|
||||
}
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects the page's console messages from now on ({@link #console}): a browser this tool
|
||||
* started logs them to its own output, but a remote one's can only be heard over the protocol.
|
||||
*/
|
||||
void collectConsole() throws IOException, InterruptedException {
|
||||
call("Runtime.enable", new JsonObject());
|
||||
}
|
||||
|
||||
/** The console messages collected so far ({@link #collectConsole}), one line each. */
|
||||
List<String> console() {
|
||||
return List.copyOf(console);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attaches to the page's workers from now on, each a session of its own, found by its name or
|
||||
* its script's address ({@link #workerSession}).
|
||||
*/
|
||||
void attachWorkers() throws IOException, InterruptedException {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("autoAttach", true);
|
||||
params.addProperty("waitForDebuggerOnStart", false);
|
||||
params.addProperty("flatten", true);
|
||||
call("Target.setAutoAttach", params);
|
||||
}
|
||||
|
||||
/**
|
||||
* The session of the latest attached worker still running whose name or script's address
|
||||
* contains {@code text}, or null.
|
||||
*/
|
||||
@Nullable
|
||||
String workerSession(String text) {
|
||||
String found = null;
|
||||
for (String session : workerOrder) {
|
||||
String about = workers.get(session);
|
||||
if (about != null && about.contains(text)) {
|
||||
found = session;
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/** {@link #evaluate(String)} in a worker's session, without a gesture. */
|
||||
String evaluateIn(String worker, String expression) throws IOException, InterruptedException {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("expression", expression);
|
||||
params.addProperty("returnByValue", true);
|
||||
params.addProperty("awaitPromise", true);
|
||||
JsonObject result = call("Runtime.evaluate", params, worker);
|
||||
JsonElement exception = result.get("exceptionDetails");
|
||||
if (exception != null) {
|
||||
return "exception: " + exception;
|
||||
}
|
||||
JsonElement value = result.getAsJsonObject("result").get("value");
|
||||
return value == null ? "undefined" : value.toString();
|
||||
}
|
||||
|
||||
/** A full collection in a worker, then the bytes its JavaScript heap holds. */
|
||||
double collectAndMeasure(String worker) throws IOException, InterruptedException {
|
||||
call("HeapProfiler.collectGarbage", new JsonObject(), worker);
|
||||
return call("Runtime.getHeapUsage", new JsonObject(), worker)
|
||||
.get("usedSize")
|
||||
.getAsDouble();
|
||||
}
|
||||
|
||||
/** A PNG of what the page shows. */
|
||||
byte[] screenshot() throws IOException, InterruptedException {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("format", "png");
|
||||
return Base64.getDecoder()
|
||||
.decode(call("Page.captureScreenshot", params).get("data").getAsString());
|
||||
}
|
||||
|
||||
/** The page's viewport in CSS pixels. */
|
||||
double[] viewport() throws IOException, InterruptedException {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("expression", "[innerWidth, innerHeight]");
|
||||
params.addProperty("returnByValue", true);
|
||||
JsonArray size =
|
||||
call("Runtime.evaluate", params).getAsJsonObject("result").getAsJsonArray("value");
|
||||
return new double[] {size.get(0).getAsDouble(), size.get(1).getAsDouble()};
|
||||
}
|
||||
|
||||
/** Runs {@code script} at the start of every page load from now on, and reloads the page. */
|
||||
void reloadWith(String script) throws IOException, InterruptedException {
|
||||
call("Page.enable", new JsonObject());
|
||||
JsonObject add = new JsonObject();
|
||||
add.addProperty("source", script);
|
||||
call("Page.addScriptToEvaluateOnNewDocument", add);
|
||||
call("Page.reload", new JsonObject());
|
||||
}
|
||||
|
||||
/** Reloads the page, as the player's F5 or the browser's reload button would. */
|
||||
void reload() throws IOException, InterruptedException {
|
||||
call("Page.reload", new JsonObject());
|
||||
}
|
||||
|
||||
/** Clears everything the browser keeps for {@code origin}: caches, service workers, storage. */
|
||||
void clearOrigin(String origin) throws IOException, InterruptedException {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("origin", origin);
|
||||
params.addProperty("storageTypes", "all");
|
||||
call("Storage.clearDataForOrigin", params);
|
||||
call("Network.clearBrowserCache", new JsonObject());
|
||||
}
|
||||
|
||||
/** Goes to {@code url} in the same tab. */
|
||||
void navigate(String url) throws IOException, InterruptedException {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("url", url);
|
||||
call("Page.navigate", params);
|
||||
}
|
||||
|
||||
/** The browser's product and version, {@code Chrome/151.0.7922.34} say. */
|
||||
String browserVersion() throws IOException, InterruptedException {
|
||||
return call("Browser.getVersion", new JsonObject(), null).get("product").getAsString();
|
||||
}
|
||||
|
||||
/**
|
||||
* The page's runtime metrics ({@code Performance.getMetrics}): {@code JSHeapUsedSize},
|
||||
* {@code JSHeapTotalSize}, {@code TaskDuration} and the rest, by name.
|
||||
*/
|
||||
Map<String, Double> metrics() throws IOException, InterruptedException {
|
||||
call("Performance.enable", new JsonObject());
|
||||
Map<String, Double> metrics = new LinkedHashMap<>();
|
||||
for (JsonElement metric :
|
||||
call("Performance.getMetrics", new JsonObject()).getAsJsonArray("metrics")) {
|
||||
JsonObject entry = metric.getAsJsonObject();
|
||||
metrics.put(entry.get("name").getAsString(), entry.get("value").getAsDouble());
|
||||
}
|
||||
return metrics;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts recording a trace of {@code categories} only (everything else excluded, so the trace
|
||||
* costs the page little), until {@link #stopTracing}.
|
||||
*/
|
||||
void startTracing(List<String> categories) throws IOException, InterruptedException {
|
||||
traceEvents.clear();
|
||||
JsonObject config = new JsonObject();
|
||||
JsonArray included = new JsonArray();
|
||||
categories.forEach(included::add);
|
||||
config.add("includedCategories", included);
|
||||
JsonArray excluded = new JsonArray();
|
||||
excluded.add("*");
|
||||
config.add("excludedCategories", excluded);
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("transferMode", "ReportEvents");
|
||||
params.add("traceConfig", config);
|
||||
call("Tracing.start", params);
|
||||
}
|
||||
|
||||
/** Stops the trace {@link #startTracing} started; its events. */
|
||||
List<JsonObject> stopTracing() throws IOException, InterruptedException {
|
||||
call("Tracing.end", new JsonObject());
|
||||
if (awaitEvent("Tracing.tracingComplete", 60) == null) {
|
||||
throw new IOException("The trace didn't finish");
|
||||
}
|
||||
List<JsonObject> collected = new ArrayList<>(traceEvents);
|
||||
traceEvents.clear();
|
||||
return collected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clicks at ({@code x}, {@code y}), where the page opens a file chooser, and picks
|
||||
* {@code paths} in it as the player would.
|
||||
*/
|
||||
void chooseFiles(double x, double y, List<String> paths) throws IOException, InterruptedException {
|
||||
call("Page.enable", new JsonObject());
|
||||
JsonObject intercept = new JsonObject();
|
||||
intercept.addProperty("enabled", true);
|
||||
call("Page.setInterceptFileChooserDialog", intercept);
|
||||
events.clear();
|
||||
try {
|
||||
click(x, y);
|
||||
JsonObject opened = awaitEvent("Page.fileChooserOpened", 10);
|
||||
if (opened == null) {
|
||||
throw new IOException("The page opened no file chooser");
|
||||
}
|
||||
JsonObject params = new JsonObject();
|
||||
JsonArray files = new JsonArray();
|
||||
paths.forEach(files::add);
|
||||
params.add("files", files);
|
||||
params.add("backendNodeId", opened.get("backendNodeId"));
|
||||
call("DOM.setFileInputFiles", params);
|
||||
} finally {
|
||||
intercept.addProperty("enabled", false);
|
||||
call("Page.setInterceptFileChooserDialog", intercept);
|
||||
}
|
||||
}
|
||||
|
||||
/** Lets the page download files, into {@code directory} under the names it gives them. */
|
||||
void allowDownloads(String directory) throws IOException, InterruptedException {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("behavior", "allow");
|
||||
params.addProperty("downloadPath", directory);
|
||||
params.addProperty("eventsEnabled", true);
|
||||
callBrowser("Browser.setDownloadBehavior", params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits up to {@code seconds} for a download whose name {@code name} accepts to finish.
|
||||
*
|
||||
* @return the file's name, or null if none finished in time
|
||||
*/
|
||||
@Nullable
|
||||
String awaitDownload(Predicate<String> name, long seconds) throws InterruptedException {
|
||||
long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(seconds);
|
||||
Map<String, String> names = new HashMap<>();
|
||||
while (true) {
|
||||
long left = until - System.nanoTime();
|
||||
JsonObject event = left <= 0 ? null : events.poll(left, TimeUnit.NANOSECONDS);
|
||||
if (event == null) {
|
||||
return null;
|
||||
}
|
||||
JsonObject params = event.getAsJsonObject("params");
|
||||
switch (event.get("method").getAsString()) {
|
||||
case "Browser.downloadWillBegin" ->
|
||||
names.put(
|
||||
params.get("guid").getAsString(),
|
||||
params.get("suggestedFilename").getAsString());
|
||||
case "Browser.downloadProgress" -> {
|
||||
String file = names.get(params.get("guid").getAsString());
|
||||
if (file != null && params.get("state").getAsString().equals("completed") && name.test(file)) {
|
||||
return file;
|
||||
}
|
||||
}
|
||||
default -> {
|
||||
// Not a download's.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private @Nullable JsonObject awaitEvent(String method, long seconds) throws InterruptedException {
|
||||
long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(seconds);
|
||||
while (true) {
|
||||
long left = until - System.nanoTime();
|
||||
JsonObject event = left <= 0 ? null : events.poll(left, TimeUnit.NANOSECONDS);
|
||||
if (event == null) {
|
||||
return null;
|
||||
}
|
||||
if (event.get("method").getAsString().equals(method)) {
|
||||
return event.getAsJsonObject("params");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Evaluates {@code expression} in the page (waiting for it if it's a promise); its value as JSON. */
|
||||
String evaluate(String expression) throws IOException, InterruptedException {
|
||||
return evaluate(expression, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Like {@link #evaluate(String)}, but {@code gesture} false evaluates without counting as a
|
||||
* player's click: the page's user activation, which lets it play sound, stays as it was.
|
||||
*/
|
||||
String evaluate(String expression, boolean gesture) throws IOException, InterruptedException {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("expression", expression);
|
||||
params.addProperty("returnByValue", true);
|
||||
params.addProperty("awaitPromise", true);
|
||||
// As if the player had just clicked: fullscreen, Pointer Lock and the clipboard need it.
|
||||
params.addProperty("userGesture", gesture);
|
||||
JsonObject result = call("Runtime.evaluate", params);
|
||||
JsonElement exception = result.get("exceptionDetails");
|
||||
if (exception != null) {
|
||||
return "exception: " + exception;
|
||||
}
|
||||
JsonElement value = result.getAsJsonObject("result").get("value");
|
||||
return value == null ? "undefined" : value.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Slows the page's CPU by {@code rate} (Chrome's own throttling: 4 runs it a quarter as fast),
|
||||
* to stand in for a slower machine's CPU; 1 runs it at full speed.
|
||||
*/
|
||||
void throttleCpu(double rate) throws IOException, InterruptedException {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("rate", rate);
|
||||
call("Emulation.setCPUThrottlingRate", params);
|
||||
}
|
||||
|
||||
/** A full garbage collection in the page, so a heap figure read next counts only what's live. */
|
||||
void collectGarbage() throws IOException, InterruptedException {
|
||||
call("HeapProfiler.collectGarbage", new JsonObject());
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the sampling heap profiler: from now on it keeps a sample of every allocation, with
|
||||
* the stack that made it, until the object is collected (what holds the heap, and where
|
||||
* it was allocated). WebAssembly GC objects are sampled like JavaScript ones.
|
||||
*/
|
||||
void startHeapSampling() throws IOException, InterruptedException {
|
||||
call("HeapProfiler.enable", new JsonObject());
|
||||
JsonObject params = new JsonObject();
|
||||
// Bytes between samples, on average: fine enough for the structures that matter.
|
||||
params.addProperty("samplingInterval", 16384);
|
||||
call("HeapProfiler.startSampling", params);
|
||||
}
|
||||
|
||||
/**
|
||||
* The samples {@link #startHeapSampling} has taken of objects still alive, as Chrome's
|
||||
* {@code .heapprofile} JSON (DevTools' Memory panel opens it).
|
||||
*/
|
||||
String heapSamples() throws IOException, InterruptedException {
|
||||
return call("HeapProfiler.getSamplingProfile", new JsonObject())
|
||||
.get("profile")
|
||||
.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a heap snapshot of the page to {@code file} (Chrome's {@code .heapsnapshot}, which
|
||||
* DevTools' Memory panel opens; {@link HeapSnapshotSummary} sums it by type). Streamed: a
|
||||
* gigabyte heap's snapshot is several gigabytes of JSON.
|
||||
*/
|
||||
void heapSnapshot(Path file) throws IOException, InterruptedException {
|
||||
heapSnapshot(file, session);
|
||||
}
|
||||
|
||||
/** {@link #heapSnapshot(Path)} of a worker's session (or the page's, if null). */
|
||||
void heapSnapshot(Path file, @Nullable String target) throws IOException, InterruptedException {
|
||||
call("HeapProfiler.enable", new JsonObject(), target);
|
||||
try (Writer out = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
|
||||
snapshotSink = out;
|
||||
try {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("reportProgress", false);
|
||||
call("HeapProfiler.takeHeapSnapshot", params, target, TimeUnit.MINUTES.toSeconds(15));
|
||||
} finally {
|
||||
snapshotSink = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts sampling the page's JavaScript and WebAssembly (the DevTools protocol's profiler). */
|
||||
void startProfile() throws IOException, InterruptedException {
|
||||
startProfile(session);
|
||||
}
|
||||
|
||||
/** {@link #startProfile()} in a worker's session (or the page's, if null). */
|
||||
void startProfile(@Nullable String target) throws IOException, InterruptedException {
|
||||
call("Profiler.enable", new JsonObject(), target);
|
||||
JsonObject interval = new JsonObject();
|
||||
interval.addProperty("interval", 200);
|
||||
call("Profiler.setSamplingInterval", interval, target);
|
||||
call("Profiler.start", new JsonObject(), target);
|
||||
}
|
||||
|
||||
/** Stops the profiler {@link #startProfile} started; the profile, as Chrome's {@code .cpuprofile} JSON. */
|
||||
String stopProfile() throws IOException, InterruptedException {
|
||||
return stopProfile(session);
|
||||
}
|
||||
|
||||
/** {@link #stopProfile()} in a worker's session (or the page's, if null). */
|
||||
String stopProfile(@Nullable String target) throws IOException, InterruptedException {
|
||||
return call("Profiler.stop", new JsonObject(), target).get("profile").toString();
|
||||
}
|
||||
|
||||
/** Moves the mouse to ({@code x}, {@code y}) in CSS pixels and clicks the left button there. */
|
||||
void click(double x, double y) throws IOException, InterruptedException {
|
||||
mouse("mouseMoved", x, y, 0);
|
||||
mouse("mousePressed", x, y, 1);
|
||||
mouse("mouseReleased", x, y, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Presses the left button at ({@code x1}, {@code y1}), moves to ({@code x2}, {@code y2}) in
|
||||
* {@code steps} steps {@code stepMillis} apart with it held, and lets go there: a drag.
|
||||
*/
|
||||
void drag(double x1, double y1, double x2, double y2, int steps, long stepMillis)
|
||||
throws IOException, InterruptedException {
|
||||
mouse("mouseMoved", x1, y1, 0);
|
||||
mouse("mousePressed", x1, y1, 1);
|
||||
for (int i = 1; i <= steps; i++) {
|
||||
Thread.sleep(stepMillis);
|
||||
mouse("mouseMoved", x1 + (x2 - x1) * i / steps, y1 + (y2 - y1) * i / steps, 0, 1);
|
||||
}
|
||||
Thread.sleep(stepMillis);
|
||||
mouse("mouseReleased", x2, y2, 1);
|
||||
}
|
||||
|
||||
/** Moves the mouse without clicking, as a player's hover. */
|
||||
void move(double x, double y) throws IOException, InterruptedException {
|
||||
mouse("mouseMoved", x, y, 0);
|
||||
}
|
||||
|
||||
private void mouse(String type, double x, double y, int clickCount) throws IOException, InterruptedException {
|
||||
mouse(type, x, y, clickCount, type.equals("mousePressed") ? 1 : 0);
|
||||
}
|
||||
|
||||
/** @param buttons the buttons held, as a bit mask (1 the left) */
|
||||
private void mouse(String type, double x, double y, int clickCount, int buttons)
|
||||
throws IOException, InterruptedException {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("type", type);
|
||||
params.addProperty("x", x);
|
||||
params.addProperty("y", y);
|
||||
params.addProperty("button", clickCount == 0 && buttons == 0 ? "none" : "left");
|
||||
params.addProperty("buttons", buttons);
|
||||
params.addProperty("clickCount", clickCount);
|
||||
call("Input.dispatchMouseEvent", params);
|
||||
}
|
||||
|
||||
/** Types {@code text} as key presses, one character at a time. */
|
||||
void type(String text) throws IOException, InterruptedException {
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
String character = String.valueOf(text.charAt(i));
|
||||
JsonObject down = new JsonObject();
|
||||
down.addProperty("type", "keyDown");
|
||||
down.addProperty("text", character);
|
||||
down.addProperty("key", character);
|
||||
call("Input.dispatchKeyEvent", down);
|
||||
JsonObject up = new JsonObject();
|
||||
up.addProperty("type", "keyUp");
|
||||
up.addProperty("key", character);
|
||||
call("Input.dispatchKeyEvent", up);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Presses or releases one key, by its {@code KeyboardEvent.code}, as a keyboard with a US
|
||||
* layout would send it.
|
||||
*
|
||||
* @param modifiers the modifiers held, as the protocol's bits ({@link Keys#ALT} and so on)
|
||||
*/
|
||||
void key(String code, boolean down, int modifiers) throws IOException, InterruptedException {
|
||||
Keys.Key key = Keys.of(code, (modifiers & Keys.SHIFT) != 0);
|
||||
JsonObject params = new JsonObject();
|
||||
// A shortcut types nothing, so its press is a "raw" one, without text.
|
||||
boolean types = down && !key.text().isEmpty() && (modifiers & (Keys.CTRL | Keys.ALT | Keys.META)) == 0;
|
||||
params.addProperty("type", down ? (types ? "keyDown" : "rawKeyDown") : "keyUp");
|
||||
params.addProperty("code", code);
|
||||
params.addProperty("key", key.key());
|
||||
params.addProperty("windowsVirtualKeyCode", key.virtualKeyCode());
|
||||
params.addProperty("nativeVirtualKeyCode", key.virtualKeyCode());
|
||||
params.addProperty("modifiers", modifiers);
|
||||
if (key.location() != 0) {
|
||||
params.addProperty("location", key.location());
|
||||
}
|
||||
if (types) {
|
||||
params.addProperty("text", key.text());
|
||||
params.addProperty("unmodifiedText", key.text());
|
||||
}
|
||||
call("Input.dispatchKeyEvent", params);
|
||||
}
|
||||
|
||||
/** Commits text as an input method would, with no key events. */
|
||||
void insertText(String text) throws IOException, InterruptedException {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("text", text);
|
||||
call("Input.insertText", params);
|
||||
}
|
||||
|
||||
/** Shows an input method's uncommitted composition, with the cursor at its end. */
|
||||
void compose(String text) throws IOException, InterruptedException {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("text", text);
|
||||
params.addProperty("selectionStart", text.length());
|
||||
params.addProperty("selectionEnd", text.length());
|
||||
call("Input.imeSetComposition", params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes the page's viewport {@code width} by {@code height} CSS pixels at {@code density}
|
||||
* device pixels each: a window resize, or a move to a denser display.
|
||||
*/
|
||||
void resize(int width, int height, double density) throws IOException, InterruptedException {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("width", width);
|
||||
params.addProperty("height", height);
|
||||
params.addProperty("deviceScaleFactor", density);
|
||||
params.addProperty("mobile", false);
|
||||
call("Emulation.setDeviceMetricsOverride", params);
|
||||
}
|
||||
|
||||
/** Lets the page read and write the clipboard without asking, as a player who allowed it. */
|
||||
void grantClipboard(String origin) throws IOException, InterruptedException {
|
||||
JsonObject params = new JsonObject();
|
||||
JsonArray permissions = new JsonArray();
|
||||
permissions.add("clipboardReadWrite");
|
||||
permissions.add("clipboardSanitizedWrite");
|
||||
params.add("permissions", permissions);
|
||||
params.addProperty("origin", origin);
|
||||
callBrowser("Browser.grantPermissions", params);
|
||||
}
|
||||
|
||||
/** Drags files from the machine onto the page at ({@code x}, {@code y}) and drops them. */
|
||||
void dropFiles(double x, double y, List<String> paths) throws IOException, InterruptedException {
|
||||
JsonObject data = new JsonObject();
|
||||
data.add("items", new JsonArray());
|
||||
JsonArray files = new JsonArray();
|
||||
paths.forEach(files::add);
|
||||
data.add("files", files);
|
||||
// Copy.
|
||||
data.addProperty("dragOperationsMask", 1);
|
||||
for (String type : new String[] {"dragEnter", "dragOver", "drop"}) {
|
||||
JsonObject params = new JsonObject();
|
||||
params.addProperty("type", type);
|
||||
params.addProperty("x", x);
|
||||
params.addProperty("y", y);
|
||||
params.add("data", data);
|
||||
call("Input.dispatchDragEvent", params);
|
||||
}
|
||||
}
|
||||
|
||||
private JsonObject call(String method, JsonObject params) throws IOException, InterruptedException {
|
||||
return call(method, params, session);
|
||||
}
|
||||
|
||||
/** A command for the browser itself rather than the page. */
|
||||
private JsonObject callBrowser(String method, JsonObject params) throws IOException, InterruptedException {
|
||||
return call(method, params, null);
|
||||
}
|
||||
|
||||
private JsonObject call(String method, JsonObject params, @Nullable String target)
|
||||
throws IOException, InterruptedException {
|
||||
return call(method, params, target, TIMEOUT_SECONDS);
|
||||
}
|
||||
|
||||
private JsonObject call(String method, JsonObject params, @Nullable String target, long timeoutSeconds)
|
||||
throws IOException, InterruptedException {
|
||||
int id = ids.incrementAndGet();
|
||||
JsonObject message = new JsonObject();
|
||||
message.addProperty("id", id);
|
||||
message.addProperty("method", method);
|
||||
message.add("params", params);
|
||||
if (target != null) {
|
||||
message.addProperty("sessionId", target);
|
||||
}
|
||||
CompletableFuture<JsonObject> reply = new CompletableFuture<>();
|
||||
pending.put(id, reply);
|
||||
socket.sendText(message.toString(), true).join();
|
||||
JsonObject response;
|
||||
try {
|
||||
response = reply.get(timeoutSeconds, TimeUnit.SECONDS);
|
||||
} catch (ExecutionException | TimeoutException e) {
|
||||
throw new IOException("DevTools didn't answer " + method, e);
|
||||
} finally {
|
||||
pending.remove(id);
|
||||
}
|
||||
JsonElement error = response.get("error");
|
||||
if (error != null) {
|
||||
throw new IOException(method + " failed: " + error);
|
||||
}
|
||||
return response.getAsJsonObject("result");
|
||||
}
|
||||
|
||||
private void received(String text) {
|
||||
JsonObject message = JsonParser.parseString(text).getAsJsonObject();
|
||||
JsonElement id = message.get("id");
|
||||
if (id != null) {
|
||||
CompletableFuture<JsonObject> reply = pending.get(id.getAsInt());
|
||||
if (reply != null) {
|
||||
reply.complete(message);
|
||||
}
|
||||
} else if (message.has("method")) {
|
||||
String method = message.get("method").getAsString();
|
||||
// Only what steps wait for, and the console when it's collected over the protocol.
|
||||
Writer sink = snapshotSink;
|
||||
if (method.equals("Target.attachedToTarget")) {
|
||||
JsonObject params = message.getAsJsonObject("params");
|
||||
JsonObject info = params.getAsJsonObject("targetInfo");
|
||||
String session = params.get("sessionId").getAsString();
|
||||
workers.put(
|
||||
session,
|
||||
info.get("title").getAsString() + " " + info.get("url").getAsString());
|
||||
workerOrder.add(session);
|
||||
} else if (method.equals("Target.detachedFromTarget")) {
|
||||
String session =
|
||||
message.getAsJsonObject("params").get("sessionId").getAsString();
|
||||
workers.remove(session);
|
||||
workerOrder.remove(session);
|
||||
} else if (method.equals("Runtime.consoleAPICalled")) {
|
||||
console.add(consoleLine(message.getAsJsonObject("params")));
|
||||
} else if (method.equals("HeapProfiler.addHeapSnapshotChunk") && sink != null) {
|
||||
try {
|
||||
sink.write(message.getAsJsonObject("params").get("chunk").getAsString());
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
} else if (method.equals("Tracing.dataCollected")) {
|
||||
for (JsonElement event : message.getAsJsonObject("params").getAsJsonArray("value")) {
|
||||
traceEvents.add(event.getAsJsonObject());
|
||||
}
|
||||
} else if (method.startsWith("Browser.download")
|
||||
|| method.equals("Page.fileChooserOpened")
|
||||
|| method.equals("Tracing.tracingComplete")) {
|
||||
events.add(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A console call as one line: its level, then its arguments as the console prints them. */
|
||||
private static String consoleLine(JsonObject params) {
|
||||
StringBuilder line =
|
||||
new StringBuilder("[").append(params.get("type").getAsString()).append("]");
|
||||
for (JsonElement argument : params.getAsJsonArray("args")) {
|
||||
JsonObject value = argument.getAsJsonObject();
|
||||
line.append(' ');
|
||||
if (value.has("value")) {
|
||||
JsonElement primitive = value.get("value");
|
||||
line.append(primitive.isJsonPrimitive() ? primitive.getAsString() : primitive.toString());
|
||||
} else if (value.has("description")) {
|
||||
line.append(value.get("description").getAsString());
|
||||
} else {
|
||||
line.append(value.get("type").getAsString());
|
||||
}
|
||||
}
|
||||
return line.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
String tab = openedTab;
|
||||
if (tab != null) {
|
||||
// A browser this tool didn't start keeps running: the tab goes, or every run's game
|
||||
// would stay open in it, holding its memory.
|
||||
openedTab = null;
|
||||
try {
|
||||
JsonObject target = new JsonObject();
|
||||
target.addProperty("targetId", tab);
|
||||
callBrowser("Target.closeTarget", target);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
System.err.println("Couldn't close the tab: " + e);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
socket.abort();
|
||||
}
|
||||
|
||||
/** Collects each message's fragments and hands whole messages on. */
|
||||
private static final class Listener implements WebSocket.Listener {
|
||||
private final StringBuilder partial = new StringBuilder();
|
||||
volatile @Nullable DevTools devTools;
|
||||
|
||||
@Override
|
||||
public @Nullable CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
|
||||
partial.append(data);
|
||||
if (last) {
|
||||
String text = partial.toString();
|
||||
partial.setLength(0);
|
||||
DevTools target = devTools;
|
||||
if (target != null) {
|
||||
target.received(text);
|
||||
}
|
||||
}
|
||||
webSocket.request(1);
|
||||
// Null: the data may be reused at once, which suits a copy into the builder.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+288
@@ -0,0 +1,288 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The browser build's download-size budget ({@code app-web/download-budget.properties}), and the
|
||||
* verdict on a set of measured files. Every file the check sees must be classified, so a new file
|
||||
* in the build output fails the check until someone decides whether players download it.
|
||||
*
|
||||
* <pre>
|
||||
* file.<name or glob>=download|debug|report|vendor
|
||||
* max.<raw|gzip|brotli>.<file name or "total">=<bytes>
|
||||
* </pre>
|
||||
*/
|
||||
record DownloadBudget(Map<String, Kind> classes, List<Limit> limits) {
|
||||
|
||||
/** The name a limit uses for the sum over every {@link Kind#DOWNLOAD} file. */
|
||||
static final String TOTAL = "total";
|
||||
|
||||
/** What a file is to the player. */
|
||||
enum Kind {
|
||||
/** The page fetches it at start: measured and budgeted. */
|
||||
DOWNLOAD,
|
||||
/** Only a development build has it (TeaVM's stack deobfuscator): measured, not budgeted. */
|
||||
DEBUG,
|
||||
/** A compile report; the page never fetches it. */
|
||||
REPORT,
|
||||
/** Mojang's file, which the page fetches but Incari doesn't ship: measured, not budgeted. */
|
||||
VENDOR;
|
||||
|
||||
String label() {
|
||||
return name().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
|
||||
/** How a size is measured. */
|
||||
enum Measure {
|
||||
RAW,
|
||||
GZIP,
|
||||
BROTLI;
|
||||
|
||||
String label() {
|
||||
return name().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
|
||||
/** A ceiling on one file's size, or on the {@link #TOTAL}. */
|
||||
record Limit(Measure measure, String file, long bytes) {}
|
||||
|
||||
/** One file as the check measured it; {@code brotli} is null when brotli isn't available. */
|
||||
record Measured(
|
||||
String name,
|
||||
Kind kind,
|
||||
long raw,
|
||||
long gzip,
|
||||
@Nullable Long brotli) {
|
||||
|
||||
long size(Measure measure) {
|
||||
return switch (measure) {
|
||||
case RAW -> raw;
|
||||
case GZIP -> gzip;
|
||||
case BROTLI -> brotli == null ? -1 : brotli;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/** A limit and the size it was held against ({@code -1} when it couldn't be measured). */
|
||||
record Outcome(Limit limit, long actual) {
|
||||
|
||||
boolean over() {
|
||||
return actual > limit.bytes();
|
||||
}
|
||||
}
|
||||
|
||||
/** The check's result: every limit's outcome, and problems that fail the check. */
|
||||
record Verdict(List<Outcome> outcomes, List<String> failures, List<String> notes) {
|
||||
|
||||
boolean passed() {
|
||||
return failures.isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
static DownloadBudget load(Path file) throws IOException {
|
||||
return parse(Files.readAllLines(file), file.toString());
|
||||
}
|
||||
|
||||
static DownloadBudget parse(List<String> lines, String source) {
|
||||
Map<String, Kind> classes = new LinkedHashMap<>();
|
||||
List<Limit> limits = new ArrayList<>();
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String line = lines.get(i).strip();
|
||||
if (line.isEmpty() || line.startsWith("#")) {
|
||||
continue;
|
||||
}
|
||||
String where = source + ":" + (i + 1);
|
||||
int eq = line.indexOf('=');
|
||||
if (eq < 0) {
|
||||
throw new CliException(where + ": expected key=value, found '" + line + "'");
|
||||
}
|
||||
String key = line.substring(0, eq).strip();
|
||||
String value = line.substring(eq + 1).strip();
|
||||
if (key.startsWith("file.")) {
|
||||
String name = key.substring("file.".length());
|
||||
if (classes.put(name, kind(value, where)) != null) {
|
||||
throw new CliException(where + ": " + name + " is classified twice");
|
||||
}
|
||||
} else if (key.startsWith("max.")) {
|
||||
String rest = key.substring("max.".length());
|
||||
int dot = rest.indexOf('.');
|
||||
if (dot < 0) {
|
||||
throw new CliException(where + ": expected max.<raw|gzip|brotli>.<file>, found '" + key + "'");
|
||||
}
|
||||
Measure measure = measure(rest.substring(0, dot), where);
|
||||
String name = rest.substring(dot + 1);
|
||||
limits.add(new Limit(measure, name, bytes(value, where)));
|
||||
} else {
|
||||
throw new CliException(where + ": unknown key '" + key + "' (expected file.* or max.*)");
|
||||
}
|
||||
}
|
||||
DownloadBudget budget = new DownloadBudget(Map.copyOf(classes), List.copyOf(limits));
|
||||
for (Limit limit : limits) {
|
||||
if (limit.file().equals(TOTAL)) {
|
||||
continue;
|
||||
}
|
||||
if (isGlob(limit.file())) {
|
||||
throw new CliException(source + ": a limit names one file, not a glob: " + limit.file());
|
||||
}
|
||||
if (budget.kindOf(limit.file()) != Kind.DOWNLOAD) {
|
||||
throw new CliException(source + ": " + limit.file()
|
||||
+ " has a limit but isn't classified 'download'; only what players download is budgeted");
|
||||
}
|
||||
}
|
||||
return budget;
|
||||
}
|
||||
|
||||
/**
|
||||
* The file's class: an exact entry first, else the one glob that matches ({@code *} matches
|
||||
* within one path segment). Null when nothing classifies it.
|
||||
*/
|
||||
@Nullable
|
||||
Kind kindOf(String name) {
|
||||
Kind exact = classes.get(name);
|
||||
if (exact != null) {
|
||||
return exact;
|
||||
}
|
||||
Kind found = null;
|
||||
String foundGlob = null;
|
||||
for (Map.Entry<String, Kind> entry : classes.entrySet()) {
|
||||
if (isGlob(entry.getKey()) && glob(entry.getKey()).matcher(name).matches()) {
|
||||
if (found != null && found != entry.getValue()) {
|
||||
throw new CliException(name + " matches both " + foundGlob + " and " + entry.getKey()
|
||||
+ ", which classify it differently");
|
||||
}
|
||||
found = entry.getValue();
|
||||
foundGlob = entry.getKey();
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* Holds the measured files against the limits.
|
||||
*
|
||||
* @param optional files that may not have been built yet (extra files outside the build
|
||||
* directory, such as the shader manifest): their limits are skipped with a note
|
||||
*/
|
||||
Verdict judge(List<Measured> files, Set<String> optional) {
|
||||
Map<String, Measured> byName = new LinkedHashMap<>();
|
||||
for (Measured file : files) {
|
||||
byName.put(file.name(), file);
|
||||
}
|
||||
List<Outcome> outcomes = new ArrayList<>();
|
||||
List<String> failures = new ArrayList<>();
|
||||
List<String> notes = new ArrayList<>();
|
||||
boolean brotliMissing = files.stream().anyMatch(f -> f.brotli() == null);
|
||||
for (Limit limit : limits) {
|
||||
long actual;
|
||||
if (limit.file().equals(TOTAL)) {
|
||||
actual = total(files, limit.measure());
|
||||
} else {
|
||||
Measured file = byName.get(limit.file());
|
||||
if (file == null) {
|
||||
if (optional.contains(limit.file())) {
|
||||
notes.add(limit.file() + " isn't built yet; its "
|
||||
+ limit.measure().label() + " limit wasn't checked");
|
||||
} else {
|
||||
failures.add(limit.file() + " has a limit but isn't in the build output");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
actual = file.size(limit.measure());
|
||||
}
|
||||
if (limit.measure() == Measure.BROTLI && brotliMissing) {
|
||||
notes.add("brotli isn't available, so max.brotli." + limit.file() + " wasn't checked");
|
||||
continue;
|
||||
}
|
||||
Outcome outcome = new Outcome(limit, actual);
|
||||
outcomes.add(outcome);
|
||||
if (outcome.over()) {
|
||||
failures.add("max." + limit.measure().label() + "." + limit.file() + ": " + actual
|
||||
+ " bytes, the budget is " + limit.bytes());
|
||||
}
|
||||
}
|
||||
return new Verdict(List.copyOf(outcomes), List.copyOf(failures), List.copyOf(notes));
|
||||
}
|
||||
|
||||
/** The sum over every {@link Kind#DOWNLOAD} file; {@code -1} for brotli when it wasn't measured. */
|
||||
static long total(List<Measured> files, Measure measure) {
|
||||
long sum = 0;
|
||||
for (Measured file : files) {
|
||||
if (file.kind() == Kind.DOWNLOAD) {
|
||||
long size = file.size(measure);
|
||||
if (size < 0) {
|
||||
return -1;
|
||||
}
|
||||
sum += size;
|
||||
}
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/** The limit on one file (or the total) for a measure, if the budget sets one. */
|
||||
@Nullable
|
||||
Limit limit(Measure measure, String file) {
|
||||
for (Limit limit : limits) {
|
||||
if (limit.measure() == measure && limit.file().equals(file)) {
|
||||
return limit;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean isGlob(String name) {
|
||||
return name.indexOf('*') >= 0;
|
||||
}
|
||||
|
||||
private static Pattern glob(String glob) {
|
||||
StringBuilder regex = new StringBuilder();
|
||||
for (String part : glob.split("\\*", -1)) {
|
||||
if (regex.length() > 0) {
|
||||
regex.append("[^/]*");
|
||||
}
|
||||
regex.append(Pattern.quote(part));
|
||||
}
|
||||
return Pattern.compile(regex.toString());
|
||||
}
|
||||
|
||||
private static Kind kind(String value, String where) {
|
||||
for (Kind kind : Kind.values()) {
|
||||
if (kind.label().equals(value)) {
|
||||
return kind;
|
||||
}
|
||||
}
|
||||
throw new CliException(where + ": unknown class '" + value + "' (download, debug, report or vendor)");
|
||||
}
|
||||
|
||||
private static Measure measure(String value, String where) {
|
||||
for (Measure measure : Measure.values()) {
|
||||
if (measure.label().equals(value)) {
|
||||
return measure;
|
||||
}
|
||||
}
|
||||
throw new CliException(where + ": unknown measure '" + value + "' (raw, gzip or brotli)");
|
||||
}
|
||||
|
||||
private static long bytes(String value, String where) {
|
||||
try {
|
||||
long bytes = Long.parseLong(value.replace("_", ""));
|
||||
if (bytes < 0) {
|
||||
throw new NumberFormatException();
|
||||
}
|
||||
return bytes;
|
||||
} catch (NumberFormatException e) {
|
||||
throw new CliException(where + ": expected a byte count, found '" + value + "'", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
+479
@@ -0,0 +1,479 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import incari.tools.webbuild.DownloadBudget.Kind;
|
||||
import incari.tools.webbuild.DownloadBudget.Measure;
|
||||
import incari.tools.webbuild.DownloadBudget.Measured;
|
||||
import incari.tools.webbuild.DownloadBudget.Outcome;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Measures what a player downloads: every file in the build output and each extra file
|
||||
* the page fetches, raw and compressed, held against {@code app-web/download-budget.properties}.
|
||||
* Fails when a file is over budget or isn't classified. Run by {@code ./gradlew
|
||||
* :app-web:checkDownloadSize}.
|
||||
*
|
||||
* <p>Compressed sizes are what a static host serves from files compressed once at deploy time,
|
||||
* at the formats' highest levels: gzip level 9 and brotli quality 11. Every browser takes gzip
|
||||
* and every static host can serve it, so the budget is in gzip; brotli (smaller, but not on every
|
||||
* host) is reported alongside.
|
||||
*/
|
||||
public final class DownloadSize {
|
||||
|
||||
static final int GZIP_LEVEL = 9;
|
||||
static final int BROTLI_QUALITY = 11;
|
||||
|
||||
private DownloadSize() {}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int status;
|
||||
try {
|
||||
status = run(Options.parse(List.of(args)));
|
||||
} catch (CliException e) {
|
||||
System.err.println("error: " + e.getMessage());
|
||||
status = 1;
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
status = 2;
|
||||
}
|
||||
System.exit(status);
|
||||
}
|
||||
|
||||
static int run(Options options) throws Exception {
|
||||
DownloadBudget budget = DownloadBudget.load(options.budget());
|
||||
if (!Files.isDirectory(options.buildDirectory())) {
|
||||
throw new CliException(options.buildDirectory() + " doesn't exist; build it with ./gradlew :app-web:teavm");
|
||||
}
|
||||
Map<String, Path> files = new LinkedHashMap<>();
|
||||
try (Stream<Path> walk = Files.walk(options.buildDirectory())) {
|
||||
walk.filter(Files::isRegularFile)
|
||||
.sorted()
|
||||
.forEach(file -> files.put(
|
||||
options.buildDirectory().relativize(file).toString().replace(File.separatorChar, '/'),
|
||||
file));
|
||||
}
|
||||
List<String> notes = new ArrayList<>();
|
||||
for (Map.Entry<String, Path> extra : options.extras().entrySet()) {
|
||||
if (files.containsKey(extra.getKey())) {
|
||||
throw new CliException(
|
||||
extra.getKey() + " is both in " + options.buildDirectory() + " and an extra file");
|
||||
}
|
||||
if (Files.isRegularFile(extra.getValue())) {
|
||||
files.put(extra.getKey(), extra.getValue());
|
||||
} else if (budget.limits().stream().noneMatch(l -> l.file().equals(extra.getKey()))) {
|
||||
// A missing file with a limit gets its note from the verdict.
|
||||
notes.add(extra.getKey() + " isn't built yet (no " + extra.getValue() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
List<String> unclassified = new ArrayList<>();
|
||||
Map<String, Kind> kinds = new LinkedHashMap<>();
|
||||
for (String name : files.keySet()) {
|
||||
Kind kind = budget.kindOf(name);
|
||||
if (kind == null) {
|
||||
unclassified.add(name);
|
||||
} else {
|
||||
kinds.put(name, kind);
|
||||
}
|
||||
}
|
||||
if (!unclassified.isEmpty()) {
|
||||
throw new CliException("Not classified in " + options.budget() + ": " + String.join(", ", unclassified)
|
||||
+ ". Add a file.<name>=download|debug|report|vendor line (and a limit if players download it).");
|
||||
}
|
||||
|
||||
@Nullable Path brotli = options.brotli() ? findBrotli() : null;
|
||||
if (options.brotli() && brotli == null) {
|
||||
notes.add("no brotli command (set INCARI_BROTLI or put brotli on the PATH); brotli sizes not measured");
|
||||
}
|
||||
System.out.println("==> Measuring " + files.size() + " files (gzip -" + GZIP_LEVEL
|
||||
+ (brotli != null
|
||||
? ", brotli -q " + BROTLI_QUALITY + ", which takes a minute or two on a big module"
|
||||
: "")
|
||||
+ ")");
|
||||
List<Measured> measured = measure(files, kinds, brotli);
|
||||
|
||||
DownloadBudget.Verdict verdict = budget.judge(measured, options.extras().keySet());
|
||||
System.out.print(table(measured, budget));
|
||||
for (Outcome outcome : verdict.outcomes()) {
|
||||
if (outcome.limit().measure() != Measure.GZIP) {
|
||||
System.out.printf(
|
||||
Locale.ROOT,
|
||||
" %s %s: %s of %s%n",
|
||||
outcome.limit().measure().label(),
|
||||
outcome.limit().file(),
|
||||
human(outcome.actual()),
|
||||
human(outcome.limit().bytes()));
|
||||
}
|
||||
}
|
||||
notes.addAll(verdict.notes());
|
||||
for (String note : notes) {
|
||||
System.out.println("note: " + note);
|
||||
}
|
||||
if (options.report() != null) {
|
||||
Files.createDirectories(options.report().toAbsolutePath().getParent());
|
||||
Files.writeString(options.report(), json(measured, verdict));
|
||||
System.out.println("==> Report: " + options.report());
|
||||
}
|
||||
if (!verdict.passed()) {
|
||||
for (String failure : verdict.failures()) {
|
||||
System.err.println("Download size: " + failure);
|
||||
}
|
||||
System.err.println("Make the build smaller, or raise the limit in " + options.budget()
|
||||
+ " in this pull request and say why.");
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static List<Measured> measure(Map<String, Path> files, Map<String, Kind> kinds, @Nullable Path brotli)
|
||||
throws InterruptedException, ExecutionException, IOException {
|
||||
record Pending(
|
||||
String name,
|
||||
Kind kind,
|
||||
long raw,
|
||||
Future<Long> gzip,
|
||||
@Nullable Future<Long> brotli) {}
|
||||
// Brotli's highest quality is slow (minutes on a development build's module) and
|
||||
// single-threaded, so the files are compressed side by side, the biggest first.
|
||||
List<Map.Entry<String, Path>> bySize = new ArrayList<>(files.entrySet());
|
||||
Map<String, Long> sizes = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, Path> entry : bySize) {
|
||||
sizes.put(entry.getKey(), Files.size(entry.getValue()));
|
||||
}
|
||||
bySize.sort(Comparator.comparingLong((Map.Entry<String, Path> e) -> sizes.getOrDefault(e.getKey(), 0L))
|
||||
.reversed());
|
||||
ExecutorService pool =
|
||||
Executors.newFixedThreadPool(Math.max(2, Runtime.getRuntime().availableProcessors()));
|
||||
try {
|
||||
List<Pending> pending = new ArrayList<>();
|
||||
for (Map.Entry<String, Path> entry : bySize) {
|
||||
Path file = entry.getValue();
|
||||
Future<Long> br = brotli == null ? null : pool.submit(() -> brotliSize(brotli, file));
|
||||
pending.add(new Pending(
|
||||
entry.getKey(),
|
||||
Objects.requireNonNull(kinds.get(entry.getKey())),
|
||||
sizes.getOrDefault(entry.getKey(), 0L),
|
||||
pool.submit(() -> gzipSize(file)),
|
||||
br));
|
||||
}
|
||||
List<Measured> measured = new ArrayList<>();
|
||||
for (Pending p : pending) {
|
||||
Future<Long> br = p.brotli();
|
||||
measured.add(new Measured(p.name(), p.kind(), p.raw(), p.gzip().get(), br == null ? null : br.get()));
|
||||
}
|
||||
measured.sort(Comparator.comparing(Measured::name));
|
||||
return measured;
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
/** The file's size gzipped at {@link #GZIP_LEVEL}, as {@code gzip -9} makes it. */
|
||||
static long gzipSize(Path file) throws IOException {
|
||||
CountingStream count = new CountingStream();
|
||||
try (InputStream in = Files.newInputStream(file);
|
||||
GZIPOutputStream out = new LevelGzipStream(count, GZIP_LEVEL)) {
|
||||
in.transferTo(out);
|
||||
}
|
||||
return count.bytes;
|
||||
}
|
||||
|
||||
/** The file's size compressed by the brotli command at {@link #BROTLI_QUALITY}. */
|
||||
static long brotliSize(Path brotli, Path file) throws IOException, InterruptedException {
|
||||
Process process = new ProcessBuilder(
|
||||
brotli.toString(), "-q", String.valueOf(BROTLI_QUALITY), "-c", "--", file.toString())
|
||||
.redirectError(ProcessBuilder.Redirect.INHERIT)
|
||||
.start();
|
||||
process.getOutputStream().close();
|
||||
long bytes;
|
||||
try (InputStream out = process.getInputStream()) {
|
||||
bytes = out.transferTo(OutputStream.nullOutputStream());
|
||||
}
|
||||
int exit = process.waitFor();
|
||||
if (exit != 0) {
|
||||
throw new CliException(brotli + " failed on " + file + " (exit " + exit + ")");
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* The brotli command: {@code INCARI_BROTLI}, else {@code brotli} on the PATH. Java has no
|
||||
* brotli encoder without a native library (org.brotli:dec only decodes; brotli4j bundles
|
||||
* natives), and the command is one package on every Linux distribution.
|
||||
*/
|
||||
static @Nullable Path findBrotli() {
|
||||
String configured = System.getenv("INCARI_BROTLI");
|
||||
if (configured != null && !configured.isBlank()) {
|
||||
Path path = Path.of(configured);
|
||||
if (!Files.isExecutable(path)) {
|
||||
throw new CliException("INCARI_BROTLI is " + configured + ", which isn't an executable");
|
||||
}
|
||||
return path;
|
||||
}
|
||||
String path = System.getenv("PATH");
|
||||
if (path == null) {
|
||||
return null;
|
||||
}
|
||||
for (String dir : path.split(File.pathSeparator, -1)) {
|
||||
if (dir.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
Path candidate = Path.of(dir, "brotli");
|
||||
if (Files.isExecutable(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The console table: every file with its class and sizes, and the gzip budget. */
|
||||
static String table(List<Measured> files, DownloadBudget budget) {
|
||||
List<String[]> rows = new ArrayList<>();
|
||||
rows.add(new String[] {"file", "class", "raw", "gzip", "brotli", "budget (gzip)", "headroom"});
|
||||
List<Measured> sorted = new ArrayList<>(files);
|
||||
sorted.sort(Comparator.comparing(Measured::kind).thenComparing(Measured::name));
|
||||
for (Measured file : sorted) {
|
||||
rows.add(row(file.name(), file.kind().label(), file.raw(), file.gzip(), file.size(Measure.BROTLI), budget));
|
||||
}
|
||||
rows.add(row(
|
||||
"total downloaded",
|
||||
"download",
|
||||
DownloadBudget.total(files, Measure.RAW),
|
||||
DownloadBudget.total(files, Measure.GZIP),
|
||||
DownloadBudget.total(files, Measure.BROTLI),
|
||||
budget,
|
||||
DownloadBudget.TOTAL));
|
||||
int[] widths = new int[rows.get(0).length];
|
||||
for (String[] row : rows) {
|
||||
for (int i = 0; i < row.length; i++) {
|
||||
widths[i] = Math.max(widths[i], row[i].length());
|
||||
}
|
||||
}
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (int r = 0; r < rows.size(); r++) {
|
||||
if (r == rows.size() - 1) {
|
||||
out.append(" ")
|
||||
.append("-".repeat(sum(widths) + 2 * (widths.length - 1)))
|
||||
.append('\n');
|
||||
}
|
||||
String[] row = rows.get(r);
|
||||
out.append(" ");
|
||||
for (int i = 0; i < row.length; i++) {
|
||||
// Names and classes left-aligned, numbers right-aligned.
|
||||
String cell = i < 2 ? pad(row[i], widths[i], false) : pad(row[i], widths[i], true);
|
||||
out.append(cell);
|
||||
if (i < row.length - 1) {
|
||||
out.append(" ");
|
||||
}
|
||||
}
|
||||
out.append('\n');
|
||||
}
|
||||
return out.toString().replaceAll(" +\n", "\n");
|
||||
}
|
||||
|
||||
private static String[] row(String name, String kind, long raw, long gzip, long brotli, DownloadBudget budget) {
|
||||
return row(name, kind, raw, gzip, brotli, budget, name);
|
||||
}
|
||||
|
||||
private static String[] row(
|
||||
String name, String kind, long raw, long gzip, long brotli, DownloadBudget budget, String limitName) {
|
||||
DownloadBudget.Limit limit = budget.limit(Measure.GZIP, limitName);
|
||||
String budgetCell = limit == null ? "" : human(limit.bytes());
|
||||
String headroom = "";
|
||||
if (limit != null) {
|
||||
long left = limit.bytes() - gzip;
|
||||
headroom = (left < 0 ? "OVER " : "")
|
||||
+ human(Math.abs(left))
|
||||
+ String.format(Locale.ROOT, " (%.0f%%)", 100.0 * left / Math.max(1, limit.bytes()));
|
||||
}
|
||||
return new String[] {
|
||||
name, kind, human(raw), human(gzip), brotli < 0 ? "n/a" : human(brotli), budgetCell, headroom
|
||||
};
|
||||
}
|
||||
|
||||
private static int sum(int[] values) {
|
||||
int sum = 0;
|
||||
for (int value : values) {
|
||||
sum += value;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
private static String pad(String text, int width, boolean right) {
|
||||
String padding = " ".repeat(width - text.length());
|
||||
return right ? padding + text : text + padding;
|
||||
}
|
||||
|
||||
/** Decimal units, as download sizes are quoted. */
|
||||
static String human(long bytes) {
|
||||
if (bytes < 0) {
|
||||
return "n/a";
|
||||
}
|
||||
if (bytes < 1000) {
|
||||
return bytes + " B";
|
||||
}
|
||||
if (bytes < 1_000_000) {
|
||||
return String.format(Locale.ROOT, "%.1f kB", bytes / 1e3);
|
||||
}
|
||||
return String.format(Locale.ROOT, "%.2f MB", bytes / 1e6);
|
||||
}
|
||||
|
||||
/** The machine-readable report, for charting the sizes over time. */
|
||||
static String json(List<Measured> files, DownloadBudget.Verdict verdict) {
|
||||
StringBuilder out = new StringBuilder();
|
||||
out.append("{\n \"gzipLevel\": ")
|
||||
.append(GZIP_LEVEL)
|
||||
.append(",\n \"brotliQuality\": ")
|
||||
.append(BROTLI_QUALITY);
|
||||
out.append(",\n \"files\": [");
|
||||
for (int i = 0; i < files.size(); i++) {
|
||||
Measured file = files.get(i);
|
||||
out.append(i == 0 ? "\n" : ",\n")
|
||||
.append(" {\"name\": ")
|
||||
.append(quote(file.name()))
|
||||
.append(", \"class\": ")
|
||||
.append(quote(file.kind().label()))
|
||||
.append(", \"raw\": ")
|
||||
.append(file.raw())
|
||||
.append(", \"gzip\": ")
|
||||
.append(file.gzip())
|
||||
.append(", \"brotli\": ")
|
||||
.append(file.brotli() == null ? "null" : String.valueOf(file.brotli()))
|
||||
.append('}');
|
||||
}
|
||||
out.append("\n ],\n \"totalDownloaded\": {\"raw\": ")
|
||||
.append(DownloadBudget.total(files, Measure.RAW))
|
||||
.append(", \"gzip\": ")
|
||||
.append(DownloadBudget.total(files, Measure.GZIP))
|
||||
.append(", \"brotli\": ");
|
||||
long brotli = DownloadBudget.total(files, Measure.BROTLI);
|
||||
out.append(brotli < 0 ? "null" : String.valueOf(brotli)).append("},\n \"limits\": [");
|
||||
List<Outcome> outcomes = verdict.outcomes();
|
||||
for (int i = 0; i < outcomes.size(); i++) {
|
||||
Outcome outcome = outcomes.get(i);
|
||||
out.append(i == 0 ? "\n" : ",\n")
|
||||
.append(" {\"measure\": ")
|
||||
.append(quote(outcome.limit().measure().label()))
|
||||
.append(", \"file\": ")
|
||||
.append(quote(outcome.limit().file()))
|
||||
.append(", \"limit\": ")
|
||||
.append(outcome.limit().bytes())
|
||||
.append(", \"actual\": ")
|
||||
.append(outcome.actual())
|
||||
.append('}');
|
||||
}
|
||||
out.append("\n ],\n \"passed\": ").append(verdict.passed()).append("\n}\n");
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static String quote(String text) {
|
||||
StringBuilder out = new StringBuilder("\"");
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
switch (c) {
|
||||
case '"' -> out.append("\\\"");
|
||||
case '\\' -> out.append("\\\\");
|
||||
default -> {
|
||||
if (c < 0x20) {
|
||||
out.append(String.format(Locale.ROOT, "\\u%04x", (int) c));
|
||||
} else {
|
||||
out.append(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return out.append('"').toString();
|
||||
}
|
||||
|
||||
/** Counts what's written, so nothing compressed is kept in memory. */
|
||||
private static final class CountingStream extends OutputStream {
|
||||
long bytes;
|
||||
|
||||
@Override
|
||||
public void write(int b) {
|
||||
bytes++;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(byte[] b, int off, int len) {
|
||||
bytes += len;
|
||||
}
|
||||
}
|
||||
|
||||
/** {@link GZIPOutputStream} at a chosen level; it only exposes its deflater to subclasses. */
|
||||
private static final class LevelGzipStream extends GZIPOutputStream {
|
||||
LevelGzipStream(OutputStream out, int level) throws IOException {
|
||||
super(out, 1 << 16);
|
||||
def.setLevel(level);
|
||||
}
|
||||
}
|
||||
|
||||
/** Command-line options; Gradle passes them. */
|
||||
record Options(
|
||||
Path budget,
|
||||
Path buildDirectory,
|
||||
Map<String, Path> extras,
|
||||
@Nullable Path report,
|
||||
boolean brotli) {
|
||||
|
||||
static Options parse(List<String> args) {
|
||||
Path budget = null;
|
||||
Path directory = null;
|
||||
Map<String, Path> extras = new LinkedHashMap<>();
|
||||
Path report = null;
|
||||
boolean brotli = true;
|
||||
for (int i = 0; i < args.size(); i++) {
|
||||
String arg = args.get(i);
|
||||
switch (arg) {
|
||||
case "--budget" -> budget = Path.of(value(args, ++i, arg));
|
||||
case "--dir" -> directory = Path.of(value(args, ++i, arg));
|
||||
case "--file" -> {
|
||||
String spec = value(args, ++i, arg);
|
||||
int eq = spec.indexOf('=');
|
||||
if (eq <= 0 || eq == spec.length() - 1) {
|
||||
throw new CliException("--file takes <name>=<path>, found '" + spec + "'");
|
||||
}
|
||||
if (extras.put(spec.substring(0, eq), Path.of(spec.substring(eq + 1))) != null) {
|
||||
throw new CliException("--file " + spec.substring(0, eq) + " given twice");
|
||||
}
|
||||
}
|
||||
case "--report" -> report = Path.of(value(args, ++i, arg));
|
||||
case "--no-brotli" -> brotli = false;
|
||||
default -> throw new CliException("Unknown option '" + arg + "'");
|
||||
}
|
||||
}
|
||||
if (budget == null || directory == null) {
|
||||
throw new CliException("Usage: DownloadSize --budget <properties> --dir <build output>"
|
||||
+ " [--file <name>=<path>]... [--report <json>] [--no-brotli]");
|
||||
}
|
||||
return new Options(budget, directory, Collections.unmodifiableMap(extras), report, brotli);
|
||||
}
|
||||
|
||||
private static String value(List<String> args, int index, String option) {
|
||||
if (index >= args.size()) {
|
||||
throw new CliException(option + " needs a value");
|
||||
}
|
||||
return args.get(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A scenario's figures, from the page's frame table: one row per frame of the columns
|
||||
* platform-web's {@code Dom.installFrameMonitor} documents. Pure logic, tested on its own.
|
||||
*
|
||||
* <p>Frame rates come from the time between frames ending, which includes the wait for the display
|
||||
* (what a player sees). The 1% low is the frame rate over the slowest 1% of frames (at least one):
|
||||
* their mean frame time, so a handful of stutters shows even when the 99th percentile frame is
|
||||
* smooth. Percentiles are nearest rank. Means skip frames that didn't measure a column.
|
||||
*/
|
||||
final class FrameStats {
|
||||
|
||||
/** The frame table's columns, as the page writes them. */
|
||||
static final int COLUMNS = 16;
|
||||
|
||||
static final int INTERVAL = 1;
|
||||
static final int TICK = 4;
|
||||
static final int EXTRACT = 5;
|
||||
static final int RENDER = 6;
|
||||
static final int GPU = 7;
|
||||
static final int DRAWS = 8;
|
||||
static final int TERRAIN_DRAWS = 9;
|
||||
static final int TERRAIN_SECTIONS = 10;
|
||||
static final int MESH_QUEUE = 11;
|
||||
static final int HEAP = 12;
|
||||
static final int NATIVE = 13;
|
||||
static final int POOL = 14;
|
||||
static final int POOL_LATE = 15;
|
||||
|
||||
private final List<double[]> rows = new ArrayList<>();
|
||||
private GcStats gc = GcStats.NONE;
|
||||
|
||||
/** Adds a measured stretch's frames: {@code table} flat, {@link #COLUMNS} numbers a frame. */
|
||||
void add(double[] table) {
|
||||
if (table.length % COLUMNS != 0) {
|
||||
throw new IllegalArgumentException("A frame table of " + table.length + " numbers");
|
||||
}
|
||||
for (int i = 0; i < table.length; i += COLUMNS) {
|
||||
rows.add(Arrays.copyOfRange(table, i, i + COLUMNS));
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds a measured stretch's garbage collections. */
|
||||
void add(GcStats stretch) {
|
||||
gc = gc.plus(stretch);
|
||||
}
|
||||
|
||||
int frames() {
|
||||
return rows.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* The figures, by name, in a fixed order: the names the report and the baseline use. A figure
|
||||
* nothing measured is {@code NaN}.
|
||||
*/
|
||||
Map<String, Double> figures() {
|
||||
double[] intervals = column(INTERVAL);
|
||||
Arrays.sort(intervals);
|
||||
Map<String, Double> out = new LinkedHashMap<>();
|
||||
out.put("frames", (double) rows.size());
|
||||
out.put("fpsMean", intervals.length == 0 ? Double.NaN : intervals.length * 1000 / sum(intervals));
|
||||
out.put("fpsMedian", 1000 / percentile(intervals, 50));
|
||||
out.put("fpsLow1", 1000 / slowestMean(intervals, 1));
|
||||
out.put("frameP99Millis", percentile(intervals, 99));
|
||||
out.put("tickMillis", mean(column(TICK)));
|
||||
out.put("extractMillis", mean(column(EXTRACT)));
|
||||
out.put("renderMillis", mean(column(RENDER)));
|
||||
out.put("gpuMillis", mean(column(GPU)));
|
||||
out.put("drawCalls", mean(counts(DRAWS)));
|
||||
out.put("terrainDrawCalls", mean(counts(TERRAIN_DRAWS)));
|
||||
out.put("terrainSections", mean(counts(TERRAIN_SECTIONS)));
|
||||
out.put("poolMillis", mean(column(POOL)));
|
||||
out.put("meshQueueMean", mean(counts(MESH_QUEUE)));
|
||||
out.put("meshQueueMax", max(counts(MESH_QUEUE)));
|
||||
out.put("heapMaxMB", max(column(HEAP)));
|
||||
out.put("nativeMaxMB", max(column(NATIVE)));
|
||||
slowestFrames(out);
|
||||
out.put("gcCount", gc.count() < 0 ? Double.NaN : gc.count());
|
||||
out.put("gcTotalMillis", gc.count() < 0 ? Double.NaN : gc.totalMillis());
|
||||
out.put("gcMaxPauseMillis", gc.count() < 0 ? Double.NaN : gc.maxMillis());
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the slowest 1% of frames (by the time since the previous one) were made of, for telling
|
||||
* stutter apart: the interval, how much of it the frame itself took (from its animation frame;
|
||||
* the rest is the page's work between frames and waiting for the display), and the game's tick,
|
||||
* extract and render inside it, and the background pool's work between it and the previous one
|
||||
* (and how far past its slot that ran). Recorded, never gated (no baseline rules name them).
|
||||
*/
|
||||
private void slowestFrames(Map<String, Double> out) {
|
||||
List<double[]> measured = new ArrayList<>(
|
||||
rows.stream().filter(row -> !Double.isNaN(row[INTERVAL])).toList());
|
||||
measured.sort((a, b) -> Double.compare(b[INTERVAL], a[INTERVAL]));
|
||||
int count = Math.max(1, measured.size() / 100);
|
||||
List<double[]> slowest = measured.subList(0, Math.min(count, measured.size()));
|
||||
out.put("slow1.intervalMillis", meanOf(slowest, INTERVAL));
|
||||
out.put("slow1.frameMillis", meanOf(slowest, 2));
|
||||
out.put("slow1.tickMillis", meanOf(slowest, TICK));
|
||||
out.put("slow1.extractMillis", meanOf(slowest, EXTRACT));
|
||||
out.put("slow1.renderMillis", meanOf(slowest, RENDER));
|
||||
out.put("slow1.poolMillis", meanOf(slowest, POOL));
|
||||
out.put("slow1.poolLateMillis", meanOf(slowest, POOL_LATE));
|
||||
}
|
||||
|
||||
private static double meanOf(List<double[]> rows, int index) {
|
||||
return mean(rows.stream()
|
||||
.mapToDouble(row -> row[index])
|
||||
.filter(v -> !Double.isNaN(v))
|
||||
.toArray());
|
||||
}
|
||||
|
||||
/** A column's measured values (not {@code NaN}). */
|
||||
private double[] column(int index) {
|
||||
return rows.stream()
|
||||
.mapToDouble(row -> row[index])
|
||||
.filter(v -> !Double.isNaN(v))
|
||||
.toArray();
|
||||
}
|
||||
|
||||
/** A count column's values: -1 means the backend didn't count. */
|
||||
private double[] counts(int index) {
|
||||
return Arrays.stream(column(index)).filter(v -> v >= 0).toArray();
|
||||
}
|
||||
|
||||
/** Nearest rank; {@code sorted} ascending. NaN if empty. */
|
||||
static double percentile(double[] sorted, double percentile) {
|
||||
if (sorted.length == 0) {
|
||||
return Double.NaN;
|
||||
}
|
||||
int rank = (int) Math.ceil(percentile / 100 * sorted.length);
|
||||
return sorted[Math.max(0, Math.min(rank - 1, sorted.length - 1))];
|
||||
}
|
||||
|
||||
/** The mean of the slowest {@code percent}% of {@code sorted} (ascending), at least one; NaN if empty. */
|
||||
static double slowestMean(double[] sorted, double percent) {
|
||||
if (sorted.length == 0) {
|
||||
return Double.NaN;
|
||||
}
|
||||
int count = Math.max(1, (int) Math.floor(sorted.length * percent / 100));
|
||||
double total = 0;
|
||||
for (int i = sorted.length - count; i < sorted.length; i++) {
|
||||
total += sorted[i];
|
||||
}
|
||||
return total / count;
|
||||
}
|
||||
|
||||
private static double sum(double[] values) {
|
||||
double total = 0;
|
||||
for (double value : values) {
|
||||
total += value;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
private static double mean(double[] values) {
|
||||
return values.length == 0 ? Double.NaN : sum(values) / values.length;
|
||||
}
|
||||
|
||||
private static double max(double[] values) {
|
||||
return values.length == 0 ? Double.NaN : Arrays.stream(values).max().orElseThrow();
|
||||
}
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import incari.tools.build.CliException;
|
||||
import incari.tools.build.Downloader;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.PrintWriter;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* A vanilla dedicated server for the screenshot-diff harness, with a fresh world every run: the
|
||||
* server jar from Mojang's version metadata (checked against its SHA-1, kept in {@code work/cache},
|
||||
* never in the repository), the committed server settings plus this run's ports and a random RCON
|
||||
* password, and an RCON connection to set each scene up.
|
||||
*/
|
||||
final class GameServer implements AutoCloseable {
|
||||
|
||||
private final Process process;
|
||||
private final Rcon rcon;
|
||||
private final PrintWriter log;
|
||||
|
||||
private GameServer(Process process, Rcon rcon, PrintWriter log) {
|
||||
this.process = process;
|
||||
this.rcon = rcon;
|
||||
this.log = log;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the server in {@code directory}, deleting any world there first.
|
||||
*
|
||||
* @param versionJson the game version's metadata, which names the server jar
|
||||
* @param properties the committed {@code server.properties}; ports and RCON are added here
|
||||
*/
|
||||
static GameServer start(Path versionJson, Path cache, Path directory, Path properties, int port, int rconPort)
|
||||
throws IOException, InterruptedException {
|
||||
Path jar = serverJar(versionJson, cache);
|
||||
Chromium.deleteRecursively(directory.resolve("world"));
|
||||
Files.createDirectories(directory);
|
||||
String password = HexFormat.of().formatHex(new SecureRandom().generateSeed(12));
|
||||
List<String> settings = new ArrayList<>(Files.readAllLines(properties));
|
||||
settings.add("server-ip=127.0.0.1");
|
||||
settings.add("server-port=" + port);
|
||||
settings.add("enable-rcon=true");
|
||||
settings.add("rcon.port=" + rconPort);
|
||||
settings.add("rcon.password=" + password);
|
||||
Files.write(directory.resolve("server.properties"), settings);
|
||||
Files.writeString(directory.resolve("eula.txt"), "eula=true\n");
|
||||
|
||||
String java = ProcessHandle.current().info().command().orElse("java");
|
||||
Process process = new ProcessBuilder(
|
||||
java, "-Xmx2G", "-jar", jar.toAbsolutePath().toString(), "nogui")
|
||||
.directory(directory.toFile())
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
PrintWriter log = new PrintWriter(Files.newBufferedWriter(directory.resolve("server-output.txt")), true);
|
||||
CompletableFuture<Void> ready = new CompletableFuture<>();
|
||||
Thread.ofPlatform().daemon().start(() -> {
|
||||
try (BufferedReader out =
|
||||
new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = out.readLine()) != null) {
|
||||
log.println(line);
|
||||
if (line.contains("Done (")) {
|
||||
ready.complete(null);
|
||||
}
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// The server stopped; ready fails below if it never started.
|
||||
} finally {
|
||||
ready.completeExceptionally(new IOException("The server stopped; see its output in " + directory));
|
||||
}
|
||||
});
|
||||
System.out.println("==> Starting a vanilla server on port " + port + " (a fresh world takes a minute)");
|
||||
try {
|
||||
ready.get(5, TimeUnit.MINUTES);
|
||||
// The remote console starts listening just after the server says it's done.
|
||||
long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
|
||||
while (true) {
|
||||
try {
|
||||
return new GameServer(process, Rcon.connect("127.0.0.1:" + rconPort, password), log);
|
||||
} catch (IOException e) {
|
||||
if (System.nanoTime() > until) {
|
||||
throw e;
|
||||
}
|
||||
Thread.sleep(250);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
process.destroyForcibly();
|
||||
log.close();
|
||||
throw new IOException("The game server didn't start: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs a server command; its reply. */
|
||||
String command(String command) throws IOException {
|
||||
return rcon.command(command).strip();
|
||||
}
|
||||
|
||||
/** Waits until {@code player} is online; false if they aren't within {@code seconds}. */
|
||||
boolean awaitPlayer(String player, int seconds) throws IOException, InterruptedException {
|
||||
long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(seconds);
|
||||
while (System.nanoTime() < until) {
|
||||
if (command("list").contains(player)) {
|
||||
return true;
|
||||
}
|
||||
Thread.sleep(500);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static Path serverJar(Path versionJson, Path cache) throws IOException, InterruptedException {
|
||||
JsonObject server = JsonParser.parseString(Files.readString(versionJson))
|
||||
.getAsJsonObject()
|
||||
.getAsJsonObject("downloads")
|
||||
.getAsJsonObject("server");
|
||||
if (server == null) {
|
||||
throw new CliException(versionJson + " names no server jar");
|
||||
}
|
||||
Path jar = cache.resolve("server.jar");
|
||||
new Downloader()
|
||||
.fetch(
|
||||
URI.create(server.get("url").getAsString()),
|
||||
server.get("sha1").getAsString(),
|
||||
jar);
|
||||
return jar;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
try {
|
||||
rcon.command("stop");
|
||||
} catch (IOException e) {
|
||||
// Stopping anyway.
|
||||
}
|
||||
rcon.close();
|
||||
try {
|
||||
if (!process.waitFor(30, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
process.destroyForcibly();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
log.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/**
|
||||
* Garbage collection pauses on the page's main thread, from a DevTools trace of the
|
||||
* {@code v8} category: its {@code MinorGC} and {@code MajorGC} events, each a pause of the thread
|
||||
* that runs the game. WebAssembly GC objects are collected by the same collector as JavaScript's.
|
||||
*
|
||||
* @param count pauses; -1 where nothing traced them (a browser without DevTools)
|
||||
*/
|
||||
record GcStats(int count, double totalMillis, double maxMillis) {
|
||||
|
||||
/** Nothing traced. */
|
||||
static final GcStats NONE = new GcStats(-1, 0, 0);
|
||||
|
||||
/** The trace category the pauses are in. */
|
||||
static final String CATEGORY = "v8";
|
||||
|
||||
/**
|
||||
* V8's detailed collector events (--gc-trace, ADR 0027): a collection's phases, and the
|
||||
* incremental marking steps and finalization that come before a major one.
|
||||
*/
|
||||
static final String DETAIL_CATEGORY = "disabled-by-default-v8.gc";
|
||||
|
||||
static GcStats of(List<JsonObject> events) {
|
||||
Set<String> mainThreads = mainThreads(events);
|
||||
int count = 0;
|
||||
double total = 0;
|
||||
double max = 0;
|
||||
for (JsonObject event : events) {
|
||||
String name = string(event, "name");
|
||||
if (!("MinorGC".equals(name) || "MajorGC".equals(name)) || !"X".equals(string(event, "ph"))) {
|
||||
continue;
|
||||
}
|
||||
if (!mainThreads.isEmpty() && !mainThreads.contains(string(event, "pid") + "/" + string(event, "tid"))) {
|
||||
continue;
|
||||
}
|
||||
JsonElement duration = event.get("dur");
|
||||
double millis = duration == null ? 0 : duration.getAsDouble() / 1000;
|
||||
count++;
|
||||
total += millis;
|
||||
max = Math.max(max, millis);
|
||||
}
|
||||
return new GcStats(count, total, max);
|
||||
}
|
||||
|
||||
/** The renderer's main thread, by the trace's metadata; empty (every thread) if it has none. */
|
||||
private static Set<String> mainThreads(List<JsonObject> events) {
|
||||
Set<String> mainThreads = new HashSet<>();
|
||||
for (JsonObject event : events) {
|
||||
if ("thread_name".equals(string(event, "name")) && "M".equals(string(event, "ph"))) {
|
||||
JsonElement args = event.get("args");
|
||||
if (args != null
|
||||
&& args.isJsonObject()
|
||||
&& "CrRendererMain".equals(string(args.getAsJsonObject(), "name"))) {
|
||||
mainThreads.add(string(event, "pid") + "/" + string(event, "tid"));
|
||||
}
|
||||
}
|
||||
}
|
||||
return mainThreads;
|
||||
}
|
||||
|
||||
/**
|
||||
* The main thread's collector events in time order (--gc-trace): each one's start from the
|
||||
* first event, its name, its length and its arguments; then each name's count, total and
|
||||
* longest. A long pause shows what ran in it and what came before it.
|
||||
*/
|
||||
static String timeline(List<JsonObject> events) {
|
||||
Set<String> mainThreads = mainThreads(events);
|
||||
List<JsonObject> gc = new ArrayList<>();
|
||||
for (JsonObject event : events) {
|
||||
String name = string(event, "name");
|
||||
boolean collector = name.contains("GC")
|
||||
|| name.contains("Marking")
|
||||
|| name.contains("Scavenge")
|
||||
|| name.contains("Sweep")
|
||||
|| name.contains("MC_")
|
||||
|| name.contains("MinorMS");
|
||||
if (!collector || !"X".equals(string(event, "ph"))) {
|
||||
continue;
|
||||
}
|
||||
if (!mainThreads.isEmpty() && !mainThreads.contains(string(event, "pid") + "/" + string(event, "tid"))) {
|
||||
continue;
|
||||
}
|
||||
gc.add(event);
|
||||
}
|
||||
gc.sort(Comparator.comparingDouble(event -> event.get("ts").getAsDouble()));
|
||||
StringBuilder out = new StringBuilder();
|
||||
double start = gc.isEmpty() ? 0 : gc.get(0).get("ts").getAsDouble();
|
||||
Map<String, double[]> byName = new TreeMap<>();
|
||||
for (JsonObject event : gc) {
|
||||
double at = (event.get("ts").getAsDouble() - start) / 1000;
|
||||
JsonElement duration = event.get("dur");
|
||||
double millis = duration == null ? 0 : duration.getAsDouble() / 1000;
|
||||
String name = string(event, "name");
|
||||
JsonElement args = event.get("args");
|
||||
out.append(String.format(
|
||||
Locale.ROOT,
|
||||
"%10.1f ms %8.2f ms %s %s%n",
|
||||
at,
|
||||
millis,
|
||||
name,
|
||||
args == null || args.toString().equals("{}") ? "" : args.toString()));
|
||||
double[] summary = byName.computeIfAbsent(name, n -> new double[3]);
|
||||
summary[0]++;
|
||||
summary[1] += millis;
|
||||
summary[2] = Math.max(summary[2], millis);
|
||||
}
|
||||
out.append(String.format(Locale.ROOT, "%n%-48s %6s %10s %10s%n", "event", "count", "total ms", "max ms"));
|
||||
for (Map.Entry<String, double[]> entry : byName.entrySet()) {
|
||||
double[] summary = entry.getValue();
|
||||
out.append(String.format(
|
||||
Locale.ROOT,
|
||||
"%-48s %6d %10.2f %10.2f%n",
|
||||
entry.getKey(),
|
||||
(int) summary[0],
|
||||
summary[1],
|
||||
summary[2]));
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
/** Both stretches together. */
|
||||
GcStats plus(GcStats other) {
|
||||
if (count < 0) {
|
||||
return other;
|
||||
}
|
||||
if (other.count < 0) {
|
||||
return this;
|
||||
}
|
||||
return new GcStats(count + other.count, totalMillis + other.totalMillis, Math.max(maxMillis, other.maxMillis));
|
||||
}
|
||||
|
||||
private static String string(JsonObject object, String key) {
|
||||
JsonElement value = object.get(key);
|
||||
return value == null || value.isJsonNull() ? "" : value.getAsString();
|
||||
}
|
||||
}
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* What a heap snapshot holds, summed by type: each node's self size and count, grouped by its
|
||||
* kind and name. WebAssembly GC objects are named by their type in the module's name section, so a
|
||||
* development build's snapshot sums the game's heap by Java class. Streams the file: a gigabyte
|
||||
* heap's snapshot is several gigabytes of JSON, and only the node table and the strings are read.
|
||||
*
|
||||
* <p>{@code java HeapSnapshotSummary.java <file.heapsnapshot> [rows]}, or through the benchmark's
|
||||
* {@code --heap-snapshot}, which writes the summary beside the snapshot.
|
||||
*/
|
||||
final class HeapSnapshotSummary {
|
||||
|
||||
private HeapSnapshotSummary() {}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
System.out.print(summarize(Path.of(args[0]), args.length > 1 ? Integer.parseInt(args[1]) : 80));
|
||||
}
|
||||
|
||||
/** The summary as text: a total, then the {@code rows} largest groups. */
|
||||
static String summarize(Path file, int rows) throws IOException {
|
||||
try (Reader reader = new BufferedReader(Files.newBufferedReader(file, StandardCharsets.UTF_8), 1 << 20)) {
|
||||
return summarize(new Scanner(reader), rows);
|
||||
}
|
||||
}
|
||||
|
||||
private static String summarize(Scanner in, int rows) throws IOException {
|
||||
// {"snapshot":{"meta":{...},"node_count":N,...},"nodes":[...],"edges":[...],...,"strings":[...]}
|
||||
String head = in.textUntil("\"nodes\":[", true);
|
||||
JsonObject snapshot = JsonParser.parseString(head.substring(0, head.lastIndexOf(',')) + "}")
|
||||
.getAsJsonObject()
|
||||
.getAsJsonObject("snapshot");
|
||||
JsonObject meta = snapshot.getAsJsonObject("meta");
|
||||
List<String> fields = strings(meta.getAsJsonArray("node_fields"));
|
||||
List<String> kinds = strings(meta.getAsJsonArray("node_types").get(0).getAsJsonArray());
|
||||
int width = fields.size();
|
||||
int typeField = fields.indexOf("type");
|
||||
int nameField = fields.indexOf("name");
|
||||
int sizeField = fields.indexOf("self_size");
|
||||
int count = snapshot.get("node_count").getAsInt();
|
||||
int[] types = new int[count];
|
||||
int[] names = new int[count];
|
||||
long[] sizes = new long[count];
|
||||
for (int node = 0; node < count; node++) {
|
||||
for (int field = 0; field < width; field++) {
|
||||
long value = in.number();
|
||||
if (field == typeField) {
|
||||
types[node] = (int) value;
|
||||
} else if (field == nameField) {
|
||||
names[node] = (int) value;
|
||||
} else if (field == sizeField) {
|
||||
sizes[node] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
in.textUntil("\"strings\":[", false);
|
||||
List<String> strings = new ArrayList<>();
|
||||
String string;
|
||||
while ((string = in.string()) != null) {
|
||||
strings.add(string);
|
||||
}
|
||||
|
||||
final class Group {
|
||||
final String kind;
|
||||
final String name;
|
||||
long bytes;
|
||||
long objects;
|
||||
|
||||
Group(String kind, String name) {
|
||||
this.kind = kind;
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
Map<String, Group> groups = new HashMap<>();
|
||||
long total = 0;
|
||||
for (int node = 0; node < count; node++) {
|
||||
String kind = kinds.get(types[node]);
|
||||
String name = names[node] < strings.size() ? strings.get(names[node]) : "?";
|
||||
if (name.length() > 120) {
|
||||
name = name.substring(0, 120) + "...";
|
||||
}
|
||||
// Strings and numbers are many and each named by its contents: one group per kind.
|
||||
if (kind.contains("string") || kind.equals("number") || kind.equals("code")) {
|
||||
name = "";
|
||||
}
|
||||
String key = kind + '\u0000' + name;
|
||||
String groupName = name;
|
||||
Group group = groups.computeIfAbsent(key, k -> new Group(kind, groupName));
|
||||
group.bytes += sizes[node];
|
||||
group.objects++;
|
||||
total += sizes[node];
|
||||
}
|
||||
List<Group> sorted = new ArrayList<>(groups.values());
|
||||
sorted.sort((a, b) -> Long.compare(b.bytes, a.bytes));
|
||||
StringBuilder out = new StringBuilder();
|
||||
out.append(String.format(Locale.ROOT, "%,d nodes, %.1f MB of self sizes%n%n", count, total / 1048576.0));
|
||||
out.append(String.format(Locale.ROOT, "%10s %12s %-12s %s%n", "MB", "objects", "kind", "name"));
|
||||
for (Group group : sorted.subList(0, Math.min(rows, sorted.size()))) {
|
||||
out.append(String.format(
|
||||
Locale.ROOT,
|
||||
"%10.2f %,12d %-12s %s%n",
|
||||
group.bytes / 1048576.0,
|
||||
group.objects,
|
||||
group.kind,
|
||||
group.name));
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static List<String> strings(JsonArray array) {
|
||||
List<String> out = new ArrayList<>(array.size());
|
||||
array.forEach(element -> out.add(element.getAsString()));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Just enough JSON reading for the snapshot's layout, one character at a time. */
|
||||
private static final class Scanner {
|
||||
private final Reader reader;
|
||||
private int peeked = -2;
|
||||
|
||||
Scanner(Reader reader) {
|
||||
this.reader = reader;
|
||||
}
|
||||
|
||||
private int read() throws IOException {
|
||||
if (peeked != -2) {
|
||||
int c = peeked;
|
||||
peeked = -2;
|
||||
return c;
|
||||
}
|
||||
return reader.read();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads up to and including {@code marker}; what was read if {@code keep}, else "" (the
|
||||
* edges skipped on the way are gigabytes). The markers are JSON keys, which numbers and the
|
||||
* snapshot's head can't contain partly, so a mismatch simply starts the match again.
|
||||
*/
|
||||
String textUntil(String marker, boolean keep) throws IOException {
|
||||
StringBuilder text = new StringBuilder();
|
||||
int matched = 0;
|
||||
int c;
|
||||
while ((c = read()) != -1) {
|
||||
if (keep) {
|
||||
text.append((char) c);
|
||||
}
|
||||
if (c == marker.charAt(matched)) {
|
||||
matched++;
|
||||
if (matched == marker.length()) {
|
||||
return text.toString();
|
||||
}
|
||||
} else {
|
||||
matched = c == marker.charAt(0) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
throw new IOException("Not a heap snapshot: no " + marker);
|
||||
}
|
||||
|
||||
/** The next number in an array of numbers. */
|
||||
long number() throws IOException {
|
||||
int c = read();
|
||||
while (c == ',' || c == ' ' || c == '\n' || c == '\r') {
|
||||
c = read();
|
||||
}
|
||||
boolean negative = c == '-';
|
||||
if (negative) {
|
||||
c = read();
|
||||
}
|
||||
if (c < '0' || c > '9') {
|
||||
throw new IOException("Expected a number, found '" + (char) c + "'");
|
||||
}
|
||||
long value = 0;
|
||||
while (c >= '0' && c <= '9') {
|
||||
value = value * 10 + (c - '0');
|
||||
c = read();
|
||||
}
|
||||
peeked = c;
|
||||
return negative ? -value : value;
|
||||
}
|
||||
|
||||
/** The next string in an array of strings; null at the array's end. */
|
||||
@org.jspecify.annotations.Nullable
|
||||
String string() throws IOException {
|
||||
int c = read();
|
||||
while (c == ',' || c == ' ' || c == '\n' || c == '\r') {
|
||||
c = read();
|
||||
}
|
||||
if (c == ']' || c == -1) {
|
||||
return null;
|
||||
}
|
||||
if (c != '"') {
|
||||
throw new IOException("Expected a string, found '" + (char) c + "'");
|
||||
}
|
||||
StringBuilder out = new StringBuilder();
|
||||
while ((c = read()) != '"') {
|
||||
if (c == -1) {
|
||||
throw new IOException("A string runs past the end");
|
||||
}
|
||||
if (c == '\\') {
|
||||
int escaped = read();
|
||||
switch (escaped) {
|
||||
case 'n' -> out.append('\n');
|
||||
case 't' -> out.append('\t');
|
||||
case 'r' -> out.append('\r');
|
||||
case 'b' -> out.append('\b');
|
||||
case 'f' -> out.append('\f');
|
||||
case 'u' -> {
|
||||
char[] hex = new char[4];
|
||||
for (int i = 0; i < 4; i++) {
|
||||
hex[i] = (char) read();
|
||||
}
|
||||
out.append((char) Integer.parseInt(new String(hex), 16));
|
||||
}
|
||||
default -> out.append((char) escaped);
|
||||
}
|
||||
} else {
|
||||
out.append((char) c);
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
|
||||
/**
|
||||
* How alike two renders of the same scene look: the structural similarity index (SSIM, Wang et
|
||||
* al. 2004) over each color channel, averaged. SSIM compares local brightness, contrast and
|
||||
* structure in an 11-pixel Gaussian window rather than pixel values, so a texel's worth of
|
||||
* rasterization or filtering difference between two GPUs costs little, while missing or wrong
|
||||
* geometry, a wrong color, a missing effect or a shifted image costs a lot. 1 means identical.
|
||||
*
|
||||
* <p>Also reports the share of pixels whose largest channel differs by more than {@link #CHANGED}
|
||||
* (a plain measure to read beside SSIM) and draws a heat map of where the images differ.
|
||||
*/
|
||||
final class ImageDiff {
|
||||
|
||||
/** A channel difference, out of 255, above which a pixel counts as changed. */
|
||||
static final int CHANGED = 32;
|
||||
|
||||
private static final int RADIUS = 5;
|
||||
private static final double SIGMA = 1.5;
|
||||
private static final double C1 = Math.pow(0.01 * 255, 2);
|
||||
private static final double C2 = Math.pow(0.03 * 255, 2);
|
||||
private static final float[] KERNEL = kernel();
|
||||
|
||||
/**
|
||||
* @param ssim the mean SSIM of the red, green and blue channels
|
||||
* @param changed the share of pixels with a channel more than {@link #CHANGED} apart
|
||||
* @param heatmap the expected image in gray, with dissimilar regions in red
|
||||
*/
|
||||
record Result(double ssim, double changed, BufferedImage heatmap) {}
|
||||
|
||||
private ImageDiff() {}
|
||||
|
||||
static Result compare(BufferedImage expected, BufferedImage actual) {
|
||||
int width = expected.getWidth();
|
||||
int height = expected.getHeight();
|
||||
if (actual.getWidth() != width || actual.getHeight() != height) {
|
||||
throw new IllegalArgumentException("The images differ in size: " + width + "x" + height + " and "
|
||||
+ actual.getWidth() + "x" + actual.getHeight());
|
||||
}
|
||||
int[] a = expected.getRGB(0, 0, width, height, null, 0, width);
|
||||
int[] b = actual.getRGB(0, 0, width, height, null, 0, width);
|
||||
float[] dissimilarity = new float[width * height];
|
||||
double total = 0;
|
||||
for (int shift = 16; shift >= 0; shift -= 8) {
|
||||
total += channel(a, b, shift, width, height, dissimilarity);
|
||||
}
|
||||
int changed = 0;
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
int largest = 0;
|
||||
for (int shift = 16; shift >= 0; shift -= 8) {
|
||||
largest = Math.max(largest, Math.abs(((a[i] >> shift) & 0xFF) - ((b[i] >> shift) & 0xFF)));
|
||||
}
|
||||
if (largest > CHANGED) {
|
||||
changed++;
|
||||
}
|
||||
}
|
||||
return new Result(total / 3, changed / (double) a.length, heatmap(a, dissimilarity, width, height));
|
||||
}
|
||||
|
||||
/** The mean SSIM of one channel; adds each pixel's dissimilarity (1 - SSIM, over three) to {@code into}. */
|
||||
private static double channel(int[] a, int[] b, int shift, int width, int height, float[] into) {
|
||||
int size = width * height;
|
||||
float[] x = new float[size];
|
||||
float[] y = new float[size];
|
||||
float[] xx = new float[size];
|
||||
float[] yy = new float[size];
|
||||
float[] xy = new float[size];
|
||||
for (int i = 0; i < size; i++) {
|
||||
float p = (a[i] >> shift) & 0xFF;
|
||||
float q = (b[i] >> shift) & 0xFF;
|
||||
x[i] = p;
|
||||
y[i] = q;
|
||||
xx[i] = p * p;
|
||||
yy[i] = q * q;
|
||||
xy[i] = p * q;
|
||||
}
|
||||
float[] scratch = new float[size];
|
||||
for (float[] plane : new float[][] {x, y, xx, yy, xy}) {
|
||||
blur(plane, scratch, width, height);
|
||||
}
|
||||
double sum = 0;
|
||||
for (int i = 0; i < size; i++) {
|
||||
double mx = x[i];
|
||||
double my = y[i];
|
||||
double vx = xx[i] - mx * mx;
|
||||
double vy = yy[i] - my * my;
|
||||
double cov = xy[i] - mx * my;
|
||||
double ssim = ((2 * mx * my + C1) * (2 * cov + C2)) / ((mx * mx + my * my + C1) * (vx + vy + C2));
|
||||
sum += ssim;
|
||||
into[i] += (float) ((1 - ssim) / 3);
|
||||
}
|
||||
return sum / size;
|
||||
}
|
||||
|
||||
/** A separable Gaussian blur in place; edges repeat their outermost pixel. */
|
||||
private static void blur(float[] plane, float[] scratch, int width, int height) {
|
||||
for (int y = 0; y < height; y++) {
|
||||
int row = y * width;
|
||||
for (int x = 0; x < width; x++) {
|
||||
float value = 0;
|
||||
for (int k = -RADIUS; k <= RADIUS; k++) {
|
||||
int sx = Math.clamp(x + k, 0, width - 1);
|
||||
value += KERNEL[k + RADIUS] * plane[row + sx];
|
||||
}
|
||||
scratch[row + x] = value;
|
||||
}
|
||||
}
|
||||
for (int y = 0; y < height; y++) {
|
||||
for (int x = 0; x < width; x++) {
|
||||
float value = 0;
|
||||
for (int k = -RADIUS; k <= RADIUS; k++) {
|
||||
int sy = Math.clamp(y + k, 0, height - 1);
|
||||
value += KERNEL[k + RADIUS] * scratch[sy * width + x];
|
||||
}
|
||||
plane[y * width + x] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static float[] kernel() {
|
||||
float[] kernel = new float[2 * RADIUS + 1];
|
||||
float sum = 0;
|
||||
for (int k = -RADIUS; k <= RADIUS; k++) {
|
||||
kernel[k + RADIUS] = (float) Math.exp(-(k * k) / (2 * SIGMA * SIGMA));
|
||||
sum += kernel[k + RADIUS];
|
||||
}
|
||||
for (int i = 0; i < kernel.length; i++) {
|
||||
kernel[i] /= sum;
|
||||
}
|
||||
return kernel;
|
||||
}
|
||||
|
||||
private static BufferedImage heatmap(int[] expected, float[] dissimilarity, int width, int height) {
|
||||
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
for (int i = 0; i < expected.length; i++) {
|
||||
int rgb = expected[i];
|
||||
int gray = (((rgb >> 16) & 0xFF) + ((rgb >> 8) & 0xFF) + (rgb & 0xFF)) / 6;
|
||||
float heat = Math.clamp(dissimilarity[i] * 2, 0, 1);
|
||||
int red = Math.round(gray + (255 - gray) * heat);
|
||||
int other = Math.round(gray * (1 - heat));
|
||||
image.setRGB(i % width, i / width, (red << 16) | (other << 8) | other);
|
||||
}
|
||||
return image;
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import org.teavm.ast.InvocationExpr;
|
||||
import org.teavm.backend.wasm.BaseWasmFunctionRepository;
|
||||
import org.teavm.backend.wasm.TeaVMWasmGCHost;
|
||||
import org.teavm.backend.wasm.intrinsics.WasmGCInlineIntrinsic;
|
||||
import org.teavm.backend.wasm.intrinsics.WasmGCInlineIntrinsicContext;
|
||||
import org.teavm.backend.wasm.model.WasmLocal;
|
||||
import org.teavm.backend.wasm.model.WasmType;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmConditional;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmExternConversionType;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmInstructionBuilder;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmIntBinaryOperation;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmIntType;
|
||||
import org.teavm.model.MethodReference;
|
||||
import org.teavm.model.ValueType;
|
||||
import org.teavm.vm.spi.TeaVMHost;
|
||||
import org.teavm.vm.spi.TeaVMPlugin;
|
||||
|
||||
/**
|
||||
* An {@code int} handed to JavaScript without leaving the module. TeaVM's JSO passes each number
|
||||
* argument of a JavaScript call through its own import ({@code teavmJso.wrapInt}, which returns
|
||||
* its argument), so {@code gl.bindTexture(target, texture)} was two calls out of the module, and a
|
||||
* frame in a world made about 3,800 of them. Each costs a crossing, and in the Fast build a dearer
|
||||
* one: calls out of a JSPI stack switch stacks (docs/webgpu-backend.md, Measured).
|
||||
*
|
||||
* <p>An {@code i31ref} turned into an {@code externref} reaches JavaScript as a Number with the same
|
||||
* value (WebAssembly's JS API), so an {@code int} in [-2^30, 2^30) goes as one; WebGL's enums,
|
||||
* sizes and offsets all fit. Others still take the import.
|
||||
*
|
||||
* <p>Registered in {@code META-INF/services}, as {@link MathIntrinsics} is. The system property
|
||||
* {@code incari.jsoIntrinsics=false} ({@code -Pteavm.noJsoIntrinsics}) leaves it out, to compare.
|
||||
*/
|
||||
public final class JsoIntrinsics implements TeaVMPlugin {
|
||||
|
||||
private static final MethodReference WRAP_INT = new MethodReference(
|
||||
"org.teavm.jso.impl.JS", "wrap", ValueType.INTEGER, ValueType.object("org.teavm.jso.JSObject"));
|
||||
|
||||
@Override
|
||||
public void install(TeaVMHost host) {
|
||||
TeaVMWasmGCHost wasm = host.getExtension(TeaVMWasmGCHost.class);
|
||||
if (wasm == null || !Boolean.parseBoolean(System.getProperty("incari.jsoIntrinsics", "true"))) {
|
||||
return;
|
||||
}
|
||||
wasm.contributeToCodeGen((context, registry) ->
|
||||
registry.inlineIntrinsics().registerIntrinsic(WRAP_INT, new WrapInt(context.functions())));
|
||||
}
|
||||
|
||||
/** {@code JS.wrap(int)}: an i31 when the value fits, else the import. */
|
||||
private static final class WrapInt implements WasmGCInlineIntrinsic {
|
||||
|
||||
private final BaseWasmFunctionRepository functions;
|
||||
|
||||
WrapInt(BaseWasmFunctionRepository functions) {
|
||||
this.functions = functions;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void apply(
|
||||
InvocationExpr invocation, WasmGCInlineIntrinsicContext context, WasmInstructionBuilder builder) {
|
||||
WasmLocal value = context.tempVars().acquire(WasmType.INT32);
|
||||
context.generate(builder, invocation.getArguments().get(0));
|
||||
builder.teeLocal(value);
|
||||
// value + 2^30 < 2^31 (unsigned) exactly when value is in [-2^30, 2^30).
|
||||
builder.i32Const(1 << 30);
|
||||
builder.intBinary(WasmIntType.INT32, WasmIntBinaryOperation.ADD);
|
||||
builder.i32Const(Integer.MIN_VALUE);
|
||||
builder.intBinary(WasmIntType.INT32, WasmIntBinaryOperation.LT_UNSIGNED);
|
||||
WasmConditional fits = builder.conditional(WasmType.EXTERN);
|
||||
new WasmInstructionBuilder(fits.getThenBlock())
|
||||
.getLocal(value)
|
||||
.i31Ref()
|
||||
.externConvert(WasmExternConversionType.ANY_TO_EXTERN);
|
||||
new WasmInstructionBuilder(fits.getElseBlock()).getLocal(value).call(functions.forStaticMethod(WRAP_INT));
|
||||
context.tempVars().release(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import org.teavm.model.ClassHolder;
|
||||
import org.teavm.model.ClassHolderTransformer;
|
||||
import org.teavm.model.ClassHolderTransformerContext;
|
||||
import org.teavm.model.MethodDescriptor;
|
||||
import org.teavm.model.MethodHolder;
|
||||
import org.teavm.model.ValueType;
|
||||
import org.teavm.model.emit.ProgramEmitter;
|
||||
|
||||
/**
|
||||
* Routes TeaVM's fibers onto JSPI (WebAssembly JavaScript Promise Integration) for a {@code --jspi}
|
||||
* build: {@code Fiber.suspend} and {@code Fiber.start} call {@code Fiber.Jspi} (tools/teavm-patches)
|
||||
* instead. With the system property {@code incari.jspi} also set, TeaVM compiles no method as a
|
||||
* coroutine; every suspension goes through {@code Fiber.suspend}, which then hands the engine a
|
||||
* promise and keeps the whole stack. Only this routing makes {@code Fiber.Jspi} reachable, so other
|
||||
* builds don't import its JavaScript functions.
|
||||
*/
|
||||
public final class JspiTransformer implements ClassHolderTransformer {
|
||||
|
||||
/** The system property TeaVM's patched {@code AsyncMethodFinder} reads. */
|
||||
static final String PROPERTY = "incari.jspi";
|
||||
|
||||
private static final String FIBER = "org.teavm.runtime.Fiber";
|
||||
private static final String JSPI = FIBER + "$Jspi";
|
||||
private static final ValueType ASYNC_CALL = ValueType.object(FIBER + "$AsyncCall");
|
||||
private static final ValueType RUNNER = ValueType.object(FIBER + "$FiberRunner");
|
||||
private static final ValueType OBJECT = ValueType.object("java.lang.Object");
|
||||
|
||||
@Override
|
||||
public void transformClass(ClassHolder cls, ClassHolderTransformerContext context) {
|
||||
if (!cls.getName().equals(FIBER)) {
|
||||
return;
|
||||
}
|
||||
MethodHolder suspend = method(cls, new MethodDescriptor("suspend", ASYNC_CALL, OBJECT));
|
||||
ProgramEmitter pe = ProgramEmitter.create(suspend, context.getHierarchy());
|
||||
pe.invoke(JSPI, "suspend", OBJECT, pe.var(1, ASYNC_CALL)).returnValue();
|
||||
|
||||
MethodHolder start = method(cls, new MethodDescriptor("start", RUNNER, ValueType.BOOLEAN, ValueType.VOID));
|
||||
pe = ProgramEmitter.create(start, context.getHierarchy());
|
||||
pe.invoke(JSPI, "start", pe.var(1, RUNNER), pe.var(2, ValueType.BOOLEAN));
|
||||
pe.exit();
|
||||
}
|
||||
|
||||
private static MethodHolder method(ClassHolder cls, MethodDescriptor descriptor) {
|
||||
MethodHolder method = cls.getMethod(descriptor);
|
||||
if (method == null) {
|
||||
throw new IllegalStateException("TeaVM's Fiber has no " + descriptor + " to route onto JSPI");
|
||||
}
|
||||
return method;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Keys as the DevTools protocol sends them: what a US keyboard reports for each
|
||||
* {@code KeyboardEvent.code} (its {@code key}, Windows virtual key code and typed text), and key
|
||||
* chords written the way browser check steps name them ({@code F3+KeyB}, {@code Control+KeyV}).
|
||||
*/
|
||||
final class Keys {
|
||||
|
||||
/** The protocol's modifier bits. */
|
||||
static final int ALT = 1;
|
||||
|
||||
static final int CTRL = 2;
|
||||
static final int META = 4;
|
||||
static final int SHIFT = 8;
|
||||
|
||||
private Keys() {}
|
||||
|
||||
/**
|
||||
* One key.
|
||||
*
|
||||
* @param location 1 for the left of a pair (Shift, Control...), 2 for the right, else 0
|
||||
*/
|
||||
record Key(String key, int virtualKeyCode, String text, int location) {}
|
||||
|
||||
/** The key at {@code code}, with {@code shift} held. */
|
||||
static Key of(String code, boolean shift) {
|
||||
if (code.length() == 4 && code.startsWith("Key") && Character.isUpperCase(code.charAt(3))) {
|
||||
char letter = code.charAt(3);
|
||||
String typed = String.valueOf(shift ? letter : Character.toLowerCase(letter));
|
||||
return new Key(typed, letter, typed, 0);
|
||||
}
|
||||
if (code.length() == 6 && code.startsWith("Digit") && Character.isDigit(code.charAt(5))) {
|
||||
char digit = code.charAt(5);
|
||||
String typed = shift ? String.valueOf(")!@#$%^&*(".charAt(digit - '0')) : String.valueOf(digit);
|
||||
return new Key(typed, digit, typed, 0);
|
||||
}
|
||||
if (code.matches("F([1-9]|1[0-9]|2[0-4])")) {
|
||||
return new Key(code, 111 + Integer.parseInt(code.substring(1)), "", 0);
|
||||
}
|
||||
return switch (code) {
|
||||
case "Enter" -> new Key("Enter", 13, "\r", 0);
|
||||
case "Escape" -> new Key("Escape", 27, "", 0);
|
||||
case "Backspace" -> new Key("Backspace", 8, "", 0);
|
||||
case "Tab" -> new Key("Tab", 9, "", 0);
|
||||
case "Space" -> new Key(" ", 32, " ", 0);
|
||||
case "Delete" -> new Key("Delete", 46, "", 0);
|
||||
case "Insert" -> new Key("Insert", 45, "", 0);
|
||||
case "Home" -> new Key("Home", 36, "", 0);
|
||||
case "End" -> new Key("End", 35, "", 0);
|
||||
case "PageUp" -> new Key("PageUp", 33, "", 0);
|
||||
case "PageDown" -> new Key("PageDown", 34, "", 0);
|
||||
case "ArrowLeft" -> new Key("ArrowLeft", 37, "", 0);
|
||||
case "ArrowUp" -> new Key("ArrowUp", 38, "", 0);
|
||||
case "ArrowRight" -> new Key("ArrowRight", 39, "", 0);
|
||||
case "ArrowDown" -> new Key("ArrowDown", 40, "", 0);
|
||||
case "ShiftLeft" -> new Key("Shift", 16, "", 1);
|
||||
case "ShiftRight" -> new Key("Shift", 16, "", 2);
|
||||
case "ControlLeft" -> new Key("Control", 17, "", 1);
|
||||
case "ControlRight" -> new Key("Control", 17, "", 2);
|
||||
case "AltLeft" -> new Key("Alt", 18, "", 1);
|
||||
case "AltRight" -> new Key("Alt", 18, "", 2);
|
||||
case "MetaLeft" -> new Key("Meta", 91, "", 1);
|
||||
case "MetaRight" -> new Key("Meta", 92, "", 2);
|
||||
case "Minus" -> symbol(shift, "-", "_", 189);
|
||||
case "Equal" -> symbol(shift, "=", "+", 187);
|
||||
case "BracketLeft" -> symbol(shift, "[", "{", 219);
|
||||
case "BracketRight" -> symbol(shift, "]", "}", 221);
|
||||
case "Backslash" -> symbol(shift, "\\", "|", 220);
|
||||
case "Semicolon" -> symbol(shift, ";", ":", 186);
|
||||
case "Quote" -> symbol(shift, "'", "\"", 222);
|
||||
case "Backquote" -> symbol(shift, "`", "~", 192);
|
||||
case "Comma" -> symbol(shift, ",", "<", 188);
|
||||
case "Period" -> symbol(shift, ".", ">", 190);
|
||||
case "Slash" -> symbol(shift, "/", "?", 191);
|
||||
default -> throw new CliException("No key '" + code + "' (use KeyboardEvent.code names, like KeyA or F3)");
|
||||
};
|
||||
}
|
||||
|
||||
private static Key symbol(boolean shift, String plain, String shifted, int virtualKeyCode) {
|
||||
String typed = shift ? shifted : plain;
|
||||
return new Key(typed, virtualKeyCode, typed, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* The codes of a chord, in the order they're pressed: {@code "Control+Shift+KeyT"}. Modifiers
|
||||
* may be written short ({@code Control}, {@code Ctrl}, {@code Shift}, {@code Alt}, {@code Meta})
|
||||
* for their left key.
|
||||
*/
|
||||
static List<String> chord(String chord) {
|
||||
List<String> codes = new ArrayList<>();
|
||||
for (String part : chord.split("\\+", -1)) {
|
||||
String code =
|
||||
switch (part.toLowerCase(Locale.ROOT)) {
|
||||
case "control", "ctrl" -> "ControlLeft";
|
||||
case "shift" -> "ShiftLeft";
|
||||
case "alt" -> "AltLeft";
|
||||
case "meta", "command" -> "MetaLeft";
|
||||
default -> part;
|
||||
};
|
||||
of(code, false);
|
||||
codes.add(code);
|
||||
}
|
||||
return codes;
|
||||
}
|
||||
|
||||
/**
|
||||
* The key at {@code code} as SDL3 reports it on a US layout, for the desktop game's scene
|
||||
* agent: its scancode (the USB HID usage id) and its keycode (the character it types, or the
|
||||
* scancode with SDL's scancode-mask bit for keys that type nothing).
|
||||
*/
|
||||
record SdlKey(int scancode, int keycode) {}
|
||||
|
||||
private static final int SDLK_SCANCODE_MASK = 1 << 30;
|
||||
|
||||
static SdlKey sdl(String code) {
|
||||
if (code.length() == 4 && code.startsWith("Key") && Character.isUpperCase(code.charAt(3))) {
|
||||
char letter = code.charAt(3);
|
||||
return new SdlKey(4 + letter - 'A', Character.toLowerCase(letter));
|
||||
}
|
||||
if (code.length() == 6 && code.startsWith("Digit") && Character.isDigit(code.charAt(5))) {
|
||||
char digit = code.charAt(5);
|
||||
return new SdlKey(digit == '0' ? 39 : 30 + digit - '1', digit);
|
||||
}
|
||||
if (code.matches("F([1-9]|1[0-2])")) {
|
||||
int scancode = 57 + Integer.parseInt(code.substring(1));
|
||||
return new SdlKey(scancode, scancode | SDLK_SCANCODE_MASK);
|
||||
}
|
||||
return switch (code) {
|
||||
case "Enter" -> new SdlKey(40, '\r');
|
||||
case "Escape" -> new SdlKey(41, 0x1B);
|
||||
case "Backspace" -> new SdlKey(42, 8);
|
||||
case "Tab" -> new SdlKey(43, '\t');
|
||||
case "Space" -> new SdlKey(44, ' ');
|
||||
case "ArrowRight" -> new SdlKey(79, 79 | SDLK_SCANCODE_MASK);
|
||||
case "ArrowLeft" -> new SdlKey(80, 80 | SDLK_SCANCODE_MASK);
|
||||
case "ArrowDown" -> new SdlKey(81, 81 | SDLK_SCANCODE_MASK);
|
||||
case "ArrowUp" -> new SdlKey(82, 82 | SDLK_SCANCODE_MASK);
|
||||
case "ControlLeft" -> new SdlKey(224, 224 | SDLK_SCANCODE_MASK);
|
||||
case "ShiftLeft" -> new SdlKey(225, 225 | SDLK_SCANCODE_MASK);
|
||||
case "AltLeft" -> new SdlKey(226, 226 | SDLK_SCANCODE_MASK);
|
||||
default -> throw new CliException("The desktop scene agent has no key '" + code + "'");
|
||||
};
|
||||
}
|
||||
|
||||
/** The modifier bit a key sets while it's held, or 0. */
|
||||
static int modifierBit(String code) {
|
||||
return switch (code) {
|
||||
case "ShiftLeft", "ShiftRight" -> SHIFT;
|
||||
case "ControlLeft", "ControlRight" -> CTRL;
|
||||
case "AltLeft", "AltRight" -> ALT;
|
||||
case "MetaLeft", "MetaRight" -> META;
|
||||
default -> 0;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,463 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.build.BuildConfig;
|
||||
import incari.tools.build.CliException;
|
||||
import incari.tools.build.GameFiles;
|
||||
import incari.tools.build.Log;
|
||||
import incari.tools.build.Workspace;
|
||||
import incari.tools.survey.HostJdkHidingLoader;
|
||||
import incari.tools.survey.Origins;
|
||||
import incari.tools.survey.SurveyRules;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.diagnostics.Problem;
|
||||
import org.teavm.diagnostics.ProblemSeverity;
|
||||
import org.teavm.tooling.TeaVMProblemRenderer;
|
||||
import org.teavm.tooling.TeaVMTargetType;
|
||||
import org.teavm.tooling.TeaVMTool;
|
||||
import org.teavm.vm.TeaVMOptimizationLevel;
|
||||
|
||||
/**
|
||||
* Compiles the browser build with TeaVM: the game as {@code :client} built it, the web
|
||||
* platform, and the Mojang libraries {@code tools/survey/rules.txt} keeps, from one entry point.
|
||||
* Output (never committed or published) goes to {@code app-web/build/teavm}.
|
||||
*
|
||||
* <p>Run by {@code ./gradlew :app-web:teavm}, which passes the Incari class directories.
|
||||
*/
|
||||
public final class Main {
|
||||
|
||||
/** The game targets Java 25, and TeaVM compiles missing JDK classes from the running JDK. */
|
||||
static final int REQUIRED_JDK = 25;
|
||||
|
||||
private Main() {}
|
||||
|
||||
/** TeaVM's optimizer and code generator recurse deeply on the game's largest methods. */
|
||||
private static final long COMPILER_STACK_BYTES = 1L << 30;
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
int[] status = {2};
|
||||
Thread compiler = new Thread(
|
||||
null,
|
||||
() -> {
|
||||
try {
|
||||
status[0] = run(Options.parse(List.of(args)));
|
||||
} catch (CliException e) {
|
||||
System.err.println("error: " + e.getMessage());
|
||||
status[0] = 1;
|
||||
} catch (Exception | StackOverflowError e) {
|
||||
e.printStackTrace();
|
||||
status[0] = 2;
|
||||
}
|
||||
},
|
||||
"teavm",
|
||||
COMPILER_STACK_BYTES);
|
||||
compiler.start();
|
||||
compiler.join();
|
||||
System.exit(status[0]);
|
||||
}
|
||||
|
||||
static int run(Options options) throws Exception {
|
||||
int jdk = Runtime.version().feature();
|
||||
if (jdk != REQUIRED_JDK) {
|
||||
throw new CliException("The web build must run on JDK " + REQUIRED_JDK + " (this is JDK " + jdk + ")");
|
||||
}
|
||||
checkTeaVmPatches();
|
||||
Workspace ws = Workspace.discover(Path.of(System.getProperty("incari.cwd", ".")));
|
||||
BuildConfig config = BuildConfig.load(ws.repoRoot());
|
||||
GameFiles game = GameFiles.load(ws, config);
|
||||
SurveyRules rules = SurveyRules.load(ws.repoRoot().resolve("tools/survey/rules.txt"));
|
||||
|
||||
// The game's classes come from :client's output, not Mojang's jar; the jar map only tells
|
||||
// Origins which classes are the game's, so the JDK hiding never hides one of them.
|
||||
Map<Path, String> jars = new LinkedHashMap<>();
|
||||
jars.put(game.clientJar(), Origins.MINECRAFT);
|
||||
List<Path> classpath = new ArrayList<>(options.appClasspath());
|
||||
for (GameFiles.LibraryJar library : game.libraries()) {
|
||||
String name = library.library().name();
|
||||
if (rules.library(name).action() == SurveyRules.LibraryAction.KEEP) {
|
||||
jars.put(library.jar(), name.split(":", -1)[1]);
|
||||
classpath.add(library.jar());
|
||||
}
|
||||
}
|
||||
Origins origins = new Origins(jars, Main.class.getClassLoader());
|
||||
|
||||
Files.createDirectories(options.outputDirectory());
|
||||
URL[] urls = new URL[classpath.size()];
|
||||
for (int i = 0; i < urls.length; i++) {
|
||||
urls[i] = classpath.get(i).toUri().toURL();
|
||||
}
|
||||
Log.step("Compiling " + options.mainClass() + " with TeaVM (" + options.target() + ")");
|
||||
ClassLoader parent = new HostJdkHidingLoader(Main.class.getClassLoader(), origins);
|
||||
try (URLClassLoader loader = new URLClassLoader(urls, parent)) {
|
||||
TeaVMTool tool = new TeaVMTool();
|
||||
tool.setTargetType(options.target());
|
||||
tool.setMainClass(options.mainClass());
|
||||
tool.setEntryPointName("main");
|
||||
tool.setClassLoader(loader);
|
||||
tool.setTargetDirectory(options.outputDirectory().toFile());
|
||||
// TeaVM adds no extension to the JavaScript build's file; the page loads incari.js.
|
||||
tool.setTargetFileName(
|
||||
options.target() == TeaVMTargetType.JAVASCRIPT ? options.name() + ".js" : options.name());
|
||||
tool.setOptimizationLevel(
|
||||
options.release() ? TeaVMOptimizationLevel.ADVANCED : TeaVMOptimizationLevel.SIMPLE);
|
||||
// `--names` keeps a release build's Java names (the module's name section), so CPU
|
||||
// profiles of it read as the game's methods; the code is the release build's.
|
||||
tool.setObfuscated(options.release() && !options.names());
|
||||
tool.setIncremental(false);
|
||||
// Null checks that throw NullPointerException instead of trapping, in every build: the
|
||||
// game catches it (its system report at start, the section dispatcher's runTask), and a
|
||||
// release build without them crashed at start with "dereferencing a null pointer".
|
||||
tool.setStrict(true);
|
||||
if (!options.release()) {
|
||||
// Development builds: Java names in stack traces, with the deobfuscator the page loads.
|
||||
tool.setDebugInformationGenerated(true);
|
||||
}
|
||||
tool.setFastDependencyAnalysis(options.fastAnalysis());
|
||||
tool.setLog(new ConsoleLog(options.verbose()));
|
||||
Removals removals = new Removals(rules, origins);
|
||||
RemovalTransformer.removals = removals;
|
||||
MonitorElision.classes = classlibClasses(options.appClasspath());
|
||||
TypeCaptures.captures = TypeCaptures.scan(classpath);
|
||||
Log.step("Keeping the generic superclass of " + TypeCaptures.captures.size() + " type-capture classes");
|
||||
tool.getTransformers().add(ClasslibRenamer.class.getName());
|
||||
tool.getTransformers().add(MonitorElision.class.getName());
|
||||
tool.getTransformers().add(RemovalTransformer.class.getName());
|
||||
tool.getTransformers().add(AdditionsTransformer.class.getName());
|
||||
tool.getTransformers().add(TypeCaptures.class.getName());
|
||||
// `-Pteavm.throwCensus` (development): every throw counted, by site and thread (ADR 0033).
|
||||
boolean throwCensus = Boolean.getBoolean("incari.throwCensus");
|
||||
if (throwCensus) {
|
||||
tool.getTransformers().add(ThrowCensus.class.getName());
|
||||
}
|
||||
// `--jspi`: suspensions through JSPI instead of coroutines (JspiTransformer).
|
||||
if (options.jspi()) {
|
||||
tool.getTransformers().add(JspiTransformer.class.getName());
|
||||
System.setProperty(JspiTransformer.PROPERTY, "true");
|
||||
}
|
||||
try {
|
||||
tool.generate();
|
||||
} finally {
|
||||
RemovalTransformer.removals = null;
|
||||
TypeCaptures.captures = Map.of();
|
||||
System.clearProperty(JspiTransformer.PROPERTY);
|
||||
}
|
||||
removals.write(options.outputDirectory().resolve("removed.txt"));
|
||||
if (throwCensus) {
|
||||
ThrowCensus.write(options.outputDirectory().resolve("throw-sites.txt"));
|
||||
}
|
||||
|
||||
List<Problem> errors = tool.getProblemProvider().getSevereProblems();
|
||||
writeAsyncExplanations(tool, errors, options.outputDirectory().resolve("async.txt"), options.jspi());
|
||||
writeMissingSignatureTypes(tool, options.outputDirectory().resolve("signatures.txt"));
|
||||
BlockingCalls.write(
|
||||
tool.getDependencyInfo(), options.outputDirectory().resolve("blocking.txt"));
|
||||
ProblemReport report = ProblemReport.of(tool.getProblemProvider().getProblems());
|
||||
report.write(options.outputDirectory().resolve("problems.txt"));
|
||||
if (!errors.isEmpty()) {
|
||||
System.err.println(report.summary(40));
|
||||
if (options.verbose()) {
|
||||
TeaVMProblemRenderer.describeProblems(
|
||||
tool.getDependencyInfo().getCallGraph(), tool.getProblemProvider(), tool.getLog());
|
||||
}
|
||||
throw new CliException(errors.size() + " link errors; all of them are in "
|
||||
+ options.outputDirectory().resolve("problems.txt") + " (" + removals.count()
|
||||
+ " references removed, in removed.txt)");
|
||||
}
|
||||
long warnings = tool.getProblemProvider().getProblems().stream()
|
||||
.filter(p -> p.getSeverity() == ProblemSeverity.WARNING)
|
||||
.count();
|
||||
if (options.target() == TeaVMTargetType.WEBASSEMBLY_GC) {
|
||||
writeRuntime(options.outputDirectory(), options.name(), options.release());
|
||||
if (options.release()) {
|
||||
// A development build's debugging files, left from an earlier compile: the
|
||||
// build manifest takes their presence for a development build.
|
||||
Files.deleteIfExists(options.outputDirectory().resolve(options.name() + ".wasm-deobfuscator.wasm"));
|
||||
Files.deleteIfExists(options.outputDirectory().resolve(options.name() + ".wasm.teadbg"));
|
||||
// Binaryen over the module (ADR 0034).
|
||||
if (options.wasmOpt()) {
|
||||
WasmOpt.optimize(ws, options.outputDirectory().resolve(options.name() + ".wasm"));
|
||||
}
|
||||
} else {
|
||||
writeResource(
|
||||
"org/teavm/backend/wasm/deobfuscator.wasm",
|
||||
options.outputDirectory().resolve(options.name() + ".wasm-deobfuscator.wasm"));
|
||||
}
|
||||
}
|
||||
if (options.page() != null) {
|
||||
Files.copy(
|
||||
options.page(),
|
||||
options.outputDirectory().resolve("index.html"),
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
Log.step("Linked: " + tool.getDependencyInfo().getReachableClasses().size() + " classes, " + warnings
|
||||
+ " warnings, " + removals.count() + " references removed (removed.txt), output in "
|
||||
+ options.outputDirectory());
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The class library's classes as the compile sees them: substitutes under their JDK names,
|
||||
* everything else under its own.
|
||||
*/
|
||||
private static Set<String> classlibClasses(List<Path> classpath) throws IOException {
|
||||
Set<String> names = new HashSet<>();
|
||||
for (Path entry : classpath) {
|
||||
if (Files.isRegularFile(entry) && entry.toString().endsWith(".jar")) {
|
||||
try (java.util.jar.JarFile jar = new java.util.jar.JarFile(entry.toFile())) {
|
||||
jar.stream().map(java.util.jar.JarEntry::getName).forEach(name -> addClasslibClass(names, name));
|
||||
}
|
||||
} else if (Files.isDirectory(entry)) {
|
||||
try (java.util.stream.Stream<Path> files = Files.walk(entry)) {
|
||||
files.forEach(file -> addClasslibClass(
|
||||
names, entry.relativize(file).toString().replace(java.io.File.separatorChar, '/')));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Set.copyOf(names);
|
||||
}
|
||||
|
||||
private static void addClasslibClass(Set<String> names, String path) {
|
||||
if (path.startsWith("incari/classlib/") && path.endsWith(".class")) {
|
||||
String name = path.substring(0, path.length() - ".class".length()).replace('/', '.');
|
||||
names.add(ClasslibRenamer.original(name));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* For each method TeaVM failed to generate (its coroutine transformation has gaps), writes why
|
||||
* the method is a coroutine at all: usually a {@code synchronized} override somewhere deep in
|
||||
* a virtual call, which is what to remove.
|
||||
*/
|
||||
private static void writeAsyncExplanations(TeaVMTool tool, List<Problem> errors, Path file, boolean jspi)
|
||||
throws IOException {
|
||||
List<String> lines = new ArrayList<>();
|
||||
if (jspi) {
|
||||
lines.add("# A JSPI build: nothing below is compiled as a coroutine. The figures are what a");
|
||||
lines.add("# coroutine build of the same program would compile, for comparison.");
|
||||
}
|
||||
AsyncExplainer explainer = new AsyncExplainer(tool.getDependencyInfo());
|
||||
for (Problem problem : errors) {
|
||||
if (problem.getLocation() == null
|
||||
|| problem.getLocation().getMethod() == null
|
||||
|| !problem.getText().startsWith("Failed generating method body")) {
|
||||
continue;
|
||||
}
|
||||
lines.add(problem.getLocation().getMethod().toString());
|
||||
for (org.teavm.model.MethodReference step :
|
||||
explainer.explain(problem.getLocation().getMethod())) {
|
||||
lines.add(" -> " + step);
|
||||
}
|
||||
}
|
||||
// -Dincari.explainAsync=<method name prefix>,... explains chosen methods too.
|
||||
for (String wanted : System.getProperty("incari.explainAsync", "").split(",", -1)) {
|
||||
if (wanted.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
for (org.teavm.model.MethodReference method :
|
||||
tool.getDependencyInfo().getReachableMethods()) {
|
||||
if (method.toString().startsWith(wanted)) {
|
||||
lines.add("EXPLAIN " + method);
|
||||
for (org.teavm.model.MethodReference step : explainer.explain(method)) {
|
||||
lines.add(" -> " + step);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
lines.add("");
|
||||
lines.add("# Hot virtual methods compiled as suspension points (should be none):");
|
||||
lines.addAll(explainer.hotReport());
|
||||
Files.write(file, lines);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fails unless every class in tools/teavm-patches, not TeaVM's original of it, is the one
|
||||
* loaded. The patches' jar must come before TeaVM's on the class path.
|
||||
*/
|
||||
private static void checkTeaVmPatches() throws IOException {
|
||||
Path jar = null;
|
||||
for (String entry : System.getProperty("java.class.path").split(java.io.File.pathSeparator, -1)) {
|
||||
if (Path.of(entry).getFileName().toString().startsWith("teavm-patches")) {
|
||||
jar = Path.of(entry);
|
||||
}
|
||||
}
|
||||
if (jar == null) {
|
||||
throw new CliException("tools/teavm-patches isn't on the build tool's class path");
|
||||
}
|
||||
List<String> names = new ArrayList<>();
|
||||
try (java.util.jar.JarFile patches = new java.util.jar.JarFile(jar.toFile())) {
|
||||
patches.stream()
|
||||
.map(java.util.jar.JarEntry::getName)
|
||||
.filter(name -> name.endsWith(".class"))
|
||||
.forEach(name -> names.add(
|
||||
name.substring(0, name.length() - ".class".length()).replace('/', '.')));
|
||||
}
|
||||
for (String name : names) {
|
||||
Class<?> loaded;
|
||||
try {
|
||||
loaded = Class.forName(name, false, Main.class.getClassLoader());
|
||||
} catch (ClassNotFoundException e) {
|
||||
throw new CliException("Can't load " + name + " from tools/teavm-patches: " + e.getMessage());
|
||||
}
|
||||
java.security.CodeSource source = loaded.getProtectionDomain().getCodeSource();
|
||||
if (source == null || !source.getLocation().toString().contains("teavm-patches")) {
|
||||
throw new CliException("TeaVM's own " + name + " was loaded (from "
|
||||
+ (source == null ? "unknown" : source.getLocation()) + ") instead of the fix in"
|
||||
+ " tools/teavm-patches; it must come first on the class path");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reachable methods whose signatures name a class that doesn't exist. Removal rewrites the
|
||||
* instructions that use a missing class, not signatures, and TeaVM types a missing class in a
|
||||
* signature inconsistently, which fails WebAssembly validation (a bridge method's call into
|
||||
* its target, say). Each needs its class provided ({@code web-classlib}) or its code cut.
|
||||
*/
|
||||
private static void writeMissingSignatureTypes(TeaVMTool tool, Path file) throws IOException {
|
||||
org.teavm.model.ClassReaderSource classes = tool.getDependencyInfo().getClassSource();
|
||||
java.util.TreeMap<String, java.util.TreeSet<String>> byType = new java.util.TreeMap<>();
|
||||
for (org.teavm.model.MethodReference method : tool.getDependencyInfo().getReachableMethods()) {
|
||||
for (org.teavm.model.ValueType type : method.getSignature()) {
|
||||
org.teavm.model.ValueType item = type;
|
||||
while (item instanceof org.teavm.model.ValueType.Array array) {
|
||||
item = array.getItemType();
|
||||
}
|
||||
if (item instanceof org.teavm.model.ValueType.Object object
|
||||
&& classes.get(object.getClassName()) == null) {
|
||||
byType.computeIfAbsent(object.getClassName(), k -> new java.util.TreeSet<>())
|
||||
.add(method.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
List<String> lines = new ArrayList<>();
|
||||
lines.add("# Reachable methods whose signatures name a missing class (should be none):");
|
||||
byType.forEach((type, methods) -> {
|
||||
lines.add(type + " (" + methods.size() + ")");
|
||||
methods.stream().limit(5).forEach(m -> lines.add(" " + m));
|
||||
});
|
||||
Files.write(file, lines);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes TeaVM's loader for WebAssembly GC modules next to the module, as
|
||||
* {@code <name>.wasm-runtime.js}; the page (or a worker) loads it, then the module through it.
|
||||
*/
|
||||
private static void writeRuntime(Path outputDirectory, String name, boolean minified) throws IOException {
|
||||
String resource = "org/teavm/backend/wasm/wasm-gc-runtime" + (minified ? ".min" : "") + ".js";
|
||||
try (InputStream runtime = Main.class.getClassLoader().getResourceAsStream(resource)) {
|
||||
if (runtime == null) {
|
||||
throw new CliException("TeaVM's WebAssembly GC runtime (" + resource + ") isn't on the classpath");
|
||||
}
|
||||
Files.copy(
|
||||
runtime, outputDirectory.resolve(name + ".wasm-runtime.js"), StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
|
||||
private static void writeResource(String resource, Path target) throws IOException {
|
||||
try (InputStream in = Main.class.getClassLoader().getResourceAsStream(resource)) {
|
||||
if (in == null) {
|
||||
throw new CliException(resource + " isn't on the classpath");
|
||||
}
|
||||
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
|
||||
/** Command-line options; Gradle passes them. */
|
||||
record Options(
|
||||
String mainClass,
|
||||
List<Path> appClasspath,
|
||||
Path outputDirectory,
|
||||
TeaVMTargetType target,
|
||||
@Nullable Path page,
|
||||
String name,
|
||||
boolean release,
|
||||
boolean names,
|
||||
boolean wasmOpt,
|
||||
boolean jspi,
|
||||
boolean fastAnalysis,
|
||||
boolean verbose) {
|
||||
|
||||
static Options parse(List<String> args) {
|
||||
String mainClass = null;
|
||||
List<Path> appClasspath = new ArrayList<>();
|
||||
Path output = null;
|
||||
Path page = null;
|
||||
String name = "incari";
|
||||
TeaVMTargetType target = TeaVMTargetType.WEBASSEMBLY_GC;
|
||||
boolean release = false;
|
||||
boolean names = false;
|
||||
boolean wasmOpt = false;
|
||||
boolean jspi = false;
|
||||
boolean fast = false;
|
||||
boolean verbose = false;
|
||||
for (int i = 0; i < args.size(); i++) {
|
||||
String arg = args.get(i);
|
||||
switch (arg) {
|
||||
case "--main" -> mainClass = value(args, ++i, arg);
|
||||
case "--classpath" -> {
|
||||
for (String entry : value(args, ++i, arg).split(java.io.File.pathSeparator, -1)) {
|
||||
if (!entry.isEmpty()) {
|
||||
appClasspath.add(Path.of(entry));
|
||||
}
|
||||
}
|
||||
}
|
||||
case "--out" -> output = Path.of(value(args, ++i, arg));
|
||||
case "--page" -> page = Path.of(value(args, ++i, arg));
|
||||
case "--name" -> name = value(args, ++i, arg);
|
||||
case "--js" -> target = TeaVMTargetType.JAVASCRIPT;
|
||||
case "--release" -> release = true;
|
||||
case "--names" -> names = true;
|
||||
case "--wasm-opt" -> wasmOpt = true;
|
||||
case "--jspi" -> jspi = true;
|
||||
case "--fast-analysis" -> fast = true;
|
||||
case "--verbose" -> verbose = true;
|
||||
default -> throw new CliException("Unknown option '" + arg + "'");
|
||||
}
|
||||
}
|
||||
if (mainClass == null || output == null) {
|
||||
throw new CliException("Usage: webbuild --main <class> --classpath <entries> --out <dir>"
|
||||
+ " [--page <html>] [--name <file name>] [--js] [--release] [--names] [--wasm-opt]"
|
||||
+ " [--jspi] [--fast-analysis] [--verbose]");
|
||||
}
|
||||
if (wasmOpt && (!release || target != TeaVMTargetType.WEBASSEMBLY_GC)) {
|
||||
throw new CliException("--wasm-opt optimizes a release WebAssembly build: add --release, without --js");
|
||||
}
|
||||
if (jspi && target != TeaVMTargetType.WEBASSEMBLY_GC) {
|
||||
throw new CliException("--jspi is for the WebAssembly build: leave out --js");
|
||||
}
|
||||
return new Options(
|
||||
mainClass,
|
||||
List.copyOf(appClasspath),
|
||||
output,
|
||||
target,
|
||||
page,
|
||||
name,
|
||||
release,
|
||||
names,
|
||||
wasmOpt,
|
||||
jspi,
|
||||
fast,
|
||||
verbose);
|
||||
}
|
||||
|
||||
private static String value(List<String> args, int index, String option) {
|
||||
if (index >= args.size()) {
|
||||
throw new CliException(option + " needs a value");
|
||||
}
|
||||
return args.get(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import org.teavm.ast.InvocationExpr;
|
||||
import org.teavm.backend.wasm.TeaVMWasmGCHost;
|
||||
import org.teavm.backend.wasm.intrinsics.WasmGCInlineIntrinsic;
|
||||
import org.teavm.backend.wasm.intrinsics.WasmGCInlineIntrinsicContext;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmFloatType;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmFloatUnaryOperation;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmInstructionBuilder;
|
||||
import org.teavm.model.MethodReference;
|
||||
import org.teavm.vm.spi.TeaVMHost;
|
||||
import org.teavm.vm.spi.TeaVMPlugin;
|
||||
|
||||
/**
|
||||
* {@code Math.floor}, {@code Math.ceil} and {@code Math.sqrt} as WebAssembly's own {@code f64.floor},
|
||||
* {@code f64.ceil} and {@code f64.sqrt}. TeaVM's class library imports them from JavaScript's
|
||||
* {@code Math}, so each was a call out of the module and back: world generation's noise calls
|
||||
* {@code floor} for every sample, and those calls were 8 to 18% of the server worker's busy time
|
||||
* (the singleplayer benchmark's profiles). All three are exact in IEEE 754, which Java and
|
||||
* WebAssembly both follow, so the results are the same; only a NaN's payload may differ, which no
|
||||
* Java code can tell apart from {@code Math}'s results.
|
||||
*
|
||||
* <p>Registered in {@code META-INF/services}; TeaVM loads it from the compile's class loader. Its
|
||||
* call-site intrinsics come before any call, so the imports go unused.
|
||||
*/
|
||||
public final class MathIntrinsics implements TeaVMPlugin {
|
||||
|
||||
@Override
|
||||
public void install(TeaVMHost host) {
|
||||
TeaVMWasmGCHost wasm = host.getExtension(TeaVMWasmGCHost.class);
|
||||
if (wasm == null) {
|
||||
return;
|
||||
}
|
||||
wasm.contributeToCodeGen((context, registry) -> {
|
||||
for (String name : new String[] {"floor", "ceil", "sqrt"}) {
|
||||
registry.inlineIntrinsics()
|
||||
.registerIntrinsic(
|
||||
new MethodReference(Math.class, name, double.class, double.class),
|
||||
new Unary(operation(name)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static WasmFloatUnaryOperation operation(String name) {
|
||||
return switch (name) {
|
||||
case "floor" -> WasmFloatUnaryOperation.FLOOR;
|
||||
case "ceil" -> WasmFloatUnaryOperation.CEIL;
|
||||
case "sqrt" -> WasmFloatUnaryOperation.SQRT;
|
||||
default -> throw new IllegalArgumentException(name);
|
||||
};
|
||||
}
|
||||
|
||||
/** One {@code double -> double} instruction in place of the call. */
|
||||
private record Unary(WasmFloatUnaryOperation operation) implements WasmGCInlineIntrinsic {
|
||||
@Override
|
||||
public void apply(
|
||||
InvocationExpr invocation, WasmGCInlineIntrinsicContext context, WasmInstructionBuilder builder) {
|
||||
context.generate(builder, invocation.getArguments().get(0));
|
||||
builder.floatUnary(WasmFloatType.FLOAT64, operation);
|
||||
}
|
||||
}
|
||||
}
|
||||
+382
@@ -0,0 +1,382 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.teavm.model.BasicBlock;
|
||||
import org.teavm.model.ClassHolder;
|
||||
import org.teavm.model.ClassHolderTransformer;
|
||||
import org.teavm.model.ClassHolderTransformerContext;
|
||||
import org.teavm.model.ClassReader;
|
||||
import org.teavm.model.ClassReaderSource;
|
||||
import org.teavm.model.ElementModifier;
|
||||
import org.teavm.model.Instruction;
|
||||
import org.teavm.model.MethodHolder;
|
||||
import org.teavm.model.MethodReader;
|
||||
import org.teavm.model.MethodReference;
|
||||
import org.teavm.model.ProgramReader;
|
||||
import org.teavm.model.ValueType;
|
||||
import org.teavm.model.VariableReader;
|
||||
import org.teavm.model.instructions.AbstractInstructionReader;
|
||||
import org.teavm.model.instructions.InvocationType;
|
||||
import org.teavm.model.instructions.InvokeInstruction;
|
||||
import org.teavm.model.instructions.MonitorEnterInstruction;
|
||||
import org.teavm.model.instructions.MonitorExitInstruction;
|
||||
|
||||
/**
|
||||
* Drops monitors that guard no suspension point.
|
||||
*
|
||||
* <p>In the page, threads are coroutines that switch only where one suspends, so code that can't
|
||||
* suspend already runs exclusively; a monitor only matters if a thread suspends while holding it.
|
||||
* But TeaVM compiles any method that takes a monitor, and all its callers through every override,
|
||||
* as able to suspend: one {@code synchronized toString} makes every {@code toString} call a
|
||||
* coroutine (slower, and TeaVM's coroutine transformation has gaps). Hashtable, Guava's
|
||||
* synchronized collections and the class library all did that.
|
||||
*
|
||||
* <p>Each method with a monitor is sorted by what it (or the static, private and class library
|
||||
* methods it calls) does:
|
||||
* <ul>
|
||||
* <li>waits, or calls a blocking concurrency API ({@code Future.get}, {@code join},
|
||||
* {@code Lock.lock}, {@code BlockingQueue.take}...): its monitors stay, a real suspension;
|
||||
* <li>only notifies ({@code offer}, {@code complete}, {@code unlock} wake waiters), or neither:
|
||||
* its body can't suspend, so it runs exclusively anyway, and its monitors go.
|
||||
* </ul>
|
||||
* Every {@code notify} and {@code notifyAll} goes through {@code incari.classlib.concurrent.Wakeups},
|
||||
* which holds the monitor only for the call (with TeaVM's non-suspending {@code monitorEnterSync},
|
||||
* reentrant), so notifying never needs a removed monitor and never makes a coroutine.
|
||||
*
|
||||
* <p>Limit: a {@code synchronized} method that blocks only through an ordinary virtual call would
|
||||
* lose a monitor it needed. Nothing the browser build runs does that.
|
||||
*/
|
||||
public final class MonitorElision implements ClassHolderTransformer {
|
||||
|
||||
/** The class library's classes, under the names the compile sees; {@link Main} sets them. */
|
||||
static volatile Set<String> classes = Set.of();
|
||||
|
||||
private static final Set<String> BLOCKING_NAMES = Set.of(
|
||||
"sleep",
|
||||
"join",
|
||||
"yield",
|
||||
"onSpinWait",
|
||||
"park",
|
||||
"parkNanos",
|
||||
"parkUntil",
|
||||
"await",
|
||||
"awaitNanos",
|
||||
"awaitUninterruptibly",
|
||||
"awaitUntil",
|
||||
"awaitTermination",
|
||||
"awaitAdvance",
|
||||
"tryLock",
|
||||
"writeLock",
|
||||
"readLock",
|
||||
"tryOptimisticRead",
|
||||
"acquire",
|
||||
"acquireUninterruptibly",
|
||||
"tryAcquire",
|
||||
"take",
|
||||
"put",
|
||||
"offer",
|
||||
"poll",
|
||||
"transfer",
|
||||
"get",
|
||||
"invoke",
|
||||
"invokeAll",
|
||||
"invokeAny",
|
||||
"close",
|
||||
"managedBlock");
|
||||
|
||||
private static final MethodReference ENTER_SYNC = new MethodReference(
|
||||
"java.lang.Object", "monitorEnterSync", ValueType.object("java.lang.Object"), ValueType.VOID);
|
||||
private static final MethodReference EXIT_SYNC = new MethodReference(
|
||||
"java.lang.Object", "monitorExitSync", ValueType.object("java.lang.Object"), ValueType.VOID);
|
||||
|
||||
/** The class library's notification helper (see {@link #routeToWakeups}). */
|
||||
static final String WAKEUPS = "incari.classlib.concurrent.Wakeups";
|
||||
|
||||
/** The class library's wait helper, which times the render thread's waits (see {@link #routeToWaits}). */
|
||||
static final String WAITS = "incari.classlib.concurrent.Waits";
|
||||
|
||||
/** The class library's non-waiting lock helper (see {@link #routeToLockNow}). */
|
||||
static final String LOCKS = "incari.classlib.concurrent.Locks";
|
||||
|
||||
private final Map<MethodReference, Effect> effects = new HashMap<>();
|
||||
private org.teavm.model.@org.jspecify.annotations.Nullable ClassHierarchy hierarchy;
|
||||
|
||||
@Override
|
||||
public void transformClass(ClassHolder cls, ClassHolderTransformerContext context) {
|
||||
ClassReaderSource source = context.getHierarchy().getClassSource();
|
||||
hierarchy = context.getHierarchy();
|
||||
boolean wakeups = cls.getName().equals(WAKEUPS);
|
||||
// The helper's own waits, and Object's (its wait(long) calls wait(long, int)): routing
|
||||
// those would recurse without end.
|
||||
boolean waits = cls.getName().equals(WAITS) || cls.getName().equals("java.lang.Object");
|
||||
for (MethodHolder method : cls.getMethods()) {
|
||||
if (method.getProgram() == null) {
|
||||
continue;
|
||||
}
|
||||
boolean blocks = effect(method.getReference(), source) == Effect.BLOCKS;
|
||||
boolean dropMonitors = hasMonitor(method) && !blocks;
|
||||
if (dropMonitors) {
|
||||
method.getModifiers().remove(ElementModifier.SYNCHRONIZED);
|
||||
}
|
||||
for (int i = 0; i < method.getProgram().basicBlockCount(); i++) {
|
||||
BasicBlock block = method.getProgram().basicBlockAt(i);
|
||||
for (Instruction insn = block.getFirstInstruction(); insn != null; ) {
|
||||
Instruction next = insn.getNext();
|
||||
if (wakeups) {
|
||||
// The helper itself: take the monitor for notify, without suspending.
|
||||
takeWithoutSuspending(insn);
|
||||
} else if (insn instanceof InvokeInstruction call && isNotify(call.getMethod())) {
|
||||
// Everywhere, so a notify never depends on a monitor this pass removed.
|
||||
routeToWakeups(call);
|
||||
} else if (!waits && insn instanceof InvokeInstruction call && isObjectWait(call.getMethod())) {
|
||||
// Everywhere but the helper itself, so every wait on the render thread is timed.
|
||||
routeToWaits(call);
|
||||
} else if (!blocks && insn instanceof InvokeInstruction call && isLock(call.getMethod())) {
|
||||
routeToLockNow(call);
|
||||
} else if (dropMonitors
|
||||
&& (insn instanceof MonitorEnterInstruction || insn instanceof MonitorExitInstruction)) {
|
||||
insn.delete();
|
||||
}
|
||||
insn = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** {@code lock.lock()} becomes {@code Locks.lockNow(lock)}: take it now, or fail loudly. */
|
||||
private static void routeToLockNow(InvokeInstruction call) {
|
||||
InvokeInstruction now = new InvokeInstruction();
|
||||
now.setType(InvocationType.SPECIAL);
|
||||
now.setMethod(new MethodReference(
|
||||
LOCKS, "lockNow", ValueType.object("java.util.concurrent.locks.Lock"), ValueType.VOID));
|
||||
now.setArguments(call.getInstance());
|
||||
now.setLocation(call.getLocation());
|
||||
call.replace(now);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code lock()} or {@code lockInterruptibly()} on a {@code Lock}. Not counted as blocking: in a
|
||||
* method that doesn't otherwise block, it becomes a non-waiting acquisition (see
|
||||
* {@link #routeToLockNow}); a method that blocks anyway keeps the real one.
|
||||
*/
|
||||
private boolean isLock(MethodReference method) {
|
||||
String descriptor = method.getDescriptor().toString();
|
||||
return (descriptor.equals("lock()V") || descriptor.equals("lockInterruptibly()V"))
|
||||
&& hierarchy != null
|
||||
&& hierarchy.isSuperType("java.util.concurrent.locks.Lock", method.getClassName(), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code monitor.wait(timeout)} becomes {@code Waits.wait(monitor, timeout)}, likewise the other
|
||||
* two forms: the helper times the render thread's waits for the page's frame monitor. The
|
||||
* caller still holds the monitor, as {@code wait} needs, and still counts as blocking.
|
||||
*/
|
||||
private static void routeToWaits(InvokeInstruction call) {
|
||||
ValueType[] parameters = call.getMethod().getParameterTypes();
|
||||
ValueType[] signature = new ValueType[parameters.length + 2];
|
||||
signature[0] = ValueType.object("java.lang.Object");
|
||||
System.arraycopy(parameters, 0, signature, 1, parameters.length);
|
||||
signature[signature.length - 1] = ValueType.VOID;
|
||||
List<org.teavm.model.Variable> arguments = new ArrayList<>();
|
||||
arguments.add(call.getInstance());
|
||||
arguments.addAll(call.getArguments());
|
||||
InvokeInstruction timed = new InvokeInstruction();
|
||||
timed.setType(InvocationType.SPECIAL);
|
||||
timed.setMethod(new MethodReference(WAITS, "wait", signature));
|
||||
timed.setArguments(arguments.toArray(org.teavm.model.Variable[]::new));
|
||||
timed.setLocation(call.getLocation());
|
||||
call.replace(timed);
|
||||
}
|
||||
|
||||
/** {@code Object.wait} in its three forms (final in {@code Object}, so matched whatever class the call names). */
|
||||
static boolean isObjectWait(MethodReference method) {
|
||||
String descriptor = method.getDescriptor().toString();
|
||||
return !method.getClassName().equals(WAITS)
|
||||
&& (descriptor.equals("wait()V") || descriptor.equals("wait(J)V") || descriptor.equals("wait(JI)V"));
|
||||
}
|
||||
|
||||
/** {@code monitor.notifyAll()} becomes {@code Wakeups.notifyAll(monitor)}; likewise notify. */
|
||||
private static void routeToWakeups(InvokeInstruction call) {
|
||||
String name = call.getMethod().getName();
|
||||
InvokeInstruction wakeup = new InvokeInstruction();
|
||||
wakeup.setType(InvocationType.SPECIAL);
|
||||
wakeup.setMethod(new MethodReference(WAKEUPS, name, ValueType.object("java.lang.Object"), ValueType.VOID));
|
||||
wakeup.setArguments(call.getInstance());
|
||||
wakeup.setLocation(call.getLocation());
|
||||
call.replace(wakeup);
|
||||
}
|
||||
|
||||
/** Replaces a monitor instruction with TeaVM's non-suspending monitor call. */
|
||||
private static void takeWithoutSuspending(Instruction insn) {
|
||||
MethodReference target;
|
||||
org.teavm.model.Variable object;
|
||||
if (insn instanceof MonitorEnterInstruction enter) {
|
||||
target = ENTER_SYNC;
|
||||
object = enter.getObjectRef();
|
||||
} else if (insn instanceof MonitorExitInstruction exit) {
|
||||
target = EXIT_SYNC;
|
||||
object = exit.getObjectRef();
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
InvokeInstruction call = new InvokeInstruction();
|
||||
call.setType(InvocationType.SPECIAL);
|
||||
call.setMethod(target);
|
||||
call.setArguments(object);
|
||||
call.setLocation(insn.getLocation());
|
||||
insn.replace(call);
|
||||
}
|
||||
|
||||
private static boolean hasMonitor(MethodHolder method) {
|
||||
if (method.hasModifier(ElementModifier.SYNCHRONIZED)) {
|
||||
return true;
|
||||
}
|
||||
for (int i = 0; i < method.getProgram().basicBlockCount(); i++) {
|
||||
for (Instruction insn : method.getProgram().basicBlockAt(i)) {
|
||||
if (insn instanceof MonitorEnterInstruction) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** What a method does that its monitors matter for, itself or through the calls it follows. */
|
||||
enum Effect {
|
||||
NONE,
|
||||
NOTIFIES,
|
||||
BLOCKS
|
||||
}
|
||||
|
||||
private Effect effect(MethodReference reference, ClassReaderSource source) {
|
||||
Effect known = effects.get(reference);
|
||||
if (known != null) {
|
||||
return known;
|
||||
}
|
||||
// Assume nothing while looking, so a recursive cycle ends; a waiting or notifying method in
|
||||
// the cycle is still found from wherever the search reaches it.
|
||||
effects.put(reference, Effect.NONE);
|
||||
Effect result = scan(reference, source);
|
||||
effects.put(reference, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
private Effect scan(MethodReference reference, ClassReaderSource source) {
|
||||
ClassReader cls = source.get(reference.getClassName());
|
||||
MethodReader method = cls == null ? null : cls.getMethod(reference.getDescriptor());
|
||||
ProgramReader program = method == null ? null : method.getProgram();
|
||||
if (program == null) {
|
||||
return Effect.NONE;
|
||||
}
|
||||
CallFinder calls = new CallFinder();
|
||||
for (int i = 0; i < program.basicBlockCount(); i++) {
|
||||
program.basicBlockAt(i).readAllInstructions(calls);
|
||||
}
|
||||
Effect result = calls.effect;
|
||||
for (MethodReference callee : calls.followed) {
|
||||
if (result == Effect.BLOCKS) {
|
||||
break;
|
||||
}
|
||||
Effect calleeEffect = effect(callee, source);
|
||||
if (calleeEffect.compareTo(result) > 0) {
|
||||
result = calleeEffect;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code wait} (final in {@code Object}, so matched by name whatever class the call names) and
|
||||
* blocking-named methods of {@code Thread}, the locks, and the {@code java.util.concurrent}
|
||||
* types that can block.
|
||||
*/
|
||||
static boolean isBlocking(MethodReference method) {
|
||||
String name = method.getName();
|
||||
String descriptor = method.getDescriptor().toString();
|
||||
if (name.equals("wait")
|
||||
&& (descriptor.equals("wait()V") || descriptor.equals("wait(J)V") || descriptor.equals("wait(JI)V"))) {
|
||||
return true;
|
||||
}
|
||||
if (name.equals("wait") && method.getClassName().equals(WAITS)) {
|
||||
// A wait this pass has already routed to the helper (see routeToWaits).
|
||||
return true;
|
||||
}
|
||||
if ((name.equals("tryLock") || name.equals("tryAcquire")) && method.parameterCount() == 0) {
|
||||
// The untimed forms answer at once.
|
||||
return false;
|
||||
}
|
||||
if ((name.equals("offer") && method.parameterCount() == 1)
|
||||
|| (name.equals("poll") && method.parameterCount() == 0)) {
|
||||
// A queue's untimed offer and poll answer at once too; only the forms with a timeout
|
||||
// wait. Counting them kept ThreadPoolExecutor.execute's monitor, which made every
|
||||
// Executor.execute, and through CompletableFuture every Function.apply, a coroutine.
|
||||
return false;
|
||||
}
|
||||
String owner = method.getClassName();
|
||||
if (owner.equals("java.lang.Thread")) {
|
||||
return BLOCKING_NAMES.contains(name);
|
||||
}
|
||||
if (!owner.startsWith("java.util.concurrent.")) {
|
||||
return false;
|
||||
}
|
||||
String simpleName = owner.substring(owner.lastIndexOf('.') + 1);
|
||||
return BLOCKING_NAMES.contains(name)
|
||||
&& (owner.startsWith("java.util.concurrent.locks.")
|
||||
|| BLOCKING_TYPES.stream().anyMatch(simpleName::contains));
|
||||
}
|
||||
|
||||
/** {@code notify} and {@code notifyAll}, final in {@code Object}. */
|
||||
static boolean isNotify(MethodReference method) {
|
||||
String descriptor = method.getDescriptor().toString();
|
||||
return descriptor.equals("notify()V") || descriptor.equals("notifyAll()V");
|
||||
}
|
||||
|
||||
/** The {@code java.util.concurrent} types whose methods can block ({@code ConcurrentHashMap} can't). */
|
||||
private static final List<String> BLOCKING_TYPES = List.of(
|
||||
"Future",
|
||||
"ForkJoin",
|
||||
"Blocking",
|
||||
"Latch",
|
||||
"Semaphore",
|
||||
"Barrier",
|
||||
"Phaser",
|
||||
"Exchanger",
|
||||
"Executor",
|
||||
"CompletionService",
|
||||
"TransferQueue",
|
||||
"SynchronousQueue",
|
||||
"DelayQueue");
|
||||
|
||||
private final class CallFinder extends AbstractInstructionReader {
|
||||
Effect effect = Effect.NONE;
|
||||
final List<MethodReference> followed = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void invoke(
|
||||
VariableReader receiver,
|
||||
VariableReader instance,
|
||||
MethodReference method,
|
||||
List<? extends VariableReader> arguments,
|
||||
InvocationType type) {
|
||||
if (isLock(method)) {
|
||||
// Neither blocking nor followed: see isLock.
|
||||
return;
|
||||
}
|
||||
if (isBlocking(method)) {
|
||||
effect = Effect.BLOCKS;
|
||||
} else if (isNotify(method)) {
|
||||
if (effect == Effect.NONE) {
|
||||
effect = Effect.NOTIFIES;
|
||||
}
|
||||
} else if (type == InvocationType.SPECIAL || classes.contains(method.getClassName())) {
|
||||
// Static, private and constructor calls have one target; the class library's
|
||||
// virtual calls stay inside code whose waiting this can see.
|
||||
followed.add(method);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The page's console, read from Chromium's log on a thread of its own so the browser never waits
|
||||
* on it. Every message is echoed, queued for {@link #await} and kept for {@link #history}.
|
||||
*/
|
||||
final class PageConsole {
|
||||
|
||||
/** What web-classlib's {@code System.exit} prints (the game may prefix it: it logs standard error). */
|
||||
private static final String EXITED = "Java exited with status ";
|
||||
|
||||
/** What the page (app-web's index.html) logs when an error escapes Java. */
|
||||
private static final String CRASHED = "[Incari] Crashed: ";
|
||||
|
||||
/** Where Chromium's DevTools listen, which it prints at start with {@code --remote-debugging-port}. */
|
||||
private static final Pattern DEVTOOLS = Pattern.compile("DevTools listening on (ws://\\S+)");
|
||||
|
||||
// Chromium's stderr form of a page console message, which varies by version:
|
||||
// ...:INFO:CONSOLE(12)] "text", source: url (12) or ...:INFO:CONSOLE:12] "text", source: ...
|
||||
private static final Pattern CONSOLE =
|
||||
Pattern.compile(".*:(INFO|WARNING|ERROR):CONSOLE(?:\\(\\d+\\)|:\\d+)?\\] \"(.*)\", source: (.*)");
|
||||
|
||||
private final BlockingQueue<String> messages = new LinkedBlockingQueue<>();
|
||||
private final List<String> history = new ArrayList<>();
|
||||
private final CompletableFuture<String> devToolsUrl = new CompletableFuture<>();
|
||||
private volatile boolean ended;
|
||||
private volatile boolean quiet;
|
||||
|
||||
PageConsole(Process process) {
|
||||
Thread.ofPlatform().daemon().start(() -> {
|
||||
try (BufferedReader stderr =
|
||||
new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = stderr.readLine()) != null) {
|
||||
Matcher listening = DEVTOOLS.matcher(line);
|
||||
if (listening.find()) {
|
||||
devToolsUrl.complete(listening.group(1));
|
||||
}
|
||||
Matcher console = CONSOLE.matcher(line);
|
||||
if (!console.matches() || console.group(3).startsWith("chrome-extension:")) {
|
||||
continue;
|
||||
}
|
||||
String message = console.group(2).replace("\\n", "\n");
|
||||
if (!quiet) {
|
||||
System.out.println("[console " + console.group(1).toLowerCase(Locale.ROOT) + "] " + message);
|
||||
}
|
||||
synchronized (history) {
|
||||
history.add(message);
|
||||
}
|
||||
messages.add(message);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
// The browser went away; ended says so.
|
||||
} finally {
|
||||
ended = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Stops echoing messages (they're still queued and kept); for long runs with their own report. */
|
||||
void quiet() {
|
||||
quiet = true;
|
||||
}
|
||||
|
||||
/** Every message so far, in order. */
|
||||
List<String> history() {
|
||||
synchronized (history) {
|
||||
return List.copyOf(history);
|
||||
}
|
||||
}
|
||||
|
||||
/** Waits for {@code count} messages matching {@code expect}; false (and why) if the game ends or time runs out. */
|
||||
boolean await(Pattern expect, int count, long deadline) throws InterruptedException {
|
||||
int seen = 0;
|
||||
while (true) {
|
||||
String message = next(deadline);
|
||||
if (message == null) {
|
||||
System.out.println("==> Failed: saw " + seen + " of " + count + " messages matching " + expect.pattern()
|
||||
+ " before the browser exited or time ran out");
|
||||
return false;
|
||||
}
|
||||
if (crashed(message, seen, count, expect)) {
|
||||
return false;
|
||||
}
|
||||
if (expect.matcher(message).matches() && ++seen >= count) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Lets the page run for {@code millis}; false if the game ends meanwhile. */
|
||||
boolean idle(long millis, long deadline) throws InterruptedException {
|
||||
long until = Math.min(deadline, System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(millis));
|
||||
while (System.nanoTime() < until) {
|
||||
String message = messages.poll(
|
||||
Math.max(1, TimeUnit.NANOSECONDS.toMillis(until - System.nanoTime())), TimeUnit.MILLISECONDS);
|
||||
if (message != null && crashed(message, 0, 0, null)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
String devToolsUrl(long deadline) throws IOException, InterruptedException {
|
||||
try {
|
||||
return devToolsUrl.get(
|
||||
Math.max(1, TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime())), TimeUnit.MILLISECONDS);
|
||||
} catch (ExecutionException | TimeoutException e) {
|
||||
throw new IOException("Chromium didn't print its DevTools address", e);
|
||||
}
|
||||
}
|
||||
|
||||
private @Nullable String next(long deadline) throws InterruptedException {
|
||||
while (true) {
|
||||
long left = deadline - System.nanoTime();
|
||||
if (left <= 0) {
|
||||
return null;
|
||||
}
|
||||
String message = messages.poll(Math.min(left, TimeUnit.MILLISECONDS.toNanos(500)), TimeUnit.NANOSECONDS);
|
||||
if (message != null) {
|
||||
return message;
|
||||
}
|
||||
if (ended && messages.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean crashed(String message, int seen, int count, @Nullable Pattern expect) {
|
||||
if (message.contains(EXITED) || message.startsWith(CRASHED)) {
|
||||
// The page keeps running after System.exit; waiting on would only run out the clock.
|
||||
System.out.println("==> Failed: the game exited"
|
||||
+ (expect == null
|
||||
? ""
|
||||
: " after " + seen + " of " + count + " messages matching " + expect.pattern()));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** The page options the tools open the page with. */
|
||||
final class PageQuery {
|
||||
|
||||
/** The system property Gradle sets to the build a check or the benchmark runs: fast or compatible. */
|
||||
static final String PROPERTY = "incari.build";
|
||||
|
||||
private static final Pattern BUILD = Pattern.compile("(^|&)build=");
|
||||
|
||||
private PageQuery() {}
|
||||
|
||||
/**
|
||||
* {@code query} with {@code build=<build>} added unless it names a build already or {@code build}
|
||||
* is empty. Where both builds can run, the page waits for the player to pick Fast or Compatible
|
||||
* (boot.ts, ADR 0036); a check or the benchmark must not wait, and runs the build it compiled.
|
||||
* An experiment's build has one module and no choice, so Gradle gives no build for it.
|
||||
*/
|
||||
static String withBuild(String query, String build) {
|
||||
if (build.isEmpty() || BUILD.matcher(query).find()) {
|
||||
return query;
|
||||
}
|
||||
return query.isEmpty() ? "build=" + build : query + "&build=" + build;
|
||||
}
|
||||
|
||||
/** {@link #withBuild} with the build Gradle names in {@link #PROPERTY}. */
|
||||
static String withBuild(String query) {
|
||||
return withBuild(query, System.getProperty(PROPERTY, ""));
|
||||
}
|
||||
}
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The benchmark's baseline: {@code app-web/benchmark/baseline.properties}, the figures each
|
||||
* machine last recorded, and the rules that say how much worse a figure may get before the
|
||||
* benchmark fails. Pure logic, tested on its own.
|
||||
*
|
||||
* <pre>
|
||||
* # rule.<figure>=<higher|lower> <percent> <absolute>
|
||||
* rule.fpsMedian=higher 5 1
|
||||
* # <machine>.<scenario or group>.<figure>=<value>
|
||||
* desktop.flythrough.fpsMedian=60.0
|
||||
* </pre>
|
||||
*
|
||||
* A figure regresses when it's worse than its baseline by more than the percentage of the baseline
|
||||
* and more than the absolute amount (both, so a tiny figure's noise doesn't fail the run). Figures
|
||||
* without a rule are recorded but never fail. A figure's rule is found by the last part of its key.
|
||||
*/
|
||||
final class PerfBaseline {
|
||||
|
||||
/** Which way is better, and by how much a figure may get worse. */
|
||||
record Rule(boolean higherIsBetter, double percent, double absolute) {
|
||||
|
||||
/** How much worse {@code current} is than {@code baseline}, in the figure's units; negative if better. */
|
||||
double worsening(double baseline, double current) {
|
||||
return higherIsBetter ? baseline - current : current - baseline;
|
||||
}
|
||||
|
||||
boolean regressed(double baseline, double current) {
|
||||
double worse = worsening(baseline, current);
|
||||
return worse > Math.abs(baseline) * percent / 100 && worse > absolute;
|
||||
}
|
||||
}
|
||||
|
||||
/** One figure against its baseline. */
|
||||
record Comparison(String key, double baseline, double current, Rule rule, boolean regressed) {}
|
||||
|
||||
private final List<String> lines;
|
||||
private final Map<String, Rule> rules;
|
||||
|
||||
private PerfBaseline(List<String> lines, Map<String, Rule> rules) {
|
||||
this.lines = lines;
|
||||
this.rules = rules;
|
||||
}
|
||||
|
||||
static PerfBaseline parse(List<String> lines, String source) {
|
||||
Map<String, Rule> rules = new LinkedHashMap<>();
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String line = lines.get(i).strip();
|
||||
if (!line.startsWith("rule.")) {
|
||||
continue;
|
||||
}
|
||||
int equals = line.indexOf('=');
|
||||
String[] words = equals < 0
|
||||
? new String[0]
|
||||
: line.substring(equals + 1).strip().split("\\s+", -1);
|
||||
if (words.length != 3 || !(words[0].equals("higher") || words[0].equals("lower"))) {
|
||||
throw new CliException(
|
||||
source + ":" + (i + 1) + ": a rule is 'rule.<figure>=<higher|lower> <percent> <absolute>'");
|
||||
}
|
||||
rules.put(
|
||||
line.substring("rule.".length(), equals).strip(),
|
||||
new Rule(words[0].equals("higher"), Double.parseDouble(words[1]), Double.parseDouble(words[2])));
|
||||
}
|
||||
return new PerfBaseline(List.copyOf(lines), rules);
|
||||
}
|
||||
|
||||
/** {@code machine}'s recorded figures, by key without the machine. */
|
||||
Map<String, Double> figures(String machine) {
|
||||
Map<String, Double> out = new TreeMap<>();
|
||||
String prefix = machine + ".";
|
||||
for (String raw : lines) {
|
||||
String line = raw.strip();
|
||||
int equals = line.indexOf('=');
|
||||
if (line.startsWith("#") || line.startsWith("rule.") || equals < 0 || !line.startsWith(prefix)) {
|
||||
continue;
|
||||
}
|
||||
out.put(
|
||||
line.substring(prefix.length(), equals).strip(),
|
||||
Double.parseDouble(line.substring(equals + 1).strip()));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The rule for {@code key}'s figure (its last part), or null if it has none. */
|
||||
@Nullable
|
||||
Rule rule(String key) {
|
||||
return rules.get(key.substring(key.lastIndexOf('.') + 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code current} against {@code machine}'s baseline: every figure that has both a baseline and
|
||||
* a rule and was measured this time.
|
||||
*/
|
||||
List<Comparison> compare(String machine, Map<String, Double> current) {
|
||||
List<Comparison> out = new ArrayList<>();
|
||||
for (Map.Entry<String, Double> entry : figures(machine).entrySet()) {
|
||||
Rule rule = rule(entry.getKey());
|
||||
Double now = current.get(entry.getKey());
|
||||
if (rule == null || now == null || now.isNaN() || entry.getValue().isNaN()) {
|
||||
continue;
|
||||
}
|
||||
out.add(new Comparison(entry.getKey(), entry.getValue(), now, rule, rule.regressed(entry.getValue(), now)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The file with {@code machine}'s figures replaced by {@code current} (what isn't measured is
|
||||
* left out), everything else as it was.
|
||||
*/
|
||||
List<String> withFigures(String machine, Map<String, Double> current) {
|
||||
String prefix = machine + ".";
|
||||
List<String> out = new ArrayList<>();
|
||||
for (String line : lines) {
|
||||
if (!line.strip().startsWith(prefix)) {
|
||||
out.add(line);
|
||||
}
|
||||
}
|
||||
while (!out.isEmpty() && out.getLast().isBlank()) {
|
||||
out.removeLast();
|
||||
}
|
||||
out.add("");
|
||||
new TreeMap<>(current).forEach((key, value) -> {
|
||||
if (!value.isNaN()) {
|
||||
out.add(prefix + key + "=" + format(value));
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
static String format(double value) {
|
||||
return value == Math.rint(value) && Math.abs(value) < 1e15
|
||||
? Long.toString((long) value)
|
||||
: String.format(Locale.ROOT, "%.2f", value);
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* The benchmark's budgets (ADR 0025, 0026): {@code app-web/benchmark/budgets.properties},
|
||||
* absolute limits a figure must stay under, where the baseline ({@link PerfBaseline}) only limits how
|
||||
* much worse a figure may get than last time. Pure logic, tested on its own.
|
||||
*
|
||||
* <pre>
|
||||
* # max.<figure>=<limit>: for every machine. A * in the key stands for one part of it (a scenario).
|
||||
* max.*.heapLiveMB=600
|
||||
* # <machine>.max.<figure>=<limit>: for one machine (times depend on its speed).
|
||||
* desktop.max.load.warmTitleMillis=3000
|
||||
* </pre>
|
||||
*
|
||||
* A machine's own limit replaces the general one for the same figure. Figures a run didn't measure
|
||||
* (NaN, or absent) aren't checked.
|
||||
*/
|
||||
final class PerfBudget {
|
||||
|
||||
/** One limit: the figures it covers, as a pattern, and the most each may be. */
|
||||
record Limit(String key, Pattern figures, double max, boolean machineOnly) {}
|
||||
|
||||
/** One figure against its limit. */
|
||||
record Check(String figure, double value, Limit limit) {
|
||||
boolean over() {
|
||||
return value > limit.max();
|
||||
}
|
||||
}
|
||||
|
||||
private final List<Limit> general;
|
||||
private final Map<String, List<Limit>> byMachine;
|
||||
|
||||
private PerfBudget(List<Limit> general, Map<String, List<Limit>> byMachine) {
|
||||
this.general = general;
|
||||
this.byMachine = byMachine;
|
||||
}
|
||||
|
||||
static PerfBudget parse(List<String> lines, String source) {
|
||||
List<Limit> general = new ArrayList<>();
|
||||
Map<String, List<Limit>> byMachine = new java.util.TreeMap<>();
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String line = lines.get(i).strip();
|
||||
if (line.isEmpty() || line.startsWith("#")) {
|
||||
continue;
|
||||
}
|
||||
int equals = line.indexOf('=');
|
||||
int max = line.indexOf("max.");
|
||||
if (equals < 0 || max < 0 || max > equals || (max > 0 && line.charAt(max - 1) != '.')) {
|
||||
throw new CliException(source + ":" + (i + 1) + ": a budget is '[<machine>.]max.<figure>=<limit>'");
|
||||
}
|
||||
String key = line.substring(max + "max.".length(), equals).strip();
|
||||
double limit;
|
||||
try {
|
||||
limit = Double.parseDouble(line.substring(equals + 1).strip().replace("_", ""));
|
||||
} catch (NumberFormatException e) {
|
||||
throw new CliException(source + ":" + (i + 1) + ": not a number: " + line.substring(equals + 1));
|
||||
}
|
||||
Pattern figures = Pattern.compile(Pattern.quote(key).replace("*", "\\E[^.]+\\Q"));
|
||||
if (max == 0) {
|
||||
general.add(new Limit(key, figures, limit, false));
|
||||
} else {
|
||||
byMachine
|
||||
.computeIfAbsent(line.substring(0, max - 1), m -> new ArrayList<>())
|
||||
.add(new Limit(key, figures, limit, true));
|
||||
}
|
||||
}
|
||||
return new PerfBudget(List.copyOf(general), byMachine);
|
||||
}
|
||||
|
||||
/** Each of {@code figures} with a limit for {@code machine}, against it. */
|
||||
List<Check> check(String machine, Map<String, Double> figures) {
|
||||
List<Limit> own = byMachine.getOrDefault(machine, List.of());
|
||||
List<Check> checks = new ArrayList<>();
|
||||
figures.forEach((figure, value) -> {
|
||||
if (value == null || value.isNaN()) {
|
||||
return;
|
||||
}
|
||||
Limit limit = find(own, figure);
|
||||
if (limit == null) {
|
||||
limit = find(general, figure);
|
||||
}
|
||||
if (limit != null) {
|
||||
checks.add(new Check(figure, value, limit));
|
||||
}
|
||||
});
|
||||
return checks;
|
||||
}
|
||||
|
||||
private static @org.jspecify.annotations.Nullable Limit find(List<Limit> limits, String figure) {
|
||||
for (Limit limit : limits) {
|
||||
if (limit.figures().matcher(figure).matches()) {
|
||||
return limit;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.teavm.diagnostics.Problem;
|
||||
import org.teavm.diagnostics.ProblemSeverity;
|
||||
import org.teavm.model.CallLocation;
|
||||
|
||||
/**
|
||||
* TeaVM's link errors, grouped by what's missing. One missing class shows up at every call site;
|
||||
* the grouped view says which gaps to close first.
|
||||
*/
|
||||
final class ProblemReport {
|
||||
|
||||
/** TeaVM names what's missing in the problem text's first {{c0}} or {{m0}} argument. */
|
||||
private static final Pattern PLACEHOLDER = Pattern.compile("\\{\\{[a-z](\\d+)}}");
|
||||
|
||||
/** One missing thing and the places that need it. */
|
||||
record Group(String missing, String kind, List<String> sites) {}
|
||||
|
||||
private final List<Group> groups;
|
||||
private final List<String> other;
|
||||
|
||||
private ProblemReport(List<Group> groups, List<String> other) {
|
||||
this.groups = groups;
|
||||
this.other = other;
|
||||
}
|
||||
|
||||
static ProblemReport of(List<Problem> problems) {
|
||||
Map<String, Group> byMissing = new TreeMap<>();
|
||||
List<String> other = new ArrayList<>();
|
||||
for (Problem problem : problems) {
|
||||
if (problem.getSeverity() != ProblemSeverity.ERROR) {
|
||||
continue;
|
||||
}
|
||||
String text = render(problem);
|
||||
String site = site(problem.getLocation());
|
||||
Object[] params = problem.getParams();
|
||||
if (params != null && params.length > 0 && params[0] != null) {
|
||||
String missing = String.valueOf(params[0]);
|
||||
String kind = kind(problem.getText());
|
||||
byMissing
|
||||
.computeIfAbsent(kind + " " + missing, key -> new Group(missing, kind, new ArrayList<>()))
|
||||
.sites()
|
||||
.add(site);
|
||||
} else {
|
||||
other.add(text + " at " + site);
|
||||
}
|
||||
}
|
||||
List<Group> groups = new ArrayList<>(byMissing.values());
|
||||
groups.sort(Comparator.comparingInt((Group g) -> g.sites().size())
|
||||
.reversed()
|
||||
.thenComparing(Group::missing));
|
||||
return new ProblemReport(groups, other);
|
||||
}
|
||||
|
||||
private static String kind(String text) {
|
||||
if (text.startsWith("Class")) {
|
||||
return "class";
|
||||
}
|
||||
if (text.startsWith("Method")) {
|
||||
return "method";
|
||||
}
|
||||
if (text.startsWith("Field")) {
|
||||
return "field";
|
||||
}
|
||||
return "other";
|
||||
}
|
||||
|
||||
private static String render(Problem problem) {
|
||||
Matcher matcher = PLACEHOLDER.matcher(problem.getText());
|
||||
StringBuilder out = new StringBuilder();
|
||||
while (matcher.find()) {
|
||||
int index = Integer.parseInt(matcher.group(1));
|
||||
Object[] params = problem.getParams();
|
||||
String value = params != null && index < params.length ? String.valueOf(params[index]) : "?";
|
||||
matcher.appendReplacement(out, Matcher.quoteReplacement(value));
|
||||
}
|
||||
matcher.appendTail(out);
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static String site(CallLocation location) {
|
||||
if (location == null || location.getMethod() == null) {
|
||||
return "(unknown)";
|
||||
}
|
||||
return location.getMethod().getClassName() + "#" + location.getMethod().getName();
|
||||
}
|
||||
|
||||
String summary(int limit) {
|
||||
StringBuilder out = new StringBuilder("Link errors by what's missing (most call sites first):\n");
|
||||
for (Group group : groups.subList(0, Math.min(limit, groups.size()))) {
|
||||
out.append(String.format(
|
||||
" %4d %-6s %s (e.g. %s)%n",
|
||||
group.sites().size(),
|
||||
group.kind(),
|
||||
group.missing(),
|
||||
group.sites().getFirst()));
|
||||
}
|
||||
if (groups.size() > limit) {
|
||||
out.append(" ... and ").append(groups.size() - limit).append(" more\n");
|
||||
}
|
||||
if (!other.isEmpty()) {
|
||||
out.append(" ").append(other.size()).append(" other errors\n");
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
void write(Path file) throws IOException {
|
||||
List<String> lines = new ArrayList<>();
|
||||
for (Group group : groups) {
|
||||
lines.add(
|
||||
group.kind() + " " + group.missing() + " (" + group.sites().size() + " sites)");
|
||||
group.sites().stream().distinct().sorted().forEach(site -> lines.add(" " + site));
|
||||
}
|
||||
other.forEach(line -> lines.add("other: " + line));
|
||||
Files.write(file, lines, StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* A minimal client for a Minecraft server's remote console (RCON), so a browser check can make the
|
||||
* server act on the player while the page runs: a dimension change, a transfer, a kick.
|
||||
*
|
||||
* <p>The protocol is Source RCON: little-endian length, request id and type, then an ASCII body
|
||||
* ending in two zero bytes. Type 3 logs in, type 2 runs a command, and the server answers each
|
||||
* with the request's id (a failed login answers id -1). A command's reply is read in one packet,
|
||||
* which is enough for the short replies checks use.
|
||||
*/
|
||||
final class Rcon implements AutoCloseable {
|
||||
|
||||
private static final int LOGIN = 3;
|
||||
private static final int COMMAND = 2;
|
||||
|
||||
private final Socket socket;
|
||||
private final DataInputStream in;
|
||||
private final OutputStream out;
|
||||
private int nextId = 1;
|
||||
|
||||
private Rcon(Socket socket) throws IOException {
|
||||
this.socket = socket;
|
||||
this.in = new DataInputStream(socket.getInputStream());
|
||||
this.out = socket.getOutputStream();
|
||||
}
|
||||
|
||||
/** Connects to {@code host:port} and logs in with {@code password}. */
|
||||
static Rcon connect(String address, String password) throws IOException {
|
||||
int colon = address.lastIndexOf(':');
|
||||
if (colon < 0) {
|
||||
throw new CliException("RCON address '" + address + "' needs a port (host:port)");
|
||||
}
|
||||
Socket socket = new Socket();
|
||||
socket.connect(
|
||||
new InetSocketAddress(address.substring(0, colon), Integer.parseInt(address.substring(colon + 1))),
|
||||
5000);
|
||||
socket.setSoTimeout(10_000);
|
||||
Rcon rcon = new Rcon(socket);
|
||||
try {
|
||||
int id = rcon.send(LOGIN, password);
|
||||
if (rcon.receive().id() != id) {
|
||||
throw new CliException("RCON login to " + address + " was refused (check the password)");
|
||||
}
|
||||
} catch (IOException | RuntimeException e) {
|
||||
rcon.close();
|
||||
throw e;
|
||||
}
|
||||
return rcon;
|
||||
}
|
||||
|
||||
/** Runs a server command and returns the server's reply. */
|
||||
String command(String command) throws IOException {
|
||||
int id = send(COMMAND, command);
|
||||
Packet reply = receive();
|
||||
if (reply.id() != id) {
|
||||
throw new IOException("RCON reply for request " + reply.id() + ", expected " + id);
|
||||
}
|
||||
return reply.body();
|
||||
}
|
||||
|
||||
private int send(int type, String body) throws IOException {
|
||||
int id = nextId++;
|
||||
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||
ByteBuffer packet = ByteBuffer.allocate(4 + 4 + 4 + bytes.length + 2).order(ByteOrder.LITTLE_ENDIAN);
|
||||
packet.putInt(4 + 4 + bytes.length + 2)
|
||||
.putInt(id)
|
||||
.putInt(type)
|
||||
.put(bytes)
|
||||
.put((byte) 0)
|
||||
.put((byte) 0);
|
||||
out.write(packet.array());
|
||||
out.flush();
|
||||
return id;
|
||||
}
|
||||
|
||||
private Packet receive() throws IOException {
|
||||
int length = Integer.reverseBytes(in.readInt());
|
||||
if (length < 10 || length > 1 << 20) {
|
||||
throw new IOException("RCON packet of " + length + " bytes");
|
||||
}
|
||||
byte[] bytes = new byte[length];
|
||||
in.readFully(bytes);
|
||||
ByteBuffer packet = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
|
||||
int id = packet.getInt();
|
||||
packet.getInt(); // The type: a reply's is 0, a login's 2, and the id tells them apart already.
|
||||
return new Packet(id, new String(bytes, 8, length - 10, StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
socket.close();
|
||||
}
|
||||
|
||||
private record Packet(int id, String body) {}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import org.teavm.extension.introspect.IntrospectClass;
|
||||
import org.teavm.extension.spi.reflection.SimpleReflectionPolicy;
|
||||
|
||||
/**
|
||||
* The few members libraries look up by reflection on paths the browser build keeps, declared so
|
||||
* TeaVM compiles their metadata (it keeps none by default).
|
||||
*
|
||||
* <p>Netty's buffer classes name methods for {@code ResourceLeakDetector.addExclusions} in their
|
||||
* static initializers, which finds them with {@code getDeclaredMethods()} and throws when one is
|
||||
* missing: without these, the first buffer allocation fails.
|
||||
*
|
||||
* <p>Registered in {@code META-INF/services}; TeaVM loads it from the compile's class loader.
|
||||
*/
|
||||
public final class ReflectionDeclarations extends SimpleReflectionPolicy {
|
||||
|
||||
@Override
|
||||
protected void setup() {
|
||||
type("io.netty.buffer.AbstractByteBufAllocator").reflectableMethods(named("toLeakAwareBuffer"));
|
||||
type("io.netty.buffer.AdvancedLeakAwareByteBuf")
|
||||
.reflectableMethods(named("touch").or(named("recordLeakNonRefCountingOperation")));
|
||||
type("io.netty.util.ReferenceCountUtil").reflectableMethods(named("touch"));
|
||||
// Singleplayer's in-memory connection: Netty's bootstraps make the channels from their
|
||||
// classes (ReflectiveChannelFactory: getConstructor().newInstance()), the server's in
|
||||
// ServerConnectionListener.startMemoryChannel and the client's in Connection.connectToLocalServer.
|
||||
type("io.netty.channel.local.LocalServerChannel").reflectableMethods(named("<init>"));
|
||||
type("io.netty.channel.local.LocalChannel").reflectableMethods(named("<init>"));
|
||||
// The game's client channel, which vanilla bootstraps still name by class: the server
|
||||
// list's legacy ping (ServerStatusPinger.pingLegacyServer, after a failed ping) and
|
||||
// Connection.connect for a plain address. Without it they throw instead of failing to
|
||||
// connect, and the legacy ping runs on the game thread: the game crashed on the "Saving
|
||||
// world" screen every time the server list opened with a server it couldn't ping.
|
||||
type("incari.client.net.PlatformSocketChannel").reflectableMethods(named("<init>"));
|
||||
// The ender dragon's phases are made by reflection (EnderDragonPhase.createInstance:
|
||||
// getConstructor(EnderDragon.class).newInstance), when a dragon is created: on the client,
|
||||
// as soon as the player sees one in the End (the screenshot scenes found it).
|
||||
selectClasses((IntrospectClass<?> cls) -> cls != null
|
||||
&& cls.name().startsWith(DRAGON_PHASES + "Dragon")
|
||||
&& cls.name().endsWith("Phase"))
|
||||
.reflectableMethods(named("<init>"));
|
||||
}
|
||||
|
||||
private static final String DRAGON_PHASES = "net.minecraft.world.entity.boss.enderdragon.phases.";
|
||||
|
||||
/**
|
||||
* Not {@code selectClass}: TeaVM also asks policies about classes it couldn't introspect,
|
||||
* passing null, which {@code selectClass}'s predicate doesn't expect.
|
||||
*/
|
||||
private ClassPolicy type(String name) {
|
||||
return selectClasses(
|
||||
(IntrospectClass<?> cls) -> cls != null && cls.name().equals(name));
|
||||
}
|
||||
}
|
||||
+478
@@ -0,0 +1,478 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.survey.Finding;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.model.BasicBlock;
|
||||
import org.teavm.model.ClassHierarchy;
|
||||
import org.teavm.model.ClassHolder;
|
||||
import org.teavm.model.ClassHolderTransformer;
|
||||
import org.teavm.model.ClassHolderTransformerContext;
|
||||
import org.teavm.model.FieldReference;
|
||||
import org.teavm.model.Instruction;
|
||||
import org.teavm.model.MethodDescriptor;
|
||||
import org.teavm.model.MethodHolder;
|
||||
import org.teavm.model.MethodReference;
|
||||
import org.teavm.model.Program;
|
||||
import org.teavm.model.TryCatchBlock;
|
||||
import org.teavm.model.ValueType;
|
||||
import org.teavm.model.Variable;
|
||||
import org.teavm.model.instructions.AbstractInstructionVisitor;
|
||||
import org.teavm.model.instructions.CastInstruction;
|
||||
import org.teavm.model.instructions.ClassConstantInstruction;
|
||||
import org.teavm.model.instructions.ConstructArrayInstruction;
|
||||
import org.teavm.model.instructions.ConstructInstruction;
|
||||
import org.teavm.model.instructions.ConstructMultiArrayInstruction;
|
||||
import org.teavm.model.instructions.DoubleConstantInstruction;
|
||||
import org.teavm.model.instructions.FloatConstantInstruction;
|
||||
import org.teavm.model.instructions.GetFieldInstruction;
|
||||
import org.teavm.model.instructions.InitClassInstruction;
|
||||
import org.teavm.model.instructions.IntegerConstantInstruction;
|
||||
import org.teavm.model.instructions.InvocationType;
|
||||
import org.teavm.model.instructions.InvokeInstruction;
|
||||
import org.teavm.model.instructions.IsInstanceInstruction;
|
||||
import org.teavm.model.instructions.LongConstantInstruction;
|
||||
import org.teavm.model.instructions.NullConstantInstruction;
|
||||
import org.teavm.model.instructions.PutFieldInstruction;
|
||||
import org.teavm.model.instructions.StringConstantInstruction;
|
||||
|
||||
/**
|
||||
* Removes references to missing symbols that {@link Removals} says go, as TeaVM loads each class.
|
||||
*
|
||||
* <p>A reference to be thrown becomes a call to {@code incari.classlib.Removed.reference}, which
|
||||
* throws; a stripped one (a deleted feature) just goes. Either way, whatever value the instruction
|
||||
* produced becomes a default (null, zero), so the code after it stays well-formed, and a stripped
|
||||
* feature's calls on that null are stripped too. Three cases never throw: {@code instanceof} a removed
|
||||
* class is false (nothing can be one), its class literal is a class nothing is an instance of, and a
|
||||
* {@code catch} of one catches a type nothing throws. A
|
||||
* missing supertype is dropped (an interface) or becomes {@code Object} (a superclass).
|
||||
*
|
||||
* <p>TeaVM instantiates transformers by class name, so {@link Main} hands the rules over through
|
||||
* {@link #removals}. One compile runs at a time.
|
||||
*/
|
||||
public final class RemovalTransformer implements ClassHolderTransformer {
|
||||
|
||||
static volatile @Nullable Removals removals;
|
||||
|
||||
private static final String REMOVED = "incari.classlib.Removed";
|
||||
private static final MethodReference REFERENCE =
|
||||
new MethodReference(REMOVED, "reference", ValueType.object("java.lang.String"), ValueType.VOID);
|
||||
private static final String NEVER = REMOVED + "$Never";
|
||||
private static final java.util.regex.Pattern GENERATED =
|
||||
java.util.regex.Pattern.compile("\\$lambda\\$_\\d+_\\d+$|\\$_AtomicUpdater\\$$|\\$\\$_impl$");
|
||||
private static final String ABSENT = REMOVED + "$Absent";
|
||||
|
||||
/**
|
||||
* Whether TeaVM generates this class: for a lambda ({@code Owner$method$lambda$_1_0}), for
|
||||
* an atomic field updater ({@code Owner$field$_AtomicUpdater$}, which replaces
|
||||
* {@code AtomicIntegerFieldUpdater.newUpdater} and its kind), or for an annotation read at run
|
||||
* time ({@code Annotation$$_impl}). It does so after transformers run, so the class source
|
||||
* doesn't have it yet; it isn't missing. Treating updaters as missing broke Netty's reference
|
||||
* counts, so every buffer; treating annotation classes as missing broke Netty's
|
||||
* {@code @Sharable} check, so every pipeline.
|
||||
*/
|
||||
static boolean isGenerated(String className) {
|
||||
return GENERATED.matcher(className).find();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void transformClass(ClassHolder cls, ClassHolderTransformerContext context) {
|
||||
Removals current = removals;
|
||||
if (current == null || cls.getName().startsWith(REMOVED)) {
|
||||
return;
|
||||
}
|
||||
new Pass(cls, context.getHierarchy(), current).run();
|
||||
}
|
||||
|
||||
private static final class Pass extends AbstractInstructionVisitor {
|
||||
private final ClassHolder cls;
|
||||
private final ClassHierarchy hierarchy;
|
||||
private final Removals removals;
|
||||
|
||||
Pass(ClassHolder cls, ClassHierarchy hierarchy, Removals removals) {
|
||||
this.cls = cls;
|
||||
this.hierarchy = hierarchy;
|
||||
this.removals = removals;
|
||||
}
|
||||
|
||||
void run() {
|
||||
removeSupertypes();
|
||||
for (MethodHolder method : cls.getMethods()) {
|
||||
Program program = method.getProgram();
|
||||
if (program == null) {
|
||||
continue;
|
||||
}
|
||||
for (int i = 0; i < program.basicBlockCount(); i++) {
|
||||
BasicBlock block = program.basicBlockAt(i);
|
||||
List<Instruction> instructions = new ArrayList<>();
|
||||
block.forEach(instructions::add);
|
||||
for (Instruction instruction : instructions) {
|
||||
instruction.acceptVisitor(this);
|
||||
}
|
||||
for (TryCatchBlock tryCatch : block.getTryCatchBlocks()) {
|
||||
String type = tryCatch.getExceptionType();
|
||||
if (type != null && removedClass(type) != null) {
|
||||
tryCatch.setExceptionType(NEVER);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void removeSupertypes() {
|
||||
String parent = cls.getParent();
|
||||
if (parent != null && isMissing(parent) && removedSupertype(parent) != null) {
|
||||
cls.setParent("java.lang.Object");
|
||||
}
|
||||
for (String iface : List.copyOf(cls.getInterfaces())) {
|
||||
if (isMissing(iface) && removedSupertype(iface) != null) {
|
||||
cls.getInterfaces().remove(iface);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Removals.@Nullable Removal removedSupertype(String className) {
|
||||
return removals.removal(Finding.Kind.MISSING_SUPERTYPE, className, cls.getName());
|
||||
}
|
||||
|
||||
// --- What's missing --------------------------------------------------------------------
|
||||
|
||||
private boolean isMissing(String className) {
|
||||
return !isGenerated(className) && hierarchy.getClassSource().get(className) == null;
|
||||
}
|
||||
|
||||
/** How a reference to this class goes, or null if the class exists or stays an error. */
|
||||
private Removals.@Nullable Removal removedClass(String className) {
|
||||
return isMissing(className)
|
||||
? removals.removal(removals.missingClassKind(className), className, cls.getName())
|
||||
: null;
|
||||
}
|
||||
|
||||
private Removals.@Nullable Removal removedType(ValueType type) {
|
||||
ValueType item = type;
|
||||
while (item instanceof ValueType.Array array) {
|
||||
item = array.getItemType();
|
||||
}
|
||||
return item instanceof ValueType.Object object ? removedClass(object.getClassName()) : null;
|
||||
}
|
||||
|
||||
private Removals.@Nullable Removal removedMethod(MethodReference method) {
|
||||
String owner = method.getClassName();
|
||||
if (isGenerated(owner)) {
|
||||
return null;
|
||||
}
|
||||
String symbol = owner + "#" + method.getName();
|
||||
if (isMissing(owner)) {
|
||||
return removals.removal(removals.missingClassKind(owner), symbol, cls.getName());
|
||||
}
|
||||
return hierarchy.resolve(method) == null && !providedLater(method)
|
||||
? removals.removal(Finding.Kind.MISSING_METHOD, symbol, cls.getName())
|
||||
: null;
|
||||
}
|
||||
|
||||
private Removals.@Nullable Removal removedField(FieldReference field) {
|
||||
String owner = field.getClassName();
|
||||
if (isGenerated(owner)) {
|
||||
return null;
|
||||
}
|
||||
String symbol = owner + "#" + field.getFieldName();
|
||||
if (isMissing(owner)) {
|
||||
return removals.removal(removals.missingClassKind(owner), symbol, cls.getName());
|
||||
}
|
||||
return hasField(owner, field.getFieldName())
|
||||
? null
|
||||
: removals.removal(Finding.Kind.MISSING_FIELD, symbol, cls.getName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the build provides a method the hierarchy doesn't show. The hierarchy reads
|
||||
* classes before this compile's transformers run: a substitute's signatures still name
|
||||
* other substitutes by their {@code T} names, and additions aren't merged in yet.
|
||||
*/
|
||||
private boolean providedLater(MethodReference method) {
|
||||
MethodDescriptor wanted = method.getDescriptor();
|
||||
java.util.ArrayDeque<String> pending = new java.util.ArrayDeque<>();
|
||||
java.util.Set<String> seen = new java.util.HashSet<>();
|
||||
pending.add(method.getClassName());
|
||||
while (!pending.isEmpty()) {
|
||||
String name = pending.removeFirst();
|
||||
if (!seen.add(name)) {
|
||||
continue;
|
||||
}
|
||||
if (hasAddition(name, wanted)) {
|
||||
return true;
|
||||
}
|
||||
org.teavm.model.ClassReader reader = hierarchy.getClassSource().get(name);
|
||||
if (reader == null) {
|
||||
continue;
|
||||
}
|
||||
for (org.teavm.model.MethodReader candidate : reader.getMethods()) {
|
||||
if (candidate.getName().equals(wanted.getName())
|
||||
&& AdditionsTransformer.originalNames(candidate.getDescriptor())
|
||||
.equals(wanted)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (reader.getParent() != null) {
|
||||
pending.add(reader.getParent());
|
||||
}
|
||||
pending.addAll(reader.getInterfaces());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Whether {@code className}'s additions class adds {@code wanted}, static or instance. */
|
||||
private boolean hasAddition(String className, MethodDescriptor wanted) {
|
||||
org.teavm.model.ClassReader additions =
|
||||
hierarchy.getClassSource().get(AdditionsTransformer.PACKAGE + "." + className + "Additions");
|
||||
if (additions == null) {
|
||||
return false;
|
||||
}
|
||||
for (org.teavm.model.MethodReader addition : additions.getMethods()) {
|
||||
MethodDescriptor added = AdditionsTransformer.originalNames(addition.getDescriptor());
|
||||
if (addition.getAnnotations().get(AdditionsTransformer.CONSTRUCTOR) != null) {
|
||||
if (AdditionsTransformer.asConstructor(added).equals(wanted)) {
|
||||
return true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!addition.getName().equals(wanted.getName())) {
|
||||
continue;
|
||||
}
|
||||
if (addition.getAnnotations().get(AdditionsTransformer.INSTANCE_METHOD) != null) {
|
||||
added = AdditionsTransformer.dropReceiver(added);
|
||||
}
|
||||
if (added.equals(wanted)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the class or a supertype declares the field. Not {@code ClassHierarchy.resolve}:
|
||||
* in TeaVM it only looks at supertypes, never the class's own fields.
|
||||
*/
|
||||
private boolean hasField(String className, String fieldName) {
|
||||
java.util.ArrayDeque<String> pending = new java.util.ArrayDeque<>();
|
||||
java.util.Set<String> seen = new java.util.HashSet<>();
|
||||
pending.add(className);
|
||||
while (!pending.isEmpty()) {
|
||||
String name = pending.removeFirst();
|
||||
if (!seen.add(name)) {
|
||||
continue;
|
||||
}
|
||||
org.teavm.model.ClassReader reader = hierarchy.getClassSource().get(name);
|
||||
if (reader == null) {
|
||||
continue;
|
||||
}
|
||||
if (reader.getField(fieldName) != null) {
|
||||
return true;
|
||||
}
|
||||
if (reader.getParent() != null) {
|
||||
pending.add(reader.getParent());
|
||||
}
|
||||
pending.addAll(reader.getInterfaces());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// --- Instructions ----------------------------------------------------------------------
|
||||
|
||||
@Override
|
||||
public void visit(InvokeInstruction insn) {
|
||||
MethodReference method = insn.getMethod();
|
||||
Removals.Removal removal = removedMethod(method);
|
||||
if (removal != null) {
|
||||
replace(
|
||||
insn,
|
||||
removal,
|
||||
method.getClassName() + "#" + method.getName(),
|
||||
insn.getReceiver(),
|
||||
method.getReturnType());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(ConstructInstruction insn) {
|
||||
Removals.Removal removal = removedClass(insn.getType());
|
||||
if (removal != null) {
|
||||
replace(insn, removal, insn.getType(), insn.getReceiver(), ValueType.object(insn.getType()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(GetFieldInstruction insn) {
|
||||
Removals.Removal removal = removedField(insn.getField());
|
||||
if (removal != null) {
|
||||
replace(insn, removal, insn.getField().toString(), insn.getReceiver(), insn.getFieldType());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(PutFieldInstruction insn) {
|
||||
Removals.Removal removal = removedField(insn.getField());
|
||||
if (removal != null) {
|
||||
replace(insn, removal, insn.getField().toString(), null, null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(InitClassInstruction insn) {
|
||||
Removals.Removal removal = removedClass(insn.getClassName());
|
||||
if (removal != null) {
|
||||
replace(insn, removal, insn.getClassName(), null, null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(CastInstruction insn) {
|
||||
Removals.Removal removal = removedType(insn.getTargetType());
|
||||
if (removal != null) {
|
||||
replace(insn, removal, insn.getTargetType().toString(), insn.getReceiver(), insn.getTargetType());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(ClassConstantInstruction insn) {
|
||||
if (removedType(insn.getConstant()) != null) {
|
||||
// Libraries register handlers by class literal (Gson's adapter for InetAddress).
|
||||
// A class nothing can be an instance of keeps those registrations harmless.
|
||||
insn.setConstant(absent(insn.getConstant()));
|
||||
}
|
||||
}
|
||||
|
||||
private static ValueType absent(ValueType type) {
|
||||
return type instanceof ValueType.Array array
|
||||
? ValueType.arrayOf(absent(array.getItemType()))
|
||||
: ValueType.object(ABSENT);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(ConstructArrayInstruction insn) {
|
||||
Removals.Removal removal = removedType(insn.getItemType());
|
||||
if (removal != null) {
|
||||
replace(
|
||||
insn,
|
||||
removal,
|
||||
insn.getItemType().toString(),
|
||||
insn.getReceiver(),
|
||||
ValueType.arrayOf(insn.getItemType()));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(ConstructMultiArrayInstruction insn) {
|
||||
Removals.Removal removal = removedType(insn.getItemType());
|
||||
if (removal != null) {
|
||||
replace(insn, removal, insn.getItemType().toString(), insn.getReceiver(), insn.getItemType());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(IsInstanceInstruction insn) {
|
||||
if (removedType(insn.getType()) != null) {
|
||||
// Nothing is an instance of a class that isn't there.
|
||||
IntegerConstantInstruction no = new IntegerConstantInstruction();
|
||||
no.setConstant(0);
|
||||
no.setReceiver(insn.getReceiver());
|
||||
no.setLocation(insn.getLocation());
|
||||
insn.replace(no);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes {@code insn}: throws where it was (unless stripped), then gives its result, if
|
||||
* any, a default value.
|
||||
*/
|
||||
private void replace(
|
||||
Instruction insn,
|
||||
Removals.Removal removal,
|
||||
String symbol,
|
||||
@Nullable Variable result,
|
||||
@Nullable ValueType type) {
|
||||
if (removal == Removals.Removal.THROW) {
|
||||
Program program = insn.getProgram();
|
||||
StringConstantInstruction name = new StringConstantInstruction();
|
||||
name.setConstant(symbol);
|
||||
name.setReceiver(program.createVariable());
|
||||
name.setLocation(insn.getLocation());
|
||||
InvokeInstruction fail = new InvokeInstruction();
|
||||
fail.setType(InvocationType.SPECIAL);
|
||||
fail.setMethod(REFERENCE);
|
||||
fail.setArguments(name.getReceiver());
|
||||
fail.setLocation(insn.getLocation());
|
||||
insn.insertPrevious(name);
|
||||
insn.insertPrevious(fail);
|
||||
}
|
||||
if (result == null || type == null) {
|
||||
insn.delete();
|
||||
return;
|
||||
}
|
||||
if (type instanceof ValueType.Primitive) {
|
||||
Instruction value = defaultValue(result, type);
|
||||
value.setLocation(insn.getLocation());
|
||||
insn.replace(value);
|
||||
return;
|
||||
}
|
||||
// A typed null: an untyped one leaves TeaVM to infer the variable's type from its other
|
||||
// uses, which can be a supertype the rest of the code can't pass on (a ByteBuffer from a
|
||||
// removed allocator typed as Buffer). Only a class that exists can be cast to.
|
||||
if (!isRemovedOrMissing(type)) {
|
||||
NullConstantInstruction none = new NullConstantInstruction();
|
||||
none.setReceiver(insn.getProgram().createVariable());
|
||||
none.setLocation(insn.getLocation());
|
||||
insn.insertPrevious(none);
|
||||
CastInstruction typed = new CastInstruction();
|
||||
typed.setValue(none.getReceiver());
|
||||
typed.setTargetType(type);
|
||||
typed.setReceiver(result);
|
||||
typed.setLocation(insn.getLocation());
|
||||
insn.replace(typed);
|
||||
return;
|
||||
}
|
||||
Instruction value = defaultValue(result, type);
|
||||
value.setLocation(insn.getLocation());
|
||||
insn.replace(value);
|
||||
}
|
||||
|
||||
private boolean isRemovedOrMissing(ValueType type) {
|
||||
ValueType item = type;
|
||||
while (item instanceof ValueType.Array array) {
|
||||
item = array.getItemType();
|
||||
}
|
||||
return item instanceof ValueType.Object object && isMissing(object.getClassName());
|
||||
}
|
||||
|
||||
private static Instruction defaultValue(Variable receiver, ValueType type) {
|
||||
if (!(type instanceof ValueType.Primitive primitive)) {
|
||||
NullConstantInstruction none = new NullConstantInstruction();
|
||||
none.setReceiver(receiver);
|
||||
return none;
|
||||
}
|
||||
return switch (primitive.getKind()) {
|
||||
case LONG -> {
|
||||
LongConstantInstruction zero = new LongConstantInstruction();
|
||||
zero.setReceiver(receiver);
|
||||
yield zero;
|
||||
}
|
||||
case FLOAT -> {
|
||||
FloatConstantInstruction zero = new FloatConstantInstruction();
|
||||
zero.setReceiver(receiver);
|
||||
yield zero;
|
||||
}
|
||||
case DOUBLE -> {
|
||||
DoubleConstantInstruction zero = new DoubleConstantInstruction();
|
||||
zero.setReceiver(receiver);
|
||||
yield zero;
|
||||
}
|
||||
default -> {
|
||||
IntegerConstantInstruction zero = new IntegerConstantInstruction();
|
||||
zero.setReceiver(receiver);
|
||||
yield zero;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.survey.Finding;
|
||||
import incari.tools.survey.Origins;
|
||||
import incari.tools.survey.SurveyRules;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Decides which missing symbols the browser build removes, and keeps the list of what it removed.
|
||||
*
|
||||
* <p>The decision is the survey's: {@code tools/survey/rules.txt} files every API the browser lacks
|
||||
* under stub, shim, rewrite or delete. References to missing symbols filed under <em>delete</em>
|
||||
* (features the browser build drops) or <em>rewrite</em> (code to be replaced) are
|
||||
* removed; stub and shim symbols get real code in {@code web-classlib}, so a missing one of those
|
||||
* stays a link error. Symbols that exist are never touched, however a rule matches them.
|
||||
*
|
||||
* <p>How a reference is removed follows the category. A deleted feature is stripped: calls into it
|
||||
* vanish and anything it would have produced is null or zero, so the game carries on without it
|
||||
* (a profiler, telemetry, Realms). Code awaiting a rewrite throws where it's reached, so unported
|
||||
* code fails loudly rather than misbehaving quietly.
|
||||
*/
|
||||
final class Removals {
|
||||
|
||||
private final SurveyRules rules;
|
||||
private final Origins origins;
|
||||
// rule reason -> symbol -> callers
|
||||
private final Map<String, Map<String, Map<String, Integer>>> removed = new TreeMap<>();
|
||||
|
||||
Removals(SurveyRules rules, Origins origins) {
|
||||
this.rules = rules;
|
||||
this.origins = origins;
|
||||
}
|
||||
|
||||
/** How a reference goes: it throws where it was (rewrite), or it's stripped (delete). */
|
||||
enum Removal {
|
||||
THROW,
|
||||
STRIP
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to remove a reference to a missing symbol, and how; null leaves it (and it fails the
|
||||
* link).
|
||||
*
|
||||
* @param symbol {@code pkg.Class} or {@code pkg.Class#member}
|
||||
* @param caller the class holding the reference
|
||||
*/
|
||||
synchronized @Nullable Removal removal(Finding.Kind kind, String symbol, String caller) {
|
||||
Finding finding = new Finding(kind, symbol, "", caller, null, -1, null);
|
||||
SurveyRules.TriageRule rule = rules.classify(finding, kind.ruleName(), origins.of(caller));
|
||||
if (rule == null
|
||||
|| (rule.category() != SurveyRules.Category.DELETE
|
||||
&& rule.category() != SurveyRules.Category.REWRITE)) {
|
||||
return null;
|
||||
}
|
||||
removed.computeIfAbsent(rule.reason(), r -> new TreeMap<>())
|
||||
.computeIfAbsent(symbol, s -> new TreeMap<>())
|
||||
.merge(origins.appClass(caller), 1, Integer::sum);
|
||||
return rule.category() == SurveyRules.Category.DELETE ? Removal.STRIP : Removal.THROW;
|
||||
}
|
||||
|
||||
/** How a missing class is filed: a JDK class TeaVM lacks, or one no jar provides. */
|
||||
synchronized Finding.Kind missingClassKind(String className) {
|
||||
return Origins.HOST_JDK.equals(origins.of(className)) ? Finding.Kind.HOST_JDK : Finding.Kind.MISSING_CLASS;
|
||||
}
|
||||
|
||||
synchronized int count() {
|
||||
int count = 0;
|
||||
for (Map<String, Map<String, Integer>> symbols : removed.values()) {
|
||||
for (Map<String, Integer> callers : symbols.values()) {
|
||||
for (int n : callers.values()) {
|
||||
count += n;
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/** Writes every removed reference, grouped by the rule that removed it. */
|
||||
synchronized void write(Path file) throws IOException {
|
||||
List<String> lines = new ArrayList<>();
|
||||
lines.add("# References the browser build removed: reaching one at run time throws.");
|
||||
lines.add("# Grouped by the tools/survey/rules.txt entry (delete or rewrite) that removed them.");
|
||||
for (Map.Entry<String, Map<String, Map<String, Integer>>> group : removed.entrySet()) {
|
||||
lines.add("");
|
||||
lines.add(group.getKey());
|
||||
for (Map.Entry<String, Map<String, Integer>> symbol :
|
||||
group.getValue().entrySet()) {
|
||||
lines.add(" " + symbol.getKey());
|
||||
for (Map.Entry<String, Integer> caller : symbol.getValue().entrySet()) {
|
||||
lines.add(" from " + caller.getKey()
|
||||
+ (caller.getValue() > 1 ? " (" + caller.getValue() + ")" : ""));
|
||||
}
|
||||
}
|
||||
}
|
||||
Files.write(file, lines);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A game the screenshot-diff harness drives through its scenes: the desktop game over its scene
|
||||
* agent ({@link DesktopSceneClient}) or the browser build over the DevTools protocol
|
||||
* ({@link BrowserSceneClient}). Both take the same steps, so both render the same scene.
|
||||
*/
|
||||
interface SceneClient extends AutoCloseable {
|
||||
|
||||
/** "desktop" or "browser": the directory its screenshots go to. */
|
||||
String name();
|
||||
|
||||
/** Waits until the player is in the world with no screen open (the server already lists them). */
|
||||
void awaitWorld() throws IOException, InterruptedException;
|
||||
|
||||
/** Presses the keys of a chord in order and releases them in reverse ({@code KeyboardEvent.code} names). */
|
||||
void key(List<String> chord) throws IOException, InterruptedException;
|
||||
|
||||
/** Moves the pointer to a position in fractions of the window. */
|
||||
void move(double x, double y) throws IOException, InterruptedException;
|
||||
|
||||
/** Moves the pointer there and clicks the left button. */
|
||||
void click(double x, double y) throws IOException, InterruptedException;
|
||||
|
||||
/** What the game shows now, saved as a PNG at {@code file}. */
|
||||
BufferedImage shot(Path file) throws IOException, InterruptedException;
|
||||
|
||||
@Override
|
||||
void close() throws IOException;
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The screenshot-diff harness's scenes, as {@code app-web/screenshot-scenes/scenes.txt}
|
||||
* writes them: a threshold, setup steps run once after the player joins, and named scenes, each a
|
||||
* list of steps ending in one or more screenshots.
|
||||
*
|
||||
* <pre>
|
||||
* threshold 0.90
|
||||
* setup
|
||||
* rcon:tick freeze
|
||||
* key:F1
|
||||
* scene terrain Overworld terrain at noon
|
||||
* rcon:tp IncariShot 10 90 10 45 20
|
||||
* settle
|
||||
* shot:terrain
|
||||
* </pre>
|
||||
*
|
||||
* Steps, the same for the desktop game and the browser: {@code rcon:<command>} (a server
|
||||
* command), {@code key:<chord>} ({@code KeyboardEvent.code} names, as browser check steps write
|
||||
* them), {@code move:<x>,<y>} and {@code click:<x>,<y>} (fractions of the window),
|
||||
* {@code sleep:<ms>}, {@code settle} (wait until the picture stops changing) and
|
||||
* {@code shot:<name>}. A {@code #} starts a comment line.
|
||||
*/
|
||||
record SceneScript(double threshold, List<Step> setup, List<Scene> scenes) {
|
||||
|
||||
/** One step: its kind (the part before the colon), its value, and its line, for messages. */
|
||||
record Step(String kind, String value, int line) {}
|
||||
|
||||
record Scene(String name, String description, List<Step> steps) {
|
||||
/** The names of the screenshots the scene takes, in order. */
|
||||
List<String> shots() {
|
||||
return steps.stream()
|
||||
.filter(step -> step.kind().equals("shot"))
|
||||
.map(Step::value)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
private static final Set<String> KINDS = Set.of("rcon", "key", "move", "click", "sleep", "settle", "shot");
|
||||
|
||||
static SceneScript read(Path file) throws IOException {
|
||||
return parse(Files.readAllLines(file), file.toString());
|
||||
}
|
||||
|
||||
static SceneScript parse(List<String> lines, String source) {
|
||||
double threshold = Double.NaN;
|
||||
List<Step> setup = new ArrayList<>();
|
||||
List<Scene> scenes = new ArrayList<>();
|
||||
@Nullable List<Step> current = null;
|
||||
boolean inSetup = false;
|
||||
String name = "";
|
||||
String description = "";
|
||||
Set<String> shots = new HashSet<>();
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String raw = lines.get(i);
|
||||
String line = raw.strip();
|
||||
int number = i + 1;
|
||||
if (line.isEmpty() || line.startsWith("#")) {
|
||||
continue;
|
||||
}
|
||||
boolean indented = Character.isWhitespace(raw.charAt(0));
|
||||
if (!indented) {
|
||||
if (current != null && !inSetup) {
|
||||
scenes.add(new Scene(name, description, List.copyOf(current)));
|
||||
}
|
||||
String[] words = line.split("\\s+", 3);
|
||||
switch (words[0]) {
|
||||
case "threshold" -> {
|
||||
threshold = Double.parseDouble(words[1]);
|
||||
current = null;
|
||||
inSetup = false;
|
||||
}
|
||||
case "setup" -> {
|
||||
current = setup;
|
||||
inSetup = true;
|
||||
}
|
||||
case "scene" -> {
|
||||
if (words.length < 2) {
|
||||
throw error(source, number, "a scene needs a name");
|
||||
}
|
||||
name = words[1];
|
||||
description = words.length > 2 ? words[2] : "";
|
||||
if (scenes.stream().anyMatch(scene -> scene.name().equals(words[1]))) {
|
||||
throw error(source, number, "scene " + name + " is named twice");
|
||||
}
|
||||
current = new ArrayList<>();
|
||||
inSetup = false;
|
||||
}
|
||||
default -> throw error(source, number, "expected threshold, setup or scene, not '" + line + "'");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (current == null) {
|
||||
throw error(source, number, "a step outside setup or a scene");
|
||||
}
|
||||
int colon = line.indexOf(':');
|
||||
String kind = colon < 0 ? line : line.substring(0, colon);
|
||||
String value = colon < 0 ? "" : line.substring(colon + 1);
|
||||
if (!KINDS.contains(kind)) {
|
||||
throw error(source, number, "unknown step '" + kind + "'");
|
||||
}
|
||||
if (kind.equals("shot")) {
|
||||
if (inSetup) {
|
||||
throw error(source, number, "setup takes no screenshots");
|
||||
}
|
||||
if (!value.matches("[a-z0-9_]+") || !shots.add(value)) {
|
||||
throw error(source, number, "shot names are unique and [a-z0-9_]+: '" + value + "'");
|
||||
}
|
||||
}
|
||||
current.add(new Step(kind, value, number));
|
||||
}
|
||||
if (current != null && !inSetup) {
|
||||
scenes.add(new Scene(name, description, List.copyOf(current)));
|
||||
}
|
||||
if (Double.isNaN(threshold) || threshold <= 0 || threshold > 1) {
|
||||
throw new CliException(source + ": needs a 'threshold <ssim>' between 0 and 1");
|
||||
}
|
||||
return new SceneScript(threshold, List.copyOf(setup), List.copyOf(scenes));
|
||||
}
|
||||
|
||||
private static CliException error(String source, int line, String message) {
|
||||
return new CliException(source + ":" + line + ": " + message);
|
||||
}
|
||||
}
|
||||
+479
@@ -0,0 +1,479 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import incari.tools.wsbridge.WebSocketBridge;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.IOException;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import javax.imageio.ImageIO;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The screenshot-diff harness: renders fixed scenes with the desktop game (Mojang's OpenGL
|
||||
* backend, the reference) and with the browser build (the WebGL2 backend), and compares each pair
|
||||
* of screenshots by SSIM ({@link ImageDiff}) against the scenes file's threshold.
|
||||
*
|
||||
* <p>Both games join the same vanilla server (fresh world, fixed seed; {@link GameServer}), the
|
||||
* browser through the development WebSocket bridge, and take the same steps ({@link SceneScript}):
|
||||
* server commands over RCON place the camera and set time, weather and the scene's blocks and
|
||||
* entities, and keys and clicks go to the game. Every image is rendered on this machine at test
|
||||
* time into {@code --out}: they're pictures of Mojang's assets, never committed.
|
||||
*
|
||||
* <p>It also fails if the page logged a WebGL error or skipped a pipeline while it ran.
|
||||
*
|
||||
* <pre>
|
||||
* screenshot-diff --scenes <scenes.txt> --options <options.txt> --server-properties <file>
|
||||
* --out <dir> --build <teavm dir> --file client.jar=<jar> --file shaders.json=<json>
|
||||
* --desktop-launch <file> --version-json <file> --cache <dir>
|
||||
* [--port 18210] [--gpu gl|vulkan|swiftshader] [--only <scene>,...] [--reuse-desktop]
|
||||
* [--query <extra page options>]
|
||||
* [--chrome <path>]
|
||||
* </pre>
|
||||
*
|
||||
* Ports: the server at {@code --port}, its RCON one above, then the bridge, the desktop game's
|
||||
* scene agent, the page's server and Chromium's DevTools.
|
||||
*/
|
||||
public final class ScreenshotDiff {
|
||||
|
||||
/** The offline player both games join as: the same name gives the same skin. */
|
||||
static final String PLAYER = "IncariShot";
|
||||
|
||||
/** The game time both worlds start the scenes at. */
|
||||
private static final long START_TICK = 40;
|
||||
|
||||
private static final Pattern GAME_TIME = Pattern.compile("(\\d+) tick");
|
||||
|
||||
private static final Pattern TICK_STEP = Pattern.compile("tick step (\\d+)");
|
||||
|
||||
/** Ticks the frozen world runs for a player to join: chunks loaded, generated and lit. */
|
||||
private static final int JOIN_TICKS = 200;
|
||||
|
||||
static final int WIDTH = 1280;
|
||||
static final int HEIGHT = 720;
|
||||
|
||||
/** Two frames at least this alike, a second and a half apart, mean the scene has settled. */
|
||||
private static final double SETTLED = 0.998;
|
||||
|
||||
/** Console messages that fail the run: WebGL errors, and pipelines the backend couldn't draw. */
|
||||
static final Pattern PAGE_ERRORS = Pattern.compile(
|
||||
"(?i).*(GL_INVALID|WebGL: |CONTEXT_LOST|Skipping draws|doesn't compile|doesn't link|is incomplete).*");
|
||||
|
||||
private ScreenshotDiff() {}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
System.exit(run(args));
|
||||
} catch (CliException e) {
|
||||
System.err.println("error: " + e.getMessage());
|
||||
System.exit(1);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
private record Options(
|
||||
Path scenes,
|
||||
Path options,
|
||||
Path serverProperties,
|
||||
Path out,
|
||||
Path build,
|
||||
Map<String, Path> files,
|
||||
Path desktopLaunch,
|
||||
Path versionJson,
|
||||
Path cache,
|
||||
int port,
|
||||
Chromium.Gpu gpu,
|
||||
Set<String> only,
|
||||
boolean reuseDesktop,
|
||||
@Nullable String chrome,
|
||||
String query) {}
|
||||
|
||||
static int run(String[] args) throws IOException, InterruptedException {
|
||||
Options options = parse(args);
|
||||
SceneScript script = SceneScript.read(options.scenes());
|
||||
List<SceneScript.Scene> scenes = script.scenes().stream()
|
||||
.filter(scene -> options.only().isEmpty() || options.only().contains(scene.name()))
|
||||
.toList();
|
||||
if (scenes.isEmpty()) {
|
||||
throw new CliException("No scenes to run (--only " + String.join(",", options.only()) + ")");
|
||||
}
|
||||
Path out = options.out();
|
||||
Files.createDirectories(out);
|
||||
int port = options.port();
|
||||
List<String> pageErrors = new ArrayList<>();
|
||||
String[] gpu = {"unknown"};
|
||||
List<String> startTimes = new ArrayList<>();
|
||||
if (!options.reuseDesktop() || !allShotsExist(out.resolve("desktop"), scenes)) {
|
||||
Path gameDirectory = out.resolve("desktop-game");
|
||||
Chromium.deleteRecursively(gameDirectory);
|
||||
Files.createDirectories(gameDirectory);
|
||||
Files.copy(options.options(), gameDirectory.resolve("options.txt"));
|
||||
session(options, startTimes, server -> {
|
||||
try (DesktopSceneClient desktop = DesktopSceneClient.start(
|
||||
options.desktopLaunch(), gameDirectory, PLAYER, "127.0.0.1:" + port, port + 3, WIDTH, HEIGHT)) {
|
||||
play(desktop, server, script, scenes, out.resolve("desktop"));
|
||||
}
|
||||
});
|
||||
} else {
|
||||
System.out.println("==> Reusing the desktop screenshots in " + out.resolve("desktop"));
|
||||
}
|
||||
|
||||
// The desktop window is WIDTH x HEIGHT in the desktop's units; on a scaled display (a
|
||||
// Wayland scale of 1.25, say) its framebuffer has more pixels. The page gets exactly as
|
||||
// many, at one device pixel per CSS pixel, so both render the same number of pixels.
|
||||
BufferedImage reference = ImageIO.read(out.resolve("desktop")
|
||||
.resolve(scenes.getFirst().shots().getFirst() + ".png")
|
||||
.toFile());
|
||||
if (reference == null) {
|
||||
throw new IOException("The desktop game's first screenshot isn't readable");
|
||||
}
|
||||
int width = reference.getWidth();
|
||||
int height = reference.getHeight();
|
||||
Map<String, Path> files = new LinkedHashMap<>(options.files());
|
||||
files.put("/options.txt", options.options());
|
||||
String query = "server=ws://127.0.0.1:" + (port + 2) + "&name=" + PLAYER + "&options=options.txt"
|
||||
+ (options.query().isEmpty() ? "" : "&" + options.query());
|
||||
session(options, startTimes, server -> {
|
||||
try (BrowserSceneClient browser = BrowserSceneClient.start(
|
||||
options.build(),
|
||||
files,
|
||||
query,
|
||||
options.chrome(),
|
||||
options.gpu(),
|
||||
port + 4,
|
||||
port + 5,
|
||||
width,
|
||||
height)) {
|
||||
gpu[0] = browser.evaluate("(() => { const g = document.createElement('canvas').getContext('webgl2');"
|
||||
+ " const e = g && g.getExtension('WEBGL_debug_renderer_info');"
|
||||
+ " return e ? g.getParameter(e.UNMASKED_RENDERER_WEBGL) : 'unknown'; })()");
|
||||
System.out.println("==> The browser renders with " + gpu[0]);
|
||||
browser.console().quiet();
|
||||
play(browser, server, script, scenes, out.resolve("browser"));
|
||||
Files.write(
|
||||
out.resolve("browser-console.txt"), browser.console().history());
|
||||
for (String message : browser.console().history()) {
|
||||
if (PAGE_ERRORS.matcher(message).matches()) {
|
||||
pageErrors.add(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
System.out.println("==> Game time each world started the scenes at: " + String.join(", ", startTimes));
|
||||
return report(script, scenes, out, gpu[0], pageErrors);
|
||||
}
|
||||
|
||||
/** What one game does with its server. */
|
||||
@FunctionalInterface
|
||||
private interface Session {
|
||||
void run(GameServer server) throws IOException, InterruptedException;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs one game against a server of its own: a fresh world from the same seed, frozen as soon
|
||||
* as it's up, so each game sees the world at (almost) the same game time and every tick after
|
||||
* that is one the scenes step on purpose. Clouds and animated textures follow the game time,
|
||||
* so the two games only match if their worlds have run the same ticks.
|
||||
*/
|
||||
private static void session(Options options, List<String> startTimes, Session session)
|
||||
throws IOException, InterruptedException {
|
||||
int port = options.port();
|
||||
try (GameServer server = GameServer.start(
|
||||
options.versionJson(),
|
||||
options.cache(),
|
||||
options.out().resolve("server"),
|
||||
options.serverProperties(),
|
||||
port,
|
||||
port + 1);
|
||||
WebSocketBridge bridge = WebSocketBridge.start(
|
||||
new InetSocketAddress(InetAddress.getLoopbackAddress(), port + 2),
|
||||
new InetSocketAddress(InetAddress.getLoopbackAddress(), port),
|
||||
message -> {})) {
|
||||
server.command("tick freeze");
|
||||
startTimes.add(Long.toString(alignGameTime(server)));
|
||||
System.out.println("==> The browser joins through ws://"
|
||||
+ bridge.address().getHostString() + ":" + bridge.address().getPort());
|
||||
session.run(server);
|
||||
awaitLeft(server);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Steps a just-frozen world on to {@link #START_TICK}, so both worlds start the scenes at the
|
||||
* same game time: a server freezes a tick or three after it starts, a different number each
|
||||
* time, and rain and clouds move with the game time. Returns the game time reached.
|
||||
*/
|
||||
private static long alignGameTime(GameServer server) throws IOException, InterruptedException {
|
||||
long now = gameTime(server);
|
||||
if (now > START_TICK) {
|
||||
throw new IOException("The world ran " + now + " ticks before it froze; raise START_TICK");
|
||||
}
|
||||
if (now < START_TICK) {
|
||||
server.command("tick step " + (START_TICK - now));
|
||||
}
|
||||
long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
|
||||
while ((now = gameTime(server)) < START_TICK && System.nanoTime() < until) {
|
||||
Thread.sleep(100);
|
||||
}
|
||||
return now;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs {@code ticks} ticks of the frozen world and waits until they've all run, so every step
|
||||
* is whole: a second {@code tick step} while one is running would replace what's left of it.
|
||||
*/
|
||||
private static String stepTicks(GameServer server, int ticks) throws IOException, InterruptedException {
|
||||
long target = gameTime(server) + ticks;
|
||||
String reply = server.command("tick step " + ticks);
|
||||
long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(30 + ticks / 5);
|
||||
while (gameTime(server) < target) {
|
||||
if (System.nanoTime() > until) {
|
||||
throw new IOException("The world didn't run " + ticks + " ticks in time");
|
||||
}
|
||||
Thread.sleep(100);
|
||||
}
|
||||
return reply;
|
||||
}
|
||||
|
||||
private static long gameTime(GameServer server) throws IOException {
|
||||
Matcher matcher = GAME_TIME.matcher(server.command("time query gametime"));
|
||||
if (!matcher.find()) {
|
||||
throw new IOException("The server didn't say its game time");
|
||||
}
|
||||
return Long.parseLong(matcher.group(1));
|
||||
}
|
||||
|
||||
/** Joins, runs the setup, then every scene, saving each screenshot in {@code directory}. */
|
||||
private static void play(
|
||||
SceneClient client, GameServer server, SceneScript script, List<SceneScript.Scene> scenes, Path directory)
|
||||
throws IOException, InterruptedException {
|
||||
Files.createDirectories(directory);
|
||||
if (!server.awaitPlayer(PLAYER, 300)) {
|
||||
throw new IOException("The " + client.name() + " game never joined the server");
|
||||
}
|
||||
// The world is frozen: the ticks that load and light the chunks around the player.
|
||||
stepTicks(server, JOIN_TICKS);
|
||||
client.awaitWorld();
|
||||
System.out.println("==> The " + client.name() + " game joined; setting up");
|
||||
for (SceneScript.Step step : script.setup()) {
|
||||
step(client, server, step, directory);
|
||||
}
|
||||
for (SceneScript.Scene scene : scenes) {
|
||||
System.out.println("==> " + client.name() + ": scene " + scene.name() + " (" + scene.description() + ")");
|
||||
for (SceneScript.Step step : scene.steps()) {
|
||||
step(client, server, step, directory);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void step(SceneClient client, GameServer server, SceneScript.Step step, Path directory)
|
||||
throws IOException, InterruptedException {
|
||||
switch (step.kind()) {
|
||||
case "rcon" -> {
|
||||
Matcher ticks = TICK_STEP.matcher(step.value());
|
||||
String reply = ticks.matches()
|
||||
? stepTicks(server, Integer.parseInt(ticks.group(1)))
|
||||
: server.command(step.value());
|
||||
System.out.println(" rcon " + step.value() + (reply.isEmpty() ? "" : " -> " + reply));
|
||||
}
|
||||
case "key" -> client.key(Keys.chord(step.value()));
|
||||
case "move", "click" -> {
|
||||
String[] parts = step.value().split(",", -1);
|
||||
double x = Double.parseDouble(parts[0].strip());
|
||||
double y = Double.parseDouble(parts[1].strip());
|
||||
if (step.kind().equals("click")) {
|
||||
client.click(x, y);
|
||||
} else {
|
||||
client.move(x, y);
|
||||
}
|
||||
}
|
||||
case "sleep" -> Thread.sleep(Long.parseLong(step.value()));
|
||||
case "settle" -> settle(client, directory.resolve("settling.png"));
|
||||
case "shot" -> {
|
||||
client.shot(directory.resolve(step.value() + ".png"));
|
||||
System.out.println(" shot " + step.value());
|
||||
}
|
||||
default -> throw new CliException("line " + step.line() + ": unknown step " + step.kind());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits until the picture stops changing (chunks built, fades done): three screenshots in a
|
||||
* row, a second and a half apart, nearly identical. Gives up after two minutes and says so;
|
||||
* the scene's screenshot then shows why.
|
||||
*/
|
||||
private static void settle(SceneClient client, Path scratch) throws IOException, InterruptedException {
|
||||
long until = System.nanoTime() + TimeUnit.MINUTES.toNanos(2);
|
||||
BufferedImage previous = client.shot(scratch);
|
||||
int stable = 0;
|
||||
double last = 0;
|
||||
while (System.nanoTime() < until) {
|
||||
Thread.sleep(1500);
|
||||
BufferedImage current = client.shot(scratch);
|
||||
last = ImageDiff.compare(previous, current).ssim();
|
||||
stable = last >= SETTLED ? stable + 1 : 0;
|
||||
if (stable >= 2) {
|
||||
return;
|
||||
}
|
||||
previous = current;
|
||||
}
|
||||
System.out.println(" (still changing after two minutes: SSIM " + format(last) + " between frames)");
|
||||
}
|
||||
|
||||
/** Waits for the player to leave the server, so the next game joins a world without them. */
|
||||
private static void awaitLeft(GameServer server) throws IOException, InterruptedException {
|
||||
long until = System.nanoTime() + TimeUnit.SECONDS.toNanos(60);
|
||||
while (System.nanoTime() < until && server.command("list").contains(PLAYER)) {
|
||||
Thread.sleep(500);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean allShotsExist(Path directory, List<SceneScript.Scene> scenes) {
|
||||
return scenes.stream()
|
||||
.flatMap(scene -> scene.shots().stream())
|
||||
.allMatch(shot -> Files.isRegularFile(directory.resolve(shot + ".png")));
|
||||
}
|
||||
|
||||
private static int report(
|
||||
SceneScript script, List<SceneScript.Scene> scenes, Path out, String gpu, List<String> pageErrors)
|
||||
throws IOException {
|
||||
Path diffs = out.resolve("diff");
|
||||
Files.createDirectories(diffs);
|
||||
StringBuilder report = new StringBuilder();
|
||||
report.append("Screenshot diff: desktop (Mojang's OpenGL backend) against the browser (WebGL2 on ")
|
||||
.append(gpu)
|
||||
.append(")\n");
|
||||
report.append("Threshold: SSIM >= ").append(script.threshold()).append("\n\n");
|
||||
report.append(String.format(Locale.ROOT, "%-16s %-26s %8s %9s %s%n", "scene", "shot", "SSIM", "changed", ""));
|
||||
int failed = 0;
|
||||
for (SceneScript.Scene scene : scenes) {
|
||||
for (String shot : scene.shots()) {
|
||||
BufferedImage desktop = ImageIO.read(
|
||||
out.resolve("desktop").resolve(shot + ".png").toFile());
|
||||
BufferedImage browser = ImageIO.read(
|
||||
out.resolve("browser").resolve(shot + ".png").toFile());
|
||||
if (desktop == null || browser == null) {
|
||||
throw new IOException("Missing screenshots for " + shot);
|
||||
}
|
||||
ImageDiff.Result result = ImageDiff.compare(desktop, browser);
|
||||
ImageIO.write(
|
||||
result.heatmap(), "png", diffs.resolve(shot + ".png").toFile());
|
||||
boolean pass = result.ssim() >= script.threshold();
|
||||
if (!pass) {
|
||||
failed++;
|
||||
}
|
||||
report.append(String.format(
|
||||
Locale.ROOT,
|
||||
"%-16s %-26s %8s %8.2f%% %s%n",
|
||||
scene.name(),
|
||||
shot,
|
||||
format(result.ssim()),
|
||||
result.changed() * 100,
|
||||
pass ? "pass" : "FAIL"));
|
||||
}
|
||||
}
|
||||
report.append('\n');
|
||||
if (pageErrors.isEmpty()) {
|
||||
report.append("The page logged no WebGL errors and skipped no pipelines.\n");
|
||||
} else {
|
||||
report.append("The page logged ").append(pageErrors.size()).append(" WebGL errors or skipped pipelines:\n");
|
||||
pageErrors.stream()
|
||||
.distinct()
|
||||
.limit(40)
|
||||
.forEach(message -> report.append(" ").append(message).append('\n'));
|
||||
}
|
||||
report.append('\n')
|
||||
.append("Images: ")
|
||||
.append(out.resolve("desktop"))
|
||||
.append(", ")
|
||||
.append(out.resolve("browser"))
|
||||
.append(", heat maps in ")
|
||||
.append(diffs)
|
||||
.append('\n');
|
||||
System.out.print(report);
|
||||
Files.writeString(out.resolve("report.txt"), report);
|
||||
return failed == 0 && pageErrors.isEmpty() ? 0 : 1;
|
||||
}
|
||||
|
||||
private static String format(double ssim) {
|
||||
return String.format(Locale.ROOT, "%.4f", ssim);
|
||||
}
|
||||
|
||||
private static Options parse(String[] args) {
|
||||
Map<String, String> single = new LinkedHashMap<>();
|
||||
Map<String, Path> files = new LinkedHashMap<>();
|
||||
boolean reuseDesktop = false;
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
String option = args[i];
|
||||
switch (option) {
|
||||
case "--file" -> Serve.addFile(files, value(args, ++i, option));
|
||||
case "--dir" -> Serve.addDirectory(files, value(args, ++i, option));
|
||||
case "--reuse-desktop" -> reuseDesktop = true;
|
||||
case "--scenes",
|
||||
"--options",
|
||||
"--server-properties",
|
||||
"--out",
|
||||
"--build",
|
||||
"--desktop-launch",
|
||||
"--version-json",
|
||||
"--cache",
|
||||
"--port",
|
||||
"--gpu",
|
||||
"--only",
|
||||
"--query",
|
||||
"--chrome" -> single.put(option, value(args, ++i, option));
|
||||
default -> throw new CliException("Unknown option '" + option + "'");
|
||||
}
|
||||
}
|
||||
for (String required : List.of(
|
||||
"--scenes",
|
||||
"--options",
|
||||
"--server-properties",
|
||||
"--out",
|
||||
"--build",
|
||||
"--desktop-launch",
|
||||
"--version-json",
|
||||
"--cache")) {
|
||||
if (!single.containsKey(required)) {
|
||||
throw new CliException("screenshot-diff needs " + required);
|
||||
}
|
||||
}
|
||||
String only = single.getOrDefault("--only", "");
|
||||
return new Options(
|
||||
Path.of(single.get("--scenes")),
|
||||
Path.of(single.get("--options")),
|
||||
Path.of(single.get("--server-properties")),
|
||||
Path.of(single.get("--out")),
|
||||
Path.of(single.get("--build")),
|
||||
files,
|
||||
Path.of(single.get("--desktop-launch")),
|
||||
Path.of(single.get("--version-json")),
|
||||
Path.of(single.get("--cache")),
|
||||
Integer.parseInt(single.getOrDefault("--port", "18210")),
|
||||
Chromium.Gpu.parse(single.getOrDefault("--gpu", "gl")),
|
||||
only.isEmpty() ? Set.of() : Set.of(only.split(",")),
|
||||
reuseDesktop,
|
||||
single.get("--chrome"),
|
||||
single.getOrDefault("--query", ""));
|
||||
}
|
||||
|
||||
private static String value(String[] args, int index, String option) {
|
||||
if (index >= args.length) {
|
||||
throw new CliException(option + " needs a value");
|
||||
}
|
||||
return args[index];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Serves the browser build's output directory on localhost, for development only. Serves
|
||||
* {@code .wasm} as {@code application/wasm} (streaming compilation requires it) and sends the
|
||||
* cross-origin isolation headers the build will need for shared memory and workers. Files from
|
||||
* elsewhere are served by name beside the build: the client jar at {@code /client.jar}, where the
|
||||
* page fetches the game's resources, and the translated shaders at {@code /shaders.json}. Whole
|
||||
* directories can be mounted under a prefix the same way: the asset objects {@code ./incari assets}
|
||||
* downloaded, which the page fetches as sounds play.
|
||||
*
|
||||
* <p>Binds to the loopback address only: builds contain Mojang code and are never published.
|
||||
*/
|
||||
public final class Serve {
|
||||
|
||||
private static final Map<String, String> TYPES = Map.of(
|
||||
"html", "text/html; charset=utf-8",
|
||||
"js", "text/javascript; charset=utf-8",
|
||||
"wasm", "application/wasm",
|
||||
"json", "application/json",
|
||||
"jar", "application/java-archive",
|
||||
"map", "application/json",
|
||||
"teadbg", "application/octet-stream");
|
||||
|
||||
private Serve() {}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
if (args.length < 1) {
|
||||
System.err.println(
|
||||
"Usage: serve <directory> [--port <n>] [--file <name>=<path>]... [--dir <prefix>=<path>]...");
|
||||
System.exit(2);
|
||||
}
|
||||
Path root = Path.of(args[0]).toAbsolutePath().normalize();
|
||||
int port = 8080;
|
||||
Map<String, Path> files = new LinkedHashMap<>();
|
||||
for (int i = 1; i < args.length; i++) {
|
||||
switch (args[i]) {
|
||||
case "--port" -> port = Integer.parseInt(args[++i]);
|
||||
case "--file" -> addFile(files, args[++i]);
|
||||
case "--dir" -> addDirectory(files, args[++i]);
|
||||
default -> {
|
||||
System.err.println("Unknown option '" + args[i] + "'");
|
||||
System.exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
HttpServer server = start(root, port, files);
|
||||
System.out.println("Serving " + root + " at http://localhost:"
|
||||
+ server.getAddress().getPort() + "/ (Ctrl+C to stop)");
|
||||
}
|
||||
|
||||
/** Adds a {@code <name>=<path>} option's file, served at {@code /<name>}. */
|
||||
static void addFile(Map<String, Path> files, String option) {
|
||||
int equals = option.indexOf('=');
|
||||
if (equals <= 0) {
|
||||
throw new IllegalArgumentException("Expected <name>=<path>, got '" + option + "'");
|
||||
}
|
||||
files.put("/" + option.substring(0, equals), Path.of(option.substring(equals + 1)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a {@code <prefix>=<path>} option's directory: {@code /<prefix>/<file>} serves
|
||||
* {@code <path>/<file>}. Kept with the named files, under a key ending in a slash.
|
||||
*/
|
||||
static void addDirectory(Map<String, Path> files, String option) {
|
||||
int equals = option.indexOf('=');
|
||||
if (equals <= 0) {
|
||||
throw new IllegalArgumentException("Expected <prefix>=<path>, got '" + option + "'");
|
||||
}
|
||||
String prefix = option.substring(0, equals);
|
||||
files.put("/" + (prefix.endsWith("/") ? prefix : prefix + "/"), Path.of(option.substring(equals + 1)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts serving {@code root} on the loopback address, and each of {@code files} (URL path to
|
||||
* file) by its one name; port 0 picks a free one.
|
||||
*/
|
||||
static HttpServer start(Path root, int port, Map<String, Path> files) throws IOException {
|
||||
return start(root, InetAddress.getLoopbackAddress(), port, files);
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves on {@code address}: the loopback interface unless another machine must reach the page
|
||||
* (the benchmark runner on a Chromebook). Never on a public network: every build contains
|
||||
* Mojang code and must not be published.
|
||||
*/
|
||||
static HttpServer start(Path root, InetAddress address, int port, Map<String, Path> files) throws IOException {
|
||||
Path directory = root.toAbsolutePath().normalize();
|
||||
Map<String, Path> named = Map.copyOf(files);
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress(address, port), 0);
|
||||
server.createContext("/", exchange -> handle(directory, named, exchange));
|
||||
server.start();
|
||||
return server;
|
||||
}
|
||||
|
||||
/** The file a request names under a mounted directory, or null; never outside that directory. */
|
||||
static @Nullable Path mounted(Map<String, Path> files, String path) {
|
||||
for (Map.Entry<String, Path> entry : files.entrySet()) {
|
||||
String prefix = entry.getKey();
|
||||
if (prefix.endsWith("/") && path.startsWith(prefix)) {
|
||||
Path directory = entry.getValue().toAbsolutePath().normalize();
|
||||
Path file = directory.resolve(path.substring(prefix.length())).normalize();
|
||||
return file.startsWith(directory) ? file : null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void handle(Path root, Map<String, Path> files, HttpExchange exchange) throws IOException {
|
||||
try (exchange) {
|
||||
String path = exchange.getRequestURI().getPath();
|
||||
if (path.endsWith("/")) {
|
||||
path += "index.html";
|
||||
}
|
||||
Path file = root.resolve(path.substring(1)).normalize();
|
||||
// Only files under the root, and the named files by their one name each.
|
||||
boolean allowed = file.startsWith(root);
|
||||
Path named = files.get(path);
|
||||
if (named != null) {
|
||||
file = named;
|
||||
allowed = true;
|
||||
} else {
|
||||
Path mounted = mounted(files, path);
|
||||
if (mounted != null) {
|
||||
file = mounted;
|
||||
allowed = true;
|
||||
}
|
||||
}
|
||||
if (!allowed || !Files.isRegularFile(file)) {
|
||||
exchange.sendResponseHeaders(404, -1);
|
||||
return;
|
||||
}
|
||||
String name = file.getFileName().toString();
|
||||
String extension = name.substring(name.lastIndexOf('.') + 1).toLowerCase(Locale.ROOT);
|
||||
exchange.getResponseHeaders()
|
||||
.set("Content-Type", TYPES.getOrDefault(extension, "application/octet-stream"));
|
||||
exchange.getResponseHeaders().set("Cache-Control", "no-cache");
|
||||
exchange.getResponseHeaders().set("Cross-Origin-Opener-Policy", "same-origin");
|
||||
exchange.getResponseHeaders().set("Cross-Origin-Embedder-Policy", "require-corp");
|
||||
exchange.sendResponseHeaders(200, Files.size(file));
|
||||
try (OutputStream body = exchange.getResponseBody()) {
|
||||
Files.copy(file, body);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A singleplayer scenario's server figures, from the server worker's tick table: one row per tick of
|
||||
* the columns platform-web's {@code WorkerProfiling} documents. Pure logic, tested on its own.
|
||||
*
|
||||
* <p>Paused ticks only read the connection, so they're counted apart and left out of the rest. The
|
||||
* tick rate is the ticks that ran over the measured seconds: 20 when the server keeps up, less when
|
||||
* its ticks (or the page beside it) take more than their 50 ms. Percentiles are nearest rank.
|
||||
*/
|
||||
final class ServerTickStats {
|
||||
|
||||
/** The tick table's columns, as the worker writes them. */
|
||||
static final int COLUMNS = 4;
|
||||
|
||||
static final int MILLIS = 1;
|
||||
static final int PAUSED = 2;
|
||||
static final int CHUNKS = 3;
|
||||
|
||||
private final List<double[]> rows = new ArrayList<>();
|
||||
private double seconds;
|
||||
|
||||
/** Adds a measured stretch of {@code stretchSeconds}: its ticks, {@code table} flat. */
|
||||
void add(double[] table, double stretchSeconds) {
|
||||
if (table.length % COLUMNS != 0) {
|
||||
throw new IllegalArgumentException("A tick table of " + table.length + " numbers");
|
||||
}
|
||||
for (int i = 0; i < table.length; i += COLUMNS) {
|
||||
rows.add(Arrays.copyOfRange(table, i, i + COLUMNS));
|
||||
}
|
||||
seconds += stretchSeconds;
|
||||
}
|
||||
|
||||
int ticks() {
|
||||
return rows.size();
|
||||
}
|
||||
|
||||
/** The figures, by name, in a fixed order; a figure nothing measured is {@code NaN}. */
|
||||
Map<String, Double> figures() {
|
||||
double[] running = rows.stream()
|
||||
.filter(row -> row[PAUSED] == 0)
|
||||
.mapToDouble(row -> row[MILLIS])
|
||||
.sorted()
|
||||
.toArray();
|
||||
Map<String, Double> out = new LinkedHashMap<>();
|
||||
out.put("serverTicksPerSecond", seconds > 0 ? running.length / seconds : Double.NaN);
|
||||
out.put(
|
||||
"serverTickMillis",
|
||||
running.length == 0 ? Double.NaN : Arrays.stream(running).sum() / running.length);
|
||||
out.put("serverTickP95Millis", percentile(running, 95));
|
||||
out.put("serverTickMaxMillis", running.length == 0 ? Double.NaN : running[running.length - 1]);
|
||||
out.put("serverPausedTicks", (double) (rows.size() - running.length));
|
||||
out.put("serverChunks", rows.isEmpty() ? Double.NaN : rows.getLast()[CHUNKS]);
|
||||
return out;
|
||||
}
|
||||
|
||||
private static double percentile(double[] sorted, double percent) {
|
||||
if (sorted.length == 0) {
|
||||
return Double.NaN;
|
||||
}
|
||||
int rank = (int) Math.ceil(percent / 100 * sorted.length);
|
||||
return sorted[Math.max(0, rank - 1)];
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.FilterOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Base64;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.zip.Deflater;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
/**
|
||||
* Packs a web folder ({@link WebFolder}) into one HTML file that plays from the disk (ADR
|
||||
* 0057): every file the page fetches goes in as base64, gzipped where that's smaller, and the page's
|
||||
* {@code offline.js} inline starts it, serving those files to the page and its workers by their
|
||||
* usual names. The service worker and its cache policy stay out, since a page opened from the disk
|
||||
* can't have one.
|
||||
*
|
||||
* <p>Run by {@code ./gradlew :app-web:singleFile}, which {@code ./incari build --html} calls after
|
||||
* writing the folder. The file holds Mojang's code and files: never committed, shared or published.
|
||||
*/
|
||||
public final class SingleFile {
|
||||
|
||||
/** Starts every file this tool writes, so a rerun may replace it and nothing else is overwritten. */
|
||||
static final String SIGNATURE = "<!-- Incari single-file build, written by ./incari build --html.";
|
||||
|
||||
private static final String NOTICE = SIGNATURE + """
|
||||
|
||||
DO NOT SHARE, UPLOAD OR PUBLISH THIS FILE.
|
||||
It contains Minecraft's code and files, which Mojang doesn't allow redistributing. The Incari
|
||||
project never publishes builds and gives nobody permission to. It is for your own use, on
|
||||
your own machine; see docs/self-hosting.md. Incari is not affiliated with or endorsed by
|
||||
Mojang or Microsoft. -->
|
||||
""";
|
||||
|
||||
/** The line in {@code index.html} the inline loader replaces. */
|
||||
private static final String BOOT = "<script type=\"module\" src=\"boot.js\"></script>";
|
||||
|
||||
/** The folder's files that don't go in: the server's, and the service worker's. */
|
||||
private static final List<String> LEFT_OUT =
|
||||
List.of("index.html", ".htaccess", "README.txt", WebFolder.MARKER, "sw.js", "cache-policy.js");
|
||||
|
||||
/** The page's scripts first (decoded before the rest), then small to large. */
|
||||
private static final Comparator<Path> ORDER = Comparator.<Path, Boolean>comparing(
|
||||
path -> !path.toString().endsWith(".js"))
|
||||
.thenComparingLong(SingleFile::size);
|
||||
|
||||
private SingleFile() {}
|
||||
|
||||
record Options(Path folder, Path out, Path script) {}
|
||||
|
||||
record Summary(int files, long bytes) {}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
Options options = parse(args);
|
||||
Summary summary = write(options);
|
||||
System.out.println("==> Wrote " + options.out() + ": " + summary.files() + " files in one page, "
|
||||
+ summary.bytes() / (1024 * 1024) + " MB");
|
||||
}
|
||||
|
||||
static Options parse(String[] args) {
|
||||
Map<String, String> values = new LinkedHashMap<>();
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
String name = args[i];
|
||||
if (!name.startsWith("--") || i + 1 >= args.length) {
|
||||
throw new CliException("Unexpected argument '" + name + "'");
|
||||
}
|
||||
values.put(name.substring(2), args[++i]);
|
||||
}
|
||||
for (String name : values.keySet()) {
|
||||
if (!List.of("folder", "out", "script").contains(name)) {
|
||||
throw new CliException("Unknown option '--" + name + "'");
|
||||
}
|
||||
}
|
||||
return new Options(
|
||||
Path.of(required(values, "folder")),
|
||||
Path.of(required(values, "out")),
|
||||
Path.of(required(values, "script")));
|
||||
}
|
||||
|
||||
static Summary write(Options options) throws IOException {
|
||||
Path folder = options.folder().toAbsolutePath().normalize();
|
||||
Path out = options.out().toAbsolutePath().normalize();
|
||||
if (!Files.isRegularFile(folder.resolve(WebFolder.MARKER))) {
|
||||
throw new CliException(folder + " isn't a folder ./incari build wrote");
|
||||
}
|
||||
requireReplaceable(out);
|
||||
String page = Files.readString(folder.resolve("index.html"));
|
||||
if (!page.contains(BOOT)) {
|
||||
throw new CliException("index.html has no " + BOOT + " for the inline loader to replace");
|
||||
}
|
||||
String script = Files.readString(options.script());
|
||||
if (script.toLowerCase(Locale.ROOT).contains("</script")) {
|
||||
throw new CliException(options.script() + " can't go inline: it contains </script");
|
||||
}
|
||||
int head = page.indexOf('\n') + 1;
|
||||
|
||||
List<Path> files;
|
||||
try (Stream<Path> walk = Files.walk(folder)) {
|
||||
files = walk.filter(Files::isRegularFile)
|
||||
.filter(file -> !LEFT_OUT.contains(folder.relativize(file).toString()))
|
||||
.sorted(ORDER)
|
||||
.toList();
|
||||
}
|
||||
Files.createDirectories(out.getParent());
|
||||
Path partial = out.resolveSibling(out.getFileName() + ".partial");
|
||||
try (OutputStream stream = Files.newOutputStream(partial);
|
||||
Writer writer = new OutputStreamWriter(stream, StandardCharsets.UTF_8)) {
|
||||
writer.write(page.substring(0, head));
|
||||
writer.write(NOTICE);
|
||||
String body = page.substring(head);
|
||||
int boot = body.indexOf(BOOT);
|
||||
writer.write(body, 0, boot);
|
||||
writer.write("<script type=\"module\">\n");
|
||||
writer.write(script);
|
||||
writer.write("\nstart(window);\n</script>\n");
|
||||
for (Path file : files) {
|
||||
String path = folder.relativize(file).toString().replace('\\', '/');
|
||||
byte[] bytes = Files.readAllBytes(file);
|
||||
byte[] packed = gzip(bytes);
|
||||
boolean gzipped = packed.length < bytes.length * 9L / 10;
|
||||
writer.write("<script type=\"application/x-incari-file\" data-path=\"" + attribute(path)
|
||||
+ "\" data-type=\"" + type(path) + "\"" + (gzipped ? " data-encoding=\"gzip\"" : "") + ">");
|
||||
writer.flush();
|
||||
// Straight into the file: the largest is tens of megabytes.
|
||||
OutputStream base64 = Base64.getEncoder().wrap(new FilterOutputStream(stream) {
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
flush();
|
||||
}
|
||||
});
|
||||
base64.write(gzipped ? packed : bytes);
|
||||
base64.close();
|
||||
writer.write("</script>\n");
|
||||
}
|
||||
writer.write(body, boot + BOOT.length(), body.length() - boot - BOOT.length());
|
||||
}
|
||||
Files.move(partial, out, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
|
||||
return new Summary(files.size(), Files.size(out));
|
||||
}
|
||||
|
||||
private static byte[] gzip(byte[] bytes) throws IOException {
|
||||
ByteArrayOutputStream packed = new ByteArrayOutputStream(bytes.length / 2);
|
||||
try (GZIPOutputStream gzip = new GZIPOutputStream(packed) {
|
||||
{
|
||||
def.setLevel(Deflater.BEST_COMPRESSION);
|
||||
}
|
||||
}) {
|
||||
gzip.write(bytes);
|
||||
}
|
||||
return packed.toByteArray();
|
||||
}
|
||||
|
||||
/** The media type the file's Blob gets: the browser compiles {@code application/wasm} as it reads. */
|
||||
static String type(String path) {
|
||||
if (path.endsWith(".js")) {
|
||||
return "text/javascript";
|
||||
}
|
||||
if (path.endsWith(".wasm")) {
|
||||
return "application/wasm";
|
||||
}
|
||||
if (path.endsWith(".json")) {
|
||||
return "application/json";
|
||||
}
|
||||
if (path.endsWith(".jar")) {
|
||||
return "application/java-archive";
|
||||
}
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
private static String attribute(String value) {
|
||||
return value.replace("&", "&").replace("\"", """).replace("<", "<");
|
||||
}
|
||||
|
||||
/** Refuses to overwrite a file this tool didn't write. */
|
||||
static void requireReplaceable(Path out) throws IOException {
|
||||
if (!Files.exists(out)) {
|
||||
return;
|
||||
}
|
||||
if (!Files.isRegularFile(out)) {
|
||||
throw new CliException(out + " exists and isn't a file");
|
||||
}
|
||||
byte[] start = new byte[512];
|
||||
int read;
|
||||
try (InputStream in = Files.newInputStream(out)) {
|
||||
read = in.readNBytes(start, 0, start.length);
|
||||
}
|
||||
if (!new String(start, 0, read, StandardCharsets.UTF_8).contains(SIGNATURE)) {
|
||||
throw new CliException(out + " already exists and ./incari build didn't write it. Pick another name");
|
||||
}
|
||||
}
|
||||
|
||||
private static long size(Path file) {
|
||||
try {
|
||||
return Files.size(file);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String required(Map<String, String> values, String name) {
|
||||
String value = values.get(name);
|
||||
if (value == null) {
|
||||
throw new CliException("Missing --" + name);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* The single HTML file's sounds, as Eaglercraft packs its offline download: every sound but the
|
||||
* music and the records (293 of the 377 MB), each encoded again smaller with ffmpeg, as Ogg Vorbis
|
||||
* at 22,050 Hz and quality 0. Their own channels are kept. The 84 MB left become about 38: the
|
||||
* file grows about 51 MB as base64. A game's sound effects keep their character at that rate. The
|
||||
* browser's decoder reads them as it reads the originals, and so does the game's own (JOrbis), the
|
||||
* fallback.
|
||||
*
|
||||
* <p>Encoded files are kept under the asset objects' folder ({@code small-sounds/}, by the
|
||||
* original's hash and the settings), so only the first build encodes. Without ffmpeg the file
|
||||
* carries {@link CoreSounds} instead, as they are.
|
||||
*/
|
||||
final class SmallSounds {
|
||||
|
||||
/** The encoder's settings; part of the cache's folder name, so a change encodes again. */
|
||||
private static final List<String> SETTINGS = List.of("-ar", "22050", "-q:a", "0");
|
||||
|
||||
private static final String CACHE = "small-sounds/vorbis-22050-q0";
|
||||
|
||||
private static final List<String> LEFT_OUT = List.of("music/", "records/");
|
||||
|
||||
private static final String SOUNDS = "minecraft/sounds/";
|
||||
|
||||
private SmallSounds() {}
|
||||
|
||||
/** Whether the asset index's {@code name} is a sound file the single file carries. */
|
||||
static boolean keeps(String name) {
|
||||
if (!name.startsWith(SOUNDS) || !name.endsWith(".ogg")) {
|
||||
return false;
|
||||
}
|
||||
String path = name.substring(SOUNDS.length());
|
||||
for (String folder : LEFT_OUT) {
|
||||
if (path.startsWith(folder)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Whether ffmpeg runs here, with its Vorbis encoder. */
|
||||
static boolean available() {
|
||||
try {
|
||||
Process process = new ProcessBuilder("ffmpeg", "-hide_banner", "-encoders")
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
String encoders = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
return process.waitFor(30, TimeUnit.SECONDS) && process.exitValue() == 0 && encoders.contains("libvorbis");
|
||||
} catch (IOException e) {
|
||||
return false;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The sound object {@code hash} in {@code objects}, encoded smaller: from the cache beside
|
||||
* {@code objects} if it's there, else encoded and kept. The original if encoding didn't make it
|
||||
* smaller.
|
||||
*/
|
||||
static byte[] encode(Path objects, String hash) throws IOException {
|
||||
Path source = objects.resolve(hash.substring(0, 2) + "/" + hash);
|
||||
Path cached = cacheOf(objects).resolve(hash.substring(0, 2) + "/" + hash + ".ogg");
|
||||
if (!Files.isRegularFile(cached)) {
|
||||
Files.createDirectories(cached.getParent());
|
||||
Path partial = cached.resolveSibling(hash + ".partial.ogg");
|
||||
List<String> command = new ArrayList<>(List.of(
|
||||
"ffmpeg",
|
||||
"-nostdin",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-y",
|
||||
"-i",
|
||||
source.toString(),
|
||||
"-map_metadata",
|
||||
"-1",
|
||||
"-vn",
|
||||
"-c:a",
|
||||
"libvorbis"));
|
||||
command.addAll(SETTINGS);
|
||||
command.addAll(List.of("-f", "ogg", partial.toString()));
|
||||
Process process =
|
||||
new ProcessBuilder(command).redirectErrorStream(true).start();
|
||||
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
try {
|
||||
if (!process.waitFor(5, TimeUnit.MINUTES) || process.exitValue() != 0) {
|
||||
process.destroyForcibly();
|
||||
throw new IOException("ffmpeg couldn't encode " + source + ": " + output.strip());
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted encoding " + source, e);
|
||||
}
|
||||
Files.move(partial, cached, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
|
||||
}
|
||||
byte[] smaller = Files.readAllBytes(cached);
|
||||
return smaller.length < Files.size(source) ? smaller : Files.readAllBytes(source);
|
||||
}
|
||||
|
||||
private static Path cacheOf(Path objects) {
|
||||
Path parent = objects.toAbsolutePath().getParent();
|
||||
return (parent == null ? objects : parent).resolve(CACHE);
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.teavm.model.BasicBlock;
|
||||
import org.teavm.model.ClassHolder;
|
||||
import org.teavm.model.ClassHolderTransformer;
|
||||
import org.teavm.model.ClassHolderTransformerContext;
|
||||
import org.teavm.model.Instruction;
|
||||
import org.teavm.model.MethodHolder;
|
||||
import org.teavm.model.MethodReference;
|
||||
import org.teavm.model.Program;
|
||||
import org.teavm.model.ValueType;
|
||||
import org.teavm.model.Variable;
|
||||
import org.teavm.model.instructions.IntegerConstantInstruction;
|
||||
import org.teavm.model.instructions.InvocationType;
|
||||
import org.teavm.model.instructions.InvokeInstruction;
|
||||
import org.teavm.model.instructions.RaiseInstruction;
|
||||
|
||||
/**
|
||||
* Counts the program's throws (`-Pteavm.throwCensus`, development only). In the page a throw caught
|
||||
* on any thread but the main one costs about ten times what it costs on the main one (ADR 0033,
|
||||
* {@code app-web/probes/PacketHandoffProbe}), so exceptions thrown as a matter of course off the
|
||||
* main thread are worth finding. Before every {@code throw} in the program (rethrows too) this
|
||||
* inserts a call to the class library's {@code incari.classlib.ThrowCensus.thrown(exception, site)},
|
||||
* which counts throws by site and thread and logs the busiest; the sites are numbered here, and
|
||||
* their methods written to {@code throw-sites.txt} beside the build.
|
||||
*
|
||||
* <p>Throws the backend makes itself (a null check's NullPointerException, an array index's,
|
||||
* a cast's) and exceptions from JavaScript aren't counted: they have no {@code throw} instruction.
|
||||
*/
|
||||
public final class ThrowCensus implements ClassHolderTransformer {
|
||||
|
||||
/** The class library's counter, which the web build refers to by name. */
|
||||
static final String COUNTER = "incari.classlib.ThrowCensus";
|
||||
|
||||
private static final MethodReference THROWN = new MethodReference(
|
||||
COUNTER, "thrown", ValueType.object("java.lang.Object"), ValueType.INTEGER, ValueType.VOID);
|
||||
|
||||
private static final List<String> SITES = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void transformClass(ClassHolder cls, ClassHolderTransformerContext context) {
|
||||
if (cls.getName().equals(COUNTER)) {
|
||||
// Its own throws would count themselves.
|
||||
return;
|
||||
}
|
||||
for (MethodHolder method : cls.getMethods()) {
|
||||
Program program = method.getProgram();
|
||||
if (program == null) {
|
||||
continue;
|
||||
}
|
||||
for (int i = 0; i < program.basicBlockCount(); i++) {
|
||||
BasicBlock block = program.basicBlockAt(i);
|
||||
for (Instruction insn = block.getFirstInstruction(); insn != null; insn = insn.getNext()) {
|
||||
if (insn instanceof RaiseInstruction raise) {
|
||||
count(program, raise, site(cls.getName() + "." + method.getName()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static synchronized int site(String method) {
|
||||
SITES.add(method);
|
||||
return SITES.size() - 1;
|
||||
}
|
||||
|
||||
private static void count(Program program, RaiseInstruction raise, int site) {
|
||||
Variable id = program.createVariable();
|
||||
IntegerConstantInstruction constant = new IntegerConstantInstruction();
|
||||
constant.setConstant(site);
|
||||
constant.setReceiver(id);
|
||||
constant.setLocation(raise.getLocation());
|
||||
InvokeInstruction call = new InvokeInstruction();
|
||||
call.setType(InvocationType.SPECIAL);
|
||||
call.setMethod(THROWN);
|
||||
call.setArguments(raise.getException(), id);
|
||||
call.setLocation(raise.getLocation());
|
||||
raise.insertPrevious(constant);
|
||||
raise.insertPrevious(call);
|
||||
}
|
||||
|
||||
/** Writes the sites, one a line, numbered by line (from 0). */
|
||||
static synchronized void write(Path file) throws IOException {
|
||||
Files.write(file, SITES);
|
||||
SITES.clear();
|
||||
}
|
||||
}
|
||||
+290
@@ -0,0 +1,290 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.classfile.Attributes;
|
||||
import java.lang.classfile.ClassFile;
|
||||
import java.lang.classfile.ClassModel;
|
||||
import java.lang.classfile.ClassSignature;
|
||||
import java.lang.classfile.Signature;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.stream.Stream;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.teavm.model.ClassHolder;
|
||||
import org.teavm.model.ClassHolderTransformer;
|
||||
import org.teavm.model.ClassHolderTransformerContext;
|
||||
import org.teavm.model.ClassReaderSource;
|
||||
import org.teavm.model.MethodDescriptor;
|
||||
import org.teavm.model.MethodHolder;
|
||||
import org.teavm.model.MethodReference;
|
||||
import org.teavm.model.ValueType;
|
||||
import org.teavm.model.emit.ProgramEmitter;
|
||||
import org.teavm.model.emit.ValueEmitter;
|
||||
|
||||
/**
|
||||
* Keeps the generic superclass of "type capture" classes for {@code Class.getGenericSuperclass}:
|
||||
* the anonymous {@code new TypeToken<List<String>>() {}} subclasses of Guava's and Gson's type
|
||||
* tokens (and of the copy of Gson that Via bundles), which read their type argument from their superclass. TeaVM keeps no generic
|
||||
* signatures, and DataFixerUpper and the game build such tokens while starting.
|
||||
*
|
||||
* <p>Netty's handlers read their superclass's type argument the same way
|
||||
* ({@code TypeParameterMatcher}, through {@code ReflectionUtil.resolveTypeParameter}) to decide
|
||||
* which messages they handle, and without it every handler matches every message: the game's
|
||||
* {@code PacketEncoder} was handed its pipeline's configuration messages and failed with a
|
||||
* {@code ClassCastException}. Netty only needs the argument's raw class, so for direct
|
||||
* subclasses of {@link #NETTY_BASES} an argument that names a type variable inside it
|
||||
* ({@code MessageToByteEncoder<Packet<T>>}) is kept as its raw class ({@code Packet}).
|
||||
*
|
||||
* <p>{@link Main} scans the class path for direct subclasses of {@link #BASES} and
|
||||
* {@link #NETTY_BASES} ({@link #scan});
|
||||
* this transformer then writes {@code incari.classlib.reflect.GenericSuperclasses.of} as a
|
||||
* lookup: each class's superclass signature in {@code GenericTypes}' compact form, with the
|
||||
* classes it names as class literals. A signature with a type variable isn't kept (nothing in
|
||||
* the build needs one yet), so {@code getGenericSuperclass} falls back to the raw class there.
|
||||
*
|
||||
* <p>TeaVM instantiates transformers by class name, so {@link Main} hands the scan over through
|
||||
* {@link #captures}. One compile runs at a time.
|
||||
*/
|
||||
public final class TypeCaptures implements ClassHolderTransformer {
|
||||
|
||||
/** Classes whose subclasses capture their type argument. */
|
||||
static final Set<String> BASES = Set.of(
|
||||
"com/google/common/reflect/TypeCapture",
|
||||
"com/google/common/reflect/TypeToken",
|
||||
"com/google/common/reflect/TypeParameter",
|
||||
"com/google/gson/reflect/TypeToken",
|
||||
// Via's own copy of Gson: its 1.13 translation reads JSON through one.
|
||||
"com/viaversion/viaversion/libs/gson/reflect/TypeToken");
|
||||
|
||||
/** Netty's classes that match messages (or addresses) by their subclass's type argument. */
|
||||
static final Set<String> NETTY_BASES = Set.of(
|
||||
"io/netty/channel/SimpleChannelInboundHandler",
|
||||
"io/netty/channel/SimpleUserEventChannelHandler",
|
||||
"io/netty/handler/codec/ByteToMessageCodec",
|
||||
"io/netty/handler/codec/MessageAggregator",
|
||||
"io/netty/handler/codec/MessageToByteEncoder",
|
||||
"io/netty/handler/codec/MessageToMessageCodec",
|
||||
"io/netty/handler/codec/MessageToMessageDecoder",
|
||||
"io/netty/handler/codec/MessageToMessageEncoder",
|
||||
"io/netty/resolver/AbstractAddressResolver");
|
||||
|
||||
static volatile Map<String, Capture> captures = Map.of();
|
||||
|
||||
private static final String LOOKUP = "incari.classlib.reflect.GenericSuperclasses";
|
||||
private static final MethodDescriptor OF =
|
||||
new MethodDescriptor("of", ValueType.object("java.lang.Class"), ValueType.object("java.lang.reflect.Type"));
|
||||
private static final MethodReference PARSE = new MethodReference(
|
||||
"incari.classlib.reflect.GenericTypes",
|
||||
"parse",
|
||||
ValueType.object("java.lang.String"),
|
||||
ValueType.arrayOf(ValueType.object("java.lang.Class")),
|
||||
ValueType.object("java.lang.reflect.Type"));
|
||||
|
||||
/** A superclass in {@code GenericTypes}' form: its code, and the classes it names in order. */
|
||||
record Capture(String code, List<ValueType> classes) {}
|
||||
|
||||
@Override
|
||||
public void transformClass(ClassHolder cls, ClassHolderTransformerContext context) {
|
||||
if (!cls.getName().equals(LOOKUP)) {
|
||||
return;
|
||||
}
|
||||
MethodHolder method = cls.getMethod(OF);
|
||||
if (method == null) {
|
||||
throw new IllegalStateException(LOOKUP + " has no " + OF);
|
||||
}
|
||||
ProgramEmitter pe = ProgramEmitter.create(method, context.getHierarchy());
|
||||
ValueEmitter requested = pe.var(1, ValueType.object("java.lang.Class"));
|
||||
ClassReaderSource source = context.getHierarchy().getClassSource();
|
||||
// The scan reads every jar on the class path, including libraries the build leaves out
|
||||
// (Netty's HTTP codec): a class literal of one of those wouldn't link.
|
||||
Map<String, Capture> kept = new TreeMap<>(captures);
|
||||
kept.entrySet()
|
||||
.removeIf(entry -> !exists(source, ValueType.object(entry.getKey()))
|
||||
|| !entry.getValue().classes().stream().allMatch(type -> exists(source, type)));
|
||||
kept.forEach((className, capture) -> pe.when(requested.isSame(pe.constant(ValueType.object(className))))
|
||||
.thenDo(() -> {
|
||||
ValueEmitter classes = pe.constructArray(
|
||||
ValueType.object("java.lang.Class"),
|
||||
capture.classes().size());
|
||||
for (int i = 0; i < capture.classes().size(); i++) {
|
||||
classes.setElement(i, pe.constant(capture.classes().get(i)));
|
||||
}
|
||||
pe.invoke(PARSE, pe.constant(capture.code()), classes).returnValue();
|
||||
}));
|
||||
pe.constantNull(ValueType.object("java.lang.reflect.Type")).returnValue();
|
||||
}
|
||||
|
||||
private static boolean exists(ClassReaderSource classes, ValueType type) {
|
||||
ValueType item = type;
|
||||
while (item instanceof ValueType.Array array) {
|
||||
item = array.getItemType();
|
||||
}
|
||||
return !(item instanceof ValueType.Object object) || classes.get(object.getClassName()) != null;
|
||||
}
|
||||
|
||||
/** The type-capture classes on the class path, by binary name. */
|
||||
static Map<String, Capture> scan(List<Path> classpath) throws IOException {
|
||||
Map<String, Capture> found = new TreeMap<>();
|
||||
for (Path entry : classpath) {
|
||||
if (Files.isRegularFile(entry) && entry.toString().endsWith(".jar")) {
|
||||
try (JarFile jar = new JarFile(entry.toFile())) {
|
||||
for (JarEntry file : (Iterable<JarEntry>) jar.stream()::iterator) {
|
||||
if (file.getName().endsWith(".class")) {
|
||||
consider(jar.getInputStream(file).readAllBytes(), found);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (Files.isDirectory(entry)) {
|
||||
try (Stream<Path> files = Files.walk(entry)) {
|
||||
for (Path file : (Iterable<Path>) files::iterator) {
|
||||
if (file.toString().endsWith(".class")) {
|
||||
consider(Files.readAllBytes(file), found);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
private static void consider(byte[] bytes, Map<String, Capture> found) {
|
||||
ClassModel model = ClassFile.of().parse(bytes);
|
||||
if (model.superclass().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
String superclass = model.superclass().get().asInternalName();
|
||||
boolean netty = NETTY_BASES.contains(superclass);
|
||||
if (!netty && !BASES.contains(superclass)) {
|
||||
return;
|
||||
}
|
||||
model.findAttribute(Attributes.signature()).ifPresent(signature -> {
|
||||
Signature.ClassTypeSig superclassSignature = ClassSignature.parseFrom(
|
||||
signature.signature().stringValue())
|
||||
.superclassSignature();
|
||||
Capture capture = encode(netty ? rawArguments(superclassSignature) : superclassSignature);
|
||||
if (capture != null) {
|
||||
found.put(model.thisClass().asInternalName().replace('/', '.'), capture);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code signature} with each type argument that is a parameterized class reduced to its raw
|
||||
* class, which is all Netty reads ({@code Foo<Packet<T>>} becomes {@code Foo<Packet>}). A
|
||||
* type variable itself stays one, so such a signature still isn't kept.
|
||||
*/
|
||||
static Signature.ClassTypeSig rawArguments(Signature.ClassTypeSig signature) {
|
||||
List<Signature.TypeArg> arguments = new ArrayList<>();
|
||||
for (Signature.TypeArg argument : signature.typeArgs()) {
|
||||
if (argument instanceof Signature.TypeArg.Bounded bounded
|
||||
&& bounded.wildcardIndicator() == Signature.TypeArg.Bounded.WildcardIndicator.NONE
|
||||
&& bounded.boundType() instanceof Signature.ClassTypeSig type
|
||||
&& !type.typeArgs().isEmpty()) {
|
||||
arguments.add(Signature.TypeArg.of(Signature.ClassTypeSig.of(type.classDesc())));
|
||||
} else {
|
||||
arguments.add(argument);
|
||||
}
|
||||
}
|
||||
return signature.outerType().isPresent()
|
||||
? Signature.ClassTypeSig.of(
|
||||
signature.outerType().get(), signature.className(), arguments.toArray(Signature.TypeArg[]::new))
|
||||
: Signature.ClassTypeSig.of(signature.classDesc(), arguments.toArray(Signature.TypeArg[]::new));
|
||||
}
|
||||
|
||||
/** {@code signature} in {@code GenericTypes}' form, or null if it has a type variable. */
|
||||
static @Nullable Capture encode(Signature signature) {
|
||||
StringBuilder code = new StringBuilder();
|
||||
List<ValueType> classes = new ArrayList<>();
|
||||
return encode(signature, code, classes) ? new Capture(code.toString(), List.copyOf(classes)) : null;
|
||||
}
|
||||
|
||||
private static boolean encode(Signature signature, StringBuilder code, List<ValueType> classes) {
|
||||
return switch (signature) {
|
||||
case Signature.ClassTypeSig type -> encodeClass(type, code, classes);
|
||||
case Signature.ArrayTypeSig array -> encodeArray(array, code, classes);
|
||||
case Signature.BaseTypeSig base -> {
|
||||
// Only as an array's component, which encodeArray folds into one class.
|
||||
code.append('C');
|
||||
classes.add(ValueType.parse(String.valueOf(base.baseType())));
|
||||
yield true;
|
||||
}
|
||||
case Signature.TypeVarSig variable -> false;
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean encodeClass(Signature.ClassTypeSig type, StringBuilder code, List<ValueType> classes) {
|
||||
String name = type.classDesc().descriptorString();
|
||||
ValueType self = ValueType.parse(name);
|
||||
boolean genericOwner = type.outerType().isPresent()
|
||||
&& !type.outerType().get().typeArgs().isEmpty();
|
||||
if (type.typeArgs().isEmpty() && !genericOwner) {
|
||||
code.append('C');
|
||||
classes.add(self);
|
||||
return true;
|
||||
}
|
||||
if (type.typeArgs().size() > 9) {
|
||||
return false;
|
||||
}
|
||||
code.append('P');
|
||||
classes.add(self);
|
||||
// The owner, as the JDK reports it: the enclosing type for a nested class, else none.
|
||||
String binaryName = ((ValueType.Object) self).getClassName();
|
||||
if (type.outerType().isPresent()) {
|
||||
if (!encode(type.outerType().get(), code, classes)) {
|
||||
return false;
|
||||
}
|
||||
} else if (binaryName.lastIndexOf('$') > binaryName.lastIndexOf('.')) {
|
||||
code.append('C');
|
||||
classes.add(ValueType.object(binaryName.substring(0, binaryName.lastIndexOf('$'))));
|
||||
} else {
|
||||
code.append('N');
|
||||
}
|
||||
code.append(type.typeArgs().size());
|
||||
for (Signature.TypeArg argument : type.typeArgs()) {
|
||||
boolean encoded =
|
||||
switch (argument) {
|
||||
case Signature.TypeArg.Unbounded unbounded -> {
|
||||
code.append("UC");
|
||||
classes.add(ValueType.object("java.lang.Object"));
|
||||
yield true;
|
||||
}
|
||||
case Signature.TypeArg.Bounded bounded -> {
|
||||
switch (bounded.wildcardIndicator()) {
|
||||
case EXTENDS -> code.append('U');
|
||||
case SUPER -> code.append('L');
|
||||
case NONE -> {}
|
||||
}
|
||||
yield encode(bounded.boundType(), code, classes);
|
||||
}
|
||||
};
|
||||
if (!encoded) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static boolean encodeArray(Signature.ArrayTypeSig array, StringBuilder code, List<ValueType> classes) {
|
||||
StringBuilder component = new StringBuilder();
|
||||
List<ValueType> componentClasses = new ArrayList<>();
|
||||
if (!encode(array.componentSignature(), component, componentClasses)) {
|
||||
return false;
|
||||
}
|
||||
if (component.toString().equals("C")) {
|
||||
// An array of a plain class is a class itself.
|
||||
code.append('C');
|
||||
classes.add(ValueType.arrayOf(componentClasses.get(0)));
|
||||
} else {
|
||||
code.append('A').append(component);
|
||||
classes.addAll(componentClasses);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import incari.tools.build.Downloader;
|
||||
import incari.tools.build.Log;
|
||||
import incari.tools.build.Workspace;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
|
||||
/**
|
||||
* Binaryen's {@code wasm-opt} over a release module (ADR 0034), with {@code --wasm-opt}.
|
||||
*
|
||||
* <p>The release of Binaryen is pinned (its tarball's SHA-1, taken from a copy checked against the
|
||||
* SHA-256 Binaryen publishes), fetched once into {@code work/cache/binaryen/}, and only for Linux
|
||||
* on x86-64 so far. The flags are the ones the floor stand-in was measured with (ADR 0043):
|
||||
*
|
||||
* <ul>
|
||||
* <li>{@code --closed-world}: nothing outside the module calls into it but its exports, which lets
|
||||
* Binaryen change the program's types: among other things it drops the vtable slots nothing
|
||||
* calls, which every copy of the game (the page and each worker) holds. tools/teavm-patches'
|
||||
* {@code WasmGCJsoCommonGenerator} exports every function handed to JavaScript, so that holds.
|
||||
* <li>{@code -O3}.
|
||||
* <li>No inlining ({@code -aimfs 0 -fimfs 0 -ocimfs 0 -pii 0}). With Binaryen's inlining the
|
||||
* fly-through's slowest frames got slower (their tick 3.5 to 11 ms on the floor stand-in) and,
|
||||
* uncapped, V8's optimizing compiler ran out of memory on the functions it grew. TeaVM has
|
||||
* inlined already; without Binaryen's the module is 4.6 MB smaller.
|
||||
* </ul>
|
||||
*
|
||||
* <p>Under a minute on the development desktop for the Fast build; the Compatible
|
||||
* build's took a quarter of an hour and 10 GB with ADR 0034's flags.
|
||||
*/
|
||||
final class WasmOpt {
|
||||
|
||||
static final String VERSION = "133";
|
||||
|
||||
private static final String SHA1_LINUX_X86_64 = "7fa00016442b4579141a0c7c5b47eb5b9a7d4338";
|
||||
|
||||
/** The features TeaVM's WebAssembly GC module uses; Binaryen reads nothing else in. */
|
||||
private static final List<String> FEATURES = List.of(
|
||||
"--enable-gc",
|
||||
"--enable-reference-types",
|
||||
"--enable-exception-handling",
|
||||
"--enable-bulk-memory",
|
||||
"--enable-nontrapping-float-to-int",
|
||||
"--enable-sign-ext",
|
||||
"--enable-mutable-globals",
|
||||
"--enable-multivalue");
|
||||
|
||||
static final List<String> PASSES =
|
||||
List.of("--closed-world", "-O3", "-aimfs", "0", "-fimfs", "0", "-ocimfs", "0", "-pii", "0");
|
||||
|
||||
private WasmOpt() {}
|
||||
|
||||
/** Optimizes {@code module} in place. */
|
||||
static void optimize(Workspace ws, Path module) throws IOException, InterruptedException {
|
||||
Path tool = tool(ws);
|
||||
Path optimized = module.resolveSibling(module.getFileName() + ".opt");
|
||||
List<String> command = new ArrayList<>();
|
||||
command.add(tool.toString());
|
||||
command.add(module.toString());
|
||||
command.addAll(FEATURES);
|
||||
command.addAll(PASSES);
|
||||
command.add("-o");
|
||||
command.add(optimized.toString());
|
||||
Log.step("Optimizing " + module.getFileName() + " with Binaryen " + VERSION + " (" + String.join(" ", PASSES)
|
||||
+ ")");
|
||||
long start = System.nanoTime();
|
||||
Process process = new ProcessBuilder(command).inheritIO().start();
|
||||
int status = process.waitFor();
|
||||
if (status != 0) {
|
||||
Files.deleteIfExists(optimized);
|
||||
throw new CliException("wasm-opt failed (exit " + status + ")");
|
||||
}
|
||||
long before = Files.size(module);
|
||||
Files.move(optimized, module, StandardCopyOption.REPLACE_EXISTING);
|
||||
Log.step(String.format(
|
||||
Locale.ROOT,
|
||||
"Optimized in %d s: %.1f MB to %.1f MB",
|
||||
(System.nanoTime() - start) / 1_000_000_000L,
|
||||
before / 1e6,
|
||||
Files.size(module) / 1e6));
|
||||
}
|
||||
|
||||
/** {@code wasm-opt}, fetched and unpacked into the workspace's cache the first time. */
|
||||
private static Path tool(Workspace ws) throws IOException, InterruptedException {
|
||||
String os = System.getProperty("os.name").toLowerCase(Locale.ROOT);
|
||||
String arch = System.getProperty("os.arch").toLowerCase(Locale.ROOT);
|
||||
if (!os.contains("linux") || !(arch.equals("amd64") || arch.equals("x86_64"))) {
|
||||
throw new CliException("--wasm-opt is only set up for Linux on x86-64 so far (this is " + os + " " + arch
|
||||
+ "): pin Binaryen's release for this platform in WasmOpt");
|
||||
}
|
||||
Path dir = ws.cacheDir().resolve("binaryen").resolve("version_" + VERSION);
|
||||
Path tool = dir.resolve("wasm-opt");
|
||||
if (Files.isExecutable(tool)) {
|
||||
return tool;
|
||||
}
|
||||
String file = "binaryen-version_" + VERSION + "-x86_64-linux.tar.gz";
|
||||
Path archive = dir.resolve(file);
|
||||
new Downloader()
|
||||
.fetch(
|
||||
URI.create("https://github.com/WebAssembly/binaryen/releases/download/version_" + VERSION + "/"
|
||||
+ file),
|
||||
SHA1_LINUX_X86_64,
|
||||
archive);
|
||||
extract(archive, "binaryen-version_" + VERSION + "/bin/wasm-opt", tool);
|
||||
Files.setPosixFilePermissions(tool, PosixFilePermissions.fromString("rwxr-xr-x"));
|
||||
Files.delete(archive);
|
||||
return tool;
|
||||
}
|
||||
|
||||
/** Copies one regular file out of a gzipped tar archive. */
|
||||
static void extract(Path archive, String entryName, Path target) throws IOException {
|
||||
try (InputStream in = new GZIPInputStream(Files.newInputStream(archive))) {
|
||||
byte[] header = new byte[512];
|
||||
while (in.readNBytes(header, 0, 512) == 512) {
|
||||
if (header[0] == 0) {
|
||||
break;
|
||||
}
|
||||
String name = field(header, 0, 100);
|
||||
String prefix = field(header, 345, 155);
|
||||
if (!prefix.isEmpty()) {
|
||||
name = prefix + "/" + name;
|
||||
}
|
||||
long size = Long.parseLong(field(header, 124, 12).trim(), 8);
|
||||
long padded = (size + 511) / 512 * 512;
|
||||
if (name.equals(entryName) && (header[156] == '0' || header[156] == 0)) {
|
||||
Path temp = target.resolveSibling(target.getFileName() + ".part");
|
||||
Files.write(temp, in.readNBytes((int) size));
|
||||
in.skipNBytes(padded - size);
|
||||
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
return;
|
||||
}
|
||||
in.skipNBytes(padded);
|
||||
}
|
||||
}
|
||||
throw new CliException(archive + " has no " + entryName);
|
||||
}
|
||||
|
||||
private static String field(byte[] header, int offset, int length) {
|
||||
int end = offset;
|
||||
while (end < offset + length && header[end] != 0) {
|
||||
end++;
|
||||
}
|
||||
return new String(header, offset, end - offset, StandardCharsets.US_ASCII);
|
||||
}
|
||||
}
|
||||
+535
@@ -0,0 +1,535 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import incari.tools.build.CliException;
|
||||
import incari.tools.build.FileTrees;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
import java.util.zip.Deflater;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Writes the browser build as one folder any static web server can serve (ADR 0028): what the
|
||||
* dev server serves by name ({@link Serve}), laid out as the page fetches it, with its own
|
||||
* {@code build.json} over exactly the files copied, an Apache {@code .htaccess} with the headers, and
|
||||
* a {@code README.txt} that says how to serve it and that it must not be shared.
|
||||
*
|
||||
* <p>Run by {@code ./gradlew :app-web:webFolder}, which {@code ./incari build} calls. The folder
|
||||
* holds Mojang's code and files: it is written outside the tracked tree and never published.
|
||||
*/
|
||||
public final class WebFolder {
|
||||
|
||||
/** Marks a folder this tool wrote, so a rerun may replace it and nothing else is ever deleted. */
|
||||
static final String MARKER = ".incari-web-folder";
|
||||
|
||||
/** The page's start-up scripts (src/main/ts, types stripped), beside {@code index.html}. */
|
||||
private static final List<String> SCRIPTS =
|
||||
List.of("boot", "loader", "features", "jspi", "wakeups", "cache-policy", "sw", "game-worker");
|
||||
|
||||
/**
|
||||
* The asset index's files the page fetches besides the sounds (its {@code WebAssets} and the
|
||||
* client's {@code RemoteAssets}): those read at start, then the Unicode font and the languages
|
||||
* before the reloads that read them. A name ending in {@code /} is a folder.
|
||||
*/
|
||||
private static final String SOUND_LIST = "minecraft/sounds.json";
|
||||
|
||||
private static final List<String> PAGE_ASSETS =
|
||||
List.of(SOUND_LIST, "pack.mcmeta", "minecraft/font/", "minecraft/lang/", "minecraft/resourcepacks/");
|
||||
|
||||
private WebFolder() {}
|
||||
|
||||
/** The command line, parsed. */
|
||||
record Options(
|
||||
Path out,
|
||||
String game,
|
||||
@Nullable Path compatible,
|
||||
@Nullable Path fast,
|
||||
@Nullable Path rust,
|
||||
Path mesher,
|
||||
Path page,
|
||||
Path scripts,
|
||||
Path pack,
|
||||
Path clientJar,
|
||||
@Nullable Path assetIndex,
|
||||
@Nullable Path assetObjects,
|
||||
SoundFiles soundFiles) {}
|
||||
|
||||
/**
|
||||
* Which sound files go in: all; all but music, encoded smaller ({@link SmallSounds}, the single
|
||||
* file's); the few common ones as they are ({@link CoreSounds}); or none.
|
||||
*/
|
||||
enum SoundFiles {
|
||||
ALL,
|
||||
SMALL,
|
||||
CORE,
|
||||
NONE
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
Options options = parse(args);
|
||||
Summary summary = write(options);
|
||||
System.out.println("==> Wrote " + options.out() + ": " + summary.files() + " files, "
|
||||
+ summary.bytes() / (1024 * 1024) + " MB"
|
||||
+ (summary.release() ? "" : " (a DEVELOPMENT build: larger and slower; ./incari build makes a release)")
|
||||
+ (!summary.sounds()
|
||||
? ", no sounds"
|
||||
: options.soundFiles() == SoundFiles.ALL ? "" : ", sounds but music")
|
||||
+ ", builds: " + String.join(" and ", summary.builds()));
|
||||
}
|
||||
|
||||
static Options parse(String[] args) {
|
||||
Map<String, String> values = new LinkedHashMap<>();
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
String name = args[i];
|
||||
if (!name.startsWith("--") || i + 1 >= args.length) {
|
||||
throw new CliException("Unexpected argument '" + name + "'");
|
||||
}
|
||||
values.put(name.substring(2), args[++i]);
|
||||
}
|
||||
List<String> known = List.of(
|
||||
"out",
|
||||
"game",
|
||||
"compatible",
|
||||
"fast",
|
||||
"rust",
|
||||
"mesher",
|
||||
"page",
|
||||
"scripts",
|
||||
"pack",
|
||||
"client-jar",
|
||||
"asset-index",
|
||||
"asset-objects",
|
||||
"sound-files");
|
||||
for (String name : values.keySet()) {
|
||||
if (!known.contains(name)) {
|
||||
throw new CliException("Unknown option '--" + name + "'");
|
||||
}
|
||||
}
|
||||
if (values.get("compatible") == null && values.get("fast") == null && values.get("rust") == null) {
|
||||
throw new CliException("Give --fast, --compatible, --rust or more: the builds to put in the folder");
|
||||
}
|
||||
if ((values.get("asset-index") == null) != (values.get("asset-objects") == null)) {
|
||||
throw new CliException("--asset-index and --asset-objects go together");
|
||||
}
|
||||
SoundFiles soundFiles =
|
||||
switch (values.getOrDefault("sound-files", "yes")) {
|
||||
case "yes" -> SoundFiles.ALL;
|
||||
case "small" -> SoundFiles.SMALL;
|
||||
case "core" -> SoundFiles.CORE;
|
||||
case "no" -> SoundFiles.NONE;
|
||||
default -> throw new CliException("--sound-files takes yes, small, core or no");
|
||||
};
|
||||
return new Options(
|
||||
Path.of(required(values, "out")),
|
||||
required(values, "game"),
|
||||
optionalPath(values, "compatible"),
|
||||
optionalPath(values, "fast"),
|
||||
optionalPath(values, "rust"),
|
||||
Path.of(required(values, "mesher")),
|
||||
Path.of(required(values, "page")),
|
||||
Path.of(required(values, "scripts")),
|
||||
Path.of(required(values, "pack")),
|
||||
Path.of(required(values, "client-jar")),
|
||||
optionalPath(values, "asset-index"),
|
||||
optionalPath(values, "asset-objects"),
|
||||
soundFiles);
|
||||
}
|
||||
|
||||
record Summary(int files, long bytes, boolean release, boolean sounds, List<String> builds) {}
|
||||
|
||||
static Summary write(Options options) throws IOException {
|
||||
Path out = options.out().toAbsolutePath().normalize();
|
||||
clear(out);
|
||||
Files.createDirectories(out);
|
||||
|
||||
// The builds' files by the name the page fetches them by (BuildManifest.BUILDS): each build's
|
||||
// folder has its module as incari.wasm; TeaVM's loader is one file for both.
|
||||
Map<String, Path> build = new LinkedHashMap<>();
|
||||
Map<String, @Nullable Path> folders = new LinkedHashMap<>();
|
||||
folders.put("fast", options.fast());
|
||||
folders.put("compatible", options.compatible());
|
||||
List<String> builds = new ArrayList<>();
|
||||
// Whether the builds so far are development builds (TeaVM's deobfuscator beside them): -1 none yet.
|
||||
int development = -1;
|
||||
for (Map.Entry<String, String> entry : BuildManifest.BUILDS.entrySet()) {
|
||||
Path folder = folders.get(entry.getKey());
|
||||
if (folder == null) {
|
||||
continue;
|
||||
}
|
||||
String module = entry.getValue();
|
||||
requireFile(
|
||||
folder.resolve("incari.wasm"),
|
||||
"Compile it first: ./gradlew :app-web:teavm -Pteavm.release"
|
||||
+ (entry.getKey().equals("fast") ? " -Pteavm.fast" : ""));
|
||||
build.putIfAbsent(
|
||||
BuildManifest.RUNTIME, requireFile(folder.resolve(BuildManifest.RUNTIME), "TeaVM's loader"));
|
||||
build.put(module, folder.resolve("incari.wasm"));
|
||||
putIfFile(
|
||||
build,
|
||||
module + BuildManifest.DEOBFUSCATOR,
|
||||
folder.resolve("incari.wasm" + BuildManifest.DEOBFUSCATOR));
|
||||
putIfFile(
|
||||
build, module + BuildManifest.DEBUG_INFO, folder.resolve("incari.wasm" + BuildManifest.DEBUG_INFO));
|
||||
int isDevelopment = Files.isRegularFile(folder.resolve("incari.wasm" + BuildManifest.DEOBFUSCATOR)) ? 1 : 0;
|
||||
if (development >= 0 && development != isDevelopment) {
|
||||
throw new CliException("The Fast and Compatible builds must both be release builds (-Pteavm.release)"
|
||||
+ " or both development builds");
|
||||
}
|
||||
development = isDevelopment;
|
||||
builds.add(entry.getKey().equals("fast") ? "Fast" : "Compatible");
|
||||
}
|
||||
for (String name : List.of("mesher.wasm", "mesher.wasm-runtime.js")) {
|
||||
build.put(name, requireFile(options.mesher().resolve(name), "Run ./gradlew :app-web:teavmMesher"));
|
||||
}
|
||||
build.put("incari.pack", requireFile(options.pack(), "Run ./gradlew :app-web:assetPack"));
|
||||
|
||||
Map<String, Path> copied = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, Path> entry : build.entrySet()) {
|
||||
copied.put(entry.getKey(), copy(entry.getValue(), out.resolve(entry.getKey())));
|
||||
}
|
||||
// Rust is its own page and files, in rust/ (ADR 0068).
|
||||
Path rust = options.rust();
|
||||
if (rust != null) {
|
||||
requireFile(rust.resolve("index.html"), "Build it first: ./incari build --only rust");
|
||||
FileTrees.copyTree(rust, out.resolve("rust"), "");
|
||||
builds.add("Rust");
|
||||
}
|
||||
JsonObject manifest = BuildManifest.manifest(options.game(), copied, rust != null);
|
||||
Files.writeString(
|
||||
out.resolve("build.json"),
|
||||
new GsonBuilder().setPrettyPrinting().create().toJson(manifest) + "\n");
|
||||
|
||||
copy(requireFile(options.page(), "the page's index.html"), out.resolve("index.html"));
|
||||
for (String script : SCRIPTS) {
|
||||
copy(
|
||||
requireFile(options.scripts().resolve(script + ".js"), "Run ./gradlew :app-web:pageScripts"),
|
||||
out.resolve(script + ".js"));
|
||||
}
|
||||
Files.write(
|
||||
out.resolve("client.jar"),
|
||||
resourcesOnly(Files.readAllBytes(requireFile(options.clientJar(), "Run ./incari setup"))));
|
||||
|
||||
Path assetIndex = options.assetIndex();
|
||||
Path assetObjects = options.assetObjects();
|
||||
boolean sounds = false;
|
||||
if (assetIndex != null && assetObjects != null) {
|
||||
copyAssets(assetIndex, assetObjects, out, options.soundFiles());
|
||||
sounds = options.soundFiles() != SoundFiles.NONE;
|
||||
}
|
||||
Files.writeString(out.resolve(".htaccess"), resource("htaccess"));
|
||||
Files.writeString(out.resolve("README.txt"), resource("README.txt").replace("{game}", options.game()));
|
||||
Files.writeString(out.resolve(MARKER), "Written by ./incari build. Never publish this folder.\n");
|
||||
|
||||
long[] totals = new long[2];
|
||||
try (Stream<Path> files = Files.walk(out)) {
|
||||
files.filter(Files::isRegularFile).forEach(file -> {
|
||||
totals[0]++;
|
||||
totals[1] += size(file);
|
||||
});
|
||||
}
|
||||
return new Summary(
|
||||
(int) totals[0], totals[1], manifest.get("release").getAsBoolean(), sounds, List.copyOf(builds));
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the asset index and the objects the page fetches from it: every sound and
|
||||
* {@link #PAGE_ASSETS}, the built-in packs among them (ADR 0055). The rest (the launcher's icons,
|
||||
* Realms' pictures) stays out: the page doesn't fetch it.
|
||||
*
|
||||
* <p>With {@link SoundFiles#NONE}, the sounds stay out too, and the index is written without them
|
||||
* and without the sound list, so the game lists no sound it can't fetch and plays silent. With
|
||||
* {@link SoundFiles#SMALL} (the single file, ADR 0057: all of them are 377 MB), every sound but
|
||||
* the music is encoded smaller and listed by its new hash; without ffmpeg, or with
|
||||
* {@link SoundFiles#CORE}, only {@link CoreSounds}' are copied as they are. Either way the sound
|
||||
* list is trimmed to the sounds kept and written as an object of its own.
|
||||
*/
|
||||
static void copyAssets(Path index, Path objects, Path out, SoundFiles soundFiles) throws IOException {
|
||||
requireFile(index, "Run ./incari assets");
|
||||
JsonObject root = JsonParser.parseString(Files.readString(index)).getAsJsonObject();
|
||||
JsonObject entries = root.getAsJsonObject("objects");
|
||||
if (soundFiles == SoundFiles.SMALL && !SmallSounds.available()) {
|
||||
System.out.println("==> No ffmpeg with Vorbis here, so only the common sounds go in."
|
||||
+ " Install ffmpeg for every sound but the music");
|
||||
soundFiles = SoundFiles.CORE;
|
||||
}
|
||||
Set<String> written = new HashSet<>();
|
||||
if (soundFiles == SoundFiles.ALL) {
|
||||
copy(index, out.resolve("asset-index.json"));
|
||||
} else {
|
||||
Predicate<String> keeps =
|
||||
switch (soundFiles) {
|
||||
case SMALL -> SmallSounds::keeps;
|
||||
case CORE -> CoreSounds::keeps;
|
||||
default -> name -> false;
|
||||
};
|
||||
JsonObject kept = new JsonObject();
|
||||
entries.entrySet().stream()
|
||||
.filter(entry -> !isSound(entry.getKey()) || keeps.test(entry.getKey()))
|
||||
.forEach(entry -> kept.add(entry.getKey(), entry.getValue()));
|
||||
if (soundFiles == SoundFiles.SMALL) {
|
||||
encodeSmaller(kept, objects, out, written);
|
||||
}
|
||||
if (soundFiles != SoundFiles.NONE) {
|
||||
written.add(SOUND_LIST);
|
||||
kept.add(SOUND_LIST, writeSoundList(entries, objects, out, kept));
|
||||
}
|
||||
root.add("objects", kept);
|
||||
Files.writeString(
|
||||
out.resolve("asset-index.json"), new GsonBuilder().create().toJson(root));
|
||||
entries = kept;
|
||||
}
|
||||
List<String> missing = new ArrayList<>();
|
||||
for (Map.Entry<String, JsonElement> entry : entries.entrySet()) {
|
||||
String name = entry.getKey();
|
||||
if ((!name.endsWith(".ogg") && !forPage(name)) || written.contains(name)) {
|
||||
continue;
|
||||
}
|
||||
String hash = entry.getValue().getAsJsonObject().get("hash").getAsString();
|
||||
String path = hash.substring(0, 2) + "/" + hash;
|
||||
Path source = objects.resolve(path);
|
||||
if (!Files.isRegularFile(source)) {
|
||||
missing.add(name);
|
||||
continue;
|
||||
}
|
||||
Path target = out.resolve("assets/objects").resolve(path);
|
||||
// Content-addressed: two names with one file share it.
|
||||
if (!Files.exists(target)) {
|
||||
copy(source, target);
|
||||
}
|
||||
}
|
||||
if (!missing.isEmpty()) {
|
||||
throw new CliException(missing.size() + " assets aren't downloaded (" + missing.getFirst()
|
||||
+ ", ...). Run ./incari assets, or build without sounds");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The client jar without its classes and {@code META-INF}, which the page and the server worker
|
||||
* never read (the page's {@code ClientJar}, {@code GameWorkerMain}): 41 MB to 8 on a first visit.
|
||||
*/
|
||||
static byte[] resourcesOnly(byte[] jar) throws IOException {
|
||||
ByteArrayOutputStream kept = new ByteArrayOutputStream(jar.length / 4);
|
||||
try (ZipInputStream in = new ZipInputStream(new ByteArrayInputStream(jar));
|
||||
ZipOutputStream zip = new ZipOutputStream(kept)) {
|
||||
zip.setLevel(Deflater.BEST_COMPRESSION);
|
||||
for (ZipEntry entry = in.getNextEntry(); entry != null; entry = in.getNextEntry()) {
|
||||
String name = entry.getName();
|
||||
if (name.endsWith(".class") || name.startsWith("META-INF/")) {
|
||||
continue;
|
||||
}
|
||||
ZipEntry copy = new ZipEntry(name);
|
||||
copy.setTime(entry.getTime());
|
||||
zip.putNextEntry(copy);
|
||||
in.transferTo(zip);
|
||||
zip.closeEntry();
|
||||
}
|
||||
}
|
||||
return kept.toByteArray();
|
||||
}
|
||||
|
||||
private static boolean isSound(String name) {
|
||||
return name.endsWith(".ogg") || name.equals(SOUND_LIST);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the sound list trimmed to the sound files in {@code kept} as an object of its own,
|
||||
* named by its hash as the index's are, and returns its index entry.
|
||||
*/
|
||||
private static JsonObject writeSoundList(JsonObject entries, Path objects, Path out, JsonObject kept)
|
||||
throws IOException {
|
||||
JsonElement listed = entries.get(SOUND_LIST);
|
||||
if (listed == null) {
|
||||
throw new CliException("The asset index has no " + SOUND_LIST + ". Run ./incari assets");
|
||||
}
|
||||
String hash = listed.getAsJsonObject().get("hash").getAsString();
|
||||
Path source = requireFile(objects.resolve(hash.substring(0, 2) + "/" + hash), "Run ./incari assets");
|
||||
JsonObject trimmed =
|
||||
CoreSounds.trim(JsonParser.parseString(Files.readString(source)).getAsJsonObject(), kept::has);
|
||||
byte[] bytes = new GsonBuilder().create().toJson(trimmed).getBytes(StandardCharsets.UTF_8);
|
||||
return writeObject(out, bytes);
|
||||
}
|
||||
|
||||
/** Writes {@code bytes} as an object named by its hash, as the index's are; returns its entry. */
|
||||
private static JsonObject writeObject(Path out, byte[] bytes) throws IOException {
|
||||
String sha1;
|
||||
try {
|
||||
sha1 = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(bytes));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
Path target = out.resolve("assets/objects").resolve(sha1.substring(0, 2) + "/" + sha1);
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.write(target, bytes);
|
||||
JsonObject entry = new JsonObject();
|
||||
entry.addProperty("hash", sha1);
|
||||
entry.addProperty("size", bytes.length);
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes every sound in {@code kept} smaller ({@link SmallSounds}), side by side, writes each as
|
||||
* an object of its own and lists it in {@code kept} by its new hash; their names go in
|
||||
* {@code written}.
|
||||
*/
|
||||
private static void encodeSmaller(JsonObject kept, Path objects, Path out, Set<String> written) throws IOException {
|
||||
Map<String, String> sounds = new TreeMap<>();
|
||||
for (Map.Entry<String, JsonElement> entry : kept.entrySet()) {
|
||||
if (entry.getKey().endsWith(".ogg")) {
|
||||
sounds.put(
|
||||
entry.getKey(),
|
||||
entry.getValue().getAsJsonObject().get("hash").getAsString());
|
||||
}
|
||||
}
|
||||
List<String> missing = new ArrayList<>();
|
||||
for (Map.Entry<String, String> sound : sounds.entrySet()) {
|
||||
String hash = sound.getValue();
|
||||
if (!Files.isRegularFile(objects.resolve(hash.substring(0, 2) + "/" + hash))) {
|
||||
missing.add(sound.getKey());
|
||||
}
|
||||
}
|
||||
if (!missing.isEmpty()) {
|
||||
throw new CliException(missing.size() + " sounds aren't downloaded (" + missing.getFirst()
|
||||
+ ", ...). Run ./incari assets, or build without sounds");
|
||||
}
|
||||
System.out.println("==> Encoding " + sounds.size() + " sounds smaller (once; kept for the next build)");
|
||||
Map<String, Future<byte[]>> encoded = new LinkedHashMap<>();
|
||||
int threads = Math.max(1, Runtime.getRuntime().availableProcessors());
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(threads)) {
|
||||
for (Map.Entry<String, String> sound : sounds.entrySet()) {
|
||||
encoded.put(sound.getKey(), pool.submit(() -> SmallSounds.encode(objects, sound.getValue())));
|
||||
}
|
||||
for (Map.Entry<String, Future<byte[]>> sound : encoded.entrySet()) {
|
||||
byte[] bytes;
|
||||
try {
|
||||
bytes = sound.getValue().get();
|
||||
} catch (ExecutionException e) {
|
||||
throw e.getCause() instanceof IOException io ? io : new IOException(e.getCause());
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("Interrupted encoding the sounds", e);
|
||||
}
|
||||
kept.add(sound.getKey(), writeObject(out, bytes));
|
||||
written.add(sound.getKey());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean forPage(String name) {
|
||||
for (String asset : PAGE_ASSETS) {
|
||||
if (asset.endsWith("/") ? name.startsWith(asset) : name.equals(asset)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Empties {@code out} for a fresh write, but only if it's missing, empty, or a folder this tool
|
||||
* wrote: never someone's other files.
|
||||
*/
|
||||
static void clear(Path out) throws IOException {
|
||||
if (!Files.exists(out)) {
|
||||
return;
|
||||
}
|
||||
if (!Files.isDirectory(out)) {
|
||||
throw new CliException(out + " exists and isn't a folder");
|
||||
}
|
||||
boolean empty;
|
||||
try (Stream<Path> children = Files.list(out)) {
|
||||
empty = children.findAny().isEmpty();
|
||||
}
|
||||
if (empty) {
|
||||
return;
|
||||
}
|
||||
if (!Files.isRegularFile(out.resolve(MARKER))) {
|
||||
throw new CliException(
|
||||
out + " already has files that ./incari build didn't write. Pick an empty " + "or new folder");
|
||||
}
|
||||
try (Stream<Path> files = Files.walk(out)) {
|
||||
for (Path file : files.sorted(Comparator.reverseOrder())
|
||||
.filter(file -> !file.equals(out))
|
||||
.toList()) {
|
||||
Files.delete(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Path copy(Path source, Path target) throws IOException {
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
return target;
|
||||
}
|
||||
|
||||
private static void putIfFile(Map<String, Path> files, String name, Path path) {
|
||||
if (Files.isRegularFile(path)) {
|
||||
files.put(name, path);
|
||||
}
|
||||
}
|
||||
|
||||
private static Path requireFile(Path path, String hint) {
|
||||
if (!Files.isRegularFile(path)) {
|
||||
throw new CliException("Missing " + path + ". " + hint);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
private static String required(Map<String, String> values, String name) {
|
||||
String value = values.get(name);
|
||||
if (value == null) {
|
||||
throw new CliException("Missing --" + name);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static @Nullable Path optionalPath(Map<String, String> values, String name) {
|
||||
String value = values.get(name);
|
||||
return value == null || value.isEmpty() ? null : Path.of(value);
|
||||
}
|
||||
|
||||
private static long size(Path file) {
|
||||
try {
|
||||
return Files.size(file);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String resource(String name) throws IOException {
|
||||
try (InputStream in = WebFolder.class.getResourceAsStream("/web-folder/" + name)) {
|
||||
if (in == null) {
|
||||
throw new IllegalStateException("Missing resource web-folder/" + name);
|
||||
}
|
||||
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
incari.tools.webbuild.ReflectionDeclarations
|
||||
+1
@@ -0,0 +1 @@
|
||||
incari.tools.webbuild.ClasslibPolicy
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
incari.tools.webbuild.MathIntrinsics
|
||||
incari.tools.webbuild.JsoIntrinsics
|
||||
@@ -0,0 +1,75 @@
|
||||
Incari web build (Minecraft {game})
|
||||
===================================
|
||||
|
||||
DO NOT SHARE, UPLOAD OR PUBLISH THIS FOLDER.
|
||||
|
||||
This folder contains Minecraft's code and files (the compiled game, the client jar, its
|
||||
sounds and translated shaders). Mojang owns them and doesn't allow redistributing them. The
|
||||
Incari project publishes only patches and source code, never builds, and gives nobody
|
||||
permission to distribute a build: not on a public website, a file host, a mirror, a Discord
|
||||
server, a GitHub repository, Pages or Releases, or as a downloadable copy.
|
||||
|
||||
You built this folder yourself from your own download of the game, for your own use. If you
|
||||
put it on a web server, it's your server and your responsibility: keep it to yourself or to
|
||||
people you know, behind a login or on a private network, and take it down when you're done.
|
||||
Anyone who shares or hosts a build does so on their own, not on behalf of the Incari project
|
||||
or its contributors.
|
||||
|
||||
Incari is not affiliated with or endorsed by Mojang or Microsoft. Minecraft is a trademark of
|
||||
Mojang Studios. Players need to own Minecraft: Java Edition.
|
||||
|
||||
|
||||
Serving it
|
||||
----------
|
||||
|
||||
Any static web server works: serve this folder as it is and open index.html. Everything is
|
||||
fetched by relative path, so a sub-folder (https://example.test/incari/) works too.
|
||||
|
||||
* HTTPS (or localhost) is strongly recommended. Over plain HTTP from another machine the
|
||||
browser turns off the service worker (no caching between visits) and the origin private
|
||||
file system (saves fall back to IndexedDB).
|
||||
* Send .wasm as application/wasm. Without it the browser can't compile while downloading.
|
||||
* Turn on gzip or brotli for .wasm, .js and .json. The game module compresses to about a
|
||||
fifth of its size.
|
||||
* Optional but faster: these two headers on every response make the page cross-origin
|
||||
isolated, so the game's workers share memory instead of copying.
|
||||
|
||||
Cross-Origin-Opener-Policy: same-origin
|
||||
Cross-Origin-Embedder-Policy: require-corp
|
||||
|
||||
Apache: the .htaccess in this folder sets all of it (it needs mod_headers and AllowOverride).
|
||||
|
||||
nginx:
|
||||
|
||||
location /incari/ {
|
||||
alias /path/to/this/folder/;
|
||||
types { application/wasm wasm; text/javascript js; application/json json; text/html html; }
|
||||
gzip on;
|
||||
gzip_types application/wasm text/javascript application/json;
|
||||
add_header Cross-Origin-Opener-Policy same-origin always;
|
||||
add_header Cross-Origin-Embedder-Policy require-corp always;
|
||||
add_header Cache-Control no-cache always;
|
||||
}
|
||||
|
||||
Caddy:
|
||||
|
||||
example.test {
|
||||
root * /path/to/this/folder
|
||||
encode zstd gzip
|
||||
header Cross-Origin-Opener-Policy same-origin
|
||||
header Cross-Origin-Embedder-Policy require-corp
|
||||
header Cache-Control no-cache
|
||||
file_server
|
||||
}
|
||||
|
||||
A quick test on one machine, without the headers (it still runs, without shared memory):
|
||||
|
||||
python3 -m http.server 8080 --directory /path/to/this/folder
|
||||
|
||||
Joining servers: the browser connects over WebSocket, so a server needs a WebSocket
|
||||
front (EaglerXServer, or a WebSocket bridge). A page served over HTTPS can only open wss://
|
||||
connections.
|
||||
|
||||
Browsers: a current Chrome or Edge (what Incari is tested on) with WebGL 2 and WebAssembly GC.
|
||||
The Fast build needs Chrome or Edge 137 or Firefox 153; the Compatible build runs in Chrome 119,
|
||||
Firefox 120 and Safari 18.2 and later.
|
||||
@@ -0,0 +1,27 @@
|
||||
# Written by ./incari build for Apache (needs mod_headers; mod_mime and mod_deflate are standard).
|
||||
# Other servers: see README.txt.
|
||||
|
||||
<IfModule mod_mime.c>
|
||||
AddType application/wasm .wasm
|
||||
AddType text/javascript .js
|
||||
AddType application/json .json
|
||||
</IfModule>
|
||||
|
||||
<IfModule mod_headers.c>
|
||||
# Cross-origin isolation: lets the game share memory with its worker threads. Without these
|
||||
# headers it still runs, a little slower.
|
||||
Header set Cross-Origin-Opener-Policy "same-origin"
|
||||
Header set Cross-Origin-Embedder-Policy "require-corp"
|
||||
# The page asks for each build file with its hash (incari.wasm?v=...), so revalidating is cheap.
|
||||
Header set Cache-Control "no-cache"
|
||||
# Sounds are named by their hash and never change.
|
||||
<If "%{REQUEST_URI} =~ m#/assets/objects/#">
|
||||
Header set Cache-Control "public, max-age=31536000, immutable"
|
||||
</If>
|
||||
</IfModule>
|
||||
|
||||
<IfModule mod_deflate.c>
|
||||
AddOutputFilterByType DEFLATE application/wasm text/javascript application/json text/html
|
||||
</IfModule>
|
||||
|
||||
Options -Indexes
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ClasslibRenamerTest {
|
||||
|
||||
@Test
|
||||
void mapsSubstitutesBackToTheirOriginals() {
|
||||
assertThat(ClasslibRenamer.original("incari.classlib.substitutes.java.nio.channels.TFileChannel"))
|
||||
.isEqualTo("java.nio.channels.FileChannel");
|
||||
assertThat(ClasslibRenamer.original("incari.classlib.substitutes.java.nio.channels.TFileChannel$MapMode"))
|
||||
.isEqualTo("java.nio.channels.FileChannel$MapMode");
|
||||
assertThat(ClasslibRenamer.original("incari.classlib.substitutes.org.slf4j.TLoggerFactory"))
|
||||
.isEqualTo("org.slf4j.LoggerFactory");
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesEverythingElse() {
|
||||
assertThat(ClasslibRenamer.original("incari.classlib.nio.FileChannels"))
|
||||
.isEqualTo("incari.classlib.nio.FileChannels");
|
||||
assertThat(ClasslibRenamer.original("incari.classlib.substitutes.java.util.Helper"))
|
||||
.isEqualTo("incari.classlib.substitutes.java.util.Helper");
|
||||
assertThat(ClasslibRenamer.original("java.lang.Thread")).isEqualTo("java.lang.Thread");
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CoreSoundsTest {
|
||||
|
||||
@Test
|
||||
void keepsTheEverydaySoundsAndLeavesMusicAndTheRestOut() {
|
||||
assertThat(CoreSounds.keeps("minecraft/sounds/dig/stone1.ogg")).isTrue();
|
||||
assertThat(CoreSounds.keeps("minecraft/sounds/random/explode1.ogg")).isTrue();
|
||||
assertThat(CoreSounds.keeps("minecraft/sounds/block/chest/open.ogg")).isTrue();
|
||||
assertThat(CoreSounds.keeps("minecraft/sounds/mob/creeper/say1.ogg")).isTrue();
|
||||
|
||||
assertThat(CoreSounds.keeps("minecraft/sounds/music/game/calm1.ogg")).isFalse();
|
||||
assertThat(CoreSounds.keeps("minecraft/sounds/records/cat.ogg")).isFalse();
|
||||
assertThat(CoreSounds.keeps("minecraft/sounds/ambient/cave/cave1.ogg")).isFalse();
|
||||
assertThat(CoreSounds.keeps("minecraft/sounds/block/deepslate/break1.ogg"))
|
||||
.isFalse();
|
||||
assertThat(CoreSounds.keeps("minecraft/sounds/mob/pig/say1.ogg")).isFalse();
|
||||
// Only the sound files themselves.
|
||||
assertThat(CoreSounds.keeps("minecraft/sounds.json")).isFalse();
|
||||
assertThat(CoreSounds.keeps("minecraft/lang/dig/x.ogg")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void trimsEventsToSoundsLeftAndDropsEventsLeftEmpty() {
|
||||
JsonObject list = JsonParser.parseString("""
|
||||
{"a": {"sounds": ["dig/stone1", "dig/gone"]},
|
||||
"b": {"sounds": [{"name": "minecraft:dig/gone", "volume": 0.5}]},
|
||||
"c": {"sounds": [{"name": "b", "type": "event"}, {"name": "a", "type": "event"}]},
|
||||
"d": {"sounds": [{"name": "b", "type": "event"}]},
|
||||
"e": {"replace": true}}
|
||||
""").getAsJsonObject();
|
||||
|
||||
JsonObject trimmed = CoreSounds.trim(list, Set.of("minecraft/sounds/dig/stone1.ogg")::contains);
|
||||
|
||||
assertThat(trimmed.keySet()).containsExactlyInAnyOrder("a", "c", "e");
|
||||
assertThat(trimmed.getAsJsonObject("a").getAsJsonArray("sounds")).hasSize(1);
|
||||
assertThat(trimmed.getAsJsonObject("c").getAsJsonArray("sounds")).hasSize(1);
|
||||
// The input is left as it was.
|
||||
assertThat(list.keySet()).hasSize(5);
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import incari.tools.webbuild.DownloadBudget.Kind;
|
||||
import incari.tools.webbuild.DownloadBudget.Measure;
|
||||
import incari.tools.webbuild.DownloadBudget.Measured;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class DownloadBudgetTest {
|
||||
|
||||
private static final DownloadBudget BUDGET = DownloadBudget.parse(
|
||||
List.of(
|
||||
"# a comment",
|
||||
"",
|
||||
"file.game.wasm=download",
|
||||
"file.page.html = download",
|
||||
"file.extra.json=download",
|
||||
"file.game.teadbg=debug",
|
||||
"file.*.txt=report",
|
||||
"file.client.jar=vendor",
|
||||
"max.gzip.total=1_000",
|
||||
"max.gzip.game.wasm=900",
|
||||
"max.raw.game.wasm=5000",
|
||||
"max.gzip.extra.json=50",
|
||||
"max.brotli.page.html=10"),
|
||||
"test");
|
||||
|
||||
@Test
|
||||
void classifiesByNameThenGlob() {
|
||||
assertThat(BUDGET.kindOf("game.wasm")).isEqualTo(Kind.DOWNLOAD);
|
||||
assertThat(BUDGET.kindOf("page.html")).isEqualTo(Kind.DOWNLOAD);
|
||||
assertThat(BUDGET.kindOf("removed.txt")).isEqualTo(Kind.REPORT);
|
||||
assertThat(BUDGET.kindOf("sub/removed.txt")).isNull();
|
||||
assertThat(BUDGET.kindOf("shaders.json")).isNull();
|
||||
assertThat(BUDGET.limit(Measure.GZIP, "total")).isNotNull();
|
||||
assertThat(BUDGET.limit(Measure.BROTLI, "game.wasm")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void passesUnderBudgetAndSkipsAnOptionalFileNotBuiltYet() {
|
||||
DownloadBudget.Verdict verdict = BUDGET.judge(
|
||||
List.of(
|
||||
new Measured("game.wasm", Kind.DOWNLOAD, 4000, 800, 500L),
|
||||
new Measured("page.html", Kind.DOWNLOAD, 100, 60, 9L),
|
||||
// Debug and vendor files never count toward the total.
|
||||
new Measured("game.teadbg", Kind.DEBUG, 9000, 9000, 9000L),
|
||||
new Measured("client.jar", Kind.VENDOR, 9000, 9000, 9000L)),
|
||||
Set.of("extra.json", "client.jar"));
|
||||
assertThat(verdict.failures()).isEmpty();
|
||||
assertThat(verdict.notes()).singleElement().asString().contains("extra.json isn't built yet");
|
||||
assertThat(verdict.outcomes())
|
||||
.filteredOn(o -> o.limit().file().equals("total"))
|
||||
.singleElement()
|
||||
.extracting(DownloadBudget.Outcome::actual)
|
||||
.isEqualTo(860L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsOverBudgetAndOnAMissingBudgetedFile() {
|
||||
DownloadBudget.Verdict verdict =
|
||||
BUDGET.judge(List.of(new Measured("game.wasm", Kind.DOWNLOAD, 6000, 950, 500L)), Set.of("extra.json"));
|
||||
assertThat(verdict.passed()).isFalse();
|
||||
assertThat(verdict.failures())
|
||||
.containsExactly(
|
||||
"max.gzip.game.wasm: 950 bytes, the budget is 900",
|
||||
"max.raw.game.wasm: 6000 bytes, the budget is 5000",
|
||||
"page.html has a limit but isn't in the build output");
|
||||
}
|
||||
|
||||
@Test
|
||||
void brotliLimitsAreSkippedWithoutBrotli() {
|
||||
DownloadBudget.Verdict verdict = BUDGET.judge(
|
||||
List.of(
|
||||
new Measured("game.wasm", Kind.DOWNLOAD, 10, 10, null),
|
||||
new Measured("page.html", Kind.DOWNLOAD, 10, 10, null)),
|
||||
Set.of("extra.json"));
|
||||
assertThat(verdict.passed()).isTrue();
|
||||
assertThat(verdict.notes()).anyMatch(n -> n.contains("max.brotli.page.html wasn't checked"));
|
||||
assertThat(DownloadBudget.total(
|
||||
List.of(new Measured("game.wasm", Kind.DOWNLOAD, 10, 10, null)), Measure.BROTLI))
|
||||
.isEqualTo(-1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMistakes() {
|
||||
assertThatThrownBy(() -> DownloadBudget.parse(List.of("file.a=shipped"), "t"))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("unknown class");
|
||||
assertThatThrownBy(() -> DownloadBudget.parse(List.of("file.a=download", "file.a=debug"), "t"))
|
||||
.hasMessageContaining("classified twice");
|
||||
assertThatThrownBy(() -> DownloadBudget.parse(List.of("max.zstd.a=1", "file.a=download"), "t"))
|
||||
.hasMessageContaining("unknown measure");
|
||||
assertThatThrownBy(() -> DownloadBudget.parse(List.of("file.a=download", "max.gzip.a=lots"), "t"))
|
||||
.hasMessageContaining("byte count");
|
||||
// Only what players download is budgeted.
|
||||
assertThatThrownBy(() -> DownloadBudget.parse(List.of("file.a=debug", "max.gzip.a=1"), "t"))
|
||||
.hasMessageContaining("isn't classified 'download'");
|
||||
assertThatThrownBy(() -> DownloadBudget.parse(List.of("max.gzip.b=1"), "t"))
|
||||
.hasMessageContaining("isn't classified 'download'");
|
||||
assertThatThrownBy(() -> DownloadBudget.parse(List.of("budget=1"), "t")).hasMessageContaining("unknown key");
|
||||
DownloadBudget conflicting = DownloadBudget.parse(List.of("file.*.txt=report", "file.a.*=download"), "t");
|
||||
assertThatThrownBy(() -> conflicting.kindOf("a.txt")).hasMessageContaining("classify it differently");
|
||||
}
|
||||
|
||||
/** The checked-in budget parses, and classifies everything a development build writes today. */
|
||||
@Test
|
||||
void theRepositoryBudgetIsValid() throws Exception {
|
||||
Path file = Path.of("../../app-web/download-budget.properties");
|
||||
assertThat(Files.isRegularFile(file))
|
||||
.as(file.toAbsolutePath().toString())
|
||||
.isTrue();
|
||||
DownloadBudget budget = DownloadBudget.load(file);
|
||||
for (String name : List.of(
|
||||
"incari.wasm",
|
||||
"incari.wasm-runtime.js",
|
||||
"index.html",
|
||||
"shaders.json",
|
||||
"incari.wasm.teadbg",
|
||||
"incari.wasm-deobfuscator.wasm",
|
||||
"problems.txt",
|
||||
"async.txt",
|
||||
"removed.txt",
|
||||
"signatures.txt",
|
||||
"client.jar")) {
|
||||
assertThat(budget.kindOf(name)).as(name).isNotNull();
|
||||
}
|
||||
assertThat(budget.kindOf("incari.wasm")).isEqualTo(Kind.DOWNLOAD);
|
||||
assertThat(budget.kindOf("client.jar")).isEqualTo(Kind.VENDOR);
|
||||
assertThat(budget.limit(Measure.GZIP, DownloadBudget.TOTAL)).isNotNull();
|
||||
assertThat(budget.limit(Measure.GZIP, "incari.wasm")).isNotNull();
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class DownloadSizeTest {
|
||||
|
||||
@TempDir
|
||||
Path dir;
|
||||
|
||||
@Test
|
||||
void gzipSizeIsARealGzipStreamsSize() throws Exception {
|
||||
byte[] data =
|
||||
"the quick brown fox jumps over the lazy dog\n".repeat(1000).getBytes(StandardCharsets.UTF_8);
|
||||
Path file = dir.resolve("data.txt");
|
||||
Files.write(file, data);
|
||||
long size = DownloadSize.gzipSize(file);
|
||||
assertThat(size).isGreaterThan(18).isLessThan(data.length / 10);
|
||||
|
||||
// The same bytes, written out, decompress to the input.
|
||||
ByteArrayOutputStream compressed = new ByteArrayOutputStream();
|
||||
try (var out = new java.util.zip.GZIPOutputStream(compressed) {
|
||||
{
|
||||
def.setLevel(DownloadSize.GZIP_LEVEL);
|
||||
}
|
||||
}) {
|
||||
out.write(data);
|
||||
}
|
||||
assertThat(compressed.size()).isEqualTo(size);
|
||||
try (var in = new GZIPInputStream(new java.io.ByteArrayInputStream(compressed.toByteArray()))) {
|
||||
assertThat(in.readAllBytes()).isEqualTo(data);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void checksADirectoryAndExtraFilesAndWritesAReport() throws Exception {
|
||||
Path build = Files.createDirectories(dir.resolve("build"));
|
||||
Files.writeString(build.resolve("game.wasm"), "x".repeat(10_000));
|
||||
Files.writeString(build.resolve("problems.txt"), "");
|
||||
Path extra = dir.resolve("elsewhere/extra.json");
|
||||
Files.createDirectories(extra.getParent());
|
||||
Files.writeString(extra, "{}");
|
||||
Path budget = dir.resolve("budget.properties");
|
||||
Files.write(
|
||||
budget,
|
||||
List.of(
|
||||
"file.game.wasm=download",
|
||||
"file.extra.json=download",
|
||||
"file.later.json=download",
|
||||
"file.*.txt=report",
|
||||
"max.gzip.total=1000",
|
||||
"max.raw.game.wasm=10000",
|
||||
"max.gzip.later.json=10"));
|
||||
Path report = dir.resolve("reports/size.json");
|
||||
|
||||
int status = DownloadSize.run(DownloadSize.Options.parse(List.of(
|
||||
"--budget",
|
||||
budget.toString(),
|
||||
"--dir",
|
||||
build.toString(),
|
||||
"--file",
|
||||
"extra.json=" + extra,
|
||||
"--file",
|
||||
"later.json=" + dir.resolve("missing.json"),
|
||||
"--report",
|
||||
report.toString(),
|
||||
"--no-brotli")));
|
||||
|
||||
assertThat(status).isZero();
|
||||
String json = Files.readString(report);
|
||||
assertThat(json)
|
||||
.contains("{\"name\": \"game.wasm\", \"class\": \"download\", \"raw\": 10000, \"gzip\": ")
|
||||
.contains("{\"name\": \"extra.json\", \"class\": \"download\", \"raw\": 2, \"gzip\": ")
|
||||
.contains("\"brotli\": null")
|
||||
.contains("\"passed\": true");
|
||||
|
||||
// One byte over the raw limit fails.
|
||||
Files.writeString(build.resolve("game.wasm"), "x".repeat(10_001));
|
||||
assertThat(DownloadSize.run(DownloadSize.Options.parse(
|
||||
List.of("--budget", budget.toString(), "--dir", build.toString(), "--no-brotli"))))
|
||||
.isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnclassifiedFileFailsTheCheck() throws Exception {
|
||||
Path build = Files.createDirectories(dir.resolve("build"));
|
||||
Files.writeString(build.resolve("game.wasm"), "x");
|
||||
Files.writeString(build.resolve("new-thing.bin"), "x");
|
||||
Path budget = dir.resolve("budget.properties");
|
||||
Files.write(budget, List.of("file.game.wasm=download"));
|
||||
assertThatThrownBy(() -> DownloadSize.run(DownloadSize.Options.parse(
|
||||
List.of("--budget", budget.toString(), "--dir", build.toString(), "--no-brotli"))))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("Not classified")
|
||||
.hasMessageContaining("new-thing.bin");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tableShowsTheGzipBudgetAndHeadroom() {
|
||||
DownloadBudget budget = DownloadBudget.parse(
|
||||
List.of("file.a.wasm=download", "file.b.txt=report", "max.gzip.a.wasm=2000000"), "t");
|
||||
String table = DownloadSize.table(
|
||||
List.of(
|
||||
new DownloadBudget.Measured("a.wasm", DownloadBudget.Kind.DOWNLOAD, 5_000_000, 1_500_000, null),
|
||||
new DownloadBudget.Measured("b.txt", DownloadBudget.Kind.REPORT, 10, 30, 5L)),
|
||||
budget);
|
||||
assertThat(table)
|
||||
.contains("a.wasm")
|
||||
.contains("5.00 MB")
|
||||
.contains("2.00 MB")
|
||||
.contains("500.0 kB (25%)")
|
||||
.contains("n/a")
|
||||
.contains("total downloaded");
|
||||
assertThat(DownloadSize.human(999)).isEqualTo("999 B");
|
||||
assertThat(DownloadSize.human(1_500)).isEqualTo("1.5 kB");
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.within;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FrameStatsTest {
|
||||
|
||||
@Test
|
||||
void frameRatesComeFromTheTimeBetweenFrames() {
|
||||
FrameStats stats = new FrameStats();
|
||||
// 99 frames of 16 ms and one of 100 ms: the median is 62.5 fps, the 1% low (the slowest
|
||||
// frame, 1% of 100) 10 fps.
|
||||
double[] table = new double[100 * FrameStats.COLUMNS];
|
||||
for (int frame = 0; frame < 100; frame++) {
|
||||
int row = frame * FrameStats.COLUMNS;
|
||||
java.util.Arrays.fill(table, row, row + FrameStats.COLUMNS, Double.NaN);
|
||||
table[row + FrameStats.INTERVAL] = frame == 50 ? 100 : 16;
|
||||
table[row + FrameStats.TICK] = 2;
|
||||
table[row + FrameStats.DRAWS] = frame < 50 ? 100 : 300;
|
||||
table[row + FrameStats.TERRAIN_DRAWS] = -1;
|
||||
table[row + FrameStats.HEAP] = frame;
|
||||
}
|
||||
stats.add(table);
|
||||
|
||||
Map<String, Double> figures = stats.figures();
|
||||
|
||||
assertThat(figures.get("frames")).isEqualTo(100);
|
||||
assertThat(figures.get("fpsMedian")).isCloseTo(62.5, within(1e-9));
|
||||
assertThat(figures.get("fpsLow1")).isCloseTo(10, within(1e-9));
|
||||
assertThat(figures.get("frameP99Millis")).isEqualTo(16);
|
||||
assertThat(figures.get("tickMillis")).isEqualTo(2);
|
||||
assertThat(figures.get("drawCalls")).isEqualTo(200);
|
||||
assertThat(figures.get("terrainDrawCalls")).isNaN();
|
||||
assertThat(figures.get("gpuMillis")).isNaN();
|
||||
assertThat(figures.get("heapMaxMB")).isEqualTo(99);
|
||||
assertThat(figures.get("gcCount")).isNaN();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theOnePercentLowAveragesTheSlowestOnePercent() {
|
||||
double[] sorted = new double[200];
|
||||
java.util.Arrays.fill(sorted, 10);
|
||||
sorted[198] = 40;
|
||||
sorted[199] = 50;
|
||||
|
||||
assertThat(FrameStats.slowestMean(sorted, 1)).isEqualTo(45);
|
||||
assertThat(FrameStats.slowestMean(new double[] {5}, 1)).isEqualTo(5);
|
||||
assertThat(FrameStats.percentile(sorted, 99)).isEqualTo(10);
|
||||
assertThat(FrameStats.percentile(sorted, 50)).isEqualTo(10);
|
||||
assertThat(FrameStats.percentile(new double[0], 50)).isNaN();
|
||||
}
|
||||
|
||||
@Test
|
||||
void gcPausesAreTheMainThreadsMinorAndMajorCollections() {
|
||||
List<JsonObject> events = List.of(
|
||||
json(
|
||||
"{\"name\":\"thread_name\",\"ph\":\"M\",\"pid\":1,\"tid\":7,\"args\":{\"name\":\"CrRendererMain\"}}"),
|
||||
json("{\"name\":\"MinorGC\",\"ph\":\"X\",\"pid\":1,\"tid\":7,\"dur\":1500}"),
|
||||
json("{\"name\":\"MajorGC\",\"ph\":\"X\",\"pid\":1,\"tid\":7,\"dur\":12000}"),
|
||||
// A worker's collection doesn't pause the game.
|
||||
json("{\"name\":\"MajorGC\",\"ph\":\"X\",\"pid\":1,\"tid\":9,\"dur\":90000}"),
|
||||
json("{\"name\":\"V8.GCScavenger\",\"ph\":\"X\",\"pid\":1,\"tid\":7,\"dur\":1400}"));
|
||||
|
||||
GcStats gc = GcStats.of(events);
|
||||
|
||||
assertThat(gc.count()).isEqualTo(2);
|
||||
assertThat(gc.totalMillis()).isCloseTo(13.5, within(1e-9));
|
||||
assertThat(gc.maxMillis()).isCloseTo(12, within(1e-9));
|
||||
assertThat(GcStats.NONE.plus(gc)).isEqualTo(gc);
|
||||
}
|
||||
|
||||
private static JsonObject json(String text) {
|
||||
return JsonParser.parseString(text).getAsJsonObject();
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.assertj.core.api.Assertions.within;
|
||||
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.Random;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ImageDiffTest {
|
||||
|
||||
@Test
|
||||
void identicalImagesScoreOne() {
|
||||
BufferedImage image = checkerboard(64, 48, 0);
|
||||
ImageDiff.Result result = ImageDiff.compare(image, copy(image));
|
||||
assertThat(result.ssim()).isCloseTo(1.0, within(1e-6));
|
||||
assertThat(result.changed()).isZero();
|
||||
}
|
||||
|
||||
@Test
|
||||
void faintNoiseCostsLittleAndMissingDetailCostsMuch() {
|
||||
BufferedImage image = checkerboard(64, 48, 0);
|
||||
BufferedImage noisy = copy(image);
|
||||
Random random = new Random(1);
|
||||
for (int y = 0; y < noisy.getHeight(); y++) {
|
||||
for (int x = 0; x < noisy.getWidth(); x++) {
|
||||
int rgb = noisy.getRGB(x, y);
|
||||
int delta = random.nextInt(7) - 3;
|
||||
int red = Math.clamp(((rgb >> 16) & 0xFF) + delta, 0, 255);
|
||||
noisy.setRGB(x, y, (rgb & 0xFF00FFFF) | (red << 16));
|
||||
}
|
||||
}
|
||||
BufferedImage flat = new BufferedImage(64, 48, BufferedImage.TYPE_INT_RGB);
|
||||
assertThat(ImageDiff.compare(image, noisy).ssim()).isGreaterThan(0.95);
|
||||
assertThat(ImageDiff.compare(image, flat).ssim()).isLessThan(0.2);
|
||||
assertThat(ImageDiff.compare(image, flat).changed()).isGreaterThan(0.4);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWrongColorIsSeen() {
|
||||
BufferedImage image = checkerboard(64, 48, 0);
|
||||
BufferedImage tinted = checkerboard(64, 48, 0x00FF00);
|
||||
assertThat(ImageDiff.compare(image, tinted).ssim()).isLessThan(0.8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sizesMustMatch() {
|
||||
assertThatThrownBy(() -> ImageDiff.compare(checkerboard(8, 8, 0), checkerboard(8, 9, 0)))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
private static BufferedImage checkerboard(int width, int height, int tint) {
|
||||
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
for (int y = 0; y < height; y++) {
|
||||
for (int x = 0; x < width; x++) {
|
||||
int value = ((x / 4 + y / 4) % 2 == 0) ? 0x303030 : 0xD0D0D0;
|
||||
image.setRGB(x, y, value | tint);
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
private static BufferedImage copy(BufferedImage image) {
|
||||
BufferedImage copy = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
|
||||
copy.setData(image.getData());
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class KeysTest {
|
||||
|
||||
@Test
|
||||
void chordsNameModifiersShort() {
|
||||
assertThat(Keys.chord("Control+Shift+KeyT")).containsExactly("ControlLeft", "ShiftLeft", "KeyT");
|
||||
assertThat(Keys.chord("F3+KeyB")).containsExactly("F3", "KeyB");
|
||||
assertThat(Keys.chord("Escape")).containsExactly("Escape");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownKeysAreRefused() {
|
||||
assertThatThrownBy(() -> Keys.chord("Ctrl+Banana")).isInstanceOf(CliException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void keysAreWhatAUsKeyboardSends() {
|
||||
assertThat(Keys.of("KeyA", false)).isEqualTo(new Keys.Key("a", 'A', "a", 0));
|
||||
assertThat(Keys.of("KeyA", true)).isEqualTo(new Keys.Key("A", 'A', "A", 0));
|
||||
assertThat(Keys.of("Digit2", true)).isEqualTo(new Keys.Key("@", '2', "@", 0));
|
||||
assertThat(Keys.of("F3", false)).isEqualTo(new Keys.Key("F3", 114, "", 0));
|
||||
assertThat(Keys.of("F24", false).virtualKeyCode()).isEqualTo(135);
|
||||
assertThat(Keys.of("Slash", true).text()).isEqualTo("?");
|
||||
assertThat(Keys.of("ShiftRight", false).location()).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void sdlKeysAreHidUsagesAndSdlKeycodes() {
|
||||
assertThat(Keys.sdl("KeyE")).isEqualTo(new Keys.SdlKey(8, 'e'));
|
||||
assertThat(Keys.sdl("Digit1")).isEqualTo(new Keys.SdlKey(30, '1'));
|
||||
assertThat(Keys.sdl("Digit0")).isEqualTo(new Keys.SdlKey(39, '0'));
|
||||
assertThat(Keys.sdl("F1")).isEqualTo(new Keys.SdlKey(58, 0x4000003A));
|
||||
assertThat(Keys.sdl("F3")).isEqualTo(new Keys.SdlKey(60, 0x4000003C));
|
||||
assertThat(Keys.sdl("Escape")).isEqualTo(new Keys.SdlKey(41, 0x1B));
|
||||
assertThatThrownBy(() -> Keys.sdl("Banana")).isInstanceOf(CliException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifierKeysSetTheirBit() {
|
||||
assertThat(Keys.modifierBit("ControlRight")).isEqualTo(Keys.CTRL);
|
||||
assertThat(Keys.modifierBit("ShiftLeft")).isEqualTo(Keys.SHIFT);
|
||||
assertThat(Keys.modifierBit("KeyA")).isZero();
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.teavm.model.MethodDescriptor;
|
||||
import org.teavm.model.MethodReference;
|
||||
|
||||
class MonitorElisionTest {
|
||||
|
||||
private static MethodReference method(String owner, String nameAndDescriptor) {
|
||||
return new MethodReference(owner, MethodDescriptor.parse(nameAndDescriptor));
|
||||
}
|
||||
|
||||
@Test
|
||||
void monitorMethodsAndBlockingApisBlock() {
|
||||
assertThat(MonitorElision.isBlocking(method("net.example.Anything", "wait()V")))
|
||||
.isTrue();
|
||||
assertThat(MonitorElision.isBlocking(method("java.lang.Object", "wait(J)V")))
|
||||
.isTrue();
|
||||
assertThat(MonitorElision.isBlocking(method("net.example.Anything", "notifyAll()V")))
|
||||
.isFalse();
|
||||
assertThat(MonitorElision.isNotify(method("net.example.Anything", "notifyAll()V")))
|
||||
.isTrue();
|
||||
assertThat(MonitorElision.isBlocking(method("java.lang.Thread", "sleep(J)V")))
|
||||
.isTrue();
|
||||
assertThat(MonitorElision.isBlocking(
|
||||
method("java.util.concurrent.CompletableFuture", "join()Ljava/lang/Object;")))
|
||||
.isTrue();
|
||||
assertThat(MonitorElision.isBlocking(method(
|
||||
"java.util.concurrent.locks.ReentrantLock", "tryLock(JLjava/util/concurrent/TimeUnit;)Z")))
|
||||
.isTrue();
|
||||
// lock() is handled apart from blocking: see MonitorElision.isLock.
|
||||
assertThat(MonitorElision.isBlocking(method("java.util.concurrent.locks.ReentrantLock", "lock()V")))
|
||||
.isFalse();
|
||||
assertThat(MonitorElision.isBlocking(
|
||||
method("java.util.concurrent.LinkedBlockingQueue", "take()Ljava/lang/Object;")))
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void ordinaryCallsDoNot() {
|
||||
assertThat(MonitorElision.isBlocking(
|
||||
method("java.util.concurrent.ConcurrentHashMap", "get(Ljava/lang/Object;)Ljava/lang/Object;")))
|
||||
.isFalse();
|
||||
assertThat(MonitorElision.isBlocking(method("java.util.Map", "get(Ljava/lang/Object;)Ljava/lang/Object;")))
|
||||
.isFalse();
|
||||
assertThat(MonitorElision.isBlocking(method("net.example.Anything", "wait(I)V")))
|
||||
.isFalse();
|
||||
assertThat(MonitorElision.isBlocking(method("java.util.concurrent.locks.ReentrantLock", "tryLock()Z")))
|
||||
.isFalse();
|
||||
assertThat(MonitorElision.isBlocking(method("java.lang.Thread", "getName()Ljava/lang/String;")))
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void queuesBlockOnlyInTheirWaitingForms() {
|
||||
assertThat(MonitorElision.isBlocking(
|
||||
method("java.util.concurrent.BlockingQueue", "offer(Ljava/lang/Object;)Z")))
|
||||
.isFalse();
|
||||
assertThat(MonitorElision.isBlocking(method("java.util.concurrent.BlockingQueue", "poll()Ljava/lang/Object;")))
|
||||
.isFalse();
|
||||
assertThat(MonitorElision.isBlocking(method(
|
||||
"java.util.concurrent.BlockingQueue",
|
||||
"offer(Ljava/lang/Object;JLjava/util/concurrent/TimeUnit;)Z")))
|
||||
.isTrue();
|
||||
assertThat(MonitorElision.isBlocking(method(
|
||||
"java.util.concurrent.BlockingQueue",
|
||||
"poll(JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object;")))
|
||||
.isTrue();
|
||||
assertThat(MonitorElision.isBlocking(method("java.util.concurrent.BlockingQueue", "put(Ljava/lang/Object;)V")))
|
||||
.isTrue();
|
||||
assertThat(MonitorElision.isBlocking(method("java.util.concurrent.BlockingQueue", "take()Ljava/lang/Object;")))
|
||||
.isTrue();
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PageQueryTest {
|
||||
|
||||
@Test
|
||||
void asksForTheBuildSoThePageDoesNotWaitForAPick() {
|
||||
assertThat(PageQuery.withBuild("name=Player", "fast")).isEqualTo("name=Player&build=fast");
|
||||
assertThat(PageQuery.withBuild("", "compatible")).isEqualTo("build=compatible");
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsABuildTheQueryNamesAlready() {
|
||||
assertThat(PageQuery.withBuild("name=Player&build=compatible", "fast"))
|
||||
.isEqualTo("name=Player&build=compatible");
|
||||
}
|
||||
|
||||
@Test
|
||||
void addsNothingForAnExperimentWithOneModule() {
|
||||
assertThat(PageQuery.withBuild("name=Player", "")).isEqualTo("name=Player");
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotMistakeAnotherOptionEndingInBuildForOne() {
|
||||
assertThat(PageQuery.withBuild("rebuild=x", "fast")).isEqualTo("rebuild=x&build=fast");
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PerfBaselineTest {
|
||||
|
||||
private static final List<String> FILE = List.of(
|
||||
"# rules",
|
||||
"rule.fpsMedian=higher 5 1",
|
||||
"rule.drawCalls=lower 10 5",
|
||||
"",
|
||||
"desktop.flythrough.fpsMedian=60",
|
||||
"desktop.flythrough.drawCalls=400",
|
||||
"desktop.flythrough.frames=3600",
|
||||
"laptop.flythrough.fpsMedian=30");
|
||||
|
||||
private final PerfBaseline baseline = PerfBaseline.parse(FILE, "baseline.properties");
|
||||
|
||||
@Test
|
||||
void aFigureRegressesOnlyPastBothLimits() {
|
||||
List<PerfBaseline.Comparison> comparisons = baseline.compare(
|
||||
"desktop",
|
||||
Map.of("flythrough.fpsMedian", 56.0, "flythrough.drawCalls", 404.0, "flythrough.frames", 1.0));
|
||||
|
||||
assertThat(comparisons)
|
||||
.extracting(PerfBaseline.Comparison::key, PerfBaseline.Comparison::regressed)
|
||||
.containsExactlyInAnyOrder(
|
||||
// 4 fps worse: more than 5% of 60 and more than 1 fps.
|
||||
org.assertj.core.groups.Tuple.tuple("flythrough.fpsMedian", true),
|
||||
// 4 more draws: 1%, and under the 5 absolute.
|
||||
org.assertj.core.groups.Tuple.tuple("flythrough.drawCalls", false));
|
||||
}
|
||||
|
||||
@Test
|
||||
void betterIsNeverARegression() {
|
||||
assertThat(baseline.compare("desktop", Map.of("flythrough.fpsMedian", 144.0, "flythrough.drawCalls", 40.0)))
|
||||
.noneMatch(PerfBaseline.Comparison::regressed);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherMachinesFiguresAreItsOwn() {
|
||||
assertThat(baseline.figures("laptop")).containsExactly(Map.entry("flythrough.fpsMedian", 30.0));
|
||||
assertThat(baseline.compare("nobody", Map.of("flythrough.fpsMedian", 1.0)))
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void updatingReplacesOnlyThatMachine() {
|
||||
List<String> updated = baseline.withFigures(
|
||||
"desktop", Map.of("flythrough.fpsMedian", 61.25, "flythrough.gpuMillis", Double.NaN));
|
||||
|
||||
assertThat(updated)
|
||||
.contains(
|
||||
"rule.fpsMedian=higher 5 1",
|
||||
"laptop.flythrough.fpsMedian=30",
|
||||
"desktop.flythrough.fpsMedian=61.25")
|
||||
.doesNotContain("desktop.flythrough.drawCalls=400")
|
||||
.noneMatch(line -> line.contains("gpuMillis"));
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class PerfBudgetTest {
|
||||
|
||||
private static final PerfBudget BUDGET = PerfBudget.parse(
|
||||
List.of(
|
||||
"# heap",
|
||||
"max.*.heapLiveMB=600",
|
||||
"max.load.titleHeapLiveMB=400",
|
||||
"max.*.gcMaxPauseMillis=16",
|
||||
"desktop.max.load.warmTitleMillis=3_000",
|
||||
"desktop.max.*.gcMaxPauseMillis=8"),
|
||||
"budgets.properties");
|
||||
|
||||
@Test
|
||||
void checksEveryFigureAPatternCovers() {
|
||||
Map<String, Double> figures = new LinkedHashMap<>();
|
||||
figures.put("flythrough.heapLiveMB", 650.0);
|
||||
figures.put("combat.heapLiveMB", 500.0);
|
||||
figures.put("flythrough.fpsMedian", 60.0);
|
||||
figures.put("load.titleHeapLiveMB", 390.0);
|
||||
|
||||
List<PerfBudget.Check> checks = BUDGET.check("chromebook", figures);
|
||||
|
||||
assertThat(checks)
|
||||
.extracting(PerfBudget.Check::figure)
|
||||
.containsExactly("flythrough.heapLiveMB", "combat.heapLiveMB", "load.titleHeapLiveMB");
|
||||
assertThat(checks)
|
||||
.filteredOn(PerfBudget.Check::over)
|
||||
.extracting(PerfBudget.Check::figure)
|
||||
.containsExactly("flythrough.heapLiveMB");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMachinesOwnLimitWins() {
|
||||
Map<String, Double> figures = Map.of("lobby.gcMaxPauseMillis", 10.0, "load.warmTitleMillis", 2500.0);
|
||||
|
||||
assertThat(BUDGET.check("desktop", figures))
|
||||
.filteredOn(PerfBudget.Check::over)
|
||||
.extracting(PerfBudget.Check::figure)
|
||||
.containsExactly("lobby.gcMaxPauseMillis");
|
||||
// Another machine has no time limit, and the general pause limit.
|
||||
assertThat(BUDGET.check("laptop", figures))
|
||||
.filteredOn(PerfBudget.Check::over)
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStarIsOnePartOfTheKey() {
|
||||
assertThat(BUDGET.check("x", Map.of("a.b.heapLiveMB", 999.0))).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void figuresNotMeasuredArentChecked() {
|
||||
assertThat(BUDGET.check("x", Map.of("flythrough.heapLiveMB", Double.NaN)))
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsALineThatIsntABudget() {
|
||||
assertThatThrownBy(() -> PerfBudget.parse(List.of("heap=5"), "b")).isInstanceOf(CliException.class);
|
||||
assertThatThrownBy(() -> PerfBudget.parse(List.of("max.heap=lots"), "b"))
|
||||
.isInstanceOf(CliException.class);
|
||||
}
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class RemovalTransformerTest {
|
||||
|
||||
@Test
|
||||
void teavmLambdaClassesAreNeverMissing() {
|
||||
assertThat(RemovalTransformer.isGenerated("com.mojang.realmsclient.client.RealmsClient$<clinit>$lambda$_63_0"))
|
||||
.isTrue();
|
||||
assertThat(RemovalTransformer.isGenerated("net.example.Thing$run$lambda$_2_11"))
|
||||
.isTrue();
|
||||
assertThat(RemovalTransformer.isGenerated("net.example.Thing$lambda")).isFalse();
|
||||
assertThat(RemovalTransformer.isGenerated("net.example.Thing")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void teavmAtomicUpdaterClassesAreNeverMissing() {
|
||||
assertThat(RemovalTransformer.isGenerated("io.netty.util.internal.RefCnt$value$_AtomicUpdater$"))
|
||||
.isTrue();
|
||||
assertThat(RemovalTransformer.isGenerated("net.example.Thing$_AtomicUpdater$Other"))
|
||||
.isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void teavmAnnotationClassesAreNeverMissing() {
|
||||
assertThat(RemovalTransformer.isGenerated("io.netty.channel.ChannelHandler$Sharable$$_impl"))
|
||||
.isTrue();
|
||||
assertThat(RemovalTransformer.isGenerated("net.example.Thing$$_implementation"))
|
||||
.isFalse();
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SceneScriptTest {
|
||||
|
||||
@Test
|
||||
void readsSetupScenesAndThreshold() {
|
||||
SceneScript script = SceneScript.parse(
|
||||
List.of(
|
||||
"# Scenes",
|
||||
"threshold 0.9",
|
||||
"setup",
|
||||
" rcon:tick freeze",
|
||||
" key:F1",
|
||||
"",
|
||||
"scene terrain Overworld terrain at noon",
|
||||
" rcon:tp IncariShot 10 90 10 45 20",
|
||||
" settle",
|
||||
" shot:terrain",
|
||||
"scene gui",
|
||||
" key:KeyE",
|
||||
" shot:gui_inventory",
|
||||
" shot:gui_again"),
|
||||
"scenes.txt");
|
||||
assertThat(script.threshold()).isEqualTo(0.9);
|
||||
assertThat(script.setup())
|
||||
.containsExactly(new SceneScript.Step("rcon", "tick freeze", 4), new SceneScript.Step("key", "F1", 5));
|
||||
assertThat(script.scenes()).hasSize(2);
|
||||
assertThat(script.scenes().getFirst().name()).isEqualTo("terrain");
|
||||
assertThat(script.scenes().getFirst().description()).isEqualTo("Overworld terrain at noon");
|
||||
assertThat(script.scenes().getFirst().steps()).hasSize(3);
|
||||
assertThat(script.scenes().get(1).shots()).containsExactly("gui_inventory", "gui_again");
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesMistakes() {
|
||||
assertThatThrownBy(() -> SceneScript.parse(List.of("setup", " rcon:x"), "s"))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("threshold");
|
||||
assertThatThrownBy(() -> SceneScript.parse(List.of("threshold 0.9", "scene a", " jump:1"), "s"))
|
||||
.hasMessageContaining("unknown step");
|
||||
assertThatThrownBy(() -> SceneScript.parse(
|
||||
List.of("threshold 0.9", "scene a", " shot:x", "scene b", " shot:x"), "s"))
|
||||
.hasMessageContaining("unique");
|
||||
assertThatThrownBy(() -> SceneScript.parse(List.of("threshold 0.9", "scene a", "scene a"), "s"))
|
||||
.hasMessageContaining("twice");
|
||||
assertThatThrownBy(() -> SceneScript.parse(List.of("threshold 0.9", "setup", " shot:x"), "s"))
|
||||
.hasMessageContaining("setup takes no screenshots");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ServeTest {
|
||||
|
||||
@Test
|
||||
void mountedDirectoriesServeOnlyWhatsInside() {
|
||||
Map<String, Path> files = new LinkedHashMap<>();
|
||||
Serve.addFile(files, "client.jar=/cache/client.jar");
|
||||
Serve.addDirectory(files, "assets/objects=/cache/assets/objects");
|
||||
|
||||
assertThat(Serve.mounted(files, "/assets/objects/ab/abcdef"))
|
||||
.isEqualTo(Path.of("/cache/assets/objects/ab/abcdef"));
|
||||
assertThat(Serve.mounted(files, "/assets/objects/../../secret")).isNull();
|
||||
assertThat(Serve.mounted(files, "/assets/other")).isNull();
|
||||
// Named files aren't directories.
|
||||
assertThat(Serve.mounted(files, "/client.jar/x")).isNull();
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.assertj.core.api.Assertions.within;
|
||||
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ServerTickStatsTest {
|
||||
|
||||
@Test
|
||||
void pausedTicksAreLeftOutOfTheRest() {
|
||||
ServerTickStats stats = new ServerTickStats();
|
||||
// Two stretches of 1 s: 19 ticks of 10 ms and one of 80 ms, then 10 running ticks of 20 ms and
|
||||
// 5 paused ones.
|
||||
stats.add(ticks(19, 10, 0, 400), 1);
|
||||
stats.add(ticks(1, 80, 0, 410), 0);
|
||||
stats.add(ticks(10, 20, 0, 420), 1);
|
||||
stats.add(ticks(5, 1, 1, 430), 0);
|
||||
Map<String, Double> figures = stats.figures();
|
||||
assertThat(stats.ticks()).isEqualTo(35);
|
||||
assertThat(figures.get("serverTicksPerSecond")).isCloseTo(15, within(1e-9));
|
||||
assertThat(figures.get("serverTickMillis")).isCloseTo((19 * 10 + 80 + 10 * 20) / 30.0, within(1e-9));
|
||||
// Nearest rank: the 29th of 30 sorted ticks.
|
||||
assertThat(figures.get("serverTickP95Millis")).isEqualTo(20);
|
||||
assertThat(figures.get("serverTickMaxMillis")).isEqualTo(80);
|
||||
assertThat(figures.get("serverPausedTicks")).isEqualTo(5);
|
||||
assertThat(figures.get("serverChunks")).isEqualTo(430);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nothingMeasuredIsNotANumber() {
|
||||
Map<String, Double> figures = new ServerTickStats().figures();
|
||||
assertThat(figures.get("serverTicksPerSecond")).isNaN();
|
||||
assertThat(figures.get("serverTickMillis")).isNaN();
|
||||
assertThat(figures.get("serverChunks")).isNaN();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTableIsWholeRows() {
|
||||
assertThatThrownBy(() -> new ServerTickStats().add(new double[ServerTickStats.COLUMNS + 1], 1))
|
||||
.isInstanceOf(IllegalArgumentException.class);
|
||||
}
|
||||
|
||||
private static double[] ticks(int count, double millis, double paused, double chunks) {
|
||||
double[] table = new double[count * ServerTickStats.COLUMNS];
|
||||
for (int tick = 0; tick < count; tick++) {
|
||||
int row = tick * ServerTickStats.COLUMNS;
|
||||
table[row] = tick * 50;
|
||||
table[row + ServerTickStats.MILLIS] = millis;
|
||||
table[row + ServerTickStats.PAUSED] = paused;
|
||||
table[row + ServerTickStats.CHUNKS] = chunks;
|
||||
}
|
||||
return table;
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class SingleFileTest {
|
||||
|
||||
private static final Pattern FILE = Pattern.compile(
|
||||
"<script type=\"application/x-incari-file\" data-path=\"([^\"]+)\" data-type=\"([^\"]+)\"( data-encoding=\"gzip\")?>"
|
||||
+ "([A-Za-z0-9+/=]*)</script>");
|
||||
|
||||
@TempDir
|
||||
Path dir;
|
||||
|
||||
private Path folder;
|
||||
private Path script;
|
||||
|
||||
@BeforeEach
|
||||
void fakeFolder() throws Exception {
|
||||
folder = dir.resolve("web");
|
||||
write(WebFolder.MARKER, "Written by ./incari build.");
|
||||
write("index.html", """
|
||||
<!doctype html>
|
||||
<html><head><title>Incari</title></head>
|
||||
<body>
|
||||
<script type="module" src="boot.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
""");
|
||||
write("boot.js", "import \"./loader.js\";");
|
||||
write("loader.js", "export {};");
|
||||
write("sw.js", "service worker");
|
||||
write("cache-policy.js", "its policy");
|
||||
write(".htaccess", "apache");
|
||||
write("README.txt", "DO NOT SHARE");
|
||||
write("build.json", "{\"format\": 2}");
|
||||
// Repetitive, so it packs: as a module does.
|
||||
write("incari-fast.wasm", "module ".repeat(1000));
|
||||
write("assets/objects/cc/cc33", "lang");
|
||||
Files.write(
|
||||
folder.resolve("client.jar"),
|
||||
jar(Map.of(
|
||||
"net/minecraft/client/Main.class", "class",
|
||||
"META-INF/MANIFEST.MF", "manifest",
|
||||
"assets/minecraft/lang/en_us.json", "{}",
|
||||
"data/minecraft/tags/x.json", "[]")));
|
||||
script = dir.resolve("offline.js");
|
||||
Files.writeString(script, "export function start(page) {}\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void putsEveryFileThePageFetchesInOnePage() throws Exception {
|
||||
Path out = dir.resolve("incari.html");
|
||||
SingleFile.Summary summary = SingleFile.write(new SingleFile.Options(folder, out, script));
|
||||
|
||||
String page = Files.readString(out);
|
||||
assertThat(page).startsWith("<!doctype html>\n" + SingleFile.SIGNATURE).contains("DO NOT SHARE");
|
||||
assertThat(page).doesNotContain("src=\"boot.js\"");
|
||||
assertThat(page)
|
||||
.contains("<script type=\"module\">\nexport function start(page) {}\n\nstart(window);\n</script>");
|
||||
assertThat(page).endsWith("</body>\n</html>\n");
|
||||
|
||||
Map<String, byte[]> files = new LinkedHashMap<>();
|
||||
List<String> gzipped = new ArrayList<>();
|
||||
Matcher matcher = FILE.matcher(page);
|
||||
while (matcher.find()) {
|
||||
byte[] bytes = Base64.getDecoder().decode(matcher.group(4));
|
||||
if (matcher.group(3) != null) {
|
||||
gzipped.add(matcher.group(1));
|
||||
bytes = new GZIPInputStream(new ByteArrayInputStream(bytes)).readAllBytes();
|
||||
}
|
||||
files.put(matcher.group(1), bytes);
|
||||
}
|
||||
assertThat(summary.files()).isEqualTo(files.size());
|
||||
// The scripts first: the page decodes them before the rest.
|
||||
assertThat(List.copyOf(files.keySet()).subList(0, 2)).containsExactlyInAnyOrder("boot.js", "loader.js");
|
||||
assertThat(files.keySet())
|
||||
.containsExactlyInAnyOrder(
|
||||
"boot.js",
|
||||
"loader.js",
|
||||
"build.json",
|
||||
"incari-fast.wasm",
|
||||
"assets/objects/cc/cc33",
|
||||
"client.jar");
|
||||
assertThat(gzipped).contains("incari-fast.wasm").doesNotContain("assets/objects/cc/cc33");
|
||||
assertThat(new String(files.get("incari-fast.wasm"), StandardCharsets.UTF_8))
|
||||
.isEqualTo("module ".repeat(1000));
|
||||
assertThat(page).contains("data-path=\"incari-fast.wasm\" data-type=\"application/wasm\"");
|
||||
// The folder already cut the jar down (WebFolder.resourcesOnly): it goes in as it is.
|
||||
assertThat(files.get("client.jar")).isEqualTo(Files.readAllBytes(folder.resolve("client.jar")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacesItsOwnFileButNeverSomeoneElses() throws Exception {
|
||||
Path out = dir.resolve("incari.html");
|
||||
SingleFile.write(new SingleFile.Options(folder, out, script));
|
||||
SingleFile.write(new SingleFile.Options(folder, out, script));
|
||||
|
||||
Path other = dir.resolve("mine.html");
|
||||
Files.writeString(other, "<!doctype html><p>mine</p>");
|
||||
assertThatThrownBy(() -> SingleFile.write(new SingleFile.Options(folder, other, script)))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("didn't write it");
|
||||
assertThat(other).hasContent("<!doctype html><p>mine</p>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesAFolderItDidntWriteAndAScriptThatCantGoInline() throws Exception {
|
||||
Files.delete(folder.resolve(WebFolder.MARKER));
|
||||
assertThatThrownBy(() -> SingleFile.write(new SingleFile.Options(folder, dir.resolve("a.html"), script)))
|
||||
.isInstanceOf(CliException.class);
|
||||
|
||||
write(WebFolder.MARKER, "Written by ./incari build.");
|
||||
Files.writeString(script, "const end = \"</script>\";");
|
||||
assertThatThrownBy(() -> SingleFile.write(new SingleFile.Options(folder, dir.resolve("a.html"), script)))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("</script");
|
||||
}
|
||||
|
||||
private static byte[] jar(Map<String, String> entries) throws Exception {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
|
||||
for (String name : entries.keySet().stream().sorted().toList()) {
|
||||
zip.putNextEntry(new ZipEntry(name));
|
||||
zip.write(entries.get(name).getBytes(StandardCharsets.UTF_8));
|
||||
zip.closeEntry();
|
||||
}
|
||||
}
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
|
||||
private void write(String name, String content) throws Exception {
|
||||
Path file = folder.resolve(name);
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, content);
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class SmallSoundsTest {
|
||||
|
||||
@TempDir
|
||||
Path dir;
|
||||
|
||||
@Test
|
||||
void keepsEverySoundButTheMusicAndTheRecords() {
|
||||
assertThat(SmallSounds.keeps("minecraft/sounds/dig/stone1.ogg")).isTrue();
|
||||
assertThat(SmallSounds.keeps("minecraft/sounds/mob/pig/say1.ogg")).isTrue();
|
||||
assertThat(SmallSounds.keeps("minecraft/sounds/ambient/cave/cave1.ogg")).isTrue();
|
||||
assertThat(SmallSounds.keeps("minecraft/sounds/block/deepslate/break1.ogg"))
|
||||
.isTrue();
|
||||
|
||||
assertThat(SmallSounds.keeps("minecraft/sounds/music/game/calm1.ogg")).isFalse();
|
||||
assertThat(SmallSounds.keeps("minecraft/sounds/records/cat.ogg")).isFalse();
|
||||
assertThat(SmallSounds.keeps("minecraft/sounds.json")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void encodesSmallerOnceAndKeepsTheResult() throws Exception {
|
||||
assumeTrue(SmallSounds.available(), "ffmpeg with libvorbis");
|
||||
Path objects = dir.resolve("assets/objects");
|
||||
String hash = "ab" + "0".repeat(38);
|
||||
Path original = objects.resolve("ab/" + hash);
|
||||
Files.createDirectories(original.getParent());
|
||||
// Two seconds of a 48 kHz tone at a high quality: what the game's files are like.
|
||||
Process tone = new ProcessBuilder(
|
||||
"ffmpeg",
|
||||
"-nostdin",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-f",
|
||||
"lavfi",
|
||||
"-i",
|
||||
"sine=frequency=440:sample_rate=48000:duration=2",
|
||||
"-c:a",
|
||||
"libvorbis",
|
||||
"-q:a",
|
||||
"8",
|
||||
"-f",
|
||||
"ogg",
|
||||
original.toString())
|
||||
.inheritIO()
|
||||
.start();
|
||||
assertThat(tone.waitFor()).isZero();
|
||||
|
||||
byte[] smaller = SmallSounds.encode(objects, hash);
|
||||
assertThat(smaller.length).isLessThan((int) Files.size(original));
|
||||
assertThat(new String(smaller, 0, 4, java.nio.charset.StandardCharsets.US_ASCII))
|
||||
.isEqualTo("OggS");
|
||||
Path cached = dir.resolve("assets/small-sounds/vorbis-22050-q0/ab/" + hash + ".ogg");
|
||||
assertThat(cached).exists();
|
||||
|
||||
// The second time from the cache, not ffmpeg.
|
||||
Files.write(cached, smaller);
|
||||
assertThat(SmallSounds.encode(objects, hash)).isEqualTo(smaller);
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.lang.classfile.Signature;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.teavm.model.ValueType;
|
||||
|
||||
/** The codes here are the ones web-classlib's GenericTypesTest checks against the JDK's types. */
|
||||
class TypeCapturesTest {
|
||||
|
||||
private static TypeCaptures.@org.jspecify.annotations.Nullable Capture encode(String signature) {
|
||||
return TypeCaptures.encode(Signature.parseFrom(signature));
|
||||
}
|
||||
|
||||
@Test
|
||||
void parameterizedTypesAndWildcards() {
|
||||
assertThat(encode("Ljava/util/Map<Ljava/lang/String;Ljava/util/List<+Ljava/lang/Number;>;>;"))
|
||||
.isEqualTo(new TypeCaptures.Capture(
|
||||
"PN2CPN1UC",
|
||||
List.of(
|
||||
ValueType.object("java.util.Map"),
|
||||
ValueType.object("java.lang.String"),
|
||||
ValueType.object("java.util.List"),
|
||||
ValueType.object("java.lang.Number"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nestedOwnersGenericArraysAndLowerBounds() {
|
||||
assertThat(encode("Ljava/util/Map$Entry<[Ljava/util/List<Ljava/lang/String;>;-Ljava/lang/Integer;>;"))
|
||||
.isEqualTo(new TypeCaptures.Capture(
|
||||
"PC2APN1CLC",
|
||||
List.of(
|
||||
ValueType.object("java.util.Map$Entry"),
|
||||
ValueType.object("java.util.Map"),
|
||||
ValueType.object("java.util.List"),
|
||||
ValueType.object("java.lang.String"),
|
||||
ValueType.object("java.lang.Integer"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void arraysOfPlainClassesAreClasses() {
|
||||
assertThat(encode("Ljava/util/List<[Ljava/lang/String;>;"))
|
||||
.isEqualTo(new TypeCaptures.Capture(
|
||||
"PN1C",
|
||||
List.of(
|
||||
ValueType.object("java.util.List"),
|
||||
ValueType.arrayOf(ValueType.object("java.lang.String")))));
|
||||
assertThat(encode("Ljava/util/List<[I>;"))
|
||||
.isEqualTo(new TypeCaptures.Capture(
|
||||
"PN1C", List.of(ValueType.object("java.util.List"), ValueType.parse("[I"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unboundedWildcardsAreObject() {
|
||||
assertThat(encode("Ljava/util/List<*>;"))
|
||||
.isEqualTo(new TypeCaptures.Capture(
|
||||
"PN1UC", List.of(ValueType.object("java.util.List"), ValueType.object("java.lang.Object"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void typeVariablesAreNotKept() {
|
||||
assertThat(encode("Ljava/util/List<TT;>;")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void nettyKeepsTheRawClassOfAGenericArgument() {
|
||||
Signature.ClassTypeSig encoder = (Signature.ClassTypeSig)
|
||||
Signature.parseFrom("Lio/netty/handler/codec/MessageToByteEncoder<Lnet/example/Packet<TT;>;>;");
|
||||
assertThat(TypeCaptures.encode(encoder)).isNull();
|
||||
assertThat(TypeCaptures.encode(TypeCaptures.rawArguments(encoder)))
|
||||
.isEqualTo(new TypeCaptures.Capture(
|
||||
"PN1C",
|
||||
List.of(
|
||||
ValueType.object("io.netty.handler.codec.MessageToByteEncoder"),
|
||||
ValueType.object("net.example.Packet"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void nettyStillSkipsATypeVariableArgument() {
|
||||
Signature.ClassTypeSig encoder =
|
||||
(Signature.ClassTypeSig) Signature.parseFrom("Lio/netty/handler/codec/MessageToByteEncoder<TT;>;");
|
||||
assertThat(TypeCaptures.encode(TypeCaptures.rawArguments(encoder))).isNull();
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class WasmOptTest {
|
||||
|
||||
@TempDir
|
||||
Path dir;
|
||||
|
||||
@Test
|
||||
void extractsOneFileFromAGzippedTar() throws IOException {
|
||||
Path archive = dir.resolve("binaryen.tar.gz");
|
||||
try (OutputStream out = new GZIPOutputStream(Files.newOutputStream(archive))) {
|
||||
entry(out, "binaryen/bin/", '5', new byte[0]);
|
||||
entry(out, "binaryen/bin/wasm-dis", '0', bytes(700, 'd'));
|
||||
entry(out, "binaryen/bin/wasm-opt", '0', bytes(1000, 'o'));
|
||||
out.write(new byte[1024]);
|
||||
}
|
||||
Path target = dir.resolve("wasm-opt");
|
||||
|
||||
WasmOpt.extract(archive, "binaryen/bin/wasm-opt", target);
|
||||
|
||||
assertThat(Files.readAllBytes(target)).isEqualTo(bytes(1000, 'o'));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEntryTheArchiveLacksFails() throws IOException {
|
||||
Path archive = dir.resolve("empty.tar.gz");
|
||||
try (OutputStream out = new GZIPOutputStream(Files.newOutputStream(archive))) {
|
||||
entry(out, "binaryen/bin/wasm-dis", '0', bytes(10, 'd'));
|
||||
out.write(new byte[1024]);
|
||||
}
|
||||
|
||||
assertThatThrownBy(() -> WasmOpt.extract(archive, "binaryen/bin/wasm-opt", dir.resolve("wasm-opt")))
|
||||
.isInstanceOf(CliException.class);
|
||||
}
|
||||
|
||||
private static byte[] bytes(int count, char value) {
|
||||
byte[] data = new byte[count];
|
||||
java.util.Arrays.fill(data, (byte) value);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** One ustar entry: a 512-byte header (name, octal size, type flag), the data padded to 512. */
|
||||
private static void entry(OutputStream out, String name, char type, byte[] data) throws IOException {
|
||||
byte[] header = new byte[512];
|
||||
byte[] nameBytes = name.getBytes(StandardCharsets.US_ASCII);
|
||||
System.arraycopy(nameBytes, 0, header, 0, nameBytes.length);
|
||||
byte[] size = String.format("%011o", data.length).getBytes(StandardCharsets.US_ASCII);
|
||||
System.arraycopy(size, 0, header, 124, size.length);
|
||||
header[156] = (byte) type;
|
||||
byte[] magic = "ustar".getBytes(StandardCharsets.US_ASCII);
|
||||
System.arraycopy(magic, 0, header, 257, magic.length);
|
||||
out.write(header);
|
||||
ByteArrayOutputStream padded = new ByteArrayOutputStream();
|
||||
padded.write(data);
|
||||
padded.write(new byte[(512 - data.length % 512) % 512]);
|
||||
out.write(padded.toByteArray());
|
||||
}
|
||||
}
|
||||
+298
@@ -0,0 +1,298 @@
|
||||
package incari.tools.webbuild;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import incari.tools.build.CliException;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class WebFolderTest {
|
||||
|
||||
@TempDir
|
||||
Path dir;
|
||||
|
||||
private Path in;
|
||||
|
||||
@BeforeEach
|
||||
void fakeBuild() throws Exception {
|
||||
in = dir.resolve("in");
|
||||
write("teavm/incari.wasm", "module");
|
||||
write("teavm/incari.wasm-runtime.js", "runtime");
|
||||
write("teavm/problems.txt", "a report, not part of the build");
|
||||
write("teavm-fast/incari.wasm", "fast module");
|
||||
write("teavm-fast/incari.wasm-runtime.js", "runtime");
|
||||
write("mesher/mesher.wasm", "mesher");
|
||||
write("mesher/mesher.wasm-runtime.js", "mesher runtime");
|
||||
write("page/index.html", "<html>");
|
||||
for (String script :
|
||||
new String[] {"boot", "loader", "features", "jspi", "wakeups", "cache-policy", "sw", "game-worker"}) {
|
||||
write("page/scripts/" + script + ".js", script);
|
||||
}
|
||||
write("page/incari.pack", "pack");
|
||||
Files.write(
|
||||
in.resolve("client.jar"),
|
||||
jar(
|
||||
"net/minecraft/client/Main.class",
|
||||
"META-INF/MANIFEST.MF",
|
||||
"version.json",
|
||||
"assets/minecraft/lang/en_us.json"));
|
||||
write("index.json", """
|
||||
{"objects": {
|
||||
"minecraft/sounds.json": {"hash": "aa11", "size": 2},
|
||||
"minecraft/sounds/a.ogg": {"hash": "bb22", "size": 1},
|
||||
"minecraft/sounds/b.ogg": {"hash": "bb22", "size": 1},
|
||||
"minecraft/sounds/dig/stone1.ogg": {"hash": "ff66", "size": 1},
|
||||
"minecraft/lang/de_de.json": {"hash": "cc33", "size": 1},
|
||||
"minecraft/textures/gui/title/background/panorama_0.png": {"hash": "ee55", "size": 1},
|
||||
"icons/icon_16x16.png": {"hash": "dd44", "size": 1}
|
||||
}}
|
||||
""");
|
||||
write("objects/aa/aa11", """
|
||||
{"block.stone.break": {"sounds": ["dig/stone1"], "subtitle": "subtitles.block.generic.break"},
|
||||
"music.game": {"sounds": [{"name": "a", "stream": true}, "minecraft:b"]},
|
||||
"alias": {"sounds": [{"name": "block.stone.break", "type": "event"}]},
|
||||
"gone": {"sounds": [{"name": "minecraft:music.game", "type": "event"}]}}
|
||||
""");
|
||||
write("objects/ff/ff66", "stone");
|
||||
write("objects/bb/bb22", "ogg");
|
||||
write("objects/cc/cc33", "lang");
|
||||
write("objects/ee/ee55", "panorama");
|
||||
write("objects/dd/dd44", "icon");
|
||||
}
|
||||
|
||||
private WebFolder.Options options(Path out, boolean sounds) {
|
||||
return options(out, sounds, in.resolve("teavm"), in.resolve("teavm-fast"));
|
||||
}
|
||||
|
||||
private WebFolder.Options options(Path out, boolean sounds, @Nullable Path compatible, @Nullable Path fast) {
|
||||
return options(out, sounds, WebFolder.SoundFiles.ALL, compatible, fast);
|
||||
}
|
||||
|
||||
private WebFolder.Options options(
|
||||
Path out, boolean sounds, WebFolder.SoundFiles soundFiles, @Nullable Path compatible, @Nullable Path fast) {
|
||||
return options(out, sounds, soundFiles, compatible, fast, null);
|
||||
}
|
||||
|
||||
private WebFolder.Options options(
|
||||
Path out,
|
||||
boolean sounds,
|
||||
WebFolder.SoundFiles soundFiles,
|
||||
@Nullable Path compatible,
|
||||
@Nullable Path fast,
|
||||
@Nullable Path rust) {
|
||||
return new WebFolder.Options(
|
||||
out,
|
||||
"26.3",
|
||||
compatible,
|
||||
fast,
|
||||
rust,
|
||||
in.resolve("mesher"),
|
||||
in.resolve("page/index.html"),
|
||||
in.resolve("page/scripts"),
|
||||
in.resolve("page/incari.pack"),
|
||||
in.resolve("client.jar"),
|
||||
sounds ? in.resolve("index.json") : null,
|
||||
sounds ? in.resolve("objects") : null,
|
||||
soundFiles);
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesTheBuildThePageAndTheAssetsThePageFetches() throws Exception {
|
||||
Path out = dir.resolve("web");
|
||||
WebFolder.Summary summary = WebFolder.write(options(out, true));
|
||||
|
||||
assertThat(out.resolve("incari.wasm")).hasContent("module");
|
||||
assertThat(out.resolve("incari-fast.wasm")).hasContent("fast module");
|
||||
assertThat(out.resolve("boot.js")).exists();
|
||||
// Only what the page reads from it: no classes, no META-INF.
|
||||
assertThat(entries(out.resolve("client.jar")))
|
||||
.containsExactly("version.json", "assets/minecraft/lang/en_us.json");
|
||||
assertThat(out.resolve("asset-index.json")).exists();
|
||||
assertThat(out.resolve("assets/objects/aa/aa11")).exists();
|
||||
assertThat(out.resolve("assets/objects/bb/bb22")).exists();
|
||||
assertThat(out.resolve("assets/objects/cc/cc33")).exists();
|
||||
// The panorama: menus show Incari's photo instead.
|
||||
assertThat(out.resolve("assets/objects/ee/ee55")).doesNotExist();
|
||||
assertThat(out.resolve("assets/objects/dd/dd44")).doesNotExist();
|
||||
assertThat(out.resolve("problems.txt")).doesNotExist();
|
||||
assertThat(Files.readString(out.resolve("README.txt")))
|
||||
.contains("DO NOT SHARE")
|
||||
.contains("26.3");
|
||||
assertThat(out.resolve(".htaccess")).exists();
|
||||
assertThat(summary.release()).isTrue();
|
||||
assertThat(summary.sounds()).isTrue();
|
||||
assertThat(summary.builds()).containsExactly("Fast", "Compatible");
|
||||
|
||||
JsonObject manifest = JsonParser.parseString(Files.readString(out.resolve("build.json")))
|
||||
.getAsJsonObject();
|
||||
assertThat(manifest.get("game").getAsString()).isEqualTo("26.3");
|
||||
assertThat(manifest.get("format").getAsInt()).isEqualTo(2);
|
||||
assertThat(manifest.getAsJsonObject("fast").get("module").getAsString()).isEqualTo("incari-fast.wasm");
|
||||
assertThat(manifest.getAsJsonObject("compatible").get("module").getAsString())
|
||||
.isEqualTo("incari.wasm");
|
||||
assertThat(manifest.getAsJsonObject("programs").keySet()).containsExactly("mesher");
|
||||
assertThat(manifest.getAsJsonArray("files")).hasSize(6);
|
||||
assertThat(manifest.has("rust")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void putsTheRustBuildInItsOwnFolderAndListsItsPage() throws Exception {
|
||||
write("rust/index.html", "<html>horizon");
|
||||
write("rust/pkg/horizon-client_bg.wasm", "rust module");
|
||||
Path out = dir.resolve("web");
|
||||
WebFolder.Summary summary = WebFolder.write(options(
|
||||
out,
|
||||
false,
|
||||
WebFolder.SoundFiles.ALL,
|
||||
in.resolve("teavm"),
|
||||
in.resolve("teavm-fast"),
|
||||
in.resolve("rust")));
|
||||
|
||||
assertThat(out.resolve("rust/index.html")).hasContent("<html>horizon");
|
||||
assertThat(out.resolve("rust/pkg/horizon-client_bg.wasm")).hasContent("rust module");
|
||||
assertThat(summary.builds()).containsExactly("Fast", "Compatible", "Rust");
|
||||
JsonObject manifest = JsonParser.parseString(Files.readString(out.resolve("build.json")))
|
||||
.getAsJsonObject();
|
||||
assertThat(manifest.getAsJsonObject("rust").get("page").getAsString()).isEqualTo("rust/index.html");
|
||||
// Horizon's service worker keeps its files, so Incari's list leaves them out.
|
||||
assertThat(manifest.getAsJsonArray("files")).hasSize(6);
|
||||
}
|
||||
|
||||
@Test
|
||||
void leavesTheSoundsOutButKeepsTheLanguages() throws Exception {
|
||||
Path out = dir.resolve("web");
|
||||
WebFolder.Summary summary = WebFolder.write(
|
||||
options(out, true, WebFolder.SoundFiles.NONE, in.resolve("teavm"), in.resolve("teavm-fast")));
|
||||
|
||||
assertThat(summary.sounds()).isFalse();
|
||||
assertThat(out.resolve("assets/objects/bb/bb22")).doesNotExist();
|
||||
assertThat(out.resolve("assets/objects/aa/aa11")).doesNotExist();
|
||||
assertThat(out.resolve("assets/objects/cc/cc33")).exists();
|
||||
assertThat(out.resolve("assets/objects/ee/ee55")).doesNotExist();
|
||||
// The game lists no sound it can't fetch.
|
||||
JsonObject objects = JsonParser.parseString(Files.readString(out.resolve("asset-index.json")))
|
||||
.getAsJsonObject()
|
||||
.getAsJsonObject("objects");
|
||||
assertThat(objects.keySet())
|
||||
.containsExactlyInAnyOrder(
|
||||
"minecraft/lang/de_de.json",
|
||||
"minecraft/textures/gui/title/background/panorama_0.png",
|
||||
"icons/icon_16x16.png");
|
||||
}
|
||||
|
||||
@Test
|
||||
void keepsOnlyTheCoreSoundsAndTrimsTheSoundListToThem() throws Exception {
|
||||
Path out = dir.resolve("web");
|
||||
WebFolder.Summary summary = WebFolder.write(
|
||||
options(out, true, WebFolder.SoundFiles.CORE, in.resolve("teavm"), in.resolve("teavm-fast")));
|
||||
|
||||
assertThat(summary.sounds()).isTrue();
|
||||
assertThat(out.resolve("assets/objects/ff/ff66")).hasContent("stone");
|
||||
assertThat(out.resolve("assets/objects/bb/bb22")).doesNotExist();
|
||||
assertThat(out.resolve("assets/objects/aa/aa11")).doesNotExist();
|
||||
JsonObject objects = JsonParser.parseString(Files.readString(out.resolve("asset-index.json")))
|
||||
.getAsJsonObject()
|
||||
.getAsJsonObject("objects");
|
||||
assertThat(objects.keySet())
|
||||
.containsExactlyInAnyOrder(
|
||||
"minecraft/sounds.json",
|
||||
"minecraft/sounds/dig/stone1.ogg",
|
||||
"minecraft/lang/de_de.json",
|
||||
"minecraft/textures/gui/title/background/panorama_0.png",
|
||||
"icons/icon_16x16.png");
|
||||
|
||||
// The list is an object of its own, named by its hash, with only events that still play.
|
||||
JsonObject listed = objects.getAsJsonObject("minecraft/sounds.json");
|
||||
String hash = listed.get("hash").getAsString();
|
||||
Path list = out.resolve("assets/objects/" + hash.substring(0, 2) + "/" + hash);
|
||||
assertThat(Files.size(list)).isEqualTo(listed.get("size").getAsLong());
|
||||
JsonObject events = JsonParser.parseString(Files.readString(list)).getAsJsonObject();
|
||||
assertThat(events.keySet()).containsExactlyInAnyOrder("block.stone.break", "alias");
|
||||
assertThat(events.getAsJsonObject("block.stone.break").get("subtitle").getAsString())
|
||||
.isEqualTo("subtitles.block.generic.break");
|
||||
}
|
||||
|
||||
@Test
|
||||
void writesOneBuildAlone() throws Exception {
|
||||
Path out = dir.resolve("web");
|
||||
WebFolder.Summary summary = WebFolder.write(options(out, false, null, in.resolve("teavm-fast")));
|
||||
|
||||
assertThat(summary.builds()).containsExactly("Fast");
|
||||
assertThat(out.resolve("incari.wasm")).doesNotExist();
|
||||
JsonObject manifest = JsonParser.parseString(Files.readString(out.resolve("build.json")))
|
||||
.getAsJsonObject();
|
||||
assertThat(manifest.has("compatible")).isFalse();
|
||||
assertThat(manifest.has("fast")).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void refusesAReleaseBuildBesideADevelopmentOne() throws Exception {
|
||||
write("teavm-fast/incari.wasm-deobfuscator.wasm", "deobfuscator");
|
||||
assertThatThrownBy(() -> WebFolder.write(options(dir.resolve("web"), false)))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("both be release builds");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rewritesItsOwnFolderButNeverSomeoneElses() throws Exception {
|
||||
Path out = dir.resolve("web");
|
||||
WebFolder.write(options(out, true));
|
||||
WebFolder.write(options(out, false));
|
||||
assertThat(out.resolve("assets")).doesNotExist();
|
||||
|
||||
Path other = dir.resolve("other");
|
||||
write("../other/keep.txt", "mine");
|
||||
assertThatThrownBy(() -> WebFolder.write(options(other, false))).isInstanceOf(CliException.class);
|
||||
assertThat(other.resolve("keep.txt")).hasContent("mine");
|
||||
}
|
||||
|
||||
@Test
|
||||
void failsOnAMissingSound() throws Exception {
|
||||
Files.delete(in.resolve("objects/bb/bb22"));
|
||||
assertThatThrownBy(() -> WebFolder.write(options(dir.resolve("web"), true)))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("./incari assets");
|
||||
}
|
||||
|
||||
private static byte[] jar(String... names) throws Exception {
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
try (ZipOutputStream zip = new ZipOutputStream(bytes)) {
|
||||
for (String name : names) {
|
||||
zip.putNextEntry(new ZipEntry(name));
|
||||
zip.write(name.getBytes(StandardCharsets.UTF_8));
|
||||
zip.closeEntry();
|
||||
}
|
||||
}
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
|
||||
private static List<String> entries(Path jar) throws Exception {
|
||||
List<String> names = new ArrayList<>();
|
||||
try (ZipInputStream zip = new ZipInputStream(Files.newInputStream(jar))) {
|
||||
for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
|
||||
names.add(entry.getName());
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
private void write(String name, String content) throws Exception {
|
||||
Path file = in.resolve(name).normalize();
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, content);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user