Archive incari-client (client, 26.3, clean)
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
# tools
|
||||
|
||||
Build-time and development tools. None of them ships in a build.
|
||||
|
||||
| Tool | What it does | Docs |
|
||||
| --- | --- | --- |
|
||||
| `build/` | The `./incari` CLI: fetch, decompile, apply, rebuild, build | [README](build/README.md) |
|
||||
| `survey/` | The TeaVM compile survey that writes `docs/port-backlog.md` | [README](survey/README.md) |
|
||||
| `copycheck/` | Fails on Incari code copied from the decompiled game | [README](copycheck/README.md) |
|
||||
| `webbuild/` | The TeaVM compile, dev server, browser checks, screenshot diffs, benchmark runner | [README](webbuild/README.md) |
|
||||
| `teavm-patches/` | Fixes to TeaVM 0.16.0's own sources (Apache-2.0) | [README](teavm-patches/README.md) |
|
||||
| `shaders/` | Translates the game's shaders to GLSL ES at build time | [README](shaders/README.md) |
|
||||
| `sprites/` | Decodes the game's sprites and their mip levels at build time | [README](sprites/README.md) |
|
||||
| `wsbridge/` | A development Eagler proxy: Eagler's handshake in front of a vanilla server | [README](wsbridge/README.md) |
|
||||
| `onlinedev/` | A development stand-in for the online service, in memory; `peer.mjs` is a second player for it | `build.gradle.kts`, `peer.mjs` |
|
||||
| `ci/` | Repository guards CI runs: no Mojang content or builds, no publishing, DCO sign-offs, GLSL, the patch budget, no hard-coded game version, library pins matching Minecraft's | each script's header |
|
||||
| `git-hooks/` | The pre-commit hook `./incari setup` installs | `pre-commit` |
|
||||
| `icon/` | `make_icon.py` draws Incari's icon (`incari-icon.svg`) and its PNG sizes | the script's docstring |
|
||||
| `backdrop/` | `make_backdrop.py` makes the menus' blurred photo from its CC0 original | the script's docstring |
|
||||
| `worldgen/` | The world generation check (ADR 0041): a server script, its properties, `compare.py` for two saved worlds | `app-desktop`'s `worldgenServer` task |
|
||||
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Makes the title screen's backdrop: a snowy Alpine photo, blurred and shrunk.
|
||||
|
||||
python3 tools/backdrop/make_backdrop.py [--blur 1.5] [--darken 25] [--width 960] [--preview DIR]
|
||||
|
||||
The photo is "Snowy landscape in Eigergletscher, Lauterbrunnen" by Pascale Amez, CC0 1.0 (see
|
||||
SOURCE below and title_backdrop.txt beside the texture). The 5193 x 3466 original is downloaded
|
||||
once into work/backdrop/ (git-ignored, so the repo holds only the small result) and written to the
|
||||
Incari pack as a PNG, uncropped at 3:2: the client crops it to the screen at run time, keeping the
|
||||
peaks (FOCUS_Y), so one file serves 3:2 Chromebooks, 16:9 and ultrawide alike.
|
||||
|
||||
The blur is done here rather than in a shader, so drawing it costs one textured quad. A blurred
|
||||
image has no fine detail, so a small one stretched to the screen looks the same as a big one.
|
||||
It is darkened too, most at the bottom, so the menu's light text holds up over the white cloud.
|
||||
|
||||
It also writes the photo, as a small JPEG, and Incari's mark (tools/icon's 128-pixel PNG) into
|
||||
app-web's index.html as data URLs, so the page's loader shows the same scene before the game starts
|
||||
and the one-file build carries them too.
|
||||
|
||||
With --preview, also writes the crops each screen shape would show, for judging the composition.
|
||||
Needs ImageMagick (magick) on the path; otherwise the standard library only.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
ROOT = HERE.parent.parent
|
||||
CACHE = ROOT / "work" / "backdrop" / "eigergletscher.jpg"
|
||||
OUT = ROOT / "client/src/main/resources/incari-pack/assets/incari/textures/gui/title_backdrop.png"
|
||||
PAGE = ROOT / "app-web/src/main/web/index.html"
|
||||
MARK = OUT.parent / "icon_128.png"
|
||||
# The page's copy: small, as it's in the page itself; blurred, so it looks the same stretched.
|
||||
PAGE_WIDTH = 640
|
||||
PAGE_QUALITY = 72
|
||||
SOURCE = "https://commons.wikimedia.org/wiki/File:Snowy_landscape_in_Eigergletscher,_Lauterbrunnen.jpg"
|
||||
DOWNLOAD = "https://commons.wikimedia.org/wiki/Special:FilePath/Snowy_landscape_in_Eigergletscher,_Lauterbrunnen.jpg"
|
||||
# Where the crop is centred, as a fraction of the height: the peak line sits 20-45% down, and the
|
||||
# bright cloud below is what to lose first on wide screens.
|
||||
FOCUS_Y = 0.35
|
||||
# Screen shapes the preview crops to.
|
||||
SHAPES = {"3x2": (3, 2), "16x9": (16, 9), "16x10": (16, 10), "21x9": (21, 9)}
|
||||
|
||||
|
||||
def fetch():
|
||||
if CACHE.exists():
|
||||
return
|
||||
CACHE.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Wikimedia asks for a descriptive User-Agent.
|
||||
request = urllib.request.Request(DOWNLOAD, headers={"User-Agent": "IncariClient-backdrop/1.0 (tools/backdrop)"})
|
||||
with urllib.request.urlopen(request) as response:
|
||||
CACHE.write_bytes(response.read())
|
||||
print(f"Downloaded {CACHE}")
|
||||
|
||||
|
||||
def make(blur, darken, width):
|
||||
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
height = round(width * 3466 / 5193)
|
||||
# Shrink to twice the target first so the blur is cheap, blur by a fraction of the width (so
|
||||
# the look doesn't depend on --width), then shrink to the target.
|
||||
sigma = 2 * width * blur / 100
|
||||
# Multiplied by a grey ramp: the top keeps 60% of the darkening, the bottom has all of it.
|
||||
top = round(255 * (1 - 0.6 * darken / 100))
|
||||
bottom = round(255 * (1 - darken / 100))
|
||||
subprocess.run(["magick", str(CACHE), "-resize", f"{2 * width}x", "-blur", f"0x{sigma:.1f}",
|
||||
"-resize", f"{width}x{height}!",
|
||||
"(", "-size", f"{width}x{height}", f"gradient:rgb({top},{top},{top})-rgb({bottom},{bottom},{bottom})", ")",
|
||||
"-compose", "multiply", "-composite", "-strip", "-define", "png:compression-level=9",
|
||||
str(OUT)], check=True)
|
||||
print(f"Wrote {OUT} ({width}x{height}, {OUT.stat().st_size // 1024} KB)")
|
||||
|
||||
|
||||
def page():
|
||||
photo = subprocess.run(["magick", str(OUT), "-resize", f"{PAGE_WIDTH}x", "-strip", "-quality", str(PAGE_QUALITY),
|
||||
"jpg:-"], check=True, capture_output=True).stdout
|
||||
text = PAGE.read_text()
|
||||
for name, kind, data in (("backdrop", "jpeg", photo), ("mark", "png", MARK.read_bytes())):
|
||||
url = f'url("data:image/{kind};base64,{base64.b64encode(data).decode()}")'
|
||||
text, count = re.subn(rf"--incari-{name}: [^;]*;", lambda _: f"--incari-{name}: {url};", text, count=1)
|
||||
if count != 1:
|
||||
raise SystemExit(f"{PAGE} has no --incari-{name} to write")
|
||||
PAGE.write_text(text)
|
||||
print(f"Wrote the photo ({len(photo) // 1024} KB) and the mark into {PAGE}")
|
||||
|
||||
|
||||
def preview(directory, width):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
height = round(width * 3466 / 5193)
|
||||
for name, (w, h) in SHAPES.items():
|
||||
if w / h >= width / height:
|
||||
cw, ch = width, round(width * h / w)
|
||||
else:
|
||||
cw, ch = round(height * w / h), height
|
||||
x = (width - cw) // 2
|
||||
y = min(max(round(FOCUS_Y * height - ch / 2), 0), height - ch)
|
||||
target = directory / f"backdrop_{name}.png"
|
||||
subprocess.run(["magick", str(OUT), "-crop", f"{cw}x{ch}+{x}+{y}", "+repage", str(target)], check=True)
|
||||
print(f"Wrote {target}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
parser.add_argument("--blur", type=float, default=1.5, help="blur radius, percent of the width")
|
||||
parser.add_argument("--darken", type=float, default=25, help="darkening at the bottom, percent")
|
||||
parser.add_argument("--width", type=int, default=960, help="width of the texture in pixels")
|
||||
parser.add_argument("--preview", type=Path, help="also write each screen shape's crop here")
|
||||
args = parser.parse_args()
|
||||
if shutil.which("magick") is None:
|
||||
raise SystemExit("ImageMagick (magick) isn't on the path")
|
||||
fetch()
|
||||
make(args.blur, args.darken, args.width)
|
||||
page()
|
||||
if args.preview:
|
||||
preview(args.preview, args.width)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,6 @@
|
||||
# tools/build
|
||||
|
||||
- Output must stay deterministic: the same inputs give byte-identical patch files on every
|
||||
machine. Don't add timestamps, machine paths or locale-dependent formatting to anything written.
|
||||
- Nothing Mojang may leave `work/`. Every such path is defined in `Workspace`.
|
||||
- Test: `./gradlew :tools:build:test`. The end-to-end check is `./incari setup && ./incari rebuild --check`.
|
||||
@@ -0,0 +1,53 @@
|
||||
# tools/build: the `incari` CLI
|
||||
|
||||
Turns a fresh clone into a patched, editable Minecraft source tree, and edits to that tree back
|
||||
into patch files. This is how the repo stays patch-only. Run it through `./incari` at the repo root.
|
||||
|
||||
| Command | Does |
|
||||
| --- | --- |
|
||||
| `./incari setup` | `fetch` + `decompile` + `apply`: a fresh clone to `work/client`; also clones the pinned Horizon into `work/horizon` (ADR 0068), warning instead of failing |
|
||||
| `./incari fetch` | Download the pinned version's jar and libraries, checked against Mojang's SHA-1s |
|
||||
| `./incari decompile` | Vineflower into `work/decompiled/<version>` (skipped if unchanged) |
|
||||
| `./incari apply [--force]` | Rebuild `work/client` from the decompiled source, `classes.txt` and `patches/`. Refuses to drop unsaved work without `--force` |
|
||||
| `./incari rebuild [--check]` | Regenerate `patches/` from `work/client`'s commits. `--check` fails if stale, or if a replaced class's stamp is |
|
||||
| `./incari classes [--stamp]` | List the classes `classes.txt` replaces whose Mojang original changed since their stamp; `--stamp` records the current ones once reviewed ([`docs/updating.md`](../../docs/updating.md)) |
|
||||
| `./incari assets` | Download the asset index and sounds for the desktop and dev server |
|
||||
| `./incari build [--out <dir>] [--only fast\|compatible\|rust] [--no-sounds] [--html]` | Release builds as one folder (`dist/web/`, ADR 0028) or one HTML file (`--html`, ADR 0057). The folder has the experimental Rust build in `rust/` when this machine can build it (ADR 0068; skipped, saying why, otherwise). Never share either ([`docs/self-hosting.md`](../../docs/self-hosting.md)) |
|
||||
| `./incari survey` | The TeaVM compile survey ([`tools/survey`](../survey/README.md)) |
|
||||
| `./incari copycheck` | Fail on code copied from the game ([`tools/copycheck`](../copycheck/README.md)) |
|
||||
|
||||
Code: `Main`; `GameFiles` fetches, `Decompiler` decompiles, `ClientTree` applies and rebuilds,
|
||||
`WebBuild` runs `build`, `Horizon` fetches and builds the Rust build ([`rust/`](../../rust/README.md)).
|
||||
|
||||
## `work/` (git-ignored)
|
||||
|
||||
```
|
||||
work/
|
||||
cache/ manifest, version JSON, client.jar, libraries, jar lists for Gradle
|
||||
decompiled/<version>/ Vineflower's output and a stamp of its inputs
|
||||
client/ git repo: tag vendor -> classes.txt applied (tag base) -> one commit per patch
|
||||
survey/<version>/ survey output
|
||||
horizon/ the pinned Horizon commit (Rust build); horizon-stage/ with rust/mods applied,
|
||||
horizon-resources/<version>/, horizon-target/, horizon-out/; horizon-override/,
|
||||
an INCARI_HORIZON_DIR checkout's files without its ignored builds
|
||||
```
|
||||
|
||||
## Invariants
|
||||
|
||||
- **Nothing of Mojang's leaves `work/`.** Only patch files and `classes.txt` are tracked.
|
||||
- **Deterministic:** pinned jar and Vineflower, fixed options, git run without user config, so the
|
||||
same commits give byte-identical patches.
|
||||
- **Patches carry as little Mojang text as possible:** one line of context, no function names in
|
||||
hunk headers, no file deletions. `rebuild` rejects a commit that deletes a file or edits a class
|
||||
`classes.txt` owns.
|
||||
- **Unsaved work is never silently dropped.**
|
||||
- **Commit subjects are `<subsystem>: <summary>`;** the subsystem is the folder under `patches/`.
|
||||
- **Every replacement names its original:** a `classes.txt` stamp (`<version>@<vendor blob>`) per
|
||||
`replace` line, so a Minecraft bump that changes the original is flagged, not silently drifted.
|
||||
|
||||
## How to test
|
||||
|
||||
```sh
|
||||
./gradlew :tools:build:test # a synthetic vendor tree: no network, no Mojang jar
|
||||
./incari setup && ./incari rebuild --check # what CI runs end to end
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
plugins {
|
||||
application
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(libs.gson)
|
||||
// Not called directly: the decompile step runs Vineflower in a child JVM (its own heap,
|
||||
// and a crash can't take the CLI down). It sits on the runtime classpath so the CLI can
|
||||
// find the jar.
|
||||
runtimeOnly(libs.vineflower)
|
||||
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testImplementation(libs.assertj)
|
||||
testRuntimeOnly(libs.junit.launcher)
|
||||
}
|
||||
|
||||
application {
|
||||
applicationName = "incari-build"
|
||||
mainClass = "incari.tools.build.Main"
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
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.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
/**
|
||||
* The game's assets (sounds, music, languages, the panorama...) for the desktop runtime, in the
|
||||
* launcher's layout under {@code work/cache/assets}, so the game finds them with
|
||||
* {@code --assetsDir} and {@code --assetIndex} exactly as with Mojang's launcher.
|
||||
*
|
||||
* <p>About 480 MB for 26.3. Only the desktop runtime needs them; setup and CI don't download them.
|
||||
*/
|
||||
public final class Assets {
|
||||
|
||||
static final URI OBJECT_HOST = URI.create("https://resources.download.minecraft.net/");
|
||||
|
||||
private Assets() {}
|
||||
|
||||
/** One asset: where the game looks for it, and its content hash (also its file name). */
|
||||
record AssetObject(String name, String hash, long size) {
|
||||
String objectPath() {
|
||||
return hash.substring(0, 2) + "/" + hash;
|
||||
}
|
||||
}
|
||||
|
||||
/** Downloads the version's asset index and every object it lists that isn't cached yet. */
|
||||
public static String fetch(Workspace ws, BuildConfig config, Downloader downloader)
|
||||
throws IOException, InterruptedException {
|
||||
GameFiles game = GameFiles.load(ws, config);
|
||||
MojangMetadata.AssetIndex index = game.version().assetIndex();
|
||||
if (index == null) {
|
||||
throw new CliException("The version JSON for " + game.version().id() + " has no asset index");
|
||||
}
|
||||
Path indexFile = ws.assetsDir().resolve("indexes").resolve(index.id() + ".json");
|
||||
downloader.fetch(index.download().url(), index.download().sha1(), indexFile);
|
||||
|
||||
List<AssetObject> objects = parseIndex(Files.readString(indexFile));
|
||||
Path objectsDir = ws.assetsDir().resolve("objects");
|
||||
long totalBytes = objects.stream().mapToLong(AssetObject::size).sum();
|
||||
Log.step("Downloading " + objects.size() + " assets (" + totalBytes / (1024 * 1024)
|
||||
+ " MB, cached ones are skipped)");
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(16)) {
|
||||
List<Future<?>> pending = new ArrayList<>();
|
||||
for (AssetObject object : objects) {
|
||||
pending.add(pool.submit(() -> {
|
||||
downloader.fetch(
|
||||
OBJECT_HOST.resolve(object.objectPath()),
|
||||
object.hash(),
|
||||
objectsDir.resolve(object.objectPath()));
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
for (Future<?> future : pending) {
|
||||
Concurrency.join(future);
|
||||
}
|
||||
}
|
||||
return index.id();
|
||||
}
|
||||
|
||||
/** The objects an index lists, one per distinct hash (many names share a file), sorted by hash. */
|
||||
static List<AssetObject> parseIndex(String indexJson) {
|
||||
JsonObject objects = JsonParser.parseString(indexJson).getAsJsonObject().getAsJsonObject("objects");
|
||||
Map<String, AssetObject> byHash = new TreeMap<>();
|
||||
for (Map.Entry<String, JsonElement> entry : objects.entrySet()) {
|
||||
JsonObject object = entry.getValue().getAsJsonObject();
|
||||
String hash = object.get("hash").getAsString();
|
||||
if (!hash.matches("[0-9a-f]{40}")) {
|
||||
throw new CliException("Asset " + entry.getKey() + " has an invalid hash: " + hash);
|
||||
}
|
||||
byHash.putIfAbsent(
|
||||
hash,
|
||||
new AssetObject(entry.getKey(), hash, object.get("size").getAsLong()));
|
||||
}
|
||||
return List.copyOf(byHash.values());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Properties;
|
||||
|
||||
/**
|
||||
* The pinned game version from {@code incari.properties} at the repo root.
|
||||
*
|
||||
* <p>Pinning the hashes, not just the version id, matters because patches are text diffs
|
||||
* against decompiled output: if Mojang ever re-uploaded a jar under the same id, unpinned
|
||||
* builds would silently drift apart.
|
||||
*/
|
||||
public record BuildConfig(String minecraftVersion, String versionJsonSha1, String clientSha1) {
|
||||
|
||||
public static final String FILE_NAME = "incari.properties";
|
||||
|
||||
public static BuildConfig load(Path repoRoot) throws IOException {
|
||||
Path file = repoRoot.resolve(FILE_NAME);
|
||||
Properties props = new Properties();
|
||||
try (Reader reader = Files.newBufferedReader(file)) {
|
||||
props.load(reader);
|
||||
}
|
||||
return new BuildConfig(
|
||||
require(props, file, "minecraft.version"),
|
||||
require(props, file, "minecraft.versionJson.sha1"),
|
||||
require(props, file, "minecraft.client.sha1"));
|
||||
}
|
||||
|
||||
private static String require(Properties props, Path file, String key) {
|
||||
String value = props.getProperty(key);
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new CliException("Missing '" + key + "' in " + file);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package incari.tools.build;
|
||||
|
||||
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.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Whole-file changes to the vendor tree: classes Incari deletes outright, and classes it
|
||||
* replaces with its own source file.
|
||||
*
|
||||
* <p>These don't go through patches on purpose. A diff that deletes or rewrites a whole
|
||||
* Mojang file has to contain every one of its lines, which would republish them. A manifest
|
||||
* line names the class and contains no Mojang code at all.
|
||||
*
|
||||
* <p>Format of {@code patches/classes.txt}, one entry per line, {@code #} starts a comment:
|
||||
* <pre>
|
||||
* delete net.minecraft.client.telemetry.ClientTelemetryManager
|
||||
* replace com.mojang.blaze3d.vertex.ByteBufferBuilder render-webgl2/src/vendor/java/com/mojang/blaze3d/vertex/ByteBufferBuilder.java 26.3@3f2a9c1b07de
|
||||
* </pre>
|
||||
* Replacement paths are relative to the repo root. A replace line's last column, its {@link Stamp},
|
||||
* records which Mojang original the replacement was last checked against, so a new Minecraft
|
||||
* version (or decompiler) that changes the original is flagged for review instead of drifting
|
||||
* silently. {@code ./incari classes --stamp} writes it; nobody types it.
|
||||
*/
|
||||
public record ClassManifest(List<Entry> entries) {
|
||||
|
||||
public static final String FILE_NAME = "classes.txt";
|
||||
|
||||
private static final Pattern CLASS_NAME = Pattern.compile("[A-Za-z_$][\\w$]*(\\.[A-Za-z_$][\\w$]*)*");
|
||||
|
||||
private static final Pattern STAMP = Pattern.compile("([^@\\s]+)@([0-9a-f]{7,40})");
|
||||
|
||||
/** A replace line up to its source path, its stamp if any, and what follows (a comment). */
|
||||
private static final Pattern REPLACE_LINE =
|
||||
Pattern.compile("^(\\s*replace\\s+(\\S+)\\s+[^\\s#]+)(?:\\s+[^\\s#]+)?(\\s*(?:#.*)?)$");
|
||||
|
||||
/** Blob ids are abbreviated to this many hex digits in the manifest. */
|
||||
public static final int STAMP_DIGITS = 12;
|
||||
|
||||
public sealed interface Entry {
|
||||
String className();
|
||||
|
||||
/** Path of the class's source file, relative to the client tree root. */
|
||||
default String treePath() {
|
||||
return Workspace.CLIENT_SOURCE_DIR + "/" + className().replace('.', '/') + ".java";
|
||||
}
|
||||
}
|
||||
|
||||
public record Delete(String className) implements Entry {}
|
||||
|
||||
/**
|
||||
* The vendor original a replacement was checked against: the Minecraft version and the git blob
|
||||
* id of its decompiled, unpatched source (abbreviated). Names no Mojang code.
|
||||
*/
|
||||
public record Stamp(String version, String blob) {
|
||||
@Override
|
||||
public String toString() {
|
||||
return version + "@" + blob;
|
||||
}
|
||||
|
||||
/** Whether a full or abbreviated blob id is this stamp's file. */
|
||||
public boolean matches(String otherBlob) {
|
||||
return otherBlob.startsWith(blob) || blob.startsWith(otherBlob);
|
||||
}
|
||||
}
|
||||
|
||||
/** {@code stamp} is null until {@code ./incari classes --stamp} records one. */
|
||||
public record Replace(
|
||||
String className, String source, @Nullable Stamp stamp) implements Entry {
|
||||
public Replace(String className, String source) {
|
||||
this(className, source, null);
|
||||
}
|
||||
}
|
||||
|
||||
public static ClassManifest load(Path file) throws IOException {
|
||||
if (!Files.isRegularFile(file)) {
|
||||
return new ClassManifest(List.of());
|
||||
}
|
||||
return parse(Files.readAllLines(file), file.toString());
|
||||
}
|
||||
|
||||
static ClassManifest parse(List<String> lines, String origin) {
|
||||
List<Entry> entries = new ArrayList<>();
|
||||
Set<String> seen = new HashSet<>();
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String line = lines.get(i);
|
||||
int hash = line.indexOf('#');
|
||||
String content = (hash >= 0 ? line.substring(0, hash) : line).strip();
|
||||
if (content.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
String where = origin + ":" + (i + 1);
|
||||
String[] parts = content.split("\\s+", -1);
|
||||
Entry entry =
|
||||
switch (parts[0]) {
|
||||
case "delete" -> {
|
||||
expect(parts.length == 2, where, "expected: delete <class>");
|
||||
yield new Delete(className(parts[1], where));
|
||||
}
|
||||
case "replace" -> {
|
||||
expect(
|
||||
parts.length == 3 || parts.length == 4,
|
||||
where,
|
||||
"expected: replace <class> <source path> [<version>@<vendor blob>]");
|
||||
String source = parts[2];
|
||||
expect(
|
||||
!source.startsWith("/") && !source.contains("..") && !source.startsWith("work/"),
|
||||
where,
|
||||
"replacement source must be a repo-relative path outside work/");
|
||||
@Nullable Stamp stamp = null;
|
||||
if (parts.length == 4) {
|
||||
Matcher m = STAMP.matcher(parts[3]);
|
||||
expect(
|
||||
m.matches(),
|
||||
where,
|
||||
"'" + parts[3] + "' is not a stamp (<version>@<vendor blob>);"
|
||||
+ " write it with ./incari classes --stamp");
|
||||
stamp = new Stamp(m.group(1), m.group(2));
|
||||
}
|
||||
yield new Replace(className(parts[1], where), source, stamp);
|
||||
}
|
||||
default -> throw new CliException(where + ": unknown action '" + parts[0] + "'");
|
||||
};
|
||||
expect(seen.add(entry.className()), where, entry.className() + " is listed twice");
|
||||
entries.add(entry);
|
||||
}
|
||||
return new ClassManifest(List.copyOf(entries));
|
||||
}
|
||||
|
||||
/**
|
||||
* The manifest's lines with each replace line's stamp set from {@code stamps} (by class name),
|
||||
* aligned in one column. Every other line, comments included, is kept as it is.
|
||||
*/
|
||||
static List<String> withStamps(List<String> lines, Map<String, Stamp> stamps) {
|
||||
int width = 0;
|
||||
for (String line : lines) {
|
||||
Matcher m = REPLACE_LINE.matcher(line);
|
||||
if (m.matches() && stamps.containsKey(m.group(2))) {
|
||||
width = Math.max(width, m.group(1).length());
|
||||
}
|
||||
}
|
||||
List<String> out = new ArrayList<>(lines.size());
|
||||
for (String line : lines) {
|
||||
Matcher m = REPLACE_LINE.matcher(line);
|
||||
Stamp stamp = m.matches() ? stamps.get(m.group(2)) : null;
|
||||
if (stamp == null) {
|
||||
out.add(line);
|
||||
continue;
|
||||
}
|
||||
String head = m.group(1);
|
||||
out.add(head + " ".repeat(width - head.length() + 2) + stamp + m.group(3));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Tree paths this manifest owns. Patches must not touch them. */
|
||||
public Set<String> treePaths() {
|
||||
Set<String> paths = new HashSet<>();
|
||||
for (Entry entry : entries) {
|
||||
paths.add(entry.treePath());
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
private static String className(String value, String where) {
|
||||
expect(
|
||||
CLASS_NAME.matcher(value).matches() && !value.contains("$"),
|
||||
where,
|
||||
"'" + value + "' is not a top-level class name (nested classes can't be replaced alone)");
|
||||
return value;
|
||||
}
|
||||
|
||||
private static void expect(boolean condition, String where, String message) {
|
||||
if (!condition) {
|
||||
throw new CliException(where + ": " + message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* An expected failure with a message meant for the person running the CLI. {@link Main}
|
||||
* prints it without a stack trace; anything else is treated as a bug in the tool.
|
||||
*/
|
||||
public class CliException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
public CliException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public CliException(String message, @Nullable Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
package incari.tools.build;
|
||||
|
||||
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.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The editable client tree in {@code work/client}: a git repository whose history is
|
||||
*
|
||||
* <ol>
|
||||
* <li>one vendor commit (Vineflower's output, untouched), tagged {@code vendor};
|
||||
* <li>one commit applying {@code patches/classes.txt}, tagged {@code base};
|
||||
* <li>one commit per patch file.
|
||||
* </ol>
|
||||
*
|
||||
* <p>People edit the tree and commit there (one concern per commit, subject
|
||||
* {@code "<subsystem>: <summary>"}), then {@link #rebuildPatches} turns the commits after
|
||||
* {@code base} back into patch files. Patch files are never edited by hand.
|
||||
*/
|
||||
public final class ClientTree {
|
||||
|
||||
public static final String VENDOR_TAG = "vendor";
|
||||
public static final String BASE_TAG = "base";
|
||||
|
||||
/** HEAD at the last apply or rebuild. Anything else means unsaved work. */
|
||||
private static final String SYNCED_HEAD_FILE = "incari-synced-head";
|
||||
/** Which decompiled output the vendor commit holds, so re-applying can skip the copy. */
|
||||
private static final String VENDOR_STAMP_FILE = "incari-vendor-stamp";
|
||||
|
||||
/**
|
||||
* Minimal context keeps Mojang lines out of patch files (a unified diff repeats its context
|
||||
* lines). Full blob ids let {@code git am --3way} fall back to a merge when context drifts.
|
||||
*/
|
||||
private static final List<String> FORMAT_PATCH_OPTIONS = List.of(
|
||||
"--stdout",
|
||||
"--zero-commit",
|
||||
"--no-signature",
|
||||
"--no-stat",
|
||||
"--no-numbered",
|
||||
"--no-renames",
|
||||
"--full-index",
|
||||
"--no-color",
|
||||
"--no-ext-diff",
|
||||
"-U1");
|
||||
|
||||
private final Workspace ws;
|
||||
private final Git git;
|
||||
|
||||
public ClientTree(Workspace ws) {
|
||||
this.ws = ws;
|
||||
this.git = new Git(ws.clientTree());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------
|
||||
// Apply: decompiled sources + manifest + patches -> work/client
|
||||
// ------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Rebuilds the tree from the decompiled sources and the tracked patches. Refuses to throw
|
||||
* away commits or edits that {@code rebuild} hasn't saved, unless {@code force}.
|
||||
*/
|
||||
public void apply(Path decompiledDir, String version, boolean force) throws IOException, InterruptedException {
|
||||
Path tree = ws.clientTree();
|
||||
if (Files.isDirectory(tree.resolve(".git")) && !force) {
|
||||
requireNoUnsavedWork();
|
||||
}
|
||||
|
||||
String vendorStamp = Files.readString(decompiledDir.resolve(".incari-decompile-stamp"));
|
||||
if (vendorIsCurrent(vendorStamp)) {
|
||||
Log.step("Resetting work/client to the vendor commit");
|
||||
abortInProgressAm();
|
||||
git.run("reset", "--quiet", "--hard", VENDOR_TAG);
|
||||
git.run("clean", "--quiet", "-fdx");
|
||||
} else {
|
||||
createVendorCommit(decompiledDir, version, vendorStamp);
|
||||
}
|
||||
writeAttributes();
|
||||
|
||||
applyManifest();
|
||||
// Before the patches: a conflict there stops the apply, and this is the bump's other half.
|
||||
reportDrift(replacementDrift(version), version);
|
||||
applyPatches();
|
||||
recordSyncedHead();
|
||||
}
|
||||
|
||||
private boolean vendorIsCurrent(String vendorStamp) throws IOException, InterruptedException {
|
||||
Path stampFile = ws.clientTree().resolve(".git").resolve(VENDOR_STAMP_FILE);
|
||||
return Files.isRegularFile(stampFile)
|
||||
&& Files.readString(stampFile).equals(vendorStamp)
|
||||
&& git.tryRun("rev-parse", "--verify", "--quiet", VENDOR_TAG).exitCode() == 0;
|
||||
}
|
||||
|
||||
private void createVendorCommit(Path decompiledDir, String version, String vendorStamp)
|
||||
throws IOException, InterruptedException {
|
||||
Path tree = ws.clientTree();
|
||||
Log.step("Creating work/client from the decompiled " + version + " sources");
|
||||
FileTrees.deleteRecursively(tree);
|
||||
Files.createDirectories(tree);
|
||||
git.run("init", "--quiet");
|
||||
int files = FileTrees.copyTree(decompiledDir, tree.resolve(Workspace.CLIENT_SOURCE_DIR), ".java");
|
||||
Log.info(files + " source files");
|
||||
git.run("add", "--all");
|
||||
git.run("commit", "--quiet", "--no-verify", "-m", "Vendor: Minecraft " + version + " (decompiled, unmodified)");
|
||||
git.run("tag", VENDOR_TAG);
|
||||
Files.writeString(tree.resolve(".git").resolve(VENDOR_STAMP_FILE), vendorStamp);
|
||||
}
|
||||
|
||||
private void writeAttributes() throws IOException {
|
||||
Path info = ws.clientTree().resolve(".git").resolve("info");
|
||||
Files.createDirectories(info);
|
||||
Files.writeString(info.resolve("attributes"), "* diff=incari\n");
|
||||
}
|
||||
|
||||
private void applyManifest() throws IOException, InterruptedException {
|
||||
ClassManifest manifest = ClassManifest.load(ws.classManifest());
|
||||
Path tree = ws.clientTree();
|
||||
int deleted = 0;
|
||||
int replaced = 0;
|
||||
for (ClassManifest.Entry entry : manifest.entries()) {
|
||||
Path target = tree.resolve(entry.treePath());
|
||||
switch (entry) {
|
||||
case ClassManifest.Delete delete -> {
|
||||
requireExists(target, delete.className(), "delete");
|
||||
Files.delete(target);
|
||||
deleted++;
|
||||
}
|
||||
case ClassManifest.Replace replace -> {
|
||||
requireExists(target, replace.className(), "replace");
|
||||
Path source = ws.repoRoot().resolve(replace.source());
|
||||
if (!Files.isRegularFile(source)) {
|
||||
throw new CliException(ClassManifest.FILE_NAME + ": replacement source " + replace.source()
|
||||
+ " for " + replace.className() + " doesn't exist");
|
||||
}
|
||||
Files.copy(source, target, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
|
||||
replaced++;
|
||||
}
|
||||
}
|
||||
}
|
||||
git.run("add", "--all");
|
||||
git.run(
|
||||
"commit",
|
||||
"--quiet",
|
||||
"--no-verify",
|
||||
"--allow-empty",
|
||||
"-m",
|
||||
"Incari: class manifest (" + deleted + " deleted, " + replaced + " replaced)");
|
||||
git.run("tag", "--force", BASE_TAG);
|
||||
if (!manifest.entries().isEmpty()) {
|
||||
Log.info("Class manifest: " + deleted + " deleted, " + replaced + " replaced");
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireExists(Path target, String className, String action) {
|
||||
if (!Files.isRegularFile(target)) {
|
||||
throw new CliException(ClassManifest.FILE_NAME + ": can't " + action + " " + className
|
||||
+ ", it isn't in the vendor tree (renamed or removed in this Minecraft version?)");
|
||||
}
|
||||
}
|
||||
|
||||
private void applyPatches() throws IOException, InterruptedException {
|
||||
List<PatchSet.PatchFile> patches = PatchSet.list(ws.patchesDir());
|
||||
if (patches.isEmpty()) {
|
||||
Log.step("No patches to apply");
|
||||
return;
|
||||
}
|
||||
Log.step("Applying " + patches.size() + " patches");
|
||||
List<String> args = new ArrayList<>(List.of("am", "--quiet", "--3way", "--keep-cr", "--no-gpg-sign"));
|
||||
for (PatchSet.PatchFile patch : patches) {
|
||||
args.add(patch.path().toString());
|
||||
}
|
||||
ProcessRunner.Result result = git.tryRun(args.toArray(String[]::new));
|
||||
if (result.exitCode() != 0) {
|
||||
String current =
|
||||
git.tryRun("am", "--show-current-patch=diff").exitCode() == 0 ? currentAmPatchName() : "a patch";
|
||||
throw new CliException(
|
||||
"Patch failed to apply: " + current + "\n" + result.stderr().strip() + "\n"
|
||||
+ result.stdout().strip() + "\n\n"
|
||||
+ "work/client is stopped mid-apply. To fix it: resolve the conflicts in work/client, then\n"
|
||||
+ " git -C work/client add <files> && git -C work/client am --continue\n"
|
||||
+ "and once every patch is in, save the result with ./incari rebuild");
|
||||
}
|
||||
}
|
||||
|
||||
private String currentAmPatchName() throws IOException {
|
||||
Path next = ws.clientTree().resolve(".git/rebase-apply/next");
|
||||
Path last = ws.clientTree().resolve(".git/rebase-apply/last");
|
||||
if (!Files.isRegularFile(next)) {
|
||||
return "a patch";
|
||||
}
|
||||
String n = Files.readString(next).strip();
|
||||
return "patch " + n + " of " + Files.readString(last).strip();
|
||||
}
|
||||
|
||||
private void abortInProgressAm() throws IOException, InterruptedException {
|
||||
if (Files.isDirectory(ws.clientTree().resolve(".git/rebase-apply"))) {
|
||||
git.run("am", "--abort");
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------
|
||||
// Rebuild: commits after `base` -> patches/
|
||||
// ------------------------------------------------------------------------------------
|
||||
|
||||
/** What a rebuild wrote, or (with {@code check}) would write. */
|
||||
public record RebuildResult(int written, int unchanged, int removed) {
|
||||
public boolean changed() {
|
||||
return written > 0 || removed > 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns every commit after {@code base} into a patch file. With {@code check}, writes
|
||||
* nothing and only reports whether {@code patches/} is out of date (for CI).
|
||||
*/
|
||||
public RebuildResult rebuildPatches(boolean check) throws IOException, InterruptedException {
|
||||
requireTree();
|
||||
if (Files.isDirectory(ws.clientTree().resolve(".git/rebase-apply"))) {
|
||||
throw new CliException("work/client is in the middle of applying patches. Finish with"
|
||||
+ " `git -C work/client am --continue` (or start over with ./incari apply --force).");
|
||||
}
|
||||
if (!git.run("status", "--porcelain").isBlank()) {
|
||||
throw new CliException("work/client has uncommitted changes. Commit them first (one concern per commit,"
|
||||
+ " subject \"<subsystem>: <summary>\"), then run ./incari rebuild.");
|
||||
}
|
||||
if (git.tryRun("merge-base", "--is-ancestor", BASE_TAG, "HEAD").exitCode() != 0) {
|
||||
throw new CliException(
|
||||
"HEAD in work/client doesn't build on the '" + BASE_TAG + "' tag. Rebase your commits onto it.");
|
||||
}
|
||||
|
||||
Set<String> manifestPaths = ClassManifest.load(ws.classManifest()).treePaths();
|
||||
List<String> commits =
|
||||
git.run("rev-list", "--reverse", BASE_TAG + "..HEAD").lines().toList();
|
||||
|
||||
Map<String, byte[]> generated = new LinkedHashMap<>();
|
||||
for (int i = 0; i < commits.size(); i++) {
|
||||
String commit = commits.get(i);
|
||||
validateCommit(commit, manifestPaths);
|
||||
String subject = git.run("log", "-1", "--format=%s", commit).strip();
|
||||
String file = PatchSet.fileFor(i + 1, subject);
|
||||
List<String> args = new ArrayList<>(List.of("format-patch", "-1"));
|
||||
args.addAll(FORMAT_PATCH_OPTIONS);
|
||||
args.add(commit);
|
||||
generated.put(file, git.run(args.toArray(String[]::new)).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
return writePatches(generated, check);
|
||||
}
|
||||
|
||||
private void validateCommit(String commit, Set<String> manifestPaths) throws IOException, InterruptedException {
|
||||
String shortId = commit.substring(0, 10);
|
||||
if (git.run("rev-list", "--parents", "-n", "1", commit).strip().split(" ").length > 2) {
|
||||
throw new CliException(
|
||||
"Commit " + shortId + " is a merge. Patches must be a linear history; rebase instead.");
|
||||
}
|
||||
String changes = git.run("diff-tree", "--no-commit-id", "--name-status", "-r", "--no-renames", commit);
|
||||
for (String line : changes.lines().toList()) {
|
||||
String[] parts = line.split("\t", 2);
|
||||
String status = parts[0];
|
||||
String path = parts[1];
|
||||
if (status.startsWith("D")) {
|
||||
throw new CliException("Commit " + shortId + " deletes " + path + ". A patch that deletes a file"
|
||||
+ " republishes all of it; add a `delete` line to patches/classes.txt instead.");
|
||||
}
|
||||
if (manifestPaths.contains(path)) {
|
||||
throw new CliException("Commit " + shortId + " edits " + path + ", which patches/classes.txt deletes or"
|
||||
+ " replaces. Edit the replacement source in the repo instead.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private RebuildResult writePatches(Map<String, byte[]> generated, boolean check)
|
||||
throws IOException, InterruptedException {
|
||||
Path patchesDir = ws.patchesDir();
|
||||
List<Path> existing = new ArrayList<>();
|
||||
if (Files.isDirectory(patchesDir)) {
|
||||
try (Stream<Path> files = Files.walk(patchesDir)) {
|
||||
files.filter(p -> p.toString().endsWith(".patch")).forEach(existing::add);
|
||||
}
|
||||
}
|
||||
|
||||
int written = 0;
|
||||
int unchanged = 0;
|
||||
for (Map.Entry<String, byte[]> entry : generated.entrySet()) {
|
||||
Path target = patchesDir.resolve(entry.getKey());
|
||||
existing.remove(target);
|
||||
if (Files.isRegularFile(target) && java.util.Arrays.equals(Files.readAllBytes(target), entry.getValue())) {
|
||||
unchanged++;
|
||||
continue;
|
||||
}
|
||||
written++;
|
||||
if (check) {
|
||||
Log.info("out of date: patches/" + entry.getKey());
|
||||
} else {
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.write(target, entry.getValue());
|
||||
}
|
||||
}
|
||||
for (Path stale : existing) {
|
||||
if (check) {
|
||||
Log.info("stale: " + ws.repoRoot().relativize(stale));
|
||||
} else {
|
||||
Files.delete(stale);
|
||||
Path parent = stale.getParent();
|
||||
if (parent != null) {
|
||||
deleteIfEmpty(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!check) {
|
||||
recordSyncedHead();
|
||||
}
|
||||
return new RebuildResult(written, unchanged, existing.size());
|
||||
}
|
||||
|
||||
private void deleteIfEmpty(Path dir) throws IOException {
|
||||
if (dir.equals(ws.patchesDir())) {
|
||||
return;
|
||||
}
|
||||
try (Stream<Path> entries = Files.list(dir)) {
|
||||
if (entries.findAny().isEmpty()) {
|
||||
Files.delete(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------
|
||||
// Replacement stamps: has Mojang changed a class Incari replaces?
|
||||
// ------------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A replaced class whose vendor original isn't the one its stamp in {@code classes.txt} names
|
||||
* (or that has no stamp yet). {@code recorded} is null when there's no stamp.
|
||||
*/
|
||||
public record Drift(
|
||||
String className, ClassManifest.@Nullable Stamp recorded, ClassManifest.Stamp current, String path) {}
|
||||
|
||||
/**
|
||||
* Each replaced class whose decompiled original differs from the one it was last checked
|
||||
* against, read from the {@code vendor} commit, so it works mid-apply too.
|
||||
*/
|
||||
public List<Drift> replacementDrift(String version) throws IOException, InterruptedException {
|
||||
requireTree();
|
||||
List<Drift> drift = new ArrayList<>();
|
||||
for (ClassManifest.Entry entry : ClassManifest.load(ws.classManifest()).entries()) {
|
||||
if (!(entry instanceof ClassManifest.Replace replace)) {
|
||||
continue;
|
||||
}
|
||||
ClassManifest.Stamp current = vendorStamp(replace, version);
|
||||
ClassManifest.@Nullable Stamp recorded = replace.stamp();
|
||||
if (recorded == null || !recorded.matches(current.blob())) {
|
||||
drift.add(new Drift(replace.className(), recorded, current, replace.treePath()));
|
||||
}
|
||||
}
|
||||
return drift;
|
||||
}
|
||||
|
||||
/** Records the current vendor original of every replaced class in {@code classes.txt}. */
|
||||
public int stampReplacements(String version) throws IOException, InterruptedException {
|
||||
requireTree();
|
||||
Map<String, ClassManifest.Stamp> stamps = new LinkedHashMap<>();
|
||||
for (ClassManifest.Entry entry : ClassManifest.load(ws.classManifest()).entries()) {
|
||||
if (entry instanceof ClassManifest.Replace replace) {
|
||||
stamps.put(replace.className(), vendorStamp(replace, version));
|
||||
}
|
||||
}
|
||||
List<String> lines = Files.readAllLines(ws.classManifest());
|
||||
List<String> stamped = ClassManifest.withStamps(lines, stamps);
|
||||
if (!stamped.equals(lines)) {
|
||||
Files.write(ws.classManifest(), stamped);
|
||||
}
|
||||
return stamps.size();
|
||||
}
|
||||
|
||||
/** Logs each drifted replacement, with the command that shows what Mojang changed. */
|
||||
public void reportDrift(List<Drift> drift, String version) {
|
||||
for (Drift d : drift) {
|
||||
if (d.recorded() == null) {
|
||||
Log.warn(d.className() + " is replaced but has no stamp in patches/classes.txt");
|
||||
continue;
|
||||
}
|
||||
Log.warn(d.className() + " changed upstream: replacement written against " + d.recorded()
|
||||
+ ", vendor is now " + d.current());
|
||||
String relative = d.path().substring(Workspace.CLIENT_SOURCE_DIR.length() + 1);
|
||||
Path old = ws.decompiledDir(d.recorded().version()).resolve(relative);
|
||||
Path now = ws.decompiledDir(version).resolve(relative);
|
||||
if (!d.recorded().version().equals(version) && Files.isRegularFile(old)) {
|
||||
Log.info("see what changed: git diff --no-index "
|
||||
+ ws.repoRoot().relativize(old) + " " + ws.repoRoot().relativize(now));
|
||||
} else if (d.recorded().version().equals(version)) {
|
||||
Log.info("same version, different decompiled source: a decompiler change?");
|
||||
}
|
||||
}
|
||||
if (!drift.isEmpty()) {
|
||||
Log.info("Bring each replacement in line with the new original, then: ./incari classes --stamp");
|
||||
}
|
||||
}
|
||||
|
||||
private ClassManifest.Stamp vendorStamp(ClassManifest.Replace replace, String version)
|
||||
throws IOException, InterruptedException {
|
||||
ProcessRunner.Result result =
|
||||
git.tryRun("rev-parse", "--verify", "--quiet", VENDOR_TAG + ":" + replace.treePath());
|
||||
if (result.exitCode() != 0) {
|
||||
throw new CliException(ClassManifest.FILE_NAME + ": " + replace.className()
|
||||
+ " isn't in the vendor tree (renamed or removed in this Minecraft version?)");
|
||||
}
|
||||
return new ClassManifest.Stamp(version, result.stdout().strip().substring(0, ClassManifest.STAMP_DIGITS));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------
|
||||
// Guarding unsaved work
|
||||
// ------------------------------------------------------------------------------------
|
||||
|
||||
private void recordSyncedHead() throws IOException, InterruptedException {
|
||||
String head = git.run("rev-parse", "HEAD").strip();
|
||||
Files.writeString(ws.clientTree().resolve(".git").resolve(SYNCED_HEAD_FILE), head);
|
||||
}
|
||||
|
||||
private void requireNoUnsavedWork() throws IOException, InterruptedException {
|
||||
Path synced = ws.clientTree().resolve(".git").resolve(SYNCED_HEAD_FILE);
|
||||
if (!Files.isRegularFile(synced)) {
|
||||
// A tree from an interrupted first apply: nothing in it was ever the user's.
|
||||
return;
|
||||
}
|
||||
boolean dirty = !git.run("status", "--porcelain").isBlank();
|
||||
boolean moved = !git.run("rev-parse", "HEAD")
|
||||
.strip()
|
||||
.equals(Files.readString(synced).strip());
|
||||
if (dirty || moved) {
|
||||
throw new CliException(
|
||||
"work/client has " + (dirty ? "uncommitted changes" : "commits not saved to patches/")
|
||||
+ ". Applying would discard them.\n"
|
||||
+ " Save them first: commit, then ./incari rebuild\n"
|
||||
+ " Or throw them away: ./incari apply --force");
|
||||
}
|
||||
}
|
||||
|
||||
private void requireTree() {
|
||||
if (!Files.isDirectory(ws.clientTree().resolve(".git"))) {
|
||||
throw new CliException("work/client doesn't exist yet. Run: ./incari setup");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
final class Concurrency {
|
||||
|
||||
private Concurrency() {}
|
||||
|
||||
/** Waits for {@code future}, rethrowing its failure unwrapped so CLI errors keep their message. */
|
||||
static void join(Future<?> future) throws IOException, InterruptedException {
|
||||
try {
|
||||
future.get();
|
||||
} catch (ExecutionException e) {
|
||||
Throwable cause = e.getCause();
|
||||
if (cause == null) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
switch (cause) {
|
||||
case IOException io -> throw io;
|
||||
case RuntimeException runtime -> throw runtime;
|
||||
case InterruptedException interrupted -> throw interrupted;
|
||||
case Throwable other -> throw new IllegalStateException(other);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.jar.JarFile;
|
||||
|
||||
/**
|
||||
* Runs Vineflower over the client jar into {@code work/decompiled/<version>}.
|
||||
*
|
||||
* <p>The output is only as stable as its inputs: the same jar, the same Vineflower version
|
||||
* and the same options must give byte-identical sources on every machine, or patches stop
|
||||
* applying. All three go into a stamp file, and a matching stamp skips the (multi-minute)
|
||||
* decompile.
|
||||
*/
|
||||
public final class Decompiler {
|
||||
|
||||
private static final String MAIN_CLASS = "org.jetbrains.java.decompiler.main.decompiler.ConsoleDecompiler";
|
||||
private static final String STAMP_FILE = ".incari-decompile-stamp";
|
||||
|
||||
/**
|
||||
* Changing any of these changes every decompiled file, so every patch must be
|
||||
* regenerated. Treat an edit here like a Minecraft version bump.
|
||||
*/
|
||||
private static final List<String> OPTIONS = List.of(
|
||||
"--folder",
|
||||
// Only classes: assets and data stay in the jar and never enter the git tree.
|
||||
"--skip-extra-files",
|
||||
// Mojang's own style, so the tree reads like the game's sources.
|
||||
"--indent-string= ",
|
||||
"--log-level=warn");
|
||||
|
||||
private Decompiler() {}
|
||||
|
||||
public static void decompile(Workspace ws, GameFiles game) throws IOException, InterruptedException {
|
||||
Path output = ws.decompiledDir(game.version().id());
|
||||
Path vineflowerJar = vineflowerJar();
|
||||
String stamp = stamp(game, vineflowerJar);
|
||||
|
||||
Path stampFile = output.resolve(STAMP_FILE);
|
||||
if (Files.isRegularFile(stampFile) && Files.readString(stampFile).equals(stamp)) {
|
||||
Log.step("Decompiled sources for " + game.version().id() + " are up to date");
|
||||
return;
|
||||
}
|
||||
|
||||
Log.step("Decompiling " + game.version().id() + " with Vineflower (takes a few minutes)");
|
||||
Path temp = output.resolveSibling(output.getFileName() + ".tmp");
|
||||
FileTrees.deleteRecursively(temp);
|
||||
Files.createDirectories(temp);
|
||||
|
||||
List<String> command = new ArrayList<>();
|
||||
command.add(ProcessRunner.javaExecutable());
|
||||
command.add(System.getenv().getOrDefault("INCARI_DECOMPILE_XMX", "-Xmx8g"));
|
||||
command.add("-cp");
|
||||
command.add(vineflowerJar.toString());
|
||||
command.add(MAIN_CLASS);
|
||||
command.addAll(OPTIONS);
|
||||
for (GameFiles.LibraryJar library : game.libraries()) {
|
||||
// Libraries let Vineflower resolve generics and overloads it would otherwise
|
||||
// guess at, which means fewer casts and fewer decompile errors to patch around.
|
||||
command.add("-e=" + library.jar());
|
||||
}
|
||||
command.add(game.clientJar().toString());
|
||||
command.add(temp.toString());
|
||||
ProcessRunner.run(command, ws.repoRoot(), true);
|
||||
|
||||
Files.writeString(temp.resolve(STAMP_FILE), stamp);
|
||||
FileTrees.deleteRecursively(output);
|
||||
Files.move(temp, output);
|
||||
}
|
||||
|
||||
private static String stamp(GameFiles game, Path vineflowerJar) throws IOException {
|
||||
String vineflowerVersion;
|
||||
try (JarFile jar = new JarFile(vineflowerJar.toFile())) {
|
||||
vineflowerVersion = jar.getManifest().getMainAttributes().getValue("Implementation-Version");
|
||||
}
|
||||
return "client=" + Downloader.sha1(game.clientJar()) + "\n"
|
||||
+ "vineflower=" + vineflowerVersion + "\n"
|
||||
+ "options=" + String.join(" ", OPTIONS) + "\n"
|
||||
+ "libraries="
|
||||
+ game.libraries().stream()
|
||||
.map(l -> l.jar().getFileName().toString())
|
||||
.sorted()
|
||||
.toList() + "\n";
|
||||
}
|
||||
|
||||
private static Path vineflowerJar() {
|
||||
try {
|
||||
Class<?> main = Class.forName(MAIN_CLASS, false, Decompiler.class.getClassLoader());
|
||||
return Path.of(
|
||||
main.getProtectionDomain().getCodeSource().getLocation().toURI());
|
||||
} catch (ClassNotFoundException | URISyntaxException e) {
|
||||
throw new IllegalStateException("Vineflower must be on the CLI's runtime classpath", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
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.time.Duration;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/**
|
||||
* Downloads files and checks their SHA-1. A file already on disk with the right hash is
|
||||
* reused, so re-running {@code incari fetch} costs only the hash checks.
|
||||
*
|
||||
* <p>Writes go to a temp file first and are moved into place only after the hash matches,
|
||||
* so an interrupted download never leaves a truncated jar that later steps trust.
|
||||
*/
|
||||
public final class Downloader {
|
||||
|
||||
private static final int ATTEMPTS = 3;
|
||||
|
||||
private final HttpClient http = HttpClient.newBuilder()
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.connectTimeout(Duration.ofSeconds(30))
|
||||
.build();
|
||||
|
||||
/** Downloads {@code url} to {@code target} unless it's already there with {@code sha1}. */
|
||||
public void fetch(URI url, String sha1, Path target) throws IOException, InterruptedException {
|
||||
if (Files.isRegularFile(target) && sha1(target).equals(sha1)) {
|
||||
return;
|
||||
}
|
||||
Files.createDirectories(target.getParent());
|
||||
Path temp = target.resolveSibling(target.getFileName() + ".part");
|
||||
IOException last = null;
|
||||
for (int attempt = 1; attempt <= ATTEMPTS; attempt++) {
|
||||
try {
|
||||
download(url, temp);
|
||||
String actual = sha1(temp);
|
||||
if (!actual.equals(sha1)) {
|
||||
throw new IOException("SHA-1 mismatch for " + url + ": expected " + sha1 + ", got " + actual);
|
||||
}
|
||||
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
|
||||
return;
|
||||
} catch (IOException e) {
|
||||
last = e;
|
||||
} finally {
|
||||
Files.deleteIfExists(temp);
|
||||
}
|
||||
}
|
||||
throw new CliException("Download failed after " + ATTEMPTS + " attempts: " + url, last);
|
||||
}
|
||||
|
||||
/** Downloads without a known hash (only the version manifest, which changes over time). */
|
||||
public String fetchString(URI url) throws IOException, InterruptedException {
|
||||
HttpResponse<String> response = http.send(request(url), HttpResponse.BodyHandlers.ofString());
|
||||
checkStatus(url, response.statusCode());
|
||||
return response.body();
|
||||
}
|
||||
|
||||
private void download(URI url, Path temp) throws IOException, InterruptedException {
|
||||
HttpResponse<InputStream> response = http.send(request(url), HttpResponse.BodyHandlers.ofInputStream());
|
||||
try (InputStream body = response.body()) {
|
||||
checkStatus(url, response.statusCode());
|
||||
Files.copy(body, temp, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpRequest request(URI url) {
|
||||
return HttpRequest.newBuilder(url).timeout(Duration.ofMinutes(5)).GET().build();
|
||||
}
|
||||
|
||||
private static void checkStatus(URI url, int status) throws IOException {
|
||||
if (status != 200) {
|
||||
throw new IOException("HTTP " + status + " from " + url);
|
||||
}
|
||||
}
|
||||
|
||||
public static String sha1(Path file) throws IOException {
|
||||
MessageDigest digest;
|
||||
try {
|
||||
digest = MessageDigest.getInstance("SHA-1");
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("Every JDK ships SHA-1", e);
|
||||
}
|
||||
try (InputStream in = Files.newInputStream(file)) {
|
||||
byte[] buffer = new byte[1 << 16];
|
||||
for (int n; (n = in.read(buffer)) > 0; ) {
|
||||
digest.update(buffer, 0, n);
|
||||
}
|
||||
}
|
||||
return HexFormat.of().formatHex(digest.digest());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.FileVisitResult;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.SimpleFileVisitor;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
|
||||
/** Recursive copy and delete. */
|
||||
public final class FileTrees {
|
||||
|
||||
private FileTrees() {}
|
||||
|
||||
public static void deleteRecursively(Path root) throws IOException {
|
||||
if (!Files.exists(root, LinkOption.NOFOLLOW_LINKS)) {
|
||||
return;
|
||||
}
|
||||
Files.walkFileTree(root, new SimpleFileVisitor<>() {
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
|
||||
// Git marks its object files read-only; Windows refuses to delete those.
|
||||
file.toFile().setWritable(true);
|
||||
Files.delete(file);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
|
||||
if (exc != null) {
|
||||
throw exc;
|
||||
}
|
||||
Files.delete(dir);
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Copies every regular file under {@code from} whose name ends in {@code suffix} into {@code to}. */
|
||||
public static int copyTree(Path from, Path to, String suffix) throws IOException {
|
||||
int[] count = {0};
|
||||
Files.walkFileTree(from, new SimpleFileVisitor<>() {
|
||||
@Override
|
||||
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
|
||||
if (file.getFileName().toString().endsWith(suffix)) {
|
||||
Path target = to.resolve(from.relativize(file).toString());
|
||||
Files.createDirectories(target.getParent());
|
||||
Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING);
|
||||
count[0]++;
|
||||
}
|
||||
return FileVisitResult.CONTINUE;
|
||||
}
|
||||
});
|
||||
return count[0];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package incari.tools.build;
|
||||
|
||||
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.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
/**
|
||||
* The pinned client jar and its platform-neutral libraries, cached under {@code work/cache}.
|
||||
*
|
||||
* <p>{@link #fetch} downloads what's missing, plus this machine's native libraries for the
|
||||
* desktop runtime. {@link #load} only reads the cache, for steps (decompile, survey) that must
|
||||
* not touch the network.
|
||||
*/
|
||||
public record GameFiles(MojangMetadata.Version version, Path clientJar, List<LibraryJar> libraries) {
|
||||
|
||||
/** A platform-neutral library and where its jar is cached. */
|
||||
public record LibraryJar(MojangMetadata.Library library, Path jar) {}
|
||||
|
||||
public static GameFiles fetch(Workspace ws, BuildConfig config, Downloader downloader)
|
||||
throws IOException, InterruptedException {
|
||||
String id = config.minecraftVersion();
|
||||
Path versionJson = ws.versionJson(id);
|
||||
|
||||
if (!Files.isRegularFile(versionJson) || !Downloader.sha1(versionJson).equals(config.versionJsonSha1())) {
|
||||
Log.step("Reading Mojang's version manifest");
|
||||
String manifest = downloader.fetchString(MojangMetadata.VERSION_MANIFEST);
|
||||
Files.createDirectories(ws.cacheDir());
|
||||
Files.writeString(ws.versionManifestFile(), manifest);
|
||||
MojangMetadata.Download listed = MojangMetadata.findVersion(manifest, id);
|
||||
if (!listed.sha1().equals(config.versionJsonSha1())) {
|
||||
throw new CliException("Mojang's metadata for " + id + " has SHA-1 " + listed.sha1()
|
||||
+ " but " + BuildConfig.FILE_NAME + " pins " + config.versionJsonSha1()
|
||||
+ ". Mojang changed a published version; review before re-pinning.");
|
||||
}
|
||||
downloader.fetch(listed.url(), listed.sha1(), versionJson);
|
||||
}
|
||||
|
||||
MojangMetadata.Version version = MojangMetadata.parseVersion(Files.readString(versionJson));
|
||||
checkClientPin(version, config);
|
||||
|
||||
Log.step("Downloading client " + id);
|
||||
downloader.fetch(version.client().url(), version.client().sha1(), ws.clientJar(id));
|
||||
|
||||
List<MojangMetadata.Library> natives = hostNatives(version, NativePlatform.current());
|
||||
List<MojangMetadata.Library> libraries = new ArrayList<>(neutralLibraries(version));
|
||||
libraries.addAll(natives);
|
||||
Log.step("Downloading " + libraries.size() + " libraries (" + natives.size() + " native, for "
|
||||
+ NativePlatform.current().classifier() + ")");
|
||||
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
|
||||
List<Future<?>> pending = new ArrayList<>();
|
||||
for (MojangMetadata.Library lib : libraries) {
|
||||
pending.add(pool.submit(() -> {
|
||||
downloader.fetch(
|
||||
lib.download().url(),
|
||||
lib.download().sha1(),
|
||||
ws.librariesDir().resolve(lib.path()));
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
for (Future<?> future : pending) {
|
||||
Concurrency.join(future);
|
||||
}
|
||||
}
|
||||
writeList(ws, ws.classpathList(id), neutralLibraries(version));
|
||||
writeList(ws, ws.nativesList(id), natives);
|
||||
return load(ws, config);
|
||||
}
|
||||
|
||||
/** Reads the cache written by {@link #fetch}. Fails with a hint if it's missing. */
|
||||
public static GameFiles load(Workspace ws, BuildConfig config) throws IOException {
|
||||
String id = config.minecraftVersion();
|
||||
Path versionJson = ws.versionJson(id);
|
||||
Path clientJar = ws.clientJar(id);
|
||||
if (!Files.isRegularFile(versionJson) || !Files.isRegularFile(clientJar)) {
|
||||
throw new CliException("Minecraft " + id + " isn't downloaded yet. Run: ./incari fetch");
|
||||
}
|
||||
MojangMetadata.Version version = MojangMetadata.parseVersion(Files.readString(versionJson));
|
||||
checkClientPin(version, config);
|
||||
|
||||
List<LibraryJar> libraries = new ArrayList<>();
|
||||
for (MojangMetadata.Library lib : neutralLibraries(version)) {
|
||||
Path jar = ws.librariesDir().resolve(lib.path());
|
||||
if (!Files.isRegularFile(jar)) {
|
||||
throw new CliException("Library " + lib.name() + " is missing. Run: ./incari fetch");
|
||||
}
|
||||
libraries.add(new LibraryJar(lib, jar));
|
||||
}
|
||||
return new GameFiles(version, clientJar, List.copyOf(libraries));
|
||||
}
|
||||
|
||||
private static List<MojangMetadata.Library> neutralLibraries(MojangMetadata.Version version) {
|
||||
return version.libraries().stream()
|
||||
.filter(lib -> !lib.platformSpecific())
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** The native jars for {@code platform}, one per library that has them. */
|
||||
static List<MojangMetadata.Library> hostNatives(MojangMetadata.Version version, NativePlatform platform) {
|
||||
return version.libraries().stream()
|
||||
.filter(lib -> lib.classifier().equals(platform.classifier()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** Repo-relative jar paths, one per line: the format Gradle reads (see {@link Workspace#classpathList}). */
|
||||
private static void writeList(Workspace ws, Path file, List<MojangMetadata.Library> libraries) throws IOException {
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (MojangMetadata.Library lib : libraries) {
|
||||
Path jar = ws.librariesDir().resolve(lib.path());
|
||||
out.append(ws.repoRoot().relativize(jar).toString().replace('\\', '/'))
|
||||
.append('\n');
|
||||
}
|
||||
Files.writeString(file, out.toString());
|
||||
}
|
||||
|
||||
private static void checkClientPin(MojangMetadata.Version version, BuildConfig config) {
|
||||
if (!version.client().sha1().equals(config.clientSha1())) {
|
||||
throw new CliException("Client jar for " + version.id() + " has SHA-1 "
|
||||
+ version.client().sha1() + " but " + BuildConfig.FILE_NAME + " pins " + config.clientSha1());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Runs git in one repository, isolated from the user's and the system's git config.
|
||||
*
|
||||
* <p>Isolation is what makes patch files byte-identical across machines: settings like
|
||||
* {@code diff.noprefix}, {@code diff.algorithm} or {@code format.signature} in someone's
|
||||
* {@code ~/.gitconfig} would otherwise change every regenerated patch.
|
||||
*/
|
||||
public final class Git {
|
||||
|
||||
/** Identity for commits the tool makes itself (vendor and manifest commits, applied patches). */
|
||||
static final String TOOL_NAME = "Incari Build";
|
||||
|
||||
static final String TOOL_EMAIL = "build@incari.invalid";
|
||||
/** Fixed so the tool's own commits get the same hash on every machine. */
|
||||
static final String TOOL_DATE = "2000-01-01T00:00:00Z";
|
||||
|
||||
private final Path dir;
|
||||
|
||||
public Git(Path dir) {
|
||||
this.dir = dir;
|
||||
}
|
||||
|
||||
public Path dir() {
|
||||
return dir;
|
||||
}
|
||||
|
||||
/** Runs a git command, returning stdout. Throws with git's stderr on failure. */
|
||||
public String run(String... args) throws IOException, InterruptedException {
|
||||
ProcessRunner.Result result = tryRun(args);
|
||||
if (result.exitCode() != 0) {
|
||||
throw new CliException("git " + String.join(" ", args) + " failed in " + dir
|
||||
+ (result.stderr().isBlank() ? "" : ":\n" + result.stderr().strip()));
|
||||
}
|
||||
return result.stdout();
|
||||
}
|
||||
|
||||
public ProcessRunner.Result tryRun(String... args) throws IOException, InterruptedException {
|
||||
return ProcessRunner.start(command(args), dir, environment(), false, null);
|
||||
}
|
||||
|
||||
private static List<String> command(String... args) {
|
||||
List<String> command = new ArrayList<>(List.of(
|
||||
"git",
|
||||
"-c",
|
||||
"core.autocrlf=false",
|
||||
"-c",
|
||||
"core.safecrlf=false",
|
||||
"-c",
|
||||
"core.quotePath=false",
|
||||
"-c",
|
||||
"commit.gpgSign=false",
|
||||
"-c",
|
||||
"tag.gpgSign=false",
|
||||
// No hooks: a user's global pre-commit hook has no business running on vendor code.
|
||||
"-c",
|
||||
"core.hooksPath=.git/incari-no-hooks",
|
||||
"-c",
|
||||
"gc.auto=0",
|
||||
"-c",
|
||||
"init.defaultBranch=main",
|
||||
"-c",
|
||||
"advice.detachedHead=false",
|
||||
// Paired with the "* diff=incari" attribute ClientTree writes: a function-name
|
||||
// regex that never matches, so hunk headers don't quote a vendor line as context.
|
||||
"-c",
|
||||
"diff.incari.xfuncname=x^"));
|
||||
command.addAll(List.of(args));
|
||||
return command;
|
||||
}
|
||||
|
||||
private static Map<String, String> environment() {
|
||||
Map<String, String> env = new HashMap<>();
|
||||
env.put("GIT_CONFIG_NOSYSTEM", "1");
|
||||
env.put("GIT_CONFIG_GLOBAL", System.getProperty("os.name").startsWith("Windows") ? "NUL" : "/dev/null");
|
||||
env.put("GIT_TERMINAL_PROMPT", "0");
|
||||
env.put("GIT_COMMITTER_NAME", TOOL_NAME);
|
||||
env.put("GIT_COMMITTER_EMAIL", TOOL_EMAIL);
|
||||
env.put("GIT_COMMITTER_DATE", TOOL_DATE);
|
||||
env.put("GIT_AUTHOR_NAME", TOOL_NAME);
|
||||
env.put("GIT_AUTHOR_EMAIL", TOOL_EMAIL);
|
||||
env.put("GIT_AUTHOR_DATE", TOOL_DATE);
|
||||
return env;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/** Points the checkout's git hooks at {@code tools/git-hooks}, so the pre-commit checks run. */
|
||||
final class GitHooks {
|
||||
|
||||
static final String HOOKS_DIR = "tools/git-hooks";
|
||||
|
||||
private GitHooks() {}
|
||||
|
||||
/** Installs the hooks unless this clone already chose its own hooks directory. */
|
||||
static void install(Workspace ws) throws IOException, InterruptedException {
|
||||
Git repo = new Git(ws.repoRoot());
|
||||
if (repo.tryRun("rev-parse", "--git-dir").exitCode() != 0) {
|
||||
return; // A source archive, not a clone: nothing to install into.
|
||||
}
|
||||
// --local reads only this clone's config, not the overrides the Git class passes with -c.
|
||||
ProcessRunner.Result current = repo.tryRun("config", "--local", "--get", "core.hooksPath");
|
||||
String configured = current.stdout().strip();
|
||||
if (current.exitCode() == 0 && !configured.equals(HOOKS_DIR)) {
|
||||
Log.info("Keeping this clone's own core.hooksPath (" + configured + "); Incari's are in " + HOOKS_DIR);
|
||||
return;
|
||||
}
|
||||
if (!configured.equals(HOOKS_DIR)) {
|
||||
repo.run("config", "--local", "core.hooksPath", HOOKS_DIR);
|
||||
Log.info("Installed the pre-commit checks (" + HOOKS_DIR + ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,448 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.net.URI;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The experimental Rust build (ADR 0068): Horizon's browser port with Incari's native mods.
|
||||
*
|
||||
* <p>Horizon is pinned in {@code incari.properties} and cloned into {@code work/horizon}, never
|
||||
* committed, as the game is (ADR 0001). {@code INCARI_HORIZON_DIR} names a checkout to build
|
||||
* instead, for work on Horizon itself. {@link #build} prepares Horizon's resources from the game
|
||||
* files {@code ./incari fetch} and {@code ./incari assets} downloaded, applies {@code rust/mods}
|
||||
* with horizon-mixins into {@code work/horizon-stage}, and runs Horizon's {@code web/package.py} there.
|
||||
* The folder it writes, {@code app-web/build/rust/}, is what the page offers as Rust.
|
||||
*/
|
||||
final class Horizon {
|
||||
|
||||
/** A checkout to build instead of the pinned one. */
|
||||
static final String DIR_VARIABLE = "INCARI_HORIZON_DIR";
|
||||
|
||||
/** What {@code incari.properties} pins. */
|
||||
record Pin(String repository, String revision, String mixinsRepository, String mixinsRevision) {
|
||||
|
||||
static Pin load(Path repoRoot) throws IOException {
|
||||
Path file = repoRoot.resolve(BuildConfig.FILE_NAME);
|
||||
Properties props = new Properties();
|
||||
try (Reader reader = Files.newBufferedReader(file)) {
|
||||
props.load(reader);
|
||||
}
|
||||
return new Pin(
|
||||
require(props, file, "horizon.repository"),
|
||||
require(props, file, "horizon.revision"),
|
||||
require(props, file, "horizon.mixins.repository"),
|
||||
require(props, file, "horizon.mixins.revision"));
|
||||
}
|
||||
|
||||
private static String require(Properties props, Path file, String key) {
|
||||
String value = props.getProperty(key);
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new CliException("Missing '" + key + "' in " + file);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
}
|
||||
|
||||
private Horizon() {}
|
||||
|
||||
static Path pinnedSource(Workspace ws) {
|
||||
return ws.workDir().resolve("horizon");
|
||||
}
|
||||
|
||||
static Path stage(Workspace ws) {
|
||||
return ws.workDir().resolve("horizon-stage");
|
||||
}
|
||||
|
||||
/** Where the browser build lands, for {@code :app-web:serve} and {@code :app-web:webFolder}. */
|
||||
static Path output(Workspace ws) {
|
||||
return ws.repoRoot().resolve("app-web/build/rust");
|
||||
}
|
||||
|
||||
static Path mods(Workspace ws) {
|
||||
return ws.repoRoot().resolve("rust/mods");
|
||||
}
|
||||
|
||||
/** The checkout {@code INCARI_HORIZON_DIR} names, or null to use the pinned one. */
|
||||
static @Nullable Path override() {
|
||||
String dir = System.getenv(DIR_VARIABLE);
|
||||
if (dir == null || dir.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
Path path = Path.of(System.getProperty("incari.cwd", "."))
|
||||
.resolve(dir)
|
||||
.toAbsolutePath()
|
||||
.normalize();
|
||||
if (!Files.isRegularFile(path.resolve("web/package.py"))) {
|
||||
throw new CliException(
|
||||
DIR_VARIABLE + "=" + dir + " isn't a checkout of Horizon's browser port" + " (no web/package.py)");
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clones the pinned commit into {@code work/horizon}, or moves the clone to it. Refuses to move
|
||||
* a clone with changes in it: unsaved work is never dropped.
|
||||
*/
|
||||
static Path fetch(Workspace ws, Pin pin) throws IOException, InterruptedException {
|
||||
Path dir = pinnedSource(ws);
|
||||
if (!Files.isDirectory(dir.resolve(".git"))) {
|
||||
Log.step("Cloning Horizon " + pin.revision().substring(0, 12) + " into work/horizon");
|
||||
Files.createDirectories(dir);
|
||||
git(dir, "init", "--quiet");
|
||||
git(dir, "remote", "add", "origin", pin.repository());
|
||||
} else if (head(dir).equals(pin.revision())) {
|
||||
return dir;
|
||||
} else if (!git(dir, "status", "--porcelain").stdout().isBlank()) {
|
||||
throw new CliException("work/horizon has changes and isn't at the pinned commit. Commit them in your"
|
||||
+ " Horizon fork, or set " + DIR_VARIABLE + " to build a checkout of your own");
|
||||
} else {
|
||||
Log.step("Moving work/horizon to " + pin.revision().substring(0, 12));
|
||||
git(dir, "remote", "set-url", "origin", pin.repository());
|
||||
}
|
||||
git(dir, "fetch", "--quiet", "--depth", "1", "origin", pin.revision());
|
||||
git(dir, "checkout", "--quiet", "--detach", "FETCH_HEAD");
|
||||
if (!head(dir).equals(pin.revision())) {
|
||||
throw new CliException(
|
||||
"Fetched " + head(dir) + " but " + BuildConfig.FILE_NAME + " pins " + pin.revision());
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the Rust build needs that this machine lacks, each with how to get it; empty when it can
|
||||
* build. Reads the versions from the source: the nightly {@code web/build.sh} names, and the
|
||||
* wasm-bindgen of its {@code Cargo.lock}.
|
||||
*/
|
||||
static List<String> missingTools(Path source) throws IOException, InterruptedException {
|
||||
List<String> missing = new ArrayList<>();
|
||||
if (!runs("python3", "--version")) {
|
||||
missing.add("python3");
|
||||
}
|
||||
if (!runs("rustup", "--version") || !runs("cargo", "--version")) {
|
||||
missing.add("Rust (https://rustup.rs)");
|
||||
return missing;
|
||||
}
|
||||
String nightly = match(Files.readString(source.resolve("web/build.sh")), "(?m)^nightly=(\\S+)");
|
||||
String components = ProcessRunner.start(
|
||||
List.of("rustup", "component", "list", "--installed", "--toolchain", nightly),
|
||||
source,
|
||||
Map.of(),
|
||||
false,
|
||||
null)
|
||||
.stdout();
|
||||
if (!components.contains("rust-src") || !components.contains("rust-std-wasm32-unknown-unknown")) {
|
||||
missing.add("Rust " + nightly + ": rustup toolchain install " + nightly
|
||||
+ " --component rust-src --target wasm32-unknown-unknown");
|
||||
}
|
||||
String bindgen = match(
|
||||
Files.readString(source.resolve("Cargo.lock")), "name = \"wasm-bindgen\"\\nversion = \"([^\"]+)\"");
|
||||
ProcessRunner.Result installed =
|
||||
ProcessRunner.start(List.of("wasm-bindgen", "--version"), source, Map.of(), false, null);
|
||||
if (installed.exitCode() != 0 || !installed.stdout().strip().equals("wasm-bindgen " + bindgen)) {
|
||||
missing.add("wasm-bindgen " + bindgen + ": cargo install wasm-bindgen-cli --version " + bindgen);
|
||||
}
|
||||
if (!runs("wasm-opt", "--version")) {
|
||||
missing.add("binaryen's wasm-opt (your package manager's binaryen)");
|
||||
}
|
||||
return missing;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the Rust build into {@link #output}: Horizon's resources, the mods, and its
|
||||
* threaded WebAssembly build (the page's service worker makes it cross-origin isolated).
|
||||
*/
|
||||
static void build(Workspace ws, BuildConfig config, Path checkout, Pin pin)
|
||||
throws IOException, InterruptedException {
|
||||
Path source = checkout.equals(pinnedSource(ws)) ? checkout : snapshot(ws, checkout);
|
||||
Path resources = prepare(ws, config, source);
|
||||
incariPack(ws, resources);
|
||||
Path tool = mixins(ws, pin);
|
||||
Path stage = stage(ws);
|
||||
// web/package.py writes its builds inside the source it runs in, and horizon-mixins refuses
|
||||
// to restage over them (a symlink among them). They were copied out after the last build.
|
||||
for (String built : List.of("web/dist", "web/out")) {
|
||||
FileTrees.deleteRecursively(stage.resolve(built));
|
||||
}
|
||||
Log.step("Applying rust/mods to Horizon (horizon-mixins)");
|
||||
// horizon-mixins rewrites the stage in place, keeping unchanged files' times, so Cargo
|
||||
// recompiles only what the mods touch.
|
||||
ProcessRunner.run(
|
||||
List.of(
|
||||
tool.toString(),
|
||||
"apply",
|
||||
"--workspace",
|
||||
source.toString(),
|
||||
"--mods",
|
||||
mods(ws).toString(),
|
||||
"--out",
|
||||
stage.toString()),
|
||||
ws.repoRoot(),
|
||||
false);
|
||||
Log.step("Compiling Horizon for the browser (long the first time)");
|
||||
Path packaged = ws.workDir().resolve("horizon-out");
|
||||
ProcessRunner.Result result = ProcessRunner.start(
|
||||
List.of("python3", "web/package.py", "--out", packaged.toString()),
|
||||
stage,
|
||||
Map.of(
|
||||
"HORIZON_RESOURCES", resources.toString(),
|
||||
// Outside the stage, which horizon-mixins owns.
|
||||
"CARGO_TARGET_DIR",
|
||||
ws.workDir().resolve("horizon-target/web").toString()),
|
||||
true,
|
||||
null);
|
||||
if (result.exitCode() != 0) {
|
||||
throw new CliException("Horizon's web build failed (exit " + result.exitCode() + "); its output is above");
|
||||
}
|
||||
Path out = output(ws);
|
||||
FileTrees.deleteRecursively(out);
|
||||
FileTrees.copyTree(packaged.resolve("horizon-web"), out, "");
|
||||
brandPage(ws, out);
|
||||
Log.step("Rust build in " + ws.repoRoot().relativize(out));
|
||||
}
|
||||
|
||||
/** The tab's icon, served beside the page. */
|
||||
private static final String TAB_ICON = "icon.png";
|
||||
|
||||
/** Horizon's page is titled "Horizon" with no icon; the tab says "Incari Client" with Incari's icon, as the main page does. */
|
||||
static void brandPage(Workspace ws, Path out) throws IOException {
|
||||
Files.copy(
|
||||
ws.repoRoot().resolve(PACK).resolve("assets/incari/textures/gui/icon_256.png"),
|
||||
out.resolve(TAB_ICON),
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
Path page = out.resolve("index.html");
|
||||
String html = Files.readString(page);
|
||||
String branded = html.replace(
|
||||
"<title>Horizon</title>",
|
||||
"<title>Incari Client</title>\n<link rel=\"icon\" type=\"image/png\" href=\"" + TAB_ICON + "\">");
|
||||
if (branded.equals(html)) {
|
||||
throw new CliException(page + " has no <title>Horizon</title> to rename; Horizon's page changed");
|
||||
}
|
||||
Files.writeString(page, branded);
|
||||
}
|
||||
|
||||
/**
|
||||
* Horizon's resources, from the jars and assets {@code ./incari setup} and {@code assets} fetched:
|
||||
* {@code work/horizon-resources/<version>}. Skipped when {@code horizon-prepare --check} says
|
||||
* they're complete for this preparer.
|
||||
*/
|
||||
static Path prepare(Workspace ws, BuildConfig config, Path source) throws IOException, InterruptedException {
|
||||
String version = config.minecraftVersion();
|
||||
Path out = ws.workDir().resolve("horizon-resources").resolve(version);
|
||||
Map<String, String> env = Map.of(
|
||||
"CARGO_TARGET_DIR", ws.workDir().resolve("horizon-target/tools").toString());
|
||||
List<String> prepare = List.of("cargo", "run", "--quiet", "--release", "-p", "horizon-prepare", "--");
|
||||
List<String> check = new ArrayList<>(prepare);
|
||||
check.addAll(List.of("--check", "--root", source.toString(), "--output", out.toString()));
|
||||
if (ProcessRunner.start(check, source, env, false, null).exitCode() == 0) {
|
||||
return out;
|
||||
}
|
||||
GameFiles game = GameFiles.load(ws, config);
|
||||
Log.step("Checking the game's sounds (./incari assets)");
|
||||
Assets.fetch(ws, config, new Downloader());
|
||||
Path serverJar = serverJar(ws, config);
|
||||
Log.step("Preparing Horizon's resources from Minecraft " + version + " (several minutes, once)");
|
||||
List<String> run = new ArrayList<>(prepare);
|
||||
run.addAll(List.of(
|
||||
"--prepare",
|
||||
"--complete",
|
||||
"--root",
|
||||
source.toString(),
|
||||
"--output",
|
||||
out.toString(),
|
||||
"--version-json",
|
||||
ws.versionJson(version).toString(),
|
||||
"--client-jar",
|
||||
game.clientJar().toString(),
|
||||
"--libraries-dir",
|
||||
ws.librariesDir().toString(),
|
||||
"--assets-dir",
|
||||
ws.assetsDir().toString(),
|
||||
"--server-jar",
|
||||
serverJar.toString(),
|
||||
"--java-home",
|
||||
System.getProperty("java.home")));
|
||||
ProcessRunner.Result result = ProcessRunner.start(run, source, env, true, null);
|
||||
if (result.exitCode() != 0) {
|
||||
throw new CliException("horizon-prepare failed (exit " + result.exitCode() + "); its output is above");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Incari's pack, as the Java client serves it: listed in {@code files.txt}, by path in the pack. */
|
||||
private static final String PACK = "client/src/main/resources/incari-pack";
|
||||
|
||||
/** The pack's files {@code rust/mods/incari} compiles in (ADR 0069), into its git-ignored {@code data/}. */
|
||||
private static final List<String> BUNDLE_DATA = List.of(
|
||||
"assets/incari/textures/gui/icon_256.png",
|
||||
"assets/incari/textures/gui/title_backdrop.png",
|
||||
"assets/incari/font/michroma.ttf");
|
||||
|
||||
/**
|
||||
* Incari's pack over Horizon's prepared resources, as the Java client always has it on: its
|
||||
* fonts, the game's default font made Incari's (ADR 0069). Also the files the client's bundle
|
||||
* compiles in. One copy of each in the repo: copied at each build.
|
||||
*/
|
||||
static void incariPack(Workspace ws, Path resources) throws IOException {
|
||||
Path pack = ws.repoRoot().resolve(PACK);
|
||||
for (String line : Files.readAllLines(pack.resolve("files.txt"))) {
|
||||
String entry = line.strip();
|
||||
if (entry.isEmpty() || entry.startsWith("#")) {
|
||||
continue;
|
||||
}
|
||||
int eq = entry.indexOf('=');
|
||||
String served = (eq < 0 ? entry : entry.substring(0, eq)).strip();
|
||||
String file = (eq < 0 ? entry : entry.substring(eq + 1)).strip();
|
||||
Path to = resources.resolve(served);
|
||||
Files.createDirectories(to.getParent());
|
||||
Files.copy(pack.resolve(file), to, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
Path data = mods(ws).resolve("incari").resolve("data");
|
||||
Files.createDirectories(data);
|
||||
for (String file : BUNDLE_DATA) {
|
||||
Path from = pack.resolve(file);
|
||||
Files.copy(from, data.resolve(from.getFileName()), StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
// The version, repository and featured servers the client shows.
|
||||
Files.copy(
|
||||
ws.repoRoot().resolve(BuildConfig.FILE_NAME),
|
||||
data.resolve(BuildConfig.FILE_NAME),
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
/** The server jar, which Horizon's resources are exported from too, checked against its SHA-1. */
|
||||
private static Path serverJar(Workspace ws, BuildConfig config) throws IOException, InterruptedException {
|
||||
Path versionJson = ws.versionJson(config.minecraftVersion());
|
||||
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 = ws.versionDir(config.minecraftVersion()).resolve("server.jar");
|
||||
new Downloader()
|
||||
.fetch(
|
||||
URI.create(server.get("url").getAsString()),
|
||||
server.get("sha1").getAsString(),
|
||||
jar);
|
||||
return jar;
|
||||
}
|
||||
|
||||
/** horizon-mixins at the pinned commit, built once into {@code work/cache/horizon-mixins/<commit>}. */
|
||||
private static Path mixins(Workspace ws, Pin pin) throws IOException, InterruptedException {
|
||||
Path root = ws.cacheDir().resolve("horizon-mixins").resolve(pin.mixinsRevision());
|
||||
boolean windows = System.getProperty("os.name").startsWith("Windows");
|
||||
Path tool = root.resolve("bin").resolve(windows ? "horizon-mixins.exe" : "horizon-mixins");
|
||||
if (Files.isRegularFile(tool)) {
|
||||
return tool;
|
||||
}
|
||||
Log.step("Building horizon-mixins " + pin.mixinsRevision().substring(0, 12) + " (once)");
|
||||
ProcessRunner.run(
|
||||
List.of(
|
||||
"cargo",
|
||||
"install",
|
||||
"--quiet",
|
||||
"--locked",
|
||||
"--git",
|
||||
pin.mixinsRepository(),
|
||||
"--rev",
|
||||
pin.mixinsRevision(),
|
||||
"--root",
|
||||
root.toString(),
|
||||
"horizon-mixins-cli"),
|
||||
ws.repoRoot(),
|
||||
true);
|
||||
return tool;
|
||||
}
|
||||
|
||||
/**
|
||||
* The files of a checkout {@code INCARI_HORIZON_DIR} names, as git sees them (tracked, and new
|
||||
* ones it doesn't ignore), copied into {@code work/horizon-override}: horizon-mixins reads every
|
||||
* file of its workspace, and a checkout's own web build leaves a symlink in its ignored
|
||||
* {@code web/dist} that it refuses. Unchanged files keep their times, so the stage stays
|
||||
* incremental.
|
||||
*/
|
||||
static Path snapshot(Workspace ws, Path checkout) throws IOException, InterruptedException {
|
||||
Path copy = ws.workDir().resolve("horizon-override");
|
||||
Log.step("Copying " + checkout + " into work/horizon-override");
|
||||
Set<Path> kept = new HashSet<>();
|
||||
String names = git(checkout, "ls-files", "-z", "--cached", "--others", "--exclude-standard")
|
||||
.stdout();
|
||||
for (String name : names.split("\0", -1)) {
|
||||
Path from = checkout.resolve(name);
|
||||
// A tracked file deleted in the checkout, or a link: neither is staged.
|
||||
if (name.isEmpty() || !Files.isRegularFile(from, LinkOption.NOFOLLOW_LINKS)) {
|
||||
continue;
|
||||
}
|
||||
Path to = copy.resolve(name);
|
||||
kept.add(to);
|
||||
if (Files.isRegularFile(to, LinkOption.NOFOLLOW_LINKS)
|
||||
&& Files.size(to) == Files.size(from)
|
||||
&& Files.getLastModifiedTime(to).equals(Files.getLastModifiedTime(from))) {
|
||||
continue;
|
||||
}
|
||||
Files.createDirectories(to.getParent());
|
||||
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
|
||||
}
|
||||
List<Path> stale;
|
||||
try (Stream<Path> files = Files.walk(copy)) {
|
||||
stale = files.filter(f -> !Files.isDirectory(f, LinkOption.NOFOLLOW_LINKS) && !kept.contains(f))
|
||||
.toList();
|
||||
}
|
||||
for (Path file : stale) {
|
||||
Files.delete(file);
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static String head(Path dir) throws IOException, InterruptedException {
|
||||
ProcessRunner.Result result = ProcessRunner.start(
|
||||
List.of("git", "rev-parse", "--verify", "--quiet", "HEAD"), dir, Map.of(), false, null);
|
||||
return result.exitCode() == 0 ? result.stdout().strip() : "";
|
||||
}
|
||||
|
||||
private static ProcessRunner.Result git(Path dir, String... args) throws IOException, InterruptedException {
|
||||
List<String> command = new ArrayList<>(List.of("git"));
|
||||
command.addAll(Arrays.asList(args));
|
||||
return ProcessRunner.run(command, dir, false);
|
||||
}
|
||||
|
||||
private static boolean runs(String... command) {
|
||||
try {
|
||||
return ProcessRunner.start(List.of(command), Path.of("."), Map.of(), false, null)
|
||||
.exitCode()
|
||||
== 0;
|
||||
} catch (IOException e) {
|
||||
return false;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static String match(String text, String regex) {
|
||||
Matcher m = Pattern.compile(regex).matcher(text);
|
||||
if (!m.find()) {
|
||||
throw new CliException("Horizon's source changed: no match for " + regex);
|
||||
}
|
||||
return m.group(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package incari.tools.build;
|
||||
|
||||
/** Console output for the CLI. Kept deliberately plain so CI logs stay readable. */
|
||||
public final class Log {
|
||||
|
||||
private Log() {}
|
||||
|
||||
/** A top-level step the user is waiting on. */
|
||||
public static void step(String message) {
|
||||
System.out.println("==> " + message);
|
||||
}
|
||||
|
||||
public static void info(String message) {
|
||||
System.out.println(" " + message);
|
||||
}
|
||||
|
||||
public static void warn(String message) {
|
||||
System.err.println("warning: " + message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The {@code incari} build CLI. Run it through {@code ./incari} at the repo root.
|
||||
*
|
||||
* <p>Pipeline: {@code fetch} (Mojang jar + libraries) → {@code decompile} (Vineflower) →
|
||||
* {@code apply} (vendor commit, class manifest, patches into {@code work/client}).
|
||||
* {@code setup} runs all three. {@code rebuild} goes the other way, from commits in
|
||||
* {@code work/client} back to {@code patches/}. {@code build} compiles the browser build into a
|
||||
* folder for a web server ({@link WebBuild}).
|
||||
*/
|
||||
public final class Main {
|
||||
|
||||
private static final String USAGE = """
|
||||
Usage: ./incari <command> [options]
|
||||
|
||||
Commands:
|
||||
setup fetch + decompile + apply: a fresh clone to a patched tree
|
||||
fetch download the pinned Minecraft client jar and its libraries
|
||||
assets download the game's assets (sounds, languages; ~480 MB), for the
|
||||
desktop runtime only
|
||||
decompile decompile the client jar with Vineflower into work/decompiled
|
||||
apply [--force] rebuild work/client from the decompiled sources and patches/
|
||||
(--force discards unsaved commits and edits in work/client)
|
||||
rebuild [--check] regenerate patches/ from the commits in work/client
|
||||
(--check writes nothing, fails if patches/ is out of date
|
||||
or a replaced class's original changed, see classes)
|
||||
classes [--stamp] list the classes patches/classes.txt replaces whose Mojang
|
||||
original changed since the replacement was checked against it
|
||||
(--stamp records the current originals once they're reviewed)
|
||||
build [--out <dir>] [--only fast|compatible|rust] [--no-sounds] [--html]
|
||||
compile the release browser builds, Fast, Compatible and the
|
||||
experimental Rust (or just one with --only), into one folder for
|
||||
a static web server (default dist/web), or with --html into one
|
||||
HTML file that plays from the disk, without music or Rust
|
||||
(smaller sounds need ffmpeg) (default dist/incari.html).
|
||||
Rust is skipped, saying why, without its tools or work/horizon;
|
||||
INCARI_HORIZON_DIR builds another Horizon checkout.
|
||||
It holds Minecraft's code and files: for your own use, never
|
||||
shared or published
|
||||
survey TeaVM compile survey, see tools/survey/README.md
|
||||
copycheck fail if Incari code repeats decompiled game code, see tools/copycheck
|
||||
help show this message
|
||||
""";
|
||||
|
||||
private Main() {}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
System.exit(run(List.of(args)));
|
||||
} catch (CliException e) {
|
||||
System.err.println("error: " + e.getMessage());
|
||||
System.exit(1);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
static int run(List<String> args) throws Exception {
|
||||
if (args.isEmpty() || args.getFirst().equals("help") || args.contains("--help") || args.contains("-h")) {
|
||||
System.out.print(USAGE);
|
||||
return args.isEmpty() ? 1 : 0;
|
||||
}
|
||||
String command = args.getFirst();
|
||||
List<String> flags = new ArrayList<>(args.subList(1, args.size()));
|
||||
|
||||
Workspace ws = Workspace.discover(Path.of(System.getProperty("incari.cwd", ".")));
|
||||
BuildConfig config = BuildConfig.load(ws.repoRoot());
|
||||
|
||||
switch (command) {
|
||||
case "setup" -> {
|
||||
noFlags(command, flags);
|
||||
GameFiles game = GameFiles.fetch(ws, config, new Downloader());
|
||||
Decompiler.decompile(ws, game);
|
||||
new ClientTree(ws).apply(ws.decompiledDir(config.minecraftVersion()), config.minecraftVersion(), false);
|
||||
GitHooks.install(ws);
|
||||
// The Rust build's source (ADR 0068). Optional: Fast and Compatible build without it.
|
||||
try {
|
||||
Horizon.fetch(ws, Horizon.Pin.load(ws.repoRoot()));
|
||||
} catch (CliException e) {
|
||||
Log.warn("Horizon not fetched, so ./incari build will skip the Rust build: " + e.getMessage());
|
||||
}
|
||||
Log.step("Done. The patched tree is in work/client");
|
||||
}
|
||||
case "fetch" -> {
|
||||
noFlags(command, flags);
|
||||
GameFiles.fetch(ws, config, new Downloader());
|
||||
}
|
||||
case "assets" -> {
|
||||
noFlags(command, flags);
|
||||
String index = Assets.fetch(ws, config, new Downloader());
|
||||
Log.step("Done. Asset index " + index + " is in work/cache/assets");
|
||||
}
|
||||
case "decompile" -> {
|
||||
noFlags(command, flags);
|
||||
Decompiler.decompile(ws, GameFiles.load(ws, config));
|
||||
}
|
||||
case "apply" -> {
|
||||
boolean force = flags.remove("--force");
|
||||
noFlags(command, flags);
|
||||
Path decompiled = ws.decompiledDir(config.minecraftVersion());
|
||||
if (!decompiled.resolve(".incari-decompile-stamp").toFile().isFile()) {
|
||||
throw new CliException("No decompiled sources yet. Run: ./incari setup");
|
||||
}
|
||||
new ClientTree(ws).apply(decompiled, config.minecraftVersion(), force);
|
||||
Log.step("Done. The patched tree is in work/client");
|
||||
}
|
||||
case "rebuild" -> {
|
||||
boolean check = flags.remove("--check");
|
||||
noFlags(command, flags);
|
||||
ClientTree.RebuildResult result = new ClientTree(ws).rebuildPatches(check);
|
||||
Log.step((check ? "Checked" : "Rebuilt") + " patches: " + result.written() + " changed, "
|
||||
+ result.unchanged() + " unchanged, " + result.removed() + " removed");
|
||||
if (check && result.changed()) {
|
||||
throw new CliException(
|
||||
"patches/ doesn't match work/client. Run ./incari rebuild and commit the result.");
|
||||
}
|
||||
if (check) {
|
||||
ClientTree tree = new ClientTree(ws);
|
||||
List<ClientTree.Drift> drift = tree.replacementDrift(config.minecraftVersion());
|
||||
if (!drift.isEmpty()) {
|
||||
tree.reportDrift(drift, config.minecraftVersion());
|
||||
throw new CliException(drift.size() + " replaced class(es) in patches/classes.txt"
|
||||
+ " aren't stamped against this vendor tree. Review them, then run"
|
||||
+ " ./incari classes --stamp and commit classes.txt.");
|
||||
}
|
||||
}
|
||||
}
|
||||
case "classes" -> {
|
||||
boolean stamp = flags.remove("--stamp");
|
||||
noFlags(command, flags);
|
||||
ClientTree tree = new ClientTree(ws);
|
||||
if (stamp) {
|
||||
int count = tree.stampReplacements(config.minecraftVersion());
|
||||
Log.step("Stamped " + count + " replaced classes against Minecraft " + config.minecraftVersion());
|
||||
} else {
|
||||
List<ClientTree.Drift> drift = tree.replacementDrift(config.minecraftVersion());
|
||||
tree.reportDrift(drift, config.minecraftVersion());
|
||||
Log.step(
|
||||
drift.isEmpty()
|
||||
? "Every replaced class matches its stamp"
|
||||
: drift.size() + " replaced class(es) to review");
|
||||
return drift.isEmpty() ? 0 : 1;
|
||||
}
|
||||
}
|
||||
case "build" -> {
|
||||
boolean sounds = !flags.remove("--no-sounds");
|
||||
boolean html = flags.remove("--html");
|
||||
// The single file holds TeaVM's builds only; Rust is its own page (ADR 0068).
|
||||
List<String> builds = html ? List.of("fast", "compatible") : List.of("fast", "compatible", "rust");
|
||||
boolean only = false;
|
||||
int onlyFlag = flags.indexOf("--only");
|
||||
if (onlyFlag >= 0) {
|
||||
if (onlyFlag + 1 >= flags.size() || !builds.contains(flags.get(onlyFlag + 1))) {
|
||||
throw new CliException(
|
||||
html
|
||||
? "--only takes fast or compatible with --html"
|
||||
: "--only takes fast, compatible or rust");
|
||||
}
|
||||
builds = List.of(flags.get(onlyFlag + 1));
|
||||
only = true;
|
||||
flags.subList(onlyFlag, onlyFlag + 2).clear();
|
||||
}
|
||||
Path out = ws.repoRoot().resolve("dist").resolve(html ? "incari.html" : "web");
|
||||
int outFlag = flags.indexOf("--out");
|
||||
if (outFlag >= 0) {
|
||||
if (outFlag + 1 >= flags.size()) {
|
||||
throw new CliException(html ? "--out needs a file name" : "--out needs a folder");
|
||||
}
|
||||
out = Path.of(System.getProperty("incari.cwd", ".")).resolve(flags.get(outFlag + 1));
|
||||
flags.subList(outFlag, outFlag + 2).clear();
|
||||
}
|
||||
noFlags(command, flags);
|
||||
WebBuild.build(ws, config, out, builds, only, sounds, html);
|
||||
}
|
||||
case "survey", "copycheck" ->
|
||||
throw new CliException(
|
||||
"'" + command + "' runs in its own JVM; use ./incari " + command + " (the launcher script)");
|
||||
default -> {
|
||||
System.err.print(USAGE);
|
||||
throw new CliException("Unknown command '" + command + "'");
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static void noFlags(String command, List<String> flags) {
|
||||
if (!flags.isEmpty()) {
|
||||
throw new CliException("Unknown option(s) for " + command + ": " + String.join(" ", flags));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import java.net.URI;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The few fields Incari reads from Mojang's launcher metadata: the version manifest
|
||||
* (every version and where its JSON lives) and a version JSON (client jar and libraries).
|
||||
*
|
||||
* <p>Parsed by hand from a JSON tree rather than bound to classes, because the launcher
|
||||
* format has many fields we don't use and Mojang adds more over time.
|
||||
*/
|
||||
public final class MojangMetadata {
|
||||
|
||||
public static final URI VERSION_MANIFEST =
|
||||
URI.create("https://piston-meta.mojang.com/mc/game/version_manifest_v2.json");
|
||||
|
||||
private MojangMetadata() {}
|
||||
|
||||
/** A download Mojang describes by URL and SHA-1. */
|
||||
public record Download(URI url, String sha1, long size) {}
|
||||
|
||||
/** One library. {@code path} is the Maven-layout path, used as its cache location. */
|
||||
public record Library(String name, String path, Download download, boolean platformSpecific) {
|
||||
|
||||
/** The Maven classifier ({@code natives-linux}), or empty for a platform-neutral jar. */
|
||||
public String classifier() {
|
||||
String[] parts = name.split(":", -1);
|
||||
return parts.length > 3 ? parts[3] : "";
|
||||
}
|
||||
}
|
||||
|
||||
/** The game's asset index: which sounds, languages and other assets this version uses. */
|
||||
public record AssetIndex(String id, Download download) {}
|
||||
|
||||
/** {@code assetIndex} is null only in test fixtures; every real version JSON has one. */
|
||||
public record Version(
|
||||
String id,
|
||||
Download client,
|
||||
int javaMajorVersion,
|
||||
List<Library> libraries,
|
||||
@Nullable AssetIndex assetIndex) {}
|
||||
|
||||
/** Finds a version's JSON download in the manifest. */
|
||||
public static Download findVersion(String manifestJson, String versionId) {
|
||||
JsonObject manifest = JsonParser.parseString(manifestJson).getAsJsonObject();
|
||||
for (JsonElement element : manifest.getAsJsonArray("versions")) {
|
||||
JsonObject version = element.getAsJsonObject();
|
||||
if (version.get("id").getAsString().equals(versionId)) {
|
||||
return new Download(
|
||||
URI.create(version.get("url").getAsString()),
|
||||
version.get("sha1").getAsString(),
|
||||
-1);
|
||||
}
|
||||
}
|
||||
throw new CliException("Version " + versionId + " is not in Mojang's version manifest");
|
||||
}
|
||||
|
||||
public static Version parseVersion(String versionJson) {
|
||||
JsonObject root = JsonParser.parseString(versionJson).getAsJsonObject();
|
||||
Download client = download(root.getAsJsonObject("downloads").getAsJsonObject("client"));
|
||||
int java = root.getAsJsonObject("javaVersion").get("majorVersion").getAsInt();
|
||||
|
||||
List<Library> libraries = new ArrayList<>();
|
||||
JsonArray libs = root.getAsJsonArray("libraries");
|
||||
for (JsonElement element : libs) {
|
||||
JsonObject lib = element.getAsJsonObject();
|
||||
JsonObject downloads = lib.getAsJsonObject("downloads");
|
||||
if (downloads == null || !downloads.has("artifact")) {
|
||||
continue;
|
||||
}
|
||||
JsonObject artifact = downloads.getAsJsonObject("artifact");
|
||||
String name = lib.get("name").getAsString();
|
||||
// Natives carry a classifier ("group:artifact:version:natives-linux") and are only
|
||||
// useful to the desktop JVM, never to the browser build or the decompiler.
|
||||
boolean platformSpecific = name.split(":").length > 3;
|
||||
libraries.add(new Library(name, artifact.get("path").getAsString(), download(artifact), platformSpecific));
|
||||
}
|
||||
JsonObject assets = root.getAsJsonObject("assetIndex");
|
||||
AssetIndex assetIndex =
|
||||
assets == null ? null : new AssetIndex(assets.get("id").getAsString(), download(assets));
|
||||
return new Version(root.get("id").getAsString(), client, java, List.copyOf(libraries), assetIndex);
|
||||
}
|
||||
|
||||
private static Download download(JsonObject object) {
|
||||
return new Download(
|
||||
URI.create(object.get("url").getAsString()),
|
||||
object.get("sha1").getAsString(),
|
||||
object.get("size").getAsLong());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* The operating system and CPU the desktop runtime runs on, named the way Mojang's version JSON
|
||||
* classifies native jars ({@code natives-linux}, {@code natives-windows-arm64}, ...).
|
||||
*/
|
||||
public record NativePlatform(String os, boolean arm64) {
|
||||
|
||||
public static NativePlatform current() {
|
||||
return of(System.getProperty("os.name", ""), System.getProperty("os.arch", ""));
|
||||
}
|
||||
|
||||
static NativePlatform of(String osName, String osArch) {
|
||||
String name = osName.toLowerCase(Locale.ROOT);
|
||||
String os;
|
||||
if (name.startsWith("windows")) {
|
||||
os = "windows";
|
||||
} else if (name.startsWith("mac") || name.startsWith("darwin")) {
|
||||
os = "macos";
|
||||
} else if (name.startsWith("linux")) {
|
||||
os = "linux";
|
||||
} else {
|
||||
throw new CliException("Minecraft ships no native libraries for " + osName);
|
||||
}
|
||||
String arch = osArch.toLowerCase(Locale.ROOT);
|
||||
return new NativePlatform(os, arch.equals("aarch64") || arch.equals("arm64"));
|
||||
}
|
||||
|
||||
public String classifier() {
|
||||
return "natives-" + os + (arm64 ? "-arm64" : "");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package incari.tools.build;
|
||||
|
||||
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.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* The patch files under {@code patches/}, laid out as {@code <subsystem>/<NNNN>-<slug>.patch}.
|
||||
*
|
||||
* <p>The number is the patch's position in one global order (patches build on each other
|
||||
* across subsystems); the directory groups them for reading and review. A patch's commit
|
||||
* subject is {@code "<subsystem>: <summary>"}, which is how {@code rebuild} knows where
|
||||
* each regenerated file belongs.
|
||||
*/
|
||||
public final class PatchSet {
|
||||
|
||||
/** {@code "render: Route section compile to the mesher"} */
|
||||
static final Pattern SUBJECT = Pattern.compile("([a-z0-9][a-z0-9-]*): (\\S.*)");
|
||||
|
||||
private static final Pattern FILE_NAME = Pattern.compile("(\\d{4})-[a-z0-9-]+\\.patch");
|
||||
private static final int MAX_SLUG = 60;
|
||||
|
||||
private PatchSet() {}
|
||||
|
||||
public record PatchFile(int number, String subsystem, Path path) {}
|
||||
|
||||
/** Every patch file in application order. Rejects stray names and duplicate numbers. */
|
||||
public static List<PatchFile> list(Path patchesDir) throws IOException {
|
||||
if (!Files.isDirectory(patchesDir)) {
|
||||
return List.of();
|
||||
}
|
||||
List<PatchFile> patches = new ArrayList<>();
|
||||
try (Stream<Path> files = Files.walk(patchesDir)) {
|
||||
for (Path file : files.filter(p -> p.toString().endsWith(".patch")).toList()) {
|
||||
Path relative = patchesDir.relativize(file);
|
||||
Matcher name = FILE_NAME.matcher(file.getFileName().toString());
|
||||
if (relative.getNameCount() != 2 || !name.matches()) {
|
||||
throw new CliException("Unexpected patch file " + relative
|
||||
+ " (expected <subsystem>/<NNNN>-<slug>.patch; run ./incari rebuild to regenerate names)");
|
||||
}
|
||||
patches.add(new PatchFile(
|
||||
Integer.parseInt(name.group(1)), relative.getName(0).toString(), file));
|
||||
}
|
||||
}
|
||||
patches.sort(Comparator.comparingInt(PatchFile::number));
|
||||
Map<Integer, Path> byNumber = new HashMap<>();
|
||||
for (PatchFile patch : patches) {
|
||||
Path clash = byNumber.put(patch.number(), patch.path());
|
||||
if (clash != null) {
|
||||
throw new CliException(
|
||||
"Two patches share number " + patch.number() + ": " + clash + " and " + patch.path());
|
||||
}
|
||||
}
|
||||
return List.copyOf(patches);
|
||||
}
|
||||
|
||||
/** The repo-relative file a commit with this subject is written to, at position {@code number}. */
|
||||
static String fileFor(int number, String subject) {
|
||||
Matcher matcher = SUBJECT.matcher(subject);
|
||||
if (!matcher.matches()) {
|
||||
throw new CliException("Commit subject \"" + subject + "\" must look like \"<subsystem>: <summary>\""
|
||||
+ " (lowercase subsystem, e.g. \"render: Route section compile to the mesher\")");
|
||||
}
|
||||
return matcher.group(1) + "/" + String.format(Locale.ROOT, "%04d", number) + "-" + slug(matcher.group(2))
|
||||
+ ".patch";
|
||||
}
|
||||
|
||||
static String slug(String summary) {
|
||||
String slug =
|
||||
summary.toLowerCase(Locale.ROOT).replaceAll("[^a-z0-9]+", "-").replaceAll("^-|-$", "");
|
||||
if (slug.length() > MAX_SLUG) {
|
||||
slug = slug.substring(0, MAX_SLUG).replaceAll("-[^-]*$", "");
|
||||
}
|
||||
return slug.isEmpty() ? "patch" : slug;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package incari.tools.build;
|
||||
|
||||
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.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/** Runs child processes (git, the decompiler JVM) and turns failures into {@link CliException}s. */
|
||||
public final class ProcessRunner {
|
||||
|
||||
/** Variables with which git tells a hook which repository it runs in. */
|
||||
private static final List<String> OUTER_GIT_ENVIRONMENT = List.of(
|
||||
"GIT_DIR",
|
||||
"GIT_WORK_TREE",
|
||||
"GIT_INDEX_FILE",
|
||||
"GIT_COMMON_DIR",
|
||||
"GIT_OBJECT_DIRECTORY",
|
||||
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
||||
"GIT_PREFIX");
|
||||
|
||||
private ProcessRunner() {}
|
||||
|
||||
public record Result(int exitCode, String stdout, String stderr) {}
|
||||
|
||||
/**
|
||||
* Runs {@code command} in {@code dir}. With {@code inheritOutput}, the child writes straight
|
||||
* to the console (long-running steps the user watches); otherwise output is captured.
|
||||
* Throws on a non-zero exit.
|
||||
*/
|
||||
public static Result run(List<String> command, Path dir, boolean inheritOutput)
|
||||
throws IOException, InterruptedException {
|
||||
Result result = start(command, dir, Map.of(), inheritOutput, null);
|
||||
if (result.exitCode() != 0) {
|
||||
throw new CliException("Command failed (exit " + result.exitCode() + "): " + String.join(" ", command)
|
||||
+ (result.stderr().isBlank() ? "" : "\n" + result.stderr().strip()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Runs {@code command} and returns its result whatever the exit code. */
|
||||
public static Result start(
|
||||
List<String> command, Path dir, Map<String, String> env, boolean inheritOutput, @Nullable String stdin)
|
||||
throws IOException, InterruptedException {
|
||||
ProcessBuilder builder = new ProcessBuilder(command).directory(dir.toFile());
|
||||
// Run from a git hook (the pre-commit hook's `rebuild --check`), the CLI inherits the outer
|
||||
// repo's GIT_DIR and GIT_INDEX_FILE, which would point git in work/client at the wrong
|
||||
// repository. Every command here names its own directory.
|
||||
builder.environment().keySet().removeAll(OUTER_GIT_ENVIRONMENT);
|
||||
builder.environment().putAll(env);
|
||||
if (inheritOutput) {
|
||||
builder.redirectOutput(ProcessBuilder.Redirect.INHERIT).redirectError(ProcessBuilder.Redirect.INHERIT);
|
||||
}
|
||||
if (stdin == null) {
|
||||
builder.redirectInput(ProcessBuilder.Redirect.from(nullDevice()));
|
||||
}
|
||||
Process process = builder.start();
|
||||
if (stdin != null) {
|
||||
try (var in = process.getOutputStream()) {
|
||||
in.write(stdin.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
if (inheritOutput) {
|
||||
return new Result(process.waitFor(), "", "");
|
||||
}
|
||||
// Drain stderr on its own thread: a child that fills one pipe while we block reading
|
||||
// the other would deadlock.
|
||||
ByteArrayOutputStream err = new ByteArrayOutputStream();
|
||||
Thread errReader = Thread.ofVirtual().start(() -> copy(process.getErrorStream(), err));
|
||||
String out = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
int exit = process.waitFor();
|
||||
errReader.join();
|
||||
return new Result(exit, out, err.toString(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
/** The {@code java} binary running this CLI, so child JVMs use the same JDK. */
|
||||
public static String javaExecutable() {
|
||||
return ProcessHandle.current()
|
||||
.info()
|
||||
.command()
|
||||
.orElse(Path.of(System.getProperty("java.home"), "bin", "java").toString());
|
||||
}
|
||||
|
||||
private static java.io.File nullDevice() {
|
||||
return new java.io.File(System.getProperty("os.name").startsWith("Windows") ? "NUL" : "/dev/null");
|
||||
}
|
||||
|
||||
private static void copy(InputStream in, ByteArrayOutputStream out) {
|
||||
try (in) {
|
||||
in.transferTo(out);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package incari.tools.build;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* {@code ./incari build} (ADR 0028): from a set-up checkout to one folder a static web server
|
||||
* can serve. Compiles the game's two release builds with Gradle (ADR 0036), Compatible
|
||||
* ({@code :app-web:teavm -Pteavm.release}) and Fast (the same with {@code -Pteavm.fast}), or the one
|
||||
* {@code --only} names, then {@code :app-web:webFolder} copies them, the page, the client jar and the
|
||||
* sounds into the folder. With both, the page lets the player pick, Fast recommended. The
|
||||
* experimental Rust build ({@link Horizon}, ADR 0068) goes in its {@code rust/} folder when this
|
||||
* machine can build it; otherwise it's skipped, saying why.
|
||||
*
|
||||
* <p>With {@code --html} it packs that folder, with every sound but the music encoded smaller (about
|
||||
* 38 MB of 377; ffmpeg, else only the common sounds), into one HTML file that plays from the disk ({@code :app-web:singleFile}, ADR 0057), writing the folder under
|
||||
* {@code app-web/build/} on the way.
|
||||
*
|
||||
* <p>The folder holds Mojang's code and files. It is for the person who built it: never committed,
|
||||
* never shared or published. Inside the checkout it must be git-ignored, so it can't be committed.
|
||||
*/
|
||||
final class WebBuild {
|
||||
|
||||
static final String NOTICE = """
|
||||
|
||||
------------------------------------------------------------------------------------
|
||||
DO NOT SHARE, UPLOAD OR PUBLISH THIS BUILD.
|
||||
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's for
|
||||
your own use; if you serve it, it's your server and your responsibility.
|
||||
See docs/self-hosting.md (and README.txt in the folder).
|
||||
------------------------------------------------------------------------------------
|
||||
""";
|
||||
|
||||
private WebBuild() {}
|
||||
|
||||
/**
|
||||
* @param only true when {@code --only} named the one build: a Rust build that can't be made
|
||||
* fails instead of being skipped
|
||||
* @param html true for one HTML file at {@code out} instead of a folder
|
||||
*/
|
||||
static void build(
|
||||
Workspace ws, BuildConfig config, Path out, List<String> builds, boolean only, boolean sounds, boolean html)
|
||||
throws IOException, InterruptedException {
|
||||
if (!Files.isDirectory(ws.clientTree())) {
|
||||
throw new CliException("No patched tree in work/client yet. Run: ./incari setup");
|
||||
}
|
||||
out = out.toAbsolutePath().normalize();
|
||||
requireIgnored(ws, out, !html);
|
||||
// The single file is packed from a folder of the build's own, with its sounds smaller.
|
||||
Path folder = html ? ws.repoRoot().resolve("app-web/build/web-single") : out;
|
||||
if (sounds) {
|
||||
Log.step("Checking the game's sounds (./incari assets)");
|
||||
Assets.fetch(ws, config, new Downloader());
|
||||
}
|
||||
builds = new ArrayList<>(builds);
|
||||
if (builds.contains("rust") && !rust(ws, config, only)) {
|
||||
builds.remove("rust");
|
||||
}
|
||||
if (builds.contains("compatible")) {
|
||||
Log.step("Compiling the Compatible build (release; about ten minutes when the code changed)");
|
||||
gradle(ws, List.of(":app-web:teavm", "-Pteavm.release"));
|
||||
}
|
||||
if (builds.contains("fast")) {
|
||||
Log.step("Compiling the Fast build (release; about ten minutes when the code changed)");
|
||||
gradle(ws, List.of(":app-web:teavm", "-Pteavm.release", "-Pteavm.fast"));
|
||||
}
|
||||
Log.step("Writing " + out);
|
||||
List<String> task = new ArrayList<>(List.of(
|
||||
":app-web:webFolder",
|
||||
"-Pteavm.release",
|
||||
"-Pweb.skipBuild",
|
||||
"-Pweb.builds=" + String.join(",", builds),
|
||||
"-Pweb.out=" + folder));
|
||||
if (!sounds) {
|
||||
task.add("-Pweb.noSounds");
|
||||
}
|
||||
if (html) {
|
||||
task.addAll(List.of(":app-web:singleFile", "-Pweb.smallSounds", "-Pweb.html=" + out));
|
||||
}
|
||||
gradle(ws, task);
|
||||
Log.step(
|
||||
html
|
||||
? "Done. Open " + out
|
||||
+ " in Chrome, Edge or Firefox; it plays without a server"
|
||||
+ (sounds ? " (no music)" : " (and without sounds)")
|
||||
: "Done. Serve " + out + " with any static web server; its README.txt says how");
|
||||
System.out.print(NOTICE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds Rust (ADR 0068) into {@code app-web/build/rust/}, or says why it can't and returns false.
|
||||
* With {@code only}, a reason is an error.
|
||||
*/
|
||||
private static boolean rust(Workspace ws, BuildConfig config, boolean only)
|
||||
throws IOException, InterruptedException {
|
||||
Horizon.Pin pin = Horizon.Pin.load(ws.repoRoot());
|
||||
Path override = Horizon.override();
|
||||
Path source = null;
|
||||
List<String> missing;
|
||||
try {
|
||||
source = override != null ? override : Horizon.fetch(ws, pin);
|
||||
missing = Horizon.missingTools(source);
|
||||
} catch (CliException e) {
|
||||
missing = List.of(e.getMessage());
|
||||
}
|
||||
if (!missing.isEmpty()) {
|
||||
String why = "The Rust build needs: " + String.join("; ", missing);
|
||||
if (only) {
|
||||
throw new CliException(why);
|
||||
}
|
||||
Log.warn(why + ". Skipping it; Fast and Compatible still build");
|
||||
return false;
|
||||
}
|
||||
if (source == null) {
|
||||
throw new IllegalStateException("A source with nothing missing");
|
||||
}
|
||||
Horizon.build(ws, config, source, pin);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses an output folder (or file) inside the checkout that git would track: the build must
|
||||
* never be committed. The default, {@code dist/}, is ignored.
|
||||
*/
|
||||
static void requireIgnored(Workspace ws, Path out, boolean folder) throws IOException, InterruptedException {
|
||||
if (!out.startsWith(ws.repoRoot())) {
|
||||
return;
|
||||
}
|
||||
if (out.equals(ws.repoRoot())) {
|
||||
throw new CliException(
|
||||
"The build can't go in the checkout's root. Use the default under dist/, or somewhere outside it");
|
||||
}
|
||||
ProcessRunner.Result ignored = ProcessRunner.start(
|
||||
List.of("git", "check-ignore", "-q", "--no-index", ws.repoRoot().relativize(out) + (folder ? "/" : "")),
|
||||
ws.repoRoot(),
|
||||
Map.of(),
|
||||
false,
|
||||
null);
|
||||
if (ignored.exitCode() != 0) {
|
||||
throw new CliException(out + " is inside the checkout and not git-ignored, so the build could be "
|
||||
+ "committed. Use the default under dist/, or somewhere outside the checkout");
|
||||
}
|
||||
}
|
||||
|
||||
private static void gradle(Workspace ws, List<String> arguments) throws IOException, InterruptedException {
|
||||
boolean windows = System.getProperty("os.name").startsWith("Windows");
|
||||
Path wrapper = ws.repoRoot().resolve(windows ? "gradlew.bat" : "gradlew");
|
||||
List<String> command = new ArrayList<>(List.of(wrapper.toString(), "--console=plain"));
|
||||
command.addAll(arguments);
|
||||
ProcessRunner.run(command, ws.repoRoot(), true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Where everything lives. Two roots: the repo (tracked, Incari-owned files only) and
|
||||
* {@code work/} inside it (git-ignored, everything derived from Mojang's jar).
|
||||
*
|
||||
* <p>Nothing outside {@code work/} may ever hold Mojang content. Every path that does is
|
||||
* defined here, so that rule can be checked in one place.
|
||||
*/
|
||||
public record Workspace(Path repoRoot) {
|
||||
|
||||
/** The client tree's Java sources, relative to {@link #clientTree()}. */
|
||||
public static final String CLIENT_SOURCE_DIR = "src/main/java";
|
||||
|
||||
public Workspace {
|
||||
repoRoot = repoRoot.toAbsolutePath().normalize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the repo root by walking up from {@code start} to the directory holding
|
||||
* {@code incari.properties}. Lets the CLI run from any subdirectory.
|
||||
*/
|
||||
public static Workspace discover(Path start) {
|
||||
for (Path dir = start.toAbsolutePath().normalize(); dir != null; dir = dir.getParent()) {
|
||||
if (Files.isRegularFile(dir.resolve(BuildConfig.FILE_NAME))) {
|
||||
return new Workspace(dir);
|
||||
}
|
||||
}
|
||||
throw new CliException("Not inside an Incari checkout (no " + BuildConfig.FILE_NAME + " found above "
|
||||
+ start.toAbsolutePath() + ")");
|
||||
}
|
||||
|
||||
// --- Tracked inputs ---
|
||||
|
||||
public Path patchesDir() {
|
||||
return repoRoot.resolve("patches");
|
||||
}
|
||||
|
||||
public Path classManifest() {
|
||||
return patchesDir().resolve(ClassManifest.FILE_NAME);
|
||||
}
|
||||
|
||||
// --- Generated, git-ignored ---
|
||||
|
||||
public Path workDir() {
|
||||
return repoRoot.resolve("work");
|
||||
}
|
||||
|
||||
public Path cacheDir() {
|
||||
return workDir().resolve("cache");
|
||||
}
|
||||
|
||||
public Path versionManifestFile() {
|
||||
return cacheDir().resolve("version_manifest_v2.json");
|
||||
}
|
||||
|
||||
public Path versionDir(String version) {
|
||||
return cacheDir().resolve("versions").resolve(version);
|
||||
}
|
||||
|
||||
public Path versionJson(String version) {
|
||||
return versionDir(version).resolve(version + ".json");
|
||||
}
|
||||
|
||||
public Path clientJar(String version) {
|
||||
return versionDir(version).resolve("client.jar");
|
||||
}
|
||||
|
||||
/**
|
||||
* Repo-relative paths of the platform-neutral library jars, one per line. Written by
|
||||
* {@code fetch} for Gradle, which compiles the client tree against them.
|
||||
*/
|
||||
public Path classpathList(String version) {
|
||||
return versionDir(version).resolve("classpath.txt");
|
||||
}
|
||||
|
||||
/** Like {@link #classpathList}, for this machine's native library jars (desktop runtime only). */
|
||||
public Path nativesList(String version) {
|
||||
return versionDir(version).resolve("natives.txt");
|
||||
}
|
||||
|
||||
/** The launcher's asset layout: {@code indexes/<id>.json} and {@code objects/<ab>/<hash>}. */
|
||||
public Path assetsDir() {
|
||||
return cacheDir().resolve("assets");
|
||||
}
|
||||
|
||||
public Path librariesDir() {
|
||||
return cacheDir().resolve("libraries");
|
||||
}
|
||||
|
||||
/** Pristine Vineflower output. Never edited; the client tree is copied from it. */
|
||||
public Path decompiledDir(String version) {
|
||||
return workDir().resolve("decompiled").resolve(version);
|
||||
}
|
||||
|
||||
/** The git repo people edit: vendor commit, then the class manifest, then one commit per patch. */
|
||||
public Path clientTree() {
|
||||
return workDir().resolve("client");
|
||||
}
|
||||
|
||||
public Path surveyDir(String version) {
|
||||
return workDir().resolve("survey").resolve(version);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* The apply/rebuild cycle on a tiny synthetic "vendor" tree, so the tests need neither
|
||||
* network nor Mojang's jar.
|
||||
*/
|
||||
class ClientTreeTest {
|
||||
|
||||
@TempDir
|
||||
Path root;
|
||||
|
||||
private Workspace ws;
|
||||
private Path decompiled;
|
||||
private ClientTree tree;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws IOException {
|
||||
Files.writeString(root.resolve(BuildConfig.FILE_NAME), "minecraft.version=test\n");
|
||||
ws = new Workspace(root);
|
||||
decompiled = ws.decompiledDir("test");
|
||||
writeVendor("com/example/Greeter.java", """
|
||||
package com.example;
|
||||
|
||||
public class Greeter {
|
||||
public String greet() {
|
||||
return "hello";
|
||||
}
|
||||
}
|
||||
""");
|
||||
writeVendor("com/example/Telemetry.java", "package com.example;\n\npublic class Telemetry {}\n");
|
||||
writeVendor("com/example/Buffer.java", "package com.example;\n\npublic class Buffer { int pointer; }\n");
|
||||
Files.writeString(decompiled.resolve(".incari-decompile-stamp"), "stamp-1");
|
||||
tree = new ClientTree(ws);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rebuildThenApplyRoundTripsByteForByte() throws Exception {
|
||||
tree.apply(decompiled, "test", false);
|
||||
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
|
||||
commit("core: Change the greeting", "Explains why.");
|
||||
|
||||
ClientTree.RebuildResult first = tree.rebuildPatches(false);
|
||||
Path patch = root.resolve("patches/core/0001-change-the-greeting.patch");
|
||||
assertThat(first.written()).isEqualTo(1);
|
||||
assertThat(patch).exists();
|
||||
String text = Files.readString(patch);
|
||||
assertThat(text)
|
||||
.contains("Subject: [PATCH] core: Change the greeting")
|
||||
.contains("From: Tester <tester@example.com>")
|
||||
.doesNotContain("public class Greeter"); // no function-context hunk header
|
||||
|
||||
// Fresh apply from the patch file, then regenerate: nothing may change.
|
||||
FileTrees.deleteRecursively(ws.clientTree());
|
||||
tree.apply(decompiled, "test", false);
|
||||
assertThat(Files.readString(treeFile("com/example/Greeter.java"))).contains("\"hi\"");
|
||||
ClientTree.RebuildResult second = tree.rebuildPatches(true);
|
||||
assertThat(second.changed()).isFalse();
|
||||
assertThat(second.unchanged()).isEqualTo(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkModeReportsUnsavedCommitsWithoutWriting() throws Exception {
|
||||
tree.apply(decompiled, "test", false);
|
||||
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
|
||||
commit("core: Change the greeting", null);
|
||||
|
||||
assertThat(tree.rebuildPatches(true).changed()).isTrue();
|
||||
assertThat(root.resolve("patches")).doesNotExist();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rebuildRemovesPatchesWhoseCommitsWereDropped() throws Exception {
|
||||
tree.apply(decompiled, "test", false);
|
||||
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
|
||||
commit("core: Change the greeting", null);
|
||||
tree.rebuildPatches(false);
|
||||
|
||||
git().run("reset", "--quiet", "--hard", ClientTree.BASE_TAG);
|
||||
ClientTree.RebuildResult result = tree.rebuildPatches(false);
|
||||
|
||||
assertThat(result.removed()).isEqualTo(1);
|
||||
assertThat(root.resolve("patches/core")).doesNotExist();
|
||||
}
|
||||
|
||||
@Test
|
||||
void patchesAreNumberedInOneGlobalOrderAcrossSubsystems() throws Exception {
|
||||
tree.apply(decompiled, "test", false);
|
||||
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
|
||||
commit("core: Change the greeting", null);
|
||||
edit("com/example/Buffer.java", "int pointer;", "int offset;");
|
||||
commit("memory: Replace the raw pointer with an offset", null);
|
||||
tree.rebuildPatches(false);
|
||||
|
||||
assertThat(PatchSet.list(ws.patchesDir()))
|
||||
.extracting(p -> root.relativize(p.path()).toString())
|
||||
.containsExactly(
|
||||
"patches/core/0001-change-the-greeting.patch",
|
||||
"patches/memory/0002-replace-the-raw-pointer-with-an-offset.patch");
|
||||
|
||||
FileTrees.deleteRecursively(ws.clientTree());
|
||||
tree.apply(decompiled, "test", false);
|
||||
assertThat(tree.rebuildPatches(true).changed()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rebuildRejectsSubjectsWithoutASubsystem() throws Exception {
|
||||
tree.apply(decompiled, "test", false);
|
||||
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
|
||||
commit("Change the greeting", null);
|
||||
|
||||
assertThatThrownBy(() -> tree.rebuildPatches(false))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("<subsystem>: <summary>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rebuildRejectsFileDeletionsInPatches() throws Exception {
|
||||
tree.apply(decompiled, "test", false);
|
||||
git().run("rm", "--quiet", Workspace.CLIENT_SOURCE_DIR + "/com/example/Telemetry.java");
|
||||
commit("telemetry: Remove telemetry", null);
|
||||
|
||||
assertThatThrownBy(() -> tree.rebuildPatches(false))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("classes.txt");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rebuildRejectsUncommittedEdits() throws Exception {
|
||||
tree.apply(decompiled, "test", false);
|
||||
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
|
||||
|
||||
assertThatThrownBy(() -> tree.rebuildPatches(false))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("uncommitted changes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void applyRefusesToDiscardUnsavedWorkUnlessForced() throws Exception {
|
||||
tree.apply(decompiled, "test", false);
|
||||
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
|
||||
commit("core: Change the greeting", null);
|
||||
|
||||
assertThatThrownBy(() -> tree.apply(decompiled, "test", false))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("commits not saved");
|
||||
|
||||
tree.apply(decompiled, "test", true);
|
||||
assertThat(Files.readString(treeFile("com/example/Greeter.java"))).contains("\"hello\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
void classManifestDeletesAndReplacesWholeFiles() throws Exception {
|
||||
Path replacement = root.resolve("memory/src/Buffer.java");
|
||||
Files.createDirectories(replacement.getParent());
|
||||
Files.writeString(replacement, "package com.example;\n\npublic class Buffer { /* Incari */ }\n");
|
||||
Files.createDirectories(ws.patchesDir());
|
||||
Files.writeString(ws.classManifest(), """
|
||||
# test manifest
|
||||
delete com.example.Telemetry
|
||||
replace com.example.Buffer memory/src/Buffer.java
|
||||
""");
|
||||
|
||||
tree.apply(decompiled, "test", false);
|
||||
|
||||
assertThat(treeFile("com/example/Telemetry.java")).doesNotExist();
|
||||
assertThat(Files.readString(treeFile("com/example/Buffer.java"))).contains("/* Incari */");
|
||||
|
||||
edit("com/example/Buffer.java", "/* Incari */", "/* edited in work/ */");
|
||||
commit("memory: Edit the replaced class", null);
|
||||
assertThatThrownBy(() -> tree.rebuildPatches(false))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("replaces");
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacementsAreFlaggedWhenTheirOriginalChanges() throws Exception {
|
||||
Path replacement = root.resolve("memory/src/Buffer.java");
|
||||
Files.createDirectories(replacement.getParent());
|
||||
Files.writeString(replacement, "package com.example;\n\npublic class Buffer { /* Incari */ }\n");
|
||||
Files.createDirectories(ws.patchesDir());
|
||||
Files.writeString(ws.classManifest(), "replace com.example.Buffer memory/src/Buffer.java\n");
|
||||
|
||||
tree.apply(decompiled, "test", false);
|
||||
assertThat(tree.replacementDrift("test"))
|
||||
.singleElement()
|
||||
.satisfies(d -> assertThat(d.recorded()).isNull());
|
||||
|
||||
assertThat(tree.stampReplacements("test")).isEqualTo(1);
|
||||
assertThat(Files.readString(ws.classManifest())).matches("(?s).*memory/src/Buffer\\.java test@[0-9a-f]{12}\n");
|
||||
assertThat(tree.replacementDrift("test")).isEmpty();
|
||||
|
||||
// The next "Minecraft version" changes the original the replacement was written against.
|
||||
Files.writeString(
|
||||
decompiled.resolve("com/example/Buffer.java"),
|
||||
"package com.example;\n\npublic class Buffer { long pointer; }\n");
|
||||
Files.writeString(decompiled.resolve(".incari-decompile-stamp"), "stamp-2");
|
||||
tree.apply(decompiled, "next", false);
|
||||
|
||||
assertThat(tree.replacementDrift("next")).singleElement().satisfies(d -> {
|
||||
assertThat(d.className()).isEqualTo("com.example.Buffer");
|
||||
assertThat(d.recorded().version()).isEqualTo("test");
|
||||
assertThat(d.current().version()).isEqualTo("next");
|
||||
});
|
||||
tree.stampReplacements("next");
|
||||
assertThat(tree.replacementDrift("next")).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void manifestEntryForAMissingClassFailsClearly() throws Exception {
|
||||
Files.createDirectories(ws.patchesDir());
|
||||
Files.writeString(ws.classManifest(), "delete com.example.Gone\n");
|
||||
|
||||
assertThatThrownBy(() -> tree.apply(decompiled, "test", false))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("com.example.Gone");
|
||||
}
|
||||
|
||||
@Test
|
||||
void conflictingPatchStopsMidApplyWithInstructions() throws Exception {
|
||||
tree.apply(decompiled, "test", false);
|
||||
edit("com/example/Greeter.java", "\"hello\"", "\"hi\"");
|
||||
commit("core: Change the greeting", null);
|
||||
tree.rebuildPatches(false);
|
||||
|
||||
// A new "Minecraft version" whose line the patch touches changed underneath it.
|
||||
writeVendor(
|
||||
"com/example/Greeter.java",
|
||||
Files.readString(decompiled.resolve("com/example/Greeter.java"))
|
||||
.replace("\"hello\"", "\"hello there\""));
|
||||
Files.writeString(decompiled.resolve(".incari-decompile-stamp"), "stamp-2");
|
||||
|
||||
assertThatThrownBy(() -> tree.apply(decompiled, "test", false))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("am --continue");
|
||||
}
|
||||
|
||||
// --- helpers ---
|
||||
|
||||
private void writeVendor(String relative, String content) throws IOException {
|
||||
Path file = decompiled.resolve(relative);
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, content);
|
||||
}
|
||||
|
||||
private Path treeFile(String relative) {
|
||||
return ws.clientTree().resolve(Workspace.CLIENT_SOURCE_DIR).resolve(relative);
|
||||
}
|
||||
|
||||
private void edit(String relative, String from, String to) throws IOException {
|
||||
Path file = treeFile(relative);
|
||||
String content = Files.readString(file);
|
||||
assertThat(content).contains(from);
|
||||
Files.writeString(file, content.replace(from, to));
|
||||
}
|
||||
|
||||
private void commit(String subject, String body) throws Exception {
|
||||
git().run("add", "--all");
|
||||
List<String> args = new java.util.ArrayList<>(List.of(
|
||||
"commit",
|
||||
"--quiet",
|
||||
"--author=Tester <tester@example.com>",
|
||||
"--date=2026-09-25T12:00:00+02:00",
|
||||
"-m",
|
||||
subject));
|
||||
if (body != null) {
|
||||
args.addAll(List.of("-m", body));
|
||||
}
|
||||
git().run(args.toArray(String[]::new));
|
||||
}
|
||||
|
||||
private Git git() {
|
||||
return new Git(ws.clientTree());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package incari.tools.build;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class ParsingTest {
|
||||
|
||||
@Test
|
||||
void classManifestParsesDeletesReplacesAndComments() {
|
||||
ClassManifest manifest = ClassManifest.parse(
|
||||
List.of(
|
||||
"# comment",
|
||||
"",
|
||||
"delete a.b.Telemetry # trailing comment",
|
||||
"replace a.b.Buffer render-webgl2/src/Buffer.java"),
|
||||
"classes.txt");
|
||||
|
||||
assertThat(manifest.entries())
|
||||
.containsExactly(
|
||||
new ClassManifest.Delete("a.b.Telemetry"),
|
||||
new ClassManifest.Replace("a.b.Buffer", "render-webgl2/src/Buffer.java"));
|
||||
assertThat(manifest.treePaths())
|
||||
.containsExactlyInAnyOrder("src/main/java/a/b/Telemetry.java", "src/main/java/a/b/Buffer.java");
|
||||
}
|
||||
|
||||
@Test
|
||||
void classManifestRejectsBadLines() {
|
||||
assertThatThrownBy(() -> ClassManifest.parse(List.of("remove a.B"), "m"))
|
||||
.hasMessageContaining("m:1")
|
||||
.hasMessageContaining("unknown action");
|
||||
assertThatThrownBy(() -> ClassManifest.parse(List.of("delete a.B$Inner"), "m"))
|
||||
.hasMessageContaining("top-level");
|
||||
assertThatThrownBy(() -> ClassManifest.parse(List.of("replace a.B work/B.java"), "m"))
|
||||
.hasMessageContaining("outside work/");
|
||||
assertThatThrownBy(() -> ClassManifest.parse(List.of("replace a.B ../B.java"), "m"))
|
||||
.hasMessageContaining("outside work/");
|
||||
assertThatThrownBy(() -> ClassManifest.parse(List.of("delete a.B", "delete a.B"), "m"))
|
||||
.hasMessageContaining("twice");
|
||||
}
|
||||
|
||||
@Test
|
||||
void classManifestReadsReplacementStamps() {
|
||||
ClassManifest manifest = ClassManifest.parse(
|
||||
List.of("replace a.b.Buffer render-webgl2/src/Buffer.java 26.3@0123456789ab"), "m");
|
||||
|
||||
assertThat(manifest.entries())
|
||||
.containsExactly(new ClassManifest.Replace(
|
||||
"a.b.Buffer",
|
||||
"render-webgl2/src/Buffer.java",
|
||||
new ClassManifest.Stamp("26.3", "0123456789ab")));
|
||||
assertThatThrownBy(() -> ClassManifest.parse(List.of("replace a.B src/B.java 26.3"), "m"))
|
||||
.hasMessageContaining("not a stamp");
|
||||
assertThatThrownBy(() -> ClassManifest.parse(List.of("replace a.B src/B.java 26.3@xyz"), "m"))
|
||||
.hasMessageContaining("not a stamp");
|
||||
}
|
||||
|
||||
@Test
|
||||
void stampsAreWrittenInOneColumnAndEverythingElseIsKept() {
|
||||
List<String> lines = List.of(
|
||||
"# comment",
|
||||
"delete a.Gone",
|
||||
"replace a.Short src/Short.java",
|
||||
"replace a.LongerName src/LongerName.java 26.2@aaaaaaaaaaaa # note");
|
||||
var stamps = new java.util.LinkedHashMap<String, ClassManifest.Stamp>();
|
||||
stamps.put("a.Short", new ClassManifest.Stamp("26.3", "111111111111"));
|
||||
stamps.put("a.LongerName", new ClassManifest.Stamp("26.3", "222222222222"));
|
||||
|
||||
List<String> stamped = ClassManifest.withStamps(lines, stamps);
|
||||
|
||||
assertThat(stamped)
|
||||
.containsExactly(
|
||||
"# comment",
|
||||
"delete a.Gone",
|
||||
"replace a.Short src/Short.java 26.3@111111111111",
|
||||
"replace a.LongerName src/LongerName.java 26.3@222222222222 # note");
|
||||
assertThat(ClassManifest.withStamps(stamped, stamps)).isEqualTo(stamped);
|
||||
assertThat(ClassManifest.parse(stamped, "m").entries()).hasSize(3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void patchFileNamesComeFromTheSubject() {
|
||||
assertThat(PatchSet.fileFor(3, "render: Route section compile to the mesher"))
|
||||
.isEqualTo("render/0003-route-section-compile-to-the-mesher.patch");
|
||||
assertThat(PatchSet.slug("Fix `MemoryUtil` (again!)")).isEqualTo("fix-memoryutil-again");
|
||||
assertThat(PatchSet.slug("a".repeat(30) + " " + "b".repeat(40))).isEqualTo("a".repeat(30));
|
||||
assertThatThrownBy(() -> PatchSet.fileFor(1, "Render: capitalised subsystem"))
|
||||
.isInstanceOf(CliException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void patchListRejectsDuplicateNumbersAndStrayFiles(@TempDir Path dir) throws Exception {
|
||||
Files.createDirectories(dir.resolve("render"));
|
||||
Files.createDirectories(dir.resolve("net"));
|
||||
Files.writeString(dir.resolve("render/0002-b.patch"), "");
|
||||
Files.writeString(dir.resolve("net/0001-a.patch"), "");
|
||||
assertThat(PatchSet.list(dir)).extracting(PatchSet.PatchFile::subsystem).containsExactly("net", "render");
|
||||
|
||||
Files.writeString(dir.resolve("net/0002-c.patch"), "");
|
||||
assertThatThrownBy(() -> PatchSet.list(dir)).hasMessageContaining("share number 2");
|
||||
|
||||
Files.delete(dir.resolve("net/0002-c.patch"));
|
||||
Files.writeString(dir.resolve("loose.patch"), "");
|
||||
assertThatThrownBy(() -> PatchSet.list(dir)).hasMessageContaining("Unexpected patch file");
|
||||
}
|
||||
|
||||
@Test
|
||||
void versionJsonKeepsOnlyArtifactsAndFlagsNatives() {
|
||||
String json = """
|
||||
{
|
||||
"id": "26.3",
|
||||
"javaVersion": {"component": "java-runtime-epsilon", "majorVersion": 25},
|
||||
"downloads": {"client": {"url": "https://example.invalid/client.jar", "sha1": "abc", "size": 10}},
|
||||
"libraries": [
|
||||
{"name": "org.example:lib:1.0",
|
||||
"downloads": {"artifact": {"path": "org/example/lib/1.0/lib-1.0.jar", "url": "https://example.invalid/lib.jar", "sha1": "def", "size": 5}}},
|
||||
{"name": "org.example:lib:1.0:natives-linux",
|
||||
"downloads": {"artifact": {"path": "org/example/lib/1.0/lib-1.0-natives-linux.jar", "url": "https://example.invalid/n.jar", "sha1": "123", "size": 5}},
|
||||
"rules": [{"action": "allow", "os": {"name": "linux"}}]},
|
||||
{"name": "org.example:no-artifact:1.0"}
|
||||
]
|
||||
}
|
||||
""";
|
||||
MojangMetadata.Version version = MojangMetadata.parseVersion(json);
|
||||
|
||||
assertThat(version.javaMajorVersion()).isEqualTo(25);
|
||||
assertThat(version.client().sha1()).isEqualTo("abc");
|
||||
assertThat(version.libraries())
|
||||
.extracting(MojangMetadata.Library::name, MojangMetadata.Library::platformSpecific)
|
||||
.containsExactly(
|
||||
org.assertj.core.groups.Tuple.tuple("org.example:lib:1.0", false),
|
||||
org.assertj.core.groups.Tuple.tuple("org.example:lib:1.0:natives-linux", true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void manifestLookupFindsTheVersionJson() {
|
||||
String manifest = """
|
||||
{"latest": {"release": "26.3"},
|
||||
"versions": [{"id": "26.3", "url": "https://example.invalid/26.3.json", "sha1": "bc09"}]}
|
||||
""";
|
||||
assertThat(MojangMetadata.findVersion(manifest, "26.3").sha1()).isEqualTo("bc09");
|
||||
assertThatThrownBy(() -> MojangMetadata.findVersion(manifest, "1.0")).isInstanceOf(CliException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void workspaceIsFoundFromASubdirectory(@TempDir Path dir) throws Exception {
|
||||
Files.writeString(dir.resolve(BuildConfig.FILE_NAME), "");
|
||||
Path nested = Files.createDirectories(dir.resolve("a/b"));
|
||||
assertThat(Workspace.discover(nested).repoRoot())
|
||||
.isEqualTo(dir.toAbsolutePath().normalize());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nativePlatformNamesMatchMojangsClassifiers() {
|
||||
assertThat(NativePlatform.of("Linux", "amd64").classifier()).isEqualTo("natives-linux");
|
||||
assertThat(NativePlatform.of("Windows 11", "aarch64").classifier()).isEqualTo("natives-windows-arm64");
|
||||
assertThat(NativePlatform.of("Mac OS X", "aarch64").classifier()).isEqualTo("natives-macos-arm64");
|
||||
assertThatThrownBy(() -> NativePlatform.of("FreeBSD", "amd64")).isInstanceOf(CliException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void hostNativesPickOnlyThisPlatformsJars() {
|
||||
String json = """
|
||||
{
|
||||
"id": "26.3",
|
||||
"javaVersion": {"majorVersion": 25},
|
||||
"downloads": {"client": {"url": "https://example.invalid/c.jar", "sha1": "abc", "size": 1}},
|
||||
"libraries": [
|
||||
{"name": "org.lwjgl:lwjgl:3.4.3",
|
||||
"downloads": {"artifact": {"path": "l.jar", "url": "https://example.invalid/l.jar", "sha1": "1", "size": 1}}},
|
||||
{"name": "org.lwjgl:lwjgl:3.4.3:natives-linux",
|
||||
"downloads": {"artifact": {"path": "ll.jar", "url": "https://example.invalid/ll.jar", "sha1": "2", "size": 1}}},
|
||||
{"name": "org.lwjgl:lwjgl:3.4.3:natives-windows",
|
||||
"downloads": {"artifact": {"path": "lw.jar", "url": "https://example.invalid/lw.jar", "sha1": "3", "size": 1}}}
|
||||
]
|
||||
}
|
||||
""";
|
||||
MojangMetadata.Version version = MojangMetadata.parseVersion(json);
|
||||
|
||||
assertThat(GameFiles.hostNatives(version, NativePlatform.of("Linux", "amd64")))
|
||||
.extracting(MojangMetadata.Library::path)
|
||||
.containsExactly("ll.jar");
|
||||
assertThat(version.libraries().getFirst().classifier()).isEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env bash
|
||||
# Fails if any commit in <base>..<head> lacks a Developer Certificate of Origin sign-off.
|
||||
# Usage: tools/ci/check-dco.sh <base> <head>
|
||||
set -euo pipefail
|
||||
|
||||
base=$1
|
||||
head=$2
|
||||
missing=0
|
||||
|
||||
for commit in $(git rev-list --no-merges "$base..$head"); do
|
||||
author_email=$(git log -1 --format='%ae' "$commit")
|
||||
if ! git log -1 --format='%(trailers:key=Signed-off-by,valueonly)' "$commit" | grep -qiF "<$author_email>"; then
|
||||
echo "missing sign-off by its author: $(git log -1 --format='%h %s' "$commit")" >&2
|
||||
missing=1
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$missing" -ne 0 ]; then
|
||||
echo >&2
|
||||
echo "Every commit needs 'Signed-off-by: Name <author email>' (git commit -s). See CONTRIBUTING.md." >&2
|
||||
echo "To sign off existing commits: git rebase --signoff $base" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "DCO check passed."
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
# Validates every GLSL shader Incari tracks with glslang. Incari shaders are named by stage
|
||||
# (.vert, .frag, .comp) so glslang never has to guess; shared .glsl includes are checked through
|
||||
# the shaders that include them. Translated GLSL ES output is validated where it's generated, in
|
||||
# the render-webgl2 build.
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
shaders=$(git ls-files --cached --others --exclude-standard -- '*.vert' '*.frag' '*.comp' | grep -v '^work/' || true)
|
||||
if [ -z "$shaders" ]; then
|
||||
echo "GLSL check passed: no Incari shaders yet."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! command -v glslangValidator >/dev/null; then
|
||||
echo "glslangValidator is needed to check shaders (package: glslang)." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
failed=0
|
||||
count=0
|
||||
while IFS= read -r shader; do
|
||||
count=$((count + 1))
|
||||
if ! output=$(glslangValidator "$shader" 2>&1); then
|
||||
echo "$output" >&2
|
||||
failed=1
|
||||
fi
|
||||
done <<< "$shaders"
|
||||
|
||||
if [ "$failed" -ne 0 ]; then
|
||||
exit 1
|
||||
fi
|
||||
echo "GLSL check passed: $count shaders valid."
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env bash
|
||||
# Fails if a library pin in gradle/libs.versions.toml that must match Minecraft's version JSON
|
||||
# doesn't. Incari compiles against these jars and the game runs with Mojang's copies, so after a
|
||||
# Minecraft bump they have to move with it (docs/updating.md). Needs ./incari fetch first.
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
version=$(sed -n 's/^minecraft\.version=//p' incari.properties | tr -d '[:space:]')
|
||||
json="work/cache/versions/${version}/${version}.json"
|
||||
if [ ! -f "$json" ]; then
|
||||
echo "No ${json}. Run ./incari fetch first." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# <libs.versions.toml key> <Maven group:artifact in the version JSON>
|
||||
python3 -I - "$json" gradle/libs.versions.toml <<'EOF'
|
||||
import json, re, sys
|
||||
|
||||
pins = {
|
||||
"lwjgl": "org.lwjgl:lwjgl",
|
||||
"guava": "com.google.guava:guava",
|
||||
"gson": "com.google.code.gson:gson",
|
||||
}
|
||||
|
||||
with open(sys.argv[1]) as f:
|
||||
mojang = {}
|
||||
for lib in json.load(f)["libraries"]:
|
||||
parts = lib["name"].split(":")
|
||||
if len(parts) == 3:
|
||||
mojang[parts[0] + ":" + parts[1]] = parts[2]
|
||||
|
||||
with open(sys.argv[2]) as f:
|
||||
toml = f.read()
|
||||
section = toml.split("[versions]", 1)[1].split("\n[", 1)[0]
|
||||
ours = dict(re.findall(r'^([\w-]+)\s*=\s*"([^"]+)"', section, re.M))
|
||||
|
||||
bad = []
|
||||
for key, coordinate in pins.items():
|
||||
want = mojang.get(coordinate)
|
||||
have = ours.get(key)
|
||||
if want is None:
|
||||
bad.append(f"{coordinate} is no longer in Minecraft's version JSON (libs.versions.toml: {key} = {have})")
|
||||
elif have != want:
|
||||
bad.append(f'{key} = "{have}" in gradle/libs.versions.toml, but Minecraft ships {coordinate}:{want}')
|
||||
|
||||
if bad:
|
||||
print("\n".join(bad))
|
||||
print("Move these pins to Minecraft's versions (see their comments in gradle/libs.versions.toml).", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
print("Library pins match Minecraft's version JSON: " + ", ".join(f"{k} {ours[k]}" for k in pins))
|
||||
EOF
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# Fails if any workflow could publish a build. Every Incari build contains Mojang code, so CI
|
||||
# may compile and test, but must never upload artifacts, cut releases or deploy pages.
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
workflows=$(git ls-files '.github/workflows/*.yml' '.github/workflows/*.yaml')
|
||||
if [ -z "$workflows" ]; then
|
||||
echo "No workflows to check."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# The pattern is spelled out in pieces so this script doesn't flag its own workflow file.
|
||||
forbidden='actions/upload-''artifact|actions/upload-pages-''artifact|actions/deploy-''pages|action-gh-''release|gh release (create|upload)|(contents|packages|pages|deployments|id-token): *write'
|
||||
|
||||
# shellcheck disable=SC2086
|
||||
if matches=$(grep -nE "$forbidden" $workflows); then
|
||||
echo "Workflows must never publish builds or request write access (CONTRIBUTING.md):" >&2
|
||||
echo "$matches" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Publishing check passed: no workflow uploads, releases or deploys."
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env bash
|
||||
# Reports the size of Incari's changes to vendor code and fails if it grows past
|
||||
# patches/budget.properties. Every vendor line touched is rebase cost on the next Minecraft drop,
|
||||
# and every context line is Mojang text in the repo, so growth has to be deliberate: raise the
|
||||
# budget in the same pull request and say why.
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
budget=patches/budget.properties
|
||||
read_budget() {
|
||||
grep -E "^$1=" "$budget" | cut -d= -f2 | tr -d '[:space:]'
|
||||
}
|
||||
|
||||
patches=$(git ls-files --cached --others --exclude-standard -- 'patches/*.patch' 'patches/**/*.patch')
|
||||
patch_count=0
|
||||
changed=0
|
||||
context=0
|
||||
if [ -n "$patches" ]; then
|
||||
patch_count=$(echo "$patches" | wc -l)
|
||||
# Inside hunks: "+"/"-" lines are changes, " " lines are vendor context.
|
||||
read -r changed context < <(echo "$patches" | xargs awk '
|
||||
/^@@ / { in_hunk = 1; next }
|
||||
/^diff --git / { in_hunk = 0; next }
|
||||
in_hunk && /^[-+]/ { changed++ }
|
||||
in_hunk && /^ / { context++ }
|
||||
END { print changed + 0, context + 0 }')
|
||||
fi
|
||||
replaced=$(grep -cE '^\s*replace\s' patches/classes.txt || true)
|
||||
deleted=$(grep -cE '^\s*delete\s' patches/classes.txt || true)
|
||||
|
||||
echo "Patch budget:"
|
||||
printf ' %-28s %6s / %s\n' "patch files" "$patch_count" "$(read_budget max.patches)"
|
||||
printf ' %-28s %6s / %s\n' "changed lines (+/-)" "$changed" "$(read_budget max.changed.lines)"
|
||||
printf ' %-28s %6s / %s\n' "vendor context lines" "$context" "$(read_budget max.context.lines)"
|
||||
printf ' %-28s %6s\n' "classes deleted (manifest)" "$deleted"
|
||||
printf ' %-28s %6s\n' "classes replaced (manifest)" "$replaced"
|
||||
|
||||
over=0
|
||||
check() {
|
||||
local name=$1 value=$2 limit
|
||||
limit=$(read_budget "$name")
|
||||
if [ "$value" -gt "$limit" ]; then
|
||||
echo "Over budget: $name is $value, the budget is $limit." >&2
|
||||
over=1
|
||||
fi
|
||||
}
|
||||
check max.patches "$patch_count"
|
||||
check max.changed.lines "$changed"
|
||||
check max.context.lines "$context"
|
||||
|
||||
if [ "$over" -ne 0 ]; then
|
||||
echo "Make the patches thinner (move logic into an Incari module), or raise $budget in this" >&2
|
||||
echo "pull request and explain the growth in its description." >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env bash
|
||||
# Fails if git tracks anything that looks like Mojang content or a compiled build.
|
||||
# The repo must stay patch-only (CONTRIBUTING.md); this is the mechanical half of that rule.
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
violations=$(git ls-files -z | tr '\0' '\n' | awk '
|
||||
# The Gradle wrapper jar is the one jar allowed in the repo.
|
||||
$0 == "gradle/wrapper/gradle-wrapper.jar" { next }
|
||||
# Generated workspace: jars, decompiled source, patched tree.
|
||||
/^work\// { print "generated workspace: " $0; next }
|
||||
# Game code and compiled builds.
|
||||
/\.(jar|class|wasm|wasm\.map|teavmdbg)$/ { print "binary or build: " $0; next }
|
||||
# Game assets and data.
|
||||
/(^|\/)assets\/minecraft\// { print "Minecraft assets: " $0; next }
|
||||
/(^|\/)data\/minecraft\// { print "Minecraft data: " $0; next }
|
||||
/\.(ogg|nbt|mca|mcmeta)$/ { print "game asset format: " $0; next }
|
||||
# Mojang core shaders, translated copies included (Incari shaders use .vert/.frag/.comp).
|
||||
/\.(vsh|fsh)$/ { print "Mojang shader format: " $0; next }
|
||||
/(^|\/)shaders\/core\// { print "Mojang core shaders: " $0; next }
|
||||
')
|
||||
|
||||
if [ -n "$violations" ]; then
|
||||
echo "These tracked files must not be in the repo (see CONTRIBUTING.md):" >&2
|
||||
echo "$violations" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Repo content check passed: no Mojang content or builds tracked."
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
# Fails if a feature has no Rust status in features/README.md (ADR 0068): every features/<name>
|
||||
# has a row there, and every row's last column says Ported, Not yet or Won't port. Keeps the Rust
|
||||
# build's gaps written down as features are added.
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
table=features/README.md
|
||||
problems=$(
|
||||
# Tracked modules only: a renamed module can leave an ignored build/ folder behind.
|
||||
for build in $(git ls-files 'features/*/build.gradle.kts'); do
|
||||
name=$(basename "$(dirname "$build")")
|
||||
grep -q "](${name}/README.md)" "$table" || echo "features/${name} has no row in ${table}"
|
||||
done
|
||||
awk -F'|' '/^\| \[/ {
|
||||
status = $(NF - 1); gsub(/^ +| +$/, "", status)
|
||||
if (status != "Ported" && status != "Not yet" && status != "Won'"'"'t port") print "no Rust status: " $0
|
||||
}' "$table"
|
||||
)
|
||||
|
||||
if [ -n "$problems" ]; then
|
||||
echo "$problems"
|
||||
echo "Give each feature a Rust column in ${table}: Ported, Not yet or Won't port." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Every feature has a Rust status."
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
# Fails if shipped code spells out the pinned Minecraft version ("26.3") as a string literal.
|
||||
# incari.properties is the one place it's written: Gradle reads it, and code takes it from the
|
||||
# generated IncariBuild.MINECRAFT_VERSION or the game's SharedConstants. A literal left behind is a
|
||||
# silent bug on the next version bump (docs/updating.md). Comments, tests and docs may name it.
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
|
||||
version=$(sed -n 's/^minecraft\.version=//p' incari.properties | tr -d '[:space:]')
|
||||
if [ -z "$version" ]; then
|
||||
echo "No minecraft.version in incari.properties" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# The version as a whole quoted string: "26.3" or '26.3', not "26.3.1" or "incari/26.3".
|
||||
pattern="[\"']${version//./[.]}[\"']"
|
||||
|
||||
hits=$(
|
||||
git ls-files -z -- '*.java' '*.kt' '*.kts' '*.ts' '*.js' '*.mjs' '*.rs' \
|
||||
':!:**/src/test/**' ':!:**/tests/**' ':!:**/tests.rs' ':!:**/*.test.ts' ':!:patches/**' \
|
||||
| xargs -0 -r awk -v pat="$pattern" '
|
||||
{
|
||||
line = $0
|
||||
sub(/^[ \t]*\|/, "", line) # Kotlin trimMargin() templates
|
||||
if (line ~ /^[ \t]*(\/\/|\/\*|\*|#)/) next # comment lines
|
||||
if (line ~ pat) print FILENAME ":" FNR ": " $0
|
||||
}'
|
||||
)
|
||||
|
||||
if [ -n "$hits" ]; then
|
||||
echo "$hits"
|
||||
echo "Don't hard-code the Minecraft version ${version}: use IncariBuild.MINECRAFT_VERSION," >&2
|
||||
echo "SharedConstants.getCurrentVersion(), or read incari.properties (Gradle)." >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "No hard-coded Minecraft version ${version} in shipped code."
|
||||
@@ -0,0 +1,4 @@
|
||||
# tools/copycheck
|
||||
|
||||
- A finding is fixed by rewriting the code, never by excusing it. There is no allowlist.
|
||||
- Test: `./gradlew :tools:copycheck:test`; run for real with `./incari copycheck`.
|
||||
@@ -0,0 +1,28 @@
|
||||
# tools/copycheck: the verbatim-copy check
|
||||
|
||||
Fails if an Incari Java file has a long run of code identical to the decompiled game. Pasting
|
||||
from the decompiled tree is easy to do by accident, for people and agents. This is the mechanical
|
||||
half of "write it fresh"; review is the other half.
|
||||
|
||||
```sh
|
||||
./incari copycheck # after ./incari setup, ~10 seconds; CI runs it too
|
||||
./incari copycheck --window=40 # stricter, for spot checks
|
||||
```
|
||||
|
||||
`JavaTokens` lexes, `WindowIndex` hashes every 60-token window of the game, `CopyCheck` reports
|
||||
matching runs.
|
||||
|
||||
## Invariants
|
||||
|
||||
- **Compares against the pristine decompiled source**, not the patched tree.
|
||||
- **Checks every Java file outside `work/`** that git tracks or would track, so it works before a commit.
|
||||
- **Formatting, comments, imports and `package` lines are ignored,** so reformatting doesn't hide a
|
||||
paste. Identifiers count.
|
||||
- **A 60-token window** (5–8 lines). Shorter shared runs (signatures, common loops) are normal.
|
||||
- **No allowlist.** A finding means a rewrite.
|
||||
|
||||
## How to test
|
||||
|
||||
```sh
|
||||
./gradlew :tools:copycheck:test
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
plugins {
|
||||
application
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// The workspace layout and version pin: compares against the same decompiled tree
|
||||
// `incari setup` produced.
|
||||
implementation(project(":tools:build"))
|
||||
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testImplementation(libs.assertj)
|
||||
testRuntimeOnly(libs.junit.launcher)
|
||||
}
|
||||
|
||||
application {
|
||||
applicationName = "incari-copycheck"
|
||||
mainClass = "incari.tools.copycheck.Main"
|
||||
// The vendor tree has millions of token windows; the index is a sorted long[].
|
||||
applicationDefaultJvmArgs = listOf("-Xmx2g")
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package incari.tools.copycheck;
|
||||
|
||||
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.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Finds runs of Incari code that are token-for-token identical to code in the vendor tree.
|
||||
*
|
||||
* <p>Agents and people work next to the decompiled game, and code pasted from it into an
|
||||
* Incari module is both a quality problem and a legal one: Incari modules are published, Mojang
|
||||
* code must never be. Formatting, comments and imports are ignored, so reformatting a pasted
|
||||
* block doesn't hide it; renaming every identifier would, which is what a review is for.
|
||||
*/
|
||||
final class CopyCheck {
|
||||
|
||||
/** Enough tokens for about five to eight lines of code: past what signatures and idioms share. */
|
||||
static final int DEFAULT_WINDOW = 60;
|
||||
|
||||
/** One copied run: {@code tokens} tokens long, on lines {@code firstLine..lastLine} of {@code file}. */
|
||||
record Finding(String file, int firstLine, int lastLine, int tokens) {
|
||||
@Override
|
||||
public String toString() {
|
||||
return file + ":" + firstLine + "-" + lastLine + ": " + tokens + " tokens identical to vendor code";
|
||||
}
|
||||
}
|
||||
|
||||
private final WindowIndex index;
|
||||
|
||||
private CopyCheck(WindowIndex index) {
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
/** Indexes every {@code .java} file under {@code vendorRoot}. */
|
||||
static CopyCheck indexVendorTree(Path vendorRoot, int window) throws IOException {
|
||||
WindowIndex index = new WindowIndex(window);
|
||||
try (Stream<Path> files = Files.walk(vendorRoot)) {
|
||||
for (Path file : (Iterable<Path>) files.filter(p -> p.toString().endsWith(".java"))::iterator) {
|
||||
index.addFile(JavaTokens.tokenize(Files.readString(file, StandardCharsets.UTF_8)));
|
||||
}
|
||||
}
|
||||
index.seal();
|
||||
return new CopyCheck(index);
|
||||
}
|
||||
|
||||
static CopyCheck of(List<String> vendorSources, int window) {
|
||||
WindowIndex index = new WindowIndex(window);
|
||||
for (String source : vendorSources) {
|
||||
index.addFile(JavaTokens.tokenize(source));
|
||||
}
|
||||
index.seal();
|
||||
return new CopyCheck(index);
|
||||
}
|
||||
|
||||
/** Every copied run in one Incari file, merged where windows overlap. */
|
||||
List<Finding> check(String name, String source) {
|
||||
List<JavaTokens.Token> tokens = JavaTokens.tokenize(source);
|
||||
long[] hashes = WindowIndex.windowHashes(tokens, index.window());
|
||||
List<Finding> findings = new ArrayList<>();
|
||||
int runStart = -1;
|
||||
int runEnd = -1;
|
||||
for (int i = 0; i < hashes.length; i++) {
|
||||
if (!index.contains(hashes[i])) {
|
||||
continue;
|
||||
}
|
||||
int windowEnd = i + index.window() - 1;
|
||||
if (runStart >= 0 && i <= runEnd + 1) {
|
||||
runEnd = windowEnd;
|
||||
} else {
|
||||
if (runStart >= 0) {
|
||||
findings.add(finding(name, tokens, runStart, runEnd));
|
||||
}
|
||||
runStart = i;
|
||||
runEnd = windowEnd;
|
||||
}
|
||||
}
|
||||
if (runStart >= 0) {
|
||||
findings.add(finding(name, tokens, runStart, runEnd));
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
private static Finding finding(String name, List<JavaTokens.Token> tokens, int start, int end) {
|
||||
return new Finding(name, tokens.get(start).line(), tokens.get(end).line(), end - start + 1);
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package incari.tools.copycheck;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A deliberately small Java lexer: enough to compare code by its tokens while ignoring
|
||||
* whitespace, comments, formatting, and the {@code package}/{@code import} header.
|
||||
*
|
||||
* <p>It doesn't need to be a correct Java lexer, only a consistent one: the same text must
|
||||
* always give the same tokens, on both sides of the comparison.
|
||||
*/
|
||||
final class JavaTokens {
|
||||
|
||||
/** One token and the 1-based line it starts on. */
|
||||
record Token(String text, int line) {}
|
||||
|
||||
private JavaTokens() {}
|
||||
|
||||
static List<Token> tokenize(String source) {
|
||||
List<Token> tokens = new ArrayList<>();
|
||||
int i = 0;
|
||||
int line = 1;
|
||||
int n = source.length();
|
||||
while (i < n) {
|
||||
char c = source.charAt(i);
|
||||
if (c == '\n') {
|
||||
line++;
|
||||
i++;
|
||||
} else if (Character.isWhitespace(c)) {
|
||||
i++;
|
||||
} else if (c == '/' && i + 1 < n && source.charAt(i + 1) == '/') {
|
||||
while (i < n && source.charAt(i) != '\n') {
|
||||
i++;
|
||||
}
|
||||
} else if (c == '/' && i + 1 < n && source.charAt(i + 1) == '*') {
|
||||
int end = source.indexOf("*/", i + 2);
|
||||
int stop = end < 0 ? n : end + 2;
|
||||
line += count(source, i, stop, '\n');
|
||||
i = stop;
|
||||
} else if (source.startsWith("\"\"\"", i)) {
|
||||
int end = source.indexOf("\"\"\"", i + 3);
|
||||
int stop = end < 0 ? n : end + 3;
|
||||
tokens.add(new Token(source.substring(i, stop), line));
|
||||
line += count(source, i, stop, '\n');
|
||||
i = stop;
|
||||
} else if (c == '"' || c == '\'') {
|
||||
int stop = i + 1;
|
||||
while (stop < n && source.charAt(stop) != c && source.charAt(stop) != '\n') {
|
||||
stop += source.charAt(stop) == '\\' ? 2 : 1;
|
||||
}
|
||||
stop = Math.min(stop + 1, n);
|
||||
tokens.add(new Token(source.substring(i, stop), line));
|
||||
i = stop;
|
||||
} else if (Character.isJavaIdentifierStart(c) || Character.isDigit(c)) {
|
||||
int stop = i + 1;
|
||||
while (stop < n
|
||||
&& (Character.isJavaIdentifierPart(source.charAt(stop))
|
||||
|| isDecimalPoint(source, stop, Character.isDigit(c)))) {
|
||||
stop++;
|
||||
}
|
||||
tokens.add(new Token(source.substring(i, stop), line));
|
||||
i = stop;
|
||||
} else {
|
||||
tokens.add(new Token(String.valueOf(c), line));
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return dropHeader(tokens);
|
||||
}
|
||||
|
||||
/** Drops {@code package} and {@code import} statements: every file shares their shape. */
|
||||
private static List<Token> dropHeader(List<Token> tokens) {
|
||||
List<Token> body = new ArrayList<>(tokens.size());
|
||||
boolean skipping = false;
|
||||
for (int i = 0; i < tokens.size(); i++) {
|
||||
Token token = tokens.get(i);
|
||||
boolean statementStart = i == 0 || tokens.get(i - 1).text().equals(";");
|
||||
if (!skipping
|
||||
&& statementStart
|
||||
&& (token.text().equals("package") || token.text().equals("import"))) {
|
||||
skipping = true;
|
||||
}
|
||||
if (!skipping) {
|
||||
body.add(token);
|
||||
} else if (token.text().equals(";")) {
|
||||
skipping = false;
|
||||
}
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/** A {@code .} inside a number literal ({@code 1.5}), as opposed to a member access. */
|
||||
private static boolean isDecimalPoint(String source, int at, boolean inNumber) {
|
||||
return inNumber
|
||||
&& source.charAt(at) == '.'
|
||||
&& at + 1 < source.length()
|
||||
&& Character.isDigit(source.charAt(at + 1));
|
||||
}
|
||||
|
||||
private static int count(String text, int from, int to, char c) {
|
||||
int count = 0;
|
||||
for (int i = from; i < to; i++) {
|
||||
if (text.charAt(i) == c) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package incari.tools.copycheck;
|
||||
|
||||
import incari.tools.build.BuildConfig;
|
||||
import incari.tools.build.CliException;
|
||||
import incari.tools.build.Git;
|
||||
import incari.tools.build.Log;
|
||||
import incari.tools.build.Workspace;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* {@code ./incari copycheck}: fails if any Incari Java file contains a long run copied from
|
||||
* the decompiled game.
|
||||
*
|
||||
* <p>Compares against the pristine decompiled sources in {@code work/decompiled}, not the
|
||||
* patched tree: the patched tree holds Incari's own replacement classes, which would match
|
||||
* themselves. Checks every Java file git tracks or would track outside {@code work/}.
|
||||
*/
|
||||
public final class Main {
|
||||
|
||||
private Main() {}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
System.exit(run(List.of(args)));
|
||||
} catch (CliException e) {
|
||||
System.err.println("error: " + e.getMessage());
|
||||
System.exit(1);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
static int run(List<String> args) throws Exception {
|
||||
int window = CopyCheck.DEFAULT_WINDOW;
|
||||
for (String arg : args) {
|
||||
if (arg.startsWith("--window=")) {
|
||||
window = Integer.parseInt(arg.substring("--window=".length()));
|
||||
} else {
|
||||
throw new CliException("Unknown option '" + arg + "'. Usage: ./incari copycheck [--window=<tokens>]");
|
||||
}
|
||||
}
|
||||
|
||||
Workspace ws = Workspace.discover(Path.of(System.getProperty("incari.cwd", ".")));
|
||||
BuildConfig config = BuildConfig.load(ws.repoRoot());
|
||||
Path vendor = ws.decompiledDir(config.minecraftVersion());
|
||||
if (!Files.isDirectory(vendor)) {
|
||||
throw new CliException("No decompiled sources to compare against. Run: ./incari setup");
|
||||
}
|
||||
|
||||
Log.step("Indexing the decompiled " + config.minecraftVersion() + " sources");
|
||||
CopyCheck check = CopyCheck.indexVendorTree(vendor, window);
|
||||
|
||||
List<String> files = incariJavaFiles(ws);
|
||||
Log.step("Checking " + files.size() + " Incari Java files (" + window + "-token windows)");
|
||||
List<CopyCheck.Finding> findings = new ArrayList<>();
|
||||
for (String file : files) {
|
||||
String source = Files.readString(ws.repoRoot().resolve(file), StandardCharsets.UTF_8);
|
||||
findings.addAll(check.check(file, source));
|
||||
}
|
||||
|
||||
if (!findings.isEmpty()) {
|
||||
System.err.println("Code identical to the decompiled game (write Incari code fresh, never copy it):");
|
||||
findings.forEach(f -> System.err.println(" " + f));
|
||||
return 1;
|
||||
}
|
||||
Log.step("Copy check passed: no Incari file repeats vendor code");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Tracked and untracked-but-not-ignored Java files outside {@code work/}. */
|
||||
private static List<String> incariJavaFiles(Workspace ws) throws Exception {
|
||||
String out = new Git(ws.repoRoot())
|
||||
.run("ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", "*.java");
|
||||
List<String> files = new ArrayList<>();
|
||||
for (String file : out.split("\0", -1)) {
|
||||
if (!file.isEmpty()
|
||||
&& !file.startsWith("work/")
|
||||
&& Files.isRegularFile(ws.repoRoot().resolve(file))) {
|
||||
files.add(file);
|
||||
}
|
||||
}
|
||||
files.sort(null);
|
||||
return files;
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package incari.tools.copycheck;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Hashes of every run of {@code window} consecutive tokens in the vendor tree, sorted for
|
||||
* binary search.
|
||||
*
|
||||
* <p>A primitive sorted array rather than a hash set: the vendor tree has millions of windows,
|
||||
* and boxed longs would need several times the memory.
|
||||
*/
|
||||
final class WindowIndex {
|
||||
|
||||
private final int window;
|
||||
private long[] hashes = new long[1 << 20];
|
||||
private int size;
|
||||
private boolean sealed;
|
||||
|
||||
WindowIndex(int window) {
|
||||
this.window = window;
|
||||
}
|
||||
|
||||
int window() {
|
||||
return window;
|
||||
}
|
||||
|
||||
void addFile(List<JavaTokens.Token> tokens) {
|
||||
if (sealed) {
|
||||
throw new IllegalStateException("index is sealed");
|
||||
}
|
||||
for (long hash : windowHashes(tokens, window)) {
|
||||
if (size == hashes.length) {
|
||||
hashes = Arrays.copyOf(hashes, size * 2);
|
||||
}
|
||||
hashes[size++] = hash;
|
||||
}
|
||||
}
|
||||
|
||||
/** Sorts the hashes. Call once, after the last {@link #addFile}. */
|
||||
void seal() {
|
||||
hashes = Arrays.copyOf(hashes, size);
|
||||
Arrays.sort(hashes);
|
||||
sealed = true;
|
||||
}
|
||||
|
||||
boolean contains(long hash) {
|
||||
if (!sealed) {
|
||||
throw new IllegalStateException("seal() the index first");
|
||||
}
|
||||
return Arrays.binarySearch(hashes, hash) >= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* One hash per window: {@code result[i]} covers tokens {@code i .. i + window - 1}. Each
|
||||
* window is hashed independently, so equal windows get equal hashes wherever they occur.
|
||||
*/
|
||||
static long[] windowHashes(List<JavaTokens.Token> tokens, int window) {
|
||||
int count = tokens.size() - window + 1;
|
||||
if (count <= 0) {
|
||||
return new long[0];
|
||||
}
|
||||
long[] tokenHashes = new long[tokens.size()];
|
||||
for (int i = 0; i < tokens.size(); i++) {
|
||||
tokenHashes[i] = mix(tokens.get(i).text().hashCode());
|
||||
}
|
||||
long[] result = new long[count];
|
||||
for (int start = 0; start < count; start++) {
|
||||
long hash = 0x9E3779B97F4A7C15L;
|
||||
for (int j = start; j < start + window; j++) {
|
||||
hash = (hash ^ tokenHashes[j]) * 0x100000001B3L;
|
||||
hash = Long.rotateLeft(hash, 27);
|
||||
}
|
||||
result[start] = hash;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static long mix(long value) {
|
||||
long z = value + 0x9E3779B97F4A7C15L;
|
||||
z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L;
|
||||
z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL;
|
||||
return z ^ (z >>> 31);
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package incari.tools.copycheck;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class CopyCheckTest {
|
||||
|
||||
private static final String VENDOR = """
|
||||
package com.example.vendor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class Engine {
|
||||
private int speed;
|
||||
|
||||
public int accelerate(int delta, List<Integer> history) {
|
||||
int next = this.speed + delta;
|
||||
if (next > 100) {
|
||||
next = 100;
|
||||
} else if (next < 0) {
|
||||
next = 0;
|
||||
}
|
||||
history.add(next);
|
||||
this.speed = next;
|
||||
return next;
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
@Test
|
||||
void flagsACopiedMethodEvenWhenReformattedAndCommented() {
|
||||
String incari = """
|
||||
package incari.platform;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
|
||||
final class Pasted {
|
||||
// Looks innocent after a reformat.
|
||||
public int accelerate(int delta, List<Integer> history) { int next = this.speed + delta;
|
||||
if (next > 100) { next = 100; }
|
||||
else if (next < 0) { next = 0; }
|
||||
history.add(next); this.speed = next; return next; }
|
||||
}
|
||||
""";
|
||||
|
||||
List<CopyCheck.Finding> findings = CopyCheck.of(List.of(VENDOR), 20).check("Pasted.java", incari);
|
||||
|
||||
assertThat(findings).singleElement().satisfies(f -> {
|
||||
assertThat(f.file()).isEqualTo("Pasted.java");
|
||||
assertThat(f.firstLine()).isEqualTo(8);
|
||||
assertThat(f.lastLine()).isEqualTo(12);
|
||||
assertThat(f.tokens()).isGreaterThanOrEqualTo(40);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void ignoresSharedImportsAndShortCommonRuns() {
|
||||
String incari = """
|
||||
package incari.platform;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
final class Fresh {
|
||||
int clamp(int value) {
|
||||
return Math.max(0, Math.min(100, value));
|
||||
}
|
||||
|
||||
public int accelerate(int delta, List<Integer> history) {
|
||||
return clamp(delta);
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
assertThat(CopyCheck.of(List.of(VENDOR), 20).check("Fresh.java", incari))
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsSeparateRunsSeparately() {
|
||||
String block = IntStream.range(0, 30).mapToObj(i -> "call" + i + "();").collect(Collectors.joining("\n"));
|
||||
String vendor = "class V { void a() {\n" + block + "\n} }";
|
||||
String incari =
|
||||
"class I { void a() {\n" + block + "\nfresh(); other(); stuff(); here(); and(); more(); code();\n"
|
||||
+ "fillers(); to(); break(); the(); run(); apart(); now();\n" + block + "\n} }";
|
||||
|
||||
List<CopyCheck.Finding> findings = CopyCheck.of(List.of(vendor), 20).check("I.java", incari);
|
||||
|
||||
assertThat(findings).hasSize(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tokenizerSkipsCommentsAndKeepsLiteralsWhole() {
|
||||
List<String> tokens =
|
||||
JavaTokens.tokenize("""
|
||||
package a.b; import c.D;
|
||||
/* block
|
||||
comment */ String s = "a // not a comment"; // tail
|
||||
char c = '\\''; double d = 1.5e3; var t = \"""
|
||||
text block
|
||||
\""";
|
||||
""").stream().map(JavaTokens.Token::text).toList();
|
||||
|
||||
assertThat(tokens)
|
||||
.containsSubsequence("String", "s", "=", "\"a // not a comment\"", ";")
|
||||
.contains("'\\''", "1.5e3")
|
||||
.doesNotContain("package", "import", "block", "tail");
|
||||
assertThat(tokens.stream().filter(t -> t.startsWith("\"\"\""))).hasSize(1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
# Incari's pre-commit hook: the fast checks CI would fail on. `./incari setup` installs it
|
||||
# (git config core.hooksPath tools/git-hooks). Skip once with `git commit --no-verify`.
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(git rev-parse --show-toplevel)"
|
||||
staged=$(git diff --cached --name-only --diff-filter=ACMR)
|
||||
[ -z "$staged" ] && exit 0
|
||||
|
||||
tools/ci/check-repo-content.sh
|
||||
tools/ci/check-no-publishing.sh
|
||||
|
||||
if echo "$staged" | grep -qE '\.(java|kts)$'; then
|
||||
./gradlew --quiet spotlessCheck checkModuleBoundaries
|
||||
fi
|
||||
if echo "$staged" | grep -qE '\.java$' && [ -d work/decompiled ]; then
|
||||
./incari copycheck
|
||||
fi
|
||||
if echo "$staged" | grep -qE '\.(ts|json)$|eslint\.config\.js$' && [ -d node_modules ]; then
|
||||
npm run --silent typecheck
|
||||
npm run --silent lint
|
||||
npm run --silent format:check
|
||||
fi
|
||||
if echo "$staged" | grep -qE '\.(vert|frag|comp|glsl)$'; then
|
||||
tools/ci/check-glsl.sh
|
||||
fi
|
||||
if echo "$staged" | grep -qE '^patches/'; then
|
||||
tools/ci/check-patch-budget.sh
|
||||
if [ -d work/client/.git ]; then
|
||||
./incari rebuild --check
|
||||
fi
|
||||
fi
|
||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 189 KiB |
@@ -0,0 +1,212 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Draws Incari's icon: a snow-white pine with a comet circling up it, its tail fading below.
|
||||
|
||||
python3 tools/icon/make_icon.py
|
||||
|
||||
Writes tools/icon/incari-icon.svg (the source art, 512 units square, transparent), and with
|
||||
rsvg-convert on the path, the PNGs the client reads: the window icon's sizes and the 256-pixel
|
||||
image the GUI draws the mark from (incari.client.ui.Logo), under the Incari pack; the 32-pixel
|
||||
badge glyph the incari:badge font shows before Incari players' name tags; and the page's
|
||||
favicon, the 48-pixel PNG written into app-web's index.html (so the one-file build has it too).
|
||||
|
||||
Standard library only. The trail is a cone-shaped helix around the tree, cut in short quads: SVG
|
||||
has no gradient along a path, so each quad takes its own colour, and a mask of grey quads (opaque
|
||||
in the mask, so neighbours overlap without seams) fades the tail out. Quads behind the tree are
|
||||
drawn before it, quads in front after it, over a faint dark edge so they part from the white.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import math
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
PACK = HERE.parents[1] / "client/src/main/resources/incari-pack/assets/incari/textures/gui"
|
||||
PAGE = HERE.parents[1] / "app-web/src/main/web/index.html"
|
||||
SIZES = (16, 32, 48, 128, 256)
|
||||
FAVICON = 48
|
||||
BADGE = HERE.parents[1] / "client/src/main/resources/incari-pack/assets/incari/textures/font/badge.png"
|
||||
|
||||
CX = 256
|
||||
TIP = 50
|
||||
# Each tier: its apex, its bottom and its half width.
|
||||
TIERS = [(50, 160, 66), (100, 236, 102), (160, 316, 136), (226, 392, 168)]
|
||||
|
||||
# The comet: its head's height, how far the trail drops, how many turns it makes, the head's angle,
|
||||
# how flat the orbit looks (the ellipse's minor axis over its major), and the trail's quads.
|
||||
HEAD_Y = 118
|
||||
DROP = 290
|
||||
TURNS = 2.31
|
||||
HEAD_ANGLE = math.radians(22)
|
||||
TILT = 0.28
|
||||
QUADS = 900
|
||||
EDGE = "#1d3f5c"
|
||||
|
||||
|
||||
def half_width(y):
|
||||
"""The tree's half width at a height: the cone its tiers' tips lie on."""
|
||||
return max(0, (y - TIP) / (392 - TIP) * 168)
|
||||
|
||||
|
||||
def tier_path(apex, bottom, half):
|
||||
"""A tier: flanks curving in, a bottom of drooping points."""
|
||||
d = f"M{CX},{apex} Q{CX - half * 0.28:.1f},{apex + (bottom - apex) * 0.62:.1f} {CX - half:.1f},{bottom:.1f} "
|
||||
tips = [-1, -0.5, 0, 0.5, 1]
|
||||
for x0, x1 in zip(tips, tips[1:]):
|
||||
notch = (x0 + x1) / 2
|
||||
drop = 0 if abs(x1) == 1 else 5
|
||||
d += f"L{CX + half * notch:.1f},{bottom - 20:.1f} L{CX + half * x1:.1f},{bottom + drop:.1f} "
|
||||
d += f"Q{CX + half * 0.28:.1f},{apex + (bottom - apex) * 0.62:.1f} {CX},{apex} Z"
|
||||
return d
|
||||
|
||||
|
||||
TRUNK_BOTTOM = 452
|
||||
TRUNK = f"M{CX - 20},380 L{CX + 20},380 L{CX + 24},446 Q{CX},{TRUNK_BOTTOM} {CX - 24},446 Z"
|
||||
|
||||
|
||||
def position(s):
|
||||
"""The trail at s, 0 at the tail and 1 at the head: x, y, and how far in front of the tree."""
|
||||
centre = HEAD_Y + (1 - s) * DROP
|
||||
angle = HEAD_ANGLE - (1 - s) * TURNS * 2 * math.pi
|
||||
radius = half_width(centre) * 0.88 + 58
|
||||
return CX + radius * math.cos(angle), centre + TILT * radius * math.sin(angle), math.sin(angle)
|
||||
|
||||
|
||||
def width(s):
|
||||
return 11 * s**1.5
|
||||
|
||||
|
||||
def opacity(s):
|
||||
t = min(1, s / 0.38)
|
||||
return t * t * (3 - 2 * t)
|
||||
|
||||
|
||||
def colour(s):
|
||||
stops = [(0, (178, 204, 230)), (0.55, (206, 224, 242)), (0.85, (230, 240, 250)), (1, (255, 255, 255))]
|
||||
for (s0, c0), (s1, c1) in zip(stops, stops[1:]):
|
||||
if s <= s1:
|
||||
t = (s - s0) / (s1 - s0)
|
||||
return "#%02x%02x%02x" % tuple(round(a + (b - a) * t) for a, b in zip(c0, c1))
|
||||
return "#ffffff"
|
||||
|
||||
|
||||
POINTS = [position(i / QUADS) for i in range(QUADS + 1)]
|
||||
|
||||
|
||||
def quads(pad, fill, front):
|
||||
"""The trail's quads on one side of the tree, widened by pad, each filled by fill(s)."""
|
||||
out = []
|
||||
for i in range(QUADS):
|
||||
x0, y0, f0 = POINTS[i]
|
||||
x1, y1, f1 = POINTS[i + 1]
|
||||
if (f0 + f1 > 0) != front:
|
||||
continue
|
||||
dx, dy = x1 - x0, y1 - y0
|
||||
length = math.hypot(dx, dy)
|
||||
ux, uy = dx / length, dy / length
|
||||
# Each quad a little longer than its step, so neighbours overlap.
|
||||
x0, y0, x1, y1 = x0 - ux * 0.6, y0 - uy * 0.6, x1 + ux * 0.6, y1 + uy * 0.6
|
||||
w0 = width(i / QUADS) / 2 + pad
|
||||
w1 = width((i + 1) / QUADS) / 2 + pad
|
||||
nx, ny = -uy, ux
|
||||
corners = [(x0 + nx * w0, y0 + ny * w0), (x1 + nx * w1, y1 + ny * w1),
|
||||
(x1 - nx * w1, y1 - ny * w1), (x0 - nx * w0, y0 - ny * w0)]
|
||||
path = "L".join(f"{a:.2f},{b:.2f}" for a, b in corners)
|
||||
out.append(f'<path d="M{path}Z" fill="{fill((i + 0.5) / QUADS)}"/>')
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def grey(s):
|
||||
return "#%02x%02x%02x" % ((round(255 * opacity(s)),) * 3)
|
||||
|
||||
|
||||
def trail(front):
|
||||
"""The mask, the trail and (in front only) the dark edge under it."""
|
||||
tag = "front" if front else "back"
|
||||
mask = f'<mask id="{tag}" maskUnits="userSpaceOnUse" x="0" y="0" width="512" height="512">{quads(4, grey, front)}</mask>'
|
||||
body = f'<g mask="url(#{tag})">{quads(0, colour, front)}</g>'
|
||||
edge = (f'<g mask="url(#{tag})" clip-path="url(#tree)" opacity="0.55">'
|
||||
f'{quads(2.5, lambda s: EDGE, front)}</g>')
|
||||
return mask, body, edge
|
||||
|
||||
|
||||
def svg():
|
||||
paths = [tier_path(*tier) for tier in TIERS]
|
||||
silhouette = "".join(f'<path d="{p}"/>' for p in reversed(paths))
|
||||
back_mask, back, _ = trail(False)
|
||||
front_mask, front, edge = trail(True)
|
||||
head_x, head_y, _ = POINTS[-1]
|
||||
|
||||
# Each tier shaded like a cone (cooler on the left, white right of the ridge), lit at its top,
|
||||
# and casting a soft shadow on the tier below it.
|
||||
tree = [f'<path d="{TRUNK}" fill="url(#cone)"/>',
|
||||
f'<path d="{TRUNK}" fill="#8fa8bf" fill-opacity="0.18" clip-path="url(#left)"/>',
|
||||
f'<g clip-path="url(#trunk)"><path d="{paths[-1]}" transform="translate(0 12)" fill="#3e5a73" '
|
||||
f'fill-opacity="0.3" filter="url(#soft)"/></g>']
|
||||
for i in reversed(range(len(TIERS))):
|
||||
tree.append(f'<path d="{paths[i]}" fill="url(#cone)"/>')
|
||||
tree.append(f'<path d="{paths[i]}" fill="#8fa8bf" fill-opacity="0.13" clip-path="url(#left)"/>')
|
||||
tree.append(f'<path d="{paths[i]}" fill="url(#light{i})"/>')
|
||||
if i > 0:
|
||||
tree.append(f'<g clip-path="url(#tier{i})"><path d="{paths[i - 1]}" transform="translate(0 10)" '
|
||||
f'fill="#3e5a73" fill-opacity="0.22" filter="url(#soft)"/></g>')
|
||||
tier_clips = "".join(f'<clipPath id="tier{i}"><path d="{p}"/></clipPath>' for i, p in enumerate(paths))
|
||||
lights = "".join(
|
||||
f'<linearGradient id="light{i}" gradientUnits="userSpaceOnUse" x1="0" y1="{apex}" x2="0" y2="{bottom + 5}">'
|
||||
f'<stop offset="0" stop-color="#ffffff" stop-opacity="0.35"/>'
|
||||
f'<stop offset="0.6" stop-color="#ffffff" stop-opacity="0"/>'
|
||||
f'<stop offset="1" stop-color="#6f8ca6" stop-opacity="0.12"/></linearGradient>'
|
||||
for i, (apex, bottom, _) in enumerate(TIERS))
|
||||
return f"""<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="512" height="512">
|
||||
<defs>
|
||||
<radialGradient id="halo" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#dcecf8" stop-opacity="0.9"/><stop offset="0.35" stop-color="#dcecf8" stop-opacity="0.35"/><stop offset="1" stop-color="#dcecf8" stop-opacity="0"/></radialGradient>
|
||||
<linearGradient id="cone" gradientUnits="userSpaceOnUse" x1="88" y1="0" x2="424" y2="0"><stop offset="0" stop-color="#d6e3ee"/><stop offset="0.42" stop-color="#f2f7fb"/><stop offset="0.5" stop-color="#ffffff"/><stop offset="0.75" stop-color="#ffffff"/><stop offset="1" stop-color="#edf3f8"/></linearGradient>
|
||||
{lights}
|
||||
<filter id="soft" x="-20%" y="-20%" width="140%" height="140%"><feGaussianBlur stdDeviation="6"/></filter>
|
||||
<clipPath id="tree">{silhouette}<path d="{TRUNK}"/></clipPath>
|
||||
<clipPath id="trunk"><path d="{TRUNK}"/></clipPath>
|
||||
{tier_clips}
|
||||
<clipPath id="left"><rect x="0" y="0" width="{CX}" height="512"/></clipPath>
|
||||
{back_mask}{front_mask}
|
||||
</defs>
|
||||
{back}
|
||||
{"".join(tree)}
|
||||
{edge}{front}
|
||||
<circle cx="{head_x:.1f}" cy="{head_y:.1f}" r="40" fill="url(#halo)"/>
|
||||
<circle cx="{head_x:.1f}" cy="{head_y:.1f}" r="10" fill="#ffffff"/>
|
||||
</svg>
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
source = HERE / "incari-icon.svg"
|
||||
source.write_text(svg())
|
||||
print(f"Wrote {source}")
|
||||
if shutil.which("rsvg-convert") is None:
|
||||
print("rsvg-convert isn't on the path: the PNGs weren't made")
|
||||
return
|
||||
PACK.mkdir(parents=True, exist_ok=True)
|
||||
for size in SIZES:
|
||||
png = PACK / f"icon_{size}.png"
|
||||
subprocess.run(["rsvg-convert", "-w", str(size), "-h", str(size), str(source), "-o", str(png)], check=True)
|
||||
print(f"Wrote {png}")
|
||||
# The badge, cropped so the tree runs from the glyph's top to its baseline: incari:badge's glyph
|
||||
# is 9 units with 8 above the baseline, as tall as the name tag's capitals.
|
||||
side = (TRUNK_BOTTOM - TIP) * 9 / 8
|
||||
cropped = HERE / "badge.svg"
|
||||
cropped.write_text(svg().replace('viewBox="0 0 512 512" width="512" height="512"',
|
||||
f'viewBox="{CX - side / 2:.2f} {TIP} {side:.2f} {side:.2f}" width="32" height="32"', 1))
|
||||
subprocess.run(["rsvg-convert", "-w", "32", "-h", "32", str(cropped), "-o", str(BADGE)], check=True)
|
||||
cropped.unlink()
|
||||
print(f"Wrote {BADGE}")
|
||||
favicon = base64.b64encode((PACK / f"icon_{FAVICON}.png").read_bytes()).decode()
|
||||
page = re.sub(r'<link rel="icon" href="[^"]*">', f'<link rel="icon" href="data:image/png;base64,{favicon}">',
|
||||
PAGE.read_text(), count=1)
|
||||
PAGE.write_text(page)
|
||||
print(f"Wrote the favicon into {PAGE}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,29 @@
|
||||
plugins {
|
||||
application
|
||||
}
|
||||
|
||||
// A development stand-in for Incari's online service (ADR 0058): :online's in-process fake behind a
|
||||
// real WebSocket, so the client's account screens can be tried without the real service.
|
||||
// Keeps everything in memory, checks nothing that matters, and must never face the internet. Never
|
||||
// shipped.
|
||||
|
||||
dependencies {
|
||||
implementation(testFixtures(project(":online")))
|
||||
implementation(libs.netty.buffer)
|
||||
implementation(libs.netty.transport)
|
||||
implementation(libs.netty.codec.base)
|
||||
implementation(libs.netty.codec.http)
|
||||
implementation(libs.netty.handler)
|
||||
implementation(libs.gson)
|
||||
}
|
||||
|
||||
application {
|
||||
applicationName = "incari-onlinedev"
|
||||
mainClass = "incari.tools.onlinedev.Main"
|
||||
}
|
||||
|
||||
tasks.named<JavaExec>("run") {
|
||||
// `./gradlew :tools:onlinedev:run --args="--listen 8090"`, then the page with
|
||||
// ?online=ws://localhost:8090/v1/ws, or the desktop with -Pincari.online.url=ws://localhost:8090/v1/ws.
|
||||
standardInput = System.`in`
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// A second Incari player for trying the account screens and the chat menu (ADR 0058, ADR 0059)
|
||||
// against tools/onlinedev or the online service. Signs up as <username> (password "peer password long"),
|
||||
// then runs each command in turn; events from the service are printed as they come.
|
||||
//
|
||||
// INCARI_ONLINE_URL=ws://127.0.0.1:8090/v1/ws node tools/onlinedev/peer.mjs Alex_Builds \
|
||||
// befriend:FrostTester "say:FrostTester:hello there" wait:2000
|
||||
//
|
||||
// Commands: befriend:<username>, accept (every request received), say:<friend>:<text> (waits up to
|
||||
// two minutes for the friendship), settings:<everyone|friends|nobody>,
|
||||
// presence:<serverHash>:<name>, wait:<ms>. Development only.
|
||||
import { createHash } from "node:crypto";
|
||||
const [, , username, ...commands] = process.argv;
|
||||
const ws = new WebSocket(process.env.INCARI_ONLINE_URL ?? "ws://127.0.0.1:8090/v1/ws");
|
||||
let id = 0;
|
||||
const waiting = new Map();
|
||||
const ask = (t, body = {}) => new Promise((resolve) => { const n = ++id; waiting.set(n, resolve); ws.send(JSON.stringify({ t, id: n, ...body })); });
|
||||
ws.onmessage = (e) => { const m = JSON.parse(e.data); if (m.id && waiting.has(m.id)) { waiting.get(m.id)(m); waiting.delete(m.id); } else console.log("event", e.data); };
|
||||
const zeros = (h) => { let n = 0; for (const b of h) { if (b === 0) { n += 8; continue; } n += Math.clz32(b) - 24; break; } return n; };
|
||||
const b64 = (s) => Buffer.from(s.replace(/-/g, "+").replace(/_/g, "/"), "base64");
|
||||
ws.onopen = async () => {
|
||||
await ask("hello", { v: 1, client: "peer" });
|
||||
const c = await ask("challenge");
|
||||
const ch = b64(c.challenge);
|
||||
let nonce = 0;
|
||||
for (;; nonce++) { const buf = Buffer.alloc(24); ch.copy(buf); buf.writeBigUInt64BE(BigInt(nonce), 16); const h = createHash("sha256").update(buf).digest(); if (zeros(h) >= c.bits) break; }
|
||||
const r = await ask("signup", { username, password: "peer password long", challenge: c.challenge, nonce });
|
||||
console.log("signup", r.t);
|
||||
for (const cmd of commands) {
|
||||
const [verb, ...rest] = cmd.split(":");
|
||||
if (verb === "befriend") console.log(verb, JSON.stringify(await ask("befriend", { username: rest[0] })));
|
||||
if (verb === "settings") console.log(verb, JSON.stringify(await ask("settings", { messages: rest[0] })));
|
||||
if (verb === "presence") console.log(verb, JSON.stringify(await ask("presence", { serverHash: rest[0], name: rest[1] })));
|
||||
if (verb === "wait") await new Promise((res) => setTimeout(res, Number(rest[0])));
|
||||
if (verb === "accept") { const f = await ask("friends"); for (const q of f.requests) if (q.incoming) console.log("accept", JSON.stringify(await ask("accept", { rid: q.rid }))); }
|
||||
if (verb === "say") { let fr; for (let i = 0; i < 240 && !fr; i++) { const f = await ask("friends"); fr = f.friends.find((x) => x.username.toLowerCase() === rest[0].toLowerCase()); if (!fr) await new Promise((res) => setTimeout(res, 500)); } console.log("say", JSON.stringify(await ask("send", { fid: fr.fid, text: rest.slice(1).join(":") }))); }
|
||||
}
|
||||
setTimeout(() => {}, 1 << 30);
|
||||
};
|
||||
@@ -0,0 +1,133 @@
|
||||
package incari.tools.onlinedev;
|
||||
|
||||
import incari.online.FakeService;
|
||||
import incari.platform.api.net.NetConnection;
|
||||
import io.netty.bootstrap.ServerBootstrap;
|
||||
import io.netty.channel.Channel;
|
||||
import io.netty.channel.ChannelHandlerContext;
|
||||
import io.netty.channel.ChannelInitializer;
|
||||
import io.netty.channel.EventLoopGroup;
|
||||
import io.netty.channel.MultiThreadIoEventLoopGroup;
|
||||
import io.netty.channel.SimpleChannelInboundHandler;
|
||||
import io.netty.channel.nio.NioIoHandler;
|
||||
import io.netty.channel.socket.SocketChannel;
|
||||
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
||||
import io.netty.handler.codec.http.HttpObjectAggregator;
|
||||
import io.netty.handler.codec.http.HttpServerCodec;
|
||||
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
|
||||
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Serves {@code :online}'s fake service on {@code ws://localhost:<port>/v1/ws}, one Netty thread for
|
||||
* every connection (the fake is single-threaded). Accounts, sessions and presence live in memory and
|
||||
* are gone when it stops. Sign-up's proof of work asks for {@link FakeService#BITS} bits.
|
||||
* {@code --release <version>} names a latest release in every {@code hello} answer, and each
|
||||
* {@code --note <change>} a line of its changelog.
|
||||
*/
|
||||
// Writes are fire-and-forget: a failed one closes its channel.
|
||||
@SuppressWarnings("FutureReturnValueIgnored")
|
||||
public final class Main {
|
||||
|
||||
private Main() {}
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
int port = 8090;
|
||||
String release = null;
|
||||
List<String> notes = new ArrayList<>();
|
||||
for (int i = 0; i + 1 < args.length; i++) {
|
||||
if (args[i].equals("--listen")) {
|
||||
port = Integer.parseInt(args[i + 1]);
|
||||
} else if (args[i].equals("--release")) {
|
||||
// The latest release hello names, for the title screen's update notice.
|
||||
release = args[i + 1];
|
||||
} else if (args[i].equals("--note")) {
|
||||
notes.add(args[i + 1]);
|
||||
}
|
||||
}
|
||||
FakeService service = new FakeService();
|
||||
service.announceRelease(release, notes.toArray(String[]::new));
|
||||
// One thread: the fake is used by one thread at a time.
|
||||
EventLoopGroup group = new MultiThreadIoEventLoopGroup(1, NioIoHandler.newFactory());
|
||||
Channel server = new ServerBootstrap()
|
||||
.group(group)
|
||||
.channel(NioServerSocketChannel.class)
|
||||
.childHandler(new ChannelInitializer<SocketChannel>() {
|
||||
@Override
|
||||
protected void initChannel(SocketChannel channel) {
|
||||
channel.pipeline()
|
||||
.addLast(new HttpServerCodec())
|
||||
.addLast(new HttpObjectAggregator(16 * 1024))
|
||||
.addLast(new WebSocketServerProtocolHandler("/v1/ws", null, false, 16 * 1024))
|
||||
.addLast(new Client(service));
|
||||
}
|
||||
})
|
||||
.bind("127.0.0.1", port)
|
||||
.sync()
|
||||
.channel();
|
||||
System.out.println(
|
||||
"Incari online dev service on ws://127.0.0.1:" + port + "/v1/ws (memory only; Ctrl+C stops)");
|
||||
server.closeFuture().sync();
|
||||
}
|
||||
|
||||
/** One client's WebSocket, handed to the fake as if it had opened it. */
|
||||
private static final class Client extends SimpleChannelInboundHandler<TextWebSocketFrame> {
|
||||
|
||||
private final FakeService service;
|
||||
private @Nullable NetConnection socket;
|
||||
|
||||
Client(FakeService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void userEventTriggered(ChannelHandlerContext ctx, Object event) {
|
||||
if (!(event instanceof WebSocketServerProtocolHandler.HandshakeComplete)) {
|
||||
ctx.fireUserEventTriggered(event);
|
||||
return;
|
||||
}
|
||||
Channel channel = ctx.channel();
|
||||
System.out.println("Connected: " + channel.remoteAddress());
|
||||
socket = service.openWebSocket("ws://local", new NetConnection.Listener() {
|
||||
@Override
|
||||
public void connected() {}
|
||||
|
||||
@Override
|
||||
public void received(ByteBuffer data) {}
|
||||
|
||||
@Override
|
||||
public void receivedText(String text) {
|
||||
channel.writeAndFlush(new TextWebSocketFrame(text));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void closed(@Nullable Throwable cause) {
|
||||
channel.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame frame) {
|
||||
NetConnection open = socket;
|
||||
if (open != null) {
|
||||
String text = frame.text();
|
||||
// The type only: never the message, which may hold a password.
|
||||
System.out.println("<- " + text.replaceAll("^\\{\"t\":\"([a-z]+)\".*", "$1"));
|
||||
open.sendText(text);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void channelInactive(ChannelHandlerContext ctx) {
|
||||
NetConnection open = socket;
|
||||
if (open != null) {
|
||||
service.disconnected(open);
|
||||
}
|
||||
System.out.println("Disconnected: " + ctx.channel().remoteAddress());
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
/** A development stand-in for Incari's online service (ADR 0058). Never shipped. */
|
||||
@NullMarked
|
||||
package incari.tools.onlinedev;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
@@ -0,0 +1,6 @@
|
||||
# tools/shaders
|
||||
|
||||
- Build-time only; never referenced by code that ships. May use LWJGL and the game freely.
|
||||
- Keep the manifest format in `render-webgl2`'s `shaders` package, not here: both sides must agree.
|
||||
- A shader WebGL2 can't run is recorded as unsupported with a reason, never silently dropped.
|
||||
- Test: `./gradlew :tools:shaders:check`; run for real with `./gradlew :app-web:shaders`.
|
||||
@@ -0,0 +1,28 @@
|
||||
# tools/shaders: the game's shaders, translated for WebGL2
|
||||
|
||||
Translates every shader stage the game can compile into GLSL ES 3.00 at build time (ADR 0007), so
|
||||
the browser needs no shader compiler. `./gradlew :app-web:shaders` writes
|
||||
`app-web/build/web-shaders/shaders.json` (read by `render-webgl2`) and `shaders.txt` (what was
|
||||
translated and what WebGL2 can't run). Both hold translated Mojang shaders: never committed.
|
||||
|
||||
## How it works
|
||||
|
||||
1. `GameShaderFiles` reads shader sources and post effects from the client jar.
|
||||
2. `PipelineCatalog` loads the game's pipeline registry on this JVM and lists every distinct stage.
|
||||
3. `Includes` expands includes, `SpirvCompiler` compiles with shaderc, `EsslTranslator` turns SPIR-V
|
||||
into GLSL ES with SPIRV-Cross, and `EsslRewrites` fills WebGL2's gaps (texel buffers become 2D
|
||||
textures; output arrays become separate outputs). Stages that depend on 0-to-1 depth get a
|
||||
second variant.
|
||||
4. `GlslangCheck` compiles and links each pipeline with `glslangValidator`.
|
||||
|
||||
## Invariants
|
||||
|
||||
- **Nothing here ships.**
|
||||
- **Vanilla shaders must translate.** Only missing WebGL2 features are allowed, each listed with why.
|
||||
|
||||
## How to test
|
||||
|
||||
```sh
|
||||
./gradlew :tools:shaders:check
|
||||
./gradlew :app-web:shaders # the real run (needs ./incari setup)
|
||||
```
|
||||
@@ -0,0 +1,58 @@
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
application
|
||||
}
|
||||
|
||||
// Translates the game's shaders to GLSL ES 3.00 for the browser build. Runs on a normal
|
||||
// JVM at build time, with LWJGL's shaderc and SPIRV-Cross natives, the way the desktop game does
|
||||
// at run time. Its output holds translated Mojang shaders: build output, never committed.
|
||||
|
||||
dependencies {
|
||||
// The manifest format the WebGL2 device reads, and through it the game (RenderPipelines).
|
||||
implementation(project(":render-webgl2"))
|
||||
implementation(project(":client"))
|
||||
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testImplementation(libs.assertj)
|
||||
testRuntimeOnly(libs.junit.launcher)
|
||||
}
|
||||
|
||||
val repoRoot = rootProject.layout.projectDirectory
|
||||
val minecraftVersion: String = Properties().run {
|
||||
repoRoot.file("incari.properties").asFile.reader().use { load(it) }
|
||||
getProperty("minecraft.version")
|
||||
}
|
||||
|
||||
/** This machine's LWJGL natives (shaderc and SPIRV-Cross among them), as `incari fetch` got them. */
|
||||
val nativeJars = run {
|
||||
val root = repoRoot.asFile
|
||||
providers.fileContents(repoRoot.file("work/cache/versions/$minecraftVersion/natives.txt")).asText.map { text ->
|
||||
text.lines().filter { it.isNotBlank() }.map { root.resolve(it.trim()) }
|
||||
}.orElse(emptyList())
|
||||
}
|
||||
|
||||
dependencies {
|
||||
runtimeOnly(files(nativeJars))
|
||||
}
|
||||
|
||||
application {
|
||||
applicationName = "incari-shaders"
|
||||
mainClass = "incari.tools.shaders.Main"
|
||||
applicationDefaultJvmArgs = listOf(
|
||||
"--enable-native-access=ALL-UNNAMED",
|
||||
"-Dorg.lwjgl.system.SharedLibraryExtractPath=${repoRoot.dir("work/natives/lwjgl").asFile}",
|
||||
)
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
// Game classes loaded by tests write logs/ into the working directory; keep that in build/.
|
||||
val runDir = layout.buildDirectory.dir("test-run").get().asFile
|
||||
workingDir = runDir
|
||||
jvmArgs(
|
||||
"--enable-native-access=ALL-UNNAMED",
|
||||
"-Dorg.lwjgl.system.SharedLibraryExtractPath=${repoRoot.dir("work/natives/lwjgl").asFile}",
|
||||
)
|
||||
doFirst { runDir.mkdirs() }
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import incari.platform.api.Platform;
|
||||
import incari.platform.api.Platforms;
|
||||
import incari.platform.api.threads.PlatformThreads;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
/**
|
||||
* The platform the game sees while this tool lists its pipelines. Loading {@code RenderPipelines}
|
||||
* runs the game's static initializers, and {@code Util}'s asks the platform how many background
|
||||
* threads to make; nothing else is reached. Everything else fails loudly, so a future game version
|
||||
* that reaches further at class-load time shows up here rather than half-working.
|
||||
*/
|
||||
final class BuildPlatform {
|
||||
|
||||
private BuildPlatform() {}
|
||||
|
||||
static void install() {
|
||||
if (Platforms.isInstalled()) {
|
||||
return;
|
||||
}
|
||||
PlatformThreads inline = suggested -> 0;
|
||||
Platform platform = (Platform) Proxy.newProxyInstance(
|
||||
Platform.class.getClassLoader(),
|
||||
new Class<?>[] {Platform.class},
|
||||
(proxy, method, args) -> switch (method.getName()) {
|
||||
case "threads" -> inline;
|
||||
case "description" -> "Build-time shader translation (no game running)";
|
||||
case "nanoTime" -> System.nanoTime();
|
||||
case "toString" -> "BuildPlatform";
|
||||
default ->
|
||||
throw new UnsupportedOperationException("The shader tool's platform has no " + method.getName()
|
||||
+ "(); the game reached it while its pipelines were listed");
|
||||
});
|
||||
Platforms.install(platform);
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import incari.render.webgl2.shaders.TexelBuffers;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Rewrites of SPIRV-Cross's GLSL ES output for what GLSL ES 3.00 lacks and desktop GLSL has.
|
||||
* Pure text transforms on the translated source, whose shape SPIRV-Cross fixes (one declaration per
|
||||
* line, {@code void main()} on a line of its own), so they're tested without the natives.
|
||||
*/
|
||||
final class EsslRewrites {
|
||||
|
||||
private static final String MAIN = "void main()";
|
||||
private static final String RENAMED_MAIN = "void incari_main()";
|
||||
|
||||
// SPIRV-Cross: "layout(location = 0) out highp vec4 coeff[2];"
|
||||
private static final Pattern OUTPUT_ARRAY =
|
||||
Pattern.compile("layout\\(location = (\\d+)\\) out ((?:highp |mediump |lowp )?\\w+) (\\w+)\\[(\\d+)\\];");
|
||||
|
||||
private EsslRewrites() {}
|
||||
|
||||
/**
|
||||
* Texel buffers as 2D textures ({@link TexelBuffers}): each {@code [iu]samplerBuffer} named
|
||||
* becomes a {@code [iu]sampler2D}, and each {@code texelFetch(name, i)} reads the texel at
|
||||
* {@code (i % WIDTH, i / WIDTH)}, level 0. Also drops the texture-buffer extension SPIRV-Cross
|
||||
* asks for.
|
||||
*/
|
||||
static String texelBuffers(String glsl, List<String> names) {
|
||||
if (names.isEmpty()) {
|
||||
return glsl;
|
||||
}
|
||||
String result = glsl.replaceAll("(?m)^#extension GL_(OES|EXT)_texture_buffer : (require|enable)\\n", "");
|
||||
for (String name : names) {
|
||||
Pattern declaration = Pattern.compile(
|
||||
"uniform ((?:highp |mediump |lowp )?)([iu]?)samplerBuffer " + Pattern.quote(name) + ";");
|
||||
Matcher matcher = declaration.matcher(result);
|
||||
if (!matcher.find()) {
|
||||
throw new IllegalStateException("No samplerBuffer declaration of " + name + " in:\n" + glsl);
|
||||
}
|
||||
result = matcher.replaceFirst(Matcher.quoteReplacement("uniform highp " + matcher.group(2) + "sampler2D "
|
||||
+ name + ";\nivec2 incari_texel_" + name + "(int i)\n{\n return ivec2(i & "
|
||||
+ (TexelBuffers.WIDTH - 1) + ", i >> " + TexelBuffers.WIDTH_SHIFT + ");\n}"));
|
||||
result = rewriteFetches(result, name);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static String rewriteFetches(String glsl, String name) {
|
||||
String call = "texelFetch(" + name + ", ";
|
||||
StringBuilder out = new StringBuilder();
|
||||
int from = 0;
|
||||
while (true) {
|
||||
int start = glsl.indexOf(call, from);
|
||||
if (start < 0) {
|
||||
break;
|
||||
}
|
||||
int argument = start + call.length();
|
||||
int end = closingParenthesis(glsl, argument);
|
||||
out.append(glsl, from, start)
|
||||
.append("texelFetch(")
|
||||
.append(name)
|
||||
.append(", incari_texel_")
|
||||
.append(name)
|
||||
.append('(')
|
||||
.append(glsl, argument, end)
|
||||
.append("), 0)");
|
||||
from = end + 1;
|
||||
}
|
||||
return out.append(glsl, from, glsl.length()).toString();
|
||||
}
|
||||
|
||||
/** The index of the parenthesis that closes a call whose arguments start at {@code from}. */
|
||||
private static int closingParenthesis(String glsl, int from) {
|
||||
int depth = 0;
|
||||
for (int i = from; i < glsl.length(); i++) {
|
||||
char c = glsl.charAt(i);
|
||||
if (c == '(') {
|
||||
depth++;
|
||||
} else if (c == ')') {
|
||||
if (depth == 0) {
|
||||
return i;
|
||||
}
|
||||
depth--;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("Unbalanced texelFetch call in translated shader");
|
||||
}
|
||||
|
||||
/**
|
||||
* Fragment output arrays as separate outputs. GLSL ES 3.00 only lets a fragment shader index an
|
||||
* output array with a constant, and the game's order-independent transparency writes
|
||||
* {@code coeff[attachmentIndex]} in a loop. The array becomes a private global the shader writes
|
||||
* as before, and a new {@code main} copies each element to an output of its own at the element's
|
||||
* location after the game's {@code main} returns (a {@code discard} still discards).
|
||||
*/
|
||||
static String fragmentOutputArrays(String glsl) {
|
||||
Matcher matcher = OUTPUT_ARRAY.matcher(glsl);
|
||||
List<String> copies = new ArrayList<>();
|
||||
StringBuilder out = new StringBuilder();
|
||||
while (matcher.find()) {
|
||||
int location = Integer.parseInt(matcher.group(1));
|
||||
String type = matcher.group(2);
|
||||
String name = matcher.group(3);
|
||||
int length = Integer.parseInt(matcher.group(4));
|
||||
StringBuilder replacement = new StringBuilder();
|
||||
for (int i = 0; i < length; i++) {
|
||||
String output = "incari_out_" + name + "_" + i;
|
||||
replacement
|
||||
.append("layout(location = ")
|
||||
.append(location + i)
|
||||
.append(") out ")
|
||||
.append(type)
|
||||
.append(' ')
|
||||
.append(output)
|
||||
.append(";\n");
|
||||
copies.add(" " + output + " = " + name + "[" + i + "];\n");
|
||||
}
|
||||
replacement
|
||||
.append(type)
|
||||
.append(' ')
|
||||
.append(name)
|
||||
.append('[')
|
||||
.append(length)
|
||||
.append("];");
|
||||
matcher.appendReplacement(out, Matcher.quoteReplacement(replacement.toString()));
|
||||
}
|
||||
if (copies.isEmpty()) {
|
||||
return glsl;
|
||||
}
|
||||
matcher.appendTail(out);
|
||||
String result = out.toString();
|
||||
if (!result.contains(MAIN + "\n")) {
|
||||
throw new IllegalStateException("No main() in translated shader:\n" + glsl);
|
||||
}
|
||||
result = result.replace(MAIN + "\n", RENAMED_MAIN + "\n");
|
||||
return result + "\n" + MAIN + "\n{\n incari_main();\n" + String.join("", copies) + "}\n\n";
|
||||
}
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import java.nio.IntBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.lwjgl.PointerBuffer;
|
||||
import org.lwjgl.system.MemoryStack;
|
||||
import org.lwjgl.system.MemoryUtil;
|
||||
import org.lwjgl.util.spvc.Spvc;
|
||||
import org.lwjgl.util.spvc.SpvcReflectedResource;
|
||||
|
||||
/**
|
||||
* SPIR-V to GLSL ES 3.00 with SPIRV-Cross, plus the reflection the WebGL2 device needs.
|
||||
*
|
||||
* <p>WebGL2 changes three things about how a program is wired, and the translation follows them:
|
||||
* <ul>
|
||||
* <li>ES 3.00 has no {@code layout(binding)} and no locations on the varyings between stages,
|
||||
* which match by name there. The game's stages match by location, so both sides of each
|
||||
* varying are renamed after its location ({@code incari_io_3}).
|
||||
* <li>Uniform blocks and samplers keep the game's names, which are the pipeline's uniform
|
||||
* names: the device binds them by name when it links the program.
|
||||
* <li>Vertex inputs keep their names and locations; the device matches them to the vertex
|
||||
* format's elements by name, as the game's own pipeline builder does.
|
||||
* </ul>
|
||||
* WebGL2 has no storage buffers or push constants; a stage using one is reported unsupported
|
||||
* rather than translated wrongly. Texel buffers and fragment output arrays, which GLSL ES 3.00
|
||||
* lacks too, are rewritten ({@link EsslRewrites}).
|
||||
*/
|
||||
final class EsslTranslator {
|
||||
|
||||
// SPIR-V enum values (the SPIR-V specification's, as LWJGL passes them through).
|
||||
private static final int DECORATION_LOCATION = 30;
|
||||
private static final int DIM_2D = 1;
|
||||
private static final int DIM_CUBE = 3;
|
||||
private static final int DIM_BUFFER = 5;
|
||||
|
||||
/** The prefix of the varyings' shared names; the location follows. */
|
||||
static final String VARYING_PREFIX = "incari_io_";
|
||||
|
||||
/** The prefix of uniform block instance names; the block's name follows. */
|
||||
static final String BLOCK_PREFIX = "incari_ubo_";
|
||||
|
||||
private EsslTranslator() {}
|
||||
|
||||
static TranslatedStage translate(String key, String sourceHash, int[] spirv, ShaderType type)
|
||||
throws ShaderException {
|
||||
try (MemoryStack stack = MemoryStack.stackPush()) {
|
||||
PointerBuffer out = stack.mallocPointer(1);
|
||||
check(0, Spvc.spvc_context_create(out), "create a context");
|
||||
long context = out.get(0);
|
||||
try {
|
||||
IntBuffer words =
|
||||
MemoryUtil.memAllocInt(spirv.length).put(spirv).flip();
|
||||
try {
|
||||
check(context, Spvc.spvc_context_parse_spirv(context, words, spirv.length, out), "parse SPIR-V");
|
||||
} finally {
|
||||
MemoryUtil.memFree(words);
|
||||
}
|
||||
long ir = out.get(0);
|
||||
check(
|
||||
context,
|
||||
Spvc.spvc_context_create_compiler(
|
||||
context, Spvc.SPVC_BACKEND_GLSL, ir, Spvc.SPVC_CAPTURE_MODE_TAKE_OWNERSHIP, out),
|
||||
"create a GLSL compiler");
|
||||
long compiler = out.get(0);
|
||||
check(context, Spvc.spvc_compiler_create_shader_resources(compiler, out), "list resources");
|
||||
long resources = out.get(0);
|
||||
|
||||
String unsupported = unsupportedResources(compiler, resources, stack);
|
||||
if (unsupported != null) {
|
||||
return TranslatedStage.unsupported(key, sourceHash, unsupported);
|
||||
}
|
||||
List<TranslatedStage.Attribute> attributes = new ArrayList<>();
|
||||
if (type == ShaderType.VERTEX) {
|
||||
for (SpvcReflectedResource input : list(resources, Spvc.SPVC_RESOURCE_TYPE_STAGE_INPUT, stack)) {
|
||||
long handle = Spvc.spvc_compiler_get_type_handle(compiler, input.type_id());
|
||||
int baseType = Spvc.spvc_type_get_basetype(handle);
|
||||
attributes.add(new TranslatedStage.Attribute(
|
||||
input.nameString(),
|
||||
Spvc.spvc_compiler_get_decoration(compiler, input.id(), DECORATION_LOCATION),
|
||||
baseType == Spvc.SPVC_BASETYPE_INT32 || baseType == Spvc.SPVC_BASETYPE_UINT32));
|
||||
}
|
||||
renameVaryings(compiler, list(resources, Spvc.SPVC_RESOURCE_TYPE_STAGE_OUTPUT, stack));
|
||||
} else {
|
||||
renameVaryings(compiler, list(resources, Spvc.SPVC_RESOURCE_TYPE_STAGE_INPUT, stack));
|
||||
}
|
||||
List<String> blocks = new ArrayList<>();
|
||||
for (SpvcReflectedResource block : list(resources, Spvc.SPVC_RESOURCE_TYPE_UNIFORM_BUFFER, stack)) {
|
||||
blocks.add(block.nameString());
|
||||
// The same block gets the same instance name in both stages; SPIRV-Cross would
|
||||
// number them per stage, which the linker only tolerates.
|
||||
Spvc.spvc_compiler_set_name(compiler, block.id(), BLOCK_PREFIX + block.nameString());
|
||||
}
|
||||
List<String> samplers = new ArrayList<>();
|
||||
List<String> texelBuffers = new ArrayList<>();
|
||||
for (SpvcReflectedResource sampler : list(resources, Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE, stack)) {
|
||||
samplers.add(sampler.nameString());
|
||||
long handle = Spvc.spvc_compiler_get_type_handle(compiler, sampler.type_id());
|
||||
if (Spvc.spvc_type_get_image_dimension(handle) == DIM_BUFFER) {
|
||||
texelBuffers.add(sampler.nameString());
|
||||
}
|
||||
}
|
||||
|
||||
check(context, Spvc.spvc_compiler_create_compiler_options(compiler, out), "create options");
|
||||
long options = out.get(0);
|
||||
Spvc.spvc_compiler_options_set_uint(options, Spvc.SPVC_COMPILER_OPTION_GLSL_VERSION, 300);
|
||||
Spvc.spvc_compiler_options_set_bool(options, Spvc.SPVC_COMPILER_OPTION_GLSL_ES, true);
|
||||
// The game's shaders were written for desktop GLSL, where everything is highp.
|
||||
Spvc.spvc_compiler_options_set_bool(
|
||||
options, Spvc.SPVC_COMPILER_OPTION_GLSL_ES_DEFAULT_FLOAT_PRECISION_HIGHP, true);
|
||||
Spvc.spvc_compiler_options_set_bool(
|
||||
options, Spvc.SPVC_COMPILER_OPTION_GLSL_ES_DEFAULT_INT_PRECISION_HIGHP, true);
|
||||
// WebGL2 can't draw from a base instance, and the device says so (nonZeroFirstInstance).
|
||||
Spvc.spvc_compiler_options_set_bool(
|
||||
options, Spvc.SPVC_COMPILER_OPTION_GLSL_SUPPORT_NONZERO_BASE_INSTANCE, false);
|
||||
Spvc.spvc_compiler_options_set_bool(
|
||||
options, Spvc.SPVC_COMPILER_OPTION_GLSL_SEPARATE_SHADER_OBJECTS, false);
|
||||
Spvc.spvc_compiler_options_set_bool(
|
||||
options, Spvc.SPVC_COMPILER_OPTION_GLSL_ENABLE_420PACK_EXTENSION, false);
|
||||
check(context, Spvc.spvc_compiler_install_compiler_options(compiler, options), "set options");
|
||||
check(context, Spvc.spvc_compiler_compile(compiler, out), "translate");
|
||||
String glsl = EsslRewrites.texelBuffers(MemoryUtil.memUTF8(out.get(0)), texelBuffers);
|
||||
if (type == ShaderType.FRAGMENT) {
|
||||
glsl = EsslRewrites.fragmentOutputArrays(glsl);
|
||||
}
|
||||
return new TranslatedStage(key, sourceHash, glsl, attributes, blocks, samplers, null);
|
||||
} finally {
|
||||
Spvc.spvc_context_destroy(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Why WebGL2 can't run the stage yet, or null if it can. */
|
||||
private static @Nullable String unsupportedResources(long compiler, long resources, MemoryStack stack)
|
||||
throws ShaderException {
|
||||
if (!list(resources, Spvc.SPVC_RESOURCE_TYPE_PUSH_CONSTANT, stack).isEmpty()) {
|
||||
return "push constants (WebGL2 has none; emulating them is future work)";
|
||||
}
|
||||
if (!list(resources, Spvc.SPVC_RESOURCE_TYPE_STORAGE_BUFFER, stack).isEmpty()) {
|
||||
return "storage buffers (not in WebGL2)";
|
||||
}
|
||||
if (!list(resources, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_IMAGE, stack).isEmpty()
|
||||
|| !list(resources, Spvc.SPVC_RESOURCE_TYPE_SEPARATE_SAMPLERS, stack)
|
||||
.isEmpty()) {
|
||||
return "separate images and samplers (not in GLSL ES)";
|
||||
}
|
||||
for (SpvcReflectedResource sampler : list(resources, Spvc.SPVC_RESOURCE_TYPE_SAMPLED_IMAGE, stack)) {
|
||||
int dimension =
|
||||
Spvc.spvc_type_get_image_dimension(Spvc.spvc_compiler_get_type_handle(compiler, sampler.type_id()));
|
||||
if (dimension != DIM_2D && dimension != DIM_CUBE && dimension != DIM_BUFFER) {
|
||||
return "sampler " + sampler.nameString() + " of SPIR-V dimension " + dimension;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void renameVaryings(long compiler, List<SpvcReflectedResource> varyings) {
|
||||
for (SpvcReflectedResource varying : varyings) {
|
||||
int location = Spvc.spvc_compiler_get_decoration(compiler, varying.id(), DECORATION_LOCATION);
|
||||
Spvc.spvc_compiler_set_name(compiler, varying.id(), VARYING_PREFIX + location);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<SpvcReflectedResource> list(long resources, int type, MemoryStack stack)
|
||||
throws ShaderException {
|
||||
PointerBuffer list = stack.mallocPointer(1);
|
||||
PointerBuffer count = stack.mallocPointer(1);
|
||||
check(0, Spvc.spvc_resources_get_resource_list_for_type(resources, type, list, count), "list resources");
|
||||
List<SpvcReflectedResource> result = new ArrayList<>();
|
||||
SpvcReflectedResource.Buffer buffer = SpvcReflectedResource.create(list.get(0), (int) count.get(0));
|
||||
for (int i = 0; i < count.get(0); i++) {
|
||||
result.add(buffer.get(i));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void check(long context, int result, String what) throws ShaderException {
|
||||
if (result != Spvc.SPVC_SUCCESS) {
|
||||
String detail = context == 0 ? "" : ": " + Spvc.spvc_context_get_last_error_string(context);
|
||||
throw new ShaderException("SPIRV-Cross couldn't " + what + " (error " + result + ")" + detail);
|
||||
}
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The shader files in the game's jar, named the way the game names them at run time: a stage by
|
||||
* the file's id without extension ({@code minecraft:core/gui}), an include by its file name under
|
||||
* {@code shaders/include} ({@code minecraft:globals.glsl}), a post effect by its file name under
|
||||
* {@code post_effect} ({@code minecraft:blur}).
|
||||
*/
|
||||
final class GameShaderFiles {
|
||||
|
||||
private final Map<String, String> vertex = new HashMap<>();
|
||||
private final Map<String, String> fragment = new HashMap<>();
|
||||
private final Map<String, String> includes = new HashMap<>();
|
||||
private final Map<String, String> postEffects = new TreeMap<>();
|
||||
|
||||
static GameShaderFiles read(Path clientJar) throws IOException {
|
||||
GameShaderFiles files = new GameShaderFiles();
|
||||
try (ZipFile jar = new ZipFile(clientJar.toFile())) {
|
||||
Enumeration<? extends ZipEntry> entries = jar.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
if (!entry.isDirectory()) {
|
||||
files.add(entry.getName(), jar, entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
private void add(String name, ZipFile jar, ZipEntry entry) throws IOException {
|
||||
// assets/<namespace>/<path>
|
||||
String[] parts = name.split("/", 3);
|
||||
if (parts.length < 3 || !parts[0].equals("assets")) {
|
||||
return;
|
||||
}
|
||||
String namespace = parts[1];
|
||||
String path = parts[2];
|
||||
if (path.startsWith("shaders/include/") && path.endsWith(".glsl")) {
|
||||
includes.put(namespace + ":" + path.substring("shaders/include/".length()), text(jar, entry));
|
||||
} else if (path.startsWith("shaders/") && path.endsWith(".vsh")) {
|
||||
vertex.put(namespace + ":" + strip(path, "shaders/", ".vsh"), text(jar, entry));
|
||||
} else if (path.startsWith("shaders/") && path.endsWith(".fsh")) {
|
||||
fragment.put(namespace + ":" + strip(path, "shaders/", ".fsh"), text(jar, entry));
|
||||
} else if (path.startsWith("post_effect/") && path.endsWith(".json")) {
|
||||
postEffects.put(namespace + ":" + strip(path, "post_effect/", ".json"), text(jar, entry));
|
||||
}
|
||||
}
|
||||
|
||||
private static String strip(String path, String prefix, String suffix) {
|
||||
return path.substring(prefix.length(), path.length() - suffix.length());
|
||||
}
|
||||
|
||||
private static String text(ZipFile jar, ZipEntry entry) throws IOException {
|
||||
try (InputStream in = jar.getInputStream(entry)) {
|
||||
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
|
||||
@Nullable
|
||||
String shader(ShaderType type, String id) {
|
||||
return (type == ShaderType.VERTEX ? vertex : fragment).get(id);
|
||||
}
|
||||
|
||||
Map<String, String> includes() {
|
||||
return includes;
|
||||
}
|
||||
|
||||
/** Post effect JSON by id, sorted. */
|
||||
Map<String, String> postEffects() {
|
||||
return postEffects;
|
||||
}
|
||||
|
||||
int shaderCount() {
|
||||
return vertex.size() + fragment.size();
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Checks translated GLSL ES with glslang ({@code glslangValidator}), the reference front end: each
|
||||
* vertex and fragment pair is compiled and linked as one ES 3.00 program, which also catches
|
||||
* varyings that don't line up between the stages. It checks the language only; what a particular
|
||||
* browser's compiler accepts is checked when the device links the programs in the page.
|
||||
*/
|
||||
final class GlslangCheck implements AutoCloseable {
|
||||
|
||||
private final Path validator;
|
||||
private final Path scratch;
|
||||
private int files;
|
||||
|
||||
GlslangCheck(Path validator) throws IOException {
|
||||
this.validator = validator;
|
||||
this.scratch = Files.createTempDirectory("incari-shaders");
|
||||
}
|
||||
|
||||
/** Compiles and links one program; returns glslang's complaint, or null if it's valid. */
|
||||
@Nullable
|
||||
String link(String vertexGlsl, String fragmentGlsl) throws IOException, InterruptedException {
|
||||
// glslang picks the stage from the extension.
|
||||
Path vertex = scratch.resolve("s" + files + ".vert");
|
||||
Path fragment = scratch.resolve("s" + files + ".frag");
|
||||
files++;
|
||||
Files.writeString(vertex, vertexGlsl, StandardCharsets.UTF_8);
|
||||
Files.writeString(fragment, fragmentGlsl, StandardCharsets.UTF_8);
|
||||
Process process = new ProcessBuilder(validator.toString(), "-l", vertex.toString(), fragment.toString())
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
if (!process.waitFor(60, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
return "glslangValidator timed out";
|
||||
}
|
||||
Files.delete(vertex);
|
||||
Files.delete(fragment);
|
||||
if (process.exitValue() == 0) {
|
||||
return null;
|
||||
}
|
||||
return output.strip();
|
||||
}
|
||||
|
||||
/**
|
||||
* A GLSL ES restriction that desktop GLSL doesn't have, found in glslang's output.
|
||||
*
|
||||
* @param what the construct ES lacks, for the report
|
||||
* @param vertex whether the vertex stage (rather than the fragment stage) uses it
|
||||
*/
|
||||
record EsLimit(String what, boolean vertex) {}
|
||||
|
||||
// glslang: "ERROR: <file>.frag:113: 'variable indexing fragment shader output array' : not
|
||||
// supported with this profile: es"
|
||||
private static final Pattern ES_LIMIT =
|
||||
Pattern.compile("ERROR: \\S+\\.(vert|frag):\\d+: '([^']+)' : not supported with this profile: es");
|
||||
|
||||
/** The ES-only restriction that {@code problem} (glslang's output) reports, or null for any other error. */
|
||||
static @Nullable EsLimit esLimit(String problem) {
|
||||
Matcher matcher = ES_LIMIT.matcher(problem);
|
||||
return matcher.find() ? new EsLimit(matcher.group(2), matcher.group(1).equals("vert")) : null;
|
||||
}
|
||||
|
||||
/** glslangValidator from the path, or null if it isn't installed. */
|
||||
static @Nullable Path find() {
|
||||
for (String dir : System.getenv().getOrDefault("PATH", "").split(File.pathSeparator, -1)) {
|
||||
if (dir.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
Path candidate = Path.of(dir, "glslangValidator");
|
||||
if (Files.isExecutable(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
Files.deleteIfExists(scratch);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Expands the game's {@code #include <namespace:file.glsl>} lines in place, as shaderc's include
|
||||
* callback does for the desktop game. Every include is inserted where it stands, even inside a
|
||||
* disabled {@code #if}: the preprocessor drops it afterwards, and the files carry their own
|
||||
* include guards, so the result compiles the same.
|
||||
*/
|
||||
final class Includes {
|
||||
|
||||
private static final Pattern INCLUDE = Pattern.compile("^\\s*#\\s*include\\s*[<\"]([^>\"]+)[>\"]\\s*$");
|
||||
|
||||
/** Deeper than any real chain; only a cycle gets here. */
|
||||
private static final int MAX_DEPTH = 32;
|
||||
|
||||
private Includes() {}
|
||||
|
||||
static String expand(String source, Map<String, String> includes) throws ShaderException {
|
||||
StringBuilder out = new StringBuilder(source.length() * 2);
|
||||
expand(source, includes, out, 0);
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static void expand(String source, Map<String, String> includes, StringBuilder out, int depth)
|
||||
throws ShaderException {
|
||||
if (depth > MAX_DEPTH) {
|
||||
throw new ShaderException("Includes nest deeper than " + MAX_DEPTH + "; is there a cycle?");
|
||||
}
|
||||
for (String line : source.split("\n", -1)) {
|
||||
Matcher include = INCLUDE.matcher(line);
|
||||
if (!include.matches()) {
|
||||
out.append(line).append('\n');
|
||||
continue;
|
||||
}
|
||||
String id = include.group(1);
|
||||
String name = id.indexOf(':') >= 0 ? id : "minecraft:" + id;
|
||||
String included = includes.get(name);
|
||||
if (included == null) {
|
||||
throw new ShaderException("Include not found: " + id);
|
||||
}
|
||||
expand(included, includes, out, depth + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import incari.render.webgl2.shaders.ShaderManifest;
|
||||
import incari.render.webgl2.shaders.ShaderStageKey;
|
||||
import incari.render.webgl2.shaders.SourceHash;
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
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.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import net.minecraft.client.renderer.ShaderDefines;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Translates every shader stage the game can compile to GLSL ES 3.00 and writes the manifest the
|
||||
* WebGL2 device reads ({@code shaders.json}), with a report of what it did beside it
|
||||
* ({@code shaders.txt}).
|
||||
*
|
||||
* <pre>
|
||||
* incari-shaders --client-jar <jar> --minecraft <version> --out <shaders.json>
|
||||
* [--require-glslang]
|
||||
* </pre>
|
||||
*
|
||||
* Fails if a vanilla shader doesn't compile or translate, or if glslang rejects a translated
|
||||
* program. A stage WebGL2 can't run yet (a texel buffer, say) isn't a failure: it's written as
|
||||
* unsupported, listed in the report, and the device skips that pipeline's draws.
|
||||
*/
|
||||
public final class Main {
|
||||
|
||||
private Main() {}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
System.exit(run(args));
|
||||
} catch (UsageException e) {
|
||||
System.err.println("error: " + e.getMessage());
|
||||
System.exit(2);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
static int run(String[] args) throws IOException, InterruptedException, UsageException {
|
||||
@Nullable Path clientJar = null;
|
||||
@Nullable Path out = null;
|
||||
String minecraft = "";
|
||||
boolean requireGlslang = false;
|
||||
for (int i = 0; i < args.length; i++) {
|
||||
switch (args[i]) {
|
||||
case "--client-jar" -> clientJar = Path.of(value(args, ++i));
|
||||
case "--out" -> out = Path.of(value(args, ++i));
|
||||
case "--minecraft" -> minecraft = value(args, ++i);
|
||||
case "--require-glslang" -> requireGlslang = true;
|
||||
default -> throw new UsageException("Unknown option '" + args[i] + "'");
|
||||
}
|
||||
}
|
||||
if (clientJar == null || out == null || minecraft.isEmpty()) {
|
||||
throw new UsageException("Usage: incari-shaders --client-jar <jar> --minecraft <version> --out <file>"
|
||||
+ " [--require-glslang]");
|
||||
}
|
||||
|
||||
GameShaderFiles files = GameShaderFiles.read(clientJar);
|
||||
List<PipelineCatalog.Pipeline> pipelines;
|
||||
try {
|
||||
pipelines = PipelineCatalog.collect(files);
|
||||
} catch (ShaderException e) {
|
||||
System.err.println("error: " + e.getMessage());
|
||||
return 1;
|
||||
}
|
||||
|
||||
Map<String, TranslatedStage> stages = new TreeMap<>();
|
||||
List<String> errors = new ArrayList<>();
|
||||
try (SpirvCompiler compiler = new SpirvCompiler()) {
|
||||
for (PipelineCatalog.Pipeline pipeline : pipelines) {
|
||||
for (ShaderStageKey key : List.of(pipeline.vertex(), pipeline.fragment())) {
|
||||
if (stages.containsKey(key.asString())) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
TranslatedStage plain = translate(files, compiler, key, pipeline.defines(), false);
|
||||
stages.put(key.asString(), plain);
|
||||
// A device with clip control (0-to-1 depth, as the game's desktop backends
|
||||
// set up) compiles the game's shaders with one more define; a stage it
|
||||
// changes gets a second translation (ADR 0012). Only the order-independent
|
||||
// transparency passes read it, but every stage that includes their file
|
||||
// mentions it, so the translations are compared rather than the sources.
|
||||
if (readsZeroToOne(files, key)) {
|
||||
TranslatedStage zeroToOne = translate(files, compiler, key, pipeline.defines(), true);
|
||||
if (!zeroToOne.glsl().equals(plain.glsl())) {
|
||||
stages.put(zeroToOne.key(), zeroToOne);
|
||||
}
|
||||
}
|
||||
} catch (ShaderException e) {
|
||||
errors.add(key + " (first used by " + pipeline.name() + "): " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Path glslang = GlslangCheck.find();
|
||||
int linked = 0;
|
||||
Map<String, String> unsupportedPipelines = new LinkedHashMap<>();
|
||||
if (glslang == null && requireGlslang) {
|
||||
errors.add("glslangValidator isn't installed (package: glslang), and --require-glslang was given");
|
||||
}
|
||||
try (GlslangCheck check = glslang == null ? null : new GlslangCheck(glslang)) {
|
||||
for (PipelineCatalog.Pipeline pipeline : pipelines) {
|
||||
String vertexVariant = pipeline.vertex()
|
||||
.withFlag(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE)
|
||||
.asString();
|
||||
String fragmentVariant = pipeline.fragment()
|
||||
.withFlag(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE)
|
||||
.asString();
|
||||
boolean hasVariant = stages.containsKey(vertexVariant) || stages.containsKey(fragmentVariant);
|
||||
for (boolean zeroToOne : hasVariant ? new boolean[] {false, true} : new boolean[] {false}) {
|
||||
TranslatedStage vertex = stages.get(pipeline.vertex().asString());
|
||||
TranslatedStage fragment = stages.get(pipeline.fragment().asString());
|
||||
if (zeroToOne) {
|
||||
vertex = stages.getOrDefault(vertexVariant, vertex);
|
||||
fragment = stages.getOrDefault(fragmentVariant, fragment);
|
||||
}
|
||||
if (vertex == null || fragment == null) {
|
||||
continue; // Already an error.
|
||||
}
|
||||
if (check != null && vertex.isSupported() && fragment.isSupported()) {
|
||||
linked += check(check, pipeline, vertex, fragment, stages, errors);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (PipelineCatalog.Pipeline pipeline : pipelines) {
|
||||
TranslatedStage vertex = stages.get(pipeline.vertex().asString());
|
||||
TranslatedStage fragment = stages.get(pipeline.fragment().asString());
|
||||
if (vertex == null || fragment == null) {
|
||||
continue; // Already an error.
|
||||
}
|
||||
String unsupported = vertex.unsupported() != null ? vertex.unsupported() : fragment.unsupported();
|
||||
if (unsupported != null) {
|
||||
unsupportedPipelines.put(pipeline.name(), unsupported);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
StringBuilder report = new StringBuilder();
|
||||
report.append("Shaders for WebGL2 (GLSL ES 3.00), translated from Minecraft ")
|
||||
.append(minecraft)
|
||||
.append('\n');
|
||||
report.append(pipelines.size())
|
||||
.append(" pipelines, ")
|
||||
.append(stages.size())
|
||||
.append(" distinct stages, ")
|
||||
.append(files.shaderCount())
|
||||
.append(" shader files in the jar\n");
|
||||
report.append(
|
||||
glslang == null
|
||||
? "Not checked with glslang (glslangValidator isn't installed)\n"
|
||||
: linked + " programs compiled and linked by glslang (with the 0-to-1 depth variants)\n");
|
||||
report.append('\n')
|
||||
.append(unsupportedPipelines.size())
|
||||
.append(" pipelines WebGL2 can't run yet (their draws are skipped):\n");
|
||||
unsupportedPipelines.forEach((name, reason) ->
|
||||
report.append(" ").append(name).append(": ").append(reason).append('\n'));
|
||||
StringBuilder every = new StringBuilder();
|
||||
every.append("\nEvery pipeline, and what WebGL2 needs for it (ADR 0012):\n");
|
||||
for (PipelineCatalog.Pipeline pipeline : pipelines) {
|
||||
every.append(" ")
|
||||
.append(pipeline.name())
|
||||
.append(": ")
|
||||
.append(needs(pipeline, stages))
|
||||
.append('\n');
|
||||
}
|
||||
if (!errors.isEmpty()) {
|
||||
report.append('\n').append(errors.size()).append(" errors:\n");
|
||||
errors.forEach(error ->
|
||||
report.append(" ").append(error.replace("\n", "\n ")).append('\n'));
|
||||
}
|
||||
System.out.print(report);
|
||||
|
||||
Path parent = out.toAbsolutePath().getParent();
|
||||
if (parent != null) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
String reportName = out.getFileName().toString().replaceFirst("\\.json$", "") + ".txt";
|
||||
// The full list goes to the file only: over two hundred lines.
|
||||
Files.writeString(out.resolveSibling(reportName), report.toString() + every, StandardCharsets.UTF_8);
|
||||
if (!errors.isEmpty()) {
|
||||
Files.deleteIfExists(out);
|
||||
return 1;
|
||||
}
|
||||
Files.writeString(out, new ShaderManifest(minecraft, stages.values()).toJson(), StandardCharsets.UTF_8);
|
||||
System.out.println("Wrote " + out + " (" + Files.size(out) / 1024 + " KiB)");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** What a pipeline needs of WebGL2 beyond the basics, for the report's full list. */
|
||||
private static String needs(PipelineCatalog.Pipeline pipeline, Map<String, TranslatedStage> stages) {
|
||||
List<String> notes = new ArrayList<>();
|
||||
TranslatedStage vertex = stages.get(pipeline.vertex().asString());
|
||||
TranslatedStage fragment = stages.get(pipeline.fragment().asString());
|
||||
if (vertex == null || fragment == null) {
|
||||
return "not translated (see the errors)";
|
||||
}
|
||||
String unsupported = vertex.unsupported() != null ? vertex.unsupported() : fragment.unsupported();
|
||||
if (unsupported != null) {
|
||||
return "can't run yet: " + unsupported;
|
||||
}
|
||||
String glsl = vertex.glsl() + fragment.glsl();
|
||||
if (glsl.contains("incari_texel_")) {
|
||||
notes.add("texel buffer as a 2D texture");
|
||||
}
|
||||
if (glsl.contains("incari_out_")) {
|
||||
notes.add("fragment output array as separate outputs");
|
||||
}
|
||||
if (stages.containsKey(pipeline.vertex()
|
||||
.withFlag(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE)
|
||||
.asString())
|
||||
|| stages.containsKey(pipeline.fragment()
|
||||
.withFlag(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE)
|
||||
.asString())) {
|
||||
notes.add("a 0-to-1 depth variant");
|
||||
}
|
||||
if (pipeline.wireframe()) {
|
||||
notes.add("WEBGL_polygon_mode (skipped without it)");
|
||||
}
|
||||
return notes.isEmpty() ? "runs as translated" : String.join(", ", notes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compiles and translates one stage.
|
||||
*
|
||||
* @param zeroToOne compile with the game's define for a 0-to-1 depth range, and file the
|
||||
* result under the key with that flag
|
||||
*/
|
||||
private static TranslatedStage translate(
|
||||
GameShaderFiles files, SpirvCompiler compiler, ShaderStageKey key, ShaderDefines defines, boolean zeroToOne)
|
||||
throws ShaderException {
|
||||
String source = source(files, key);
|
||||
String expanded = Includes.expand(source, files.includes());
|
||||
Map<String, String> macros = new LinkedHashMap<>(defines.values());
|
||||
for (String flag : defines.flags()) {
|
||||
macros.put(flag, "");
|
||||
}
|
||||
if (zeroToOne) {
|
||||
macros.put(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE, "");
|
||||
}
|
||||
String extension = key.type() == ShaderType.VERTEX ? ".vsh" : ".fsh";
|
||||
int[] spirv = compiler.compile(key.id() + extension, expanded, key.type(), macros);
|
||||
String filed =
|
||||
zeroToOne ? key.withFlag(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE).asString() : key.asString();
|
||||
return EsslTranslator.translate(filed, SourceHash.of(source), spirv, key.type());
|
||||
}
|
||||
|
||||
/** Whether the stage's source, with its includes, reads the 0-to-1 depth define. */
|
||||
private static boolean readsZeroToOne(GameShaderFiles files, ShaderStageKey key) throws ShaderException {
|
||||
return Includes.expand(source(files, key), files.includes()).contains(ShaderStageKey.DEPTH_IS_ZERO_TO_ONE);
|
||||
}
|
||||
|
||||
private static String source(GameShaderFiles files, ShaderStageKey key) throws ShaderException {
|
||||
String source = files.shader(key.type(), key.id().toString());
|
||||
if (source == null) {
|
||||
throw new ShaderException("No " + key.type().getName() + " shader " + key.id() + " in the jar");
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
/**
|
||||
* Links one program with glslang: 1 if it links, 0 if it can't (then either the stage is marked
|
||||
* unsupported, for a construct GLSL ES lacks, or the problem is added to {@code errors}).
|
||||
*/
|
||||
private static int check(
|
||||
GlslangCheck check,
|
||||
PipelineCatalog.Pipeline pipeline,
|
||||
TranslatedStage vertex,
|
||||
TranslatedStage fragment,
|
||||
Map<String, TranslatedStage> stages,
|
||||
List<String> errors)
|
||||
throws IOException, InterruptedException {
|
||||
String problem = check.link(vertex.glsl(), fragment.glsl());
|
||||
GlslangCheck.EsLimit limit = problem == null ? null : GlslangCheck.esLimit(problem);
|
||||
if (limit != null) {
|
||||
// A construct GLSL ES can't express (desktop GLSL can): the stage waits for a WebGL2
|
||||
// rewrite rather than failing the build.
|
||||
TranslatedStage stage = limit.vertex() ? vertex : fragment;
|
||||
stages.put(
|
||||
stage.key(),
|
||||
TranslatedStage.unsupported(
|
||||
stage.key(), stage.sourceHash(), "GLSL ES 3.00 has no " + limit.what()));
|
||||
return 0;
|
||||
}
|
||||
if (problem != null) {
|
||||
errors.add(pipeline.name() + " (" + vertex.key() + " + " + fragment.key()
|
||||
+ ") doesn't link as GLSL ES 3.00:\n" + problem);
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static String value(String[] args, int index) throws UsageException {
|
||||
if (index >= args.length) {
|
||||
throw new UsageException(args[index - 1] + " needs a value");
|
||||
}
|
||||
return args[index];
|
||||
}
|
||||
|
||||
/** Bad command-line arguments. */
|
||||
static final class UsageException extends Exception {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
UsageException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.mojang.renderpearl.api.pipeline.PolygonMode;
|
||||
import com.mojang.renderpearl.api.pipeline.RenderPipeline;
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import incari.render.webgl2.shaders.ShaderStageKey;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import net.minecraft.client.renderer.RenderPipelines;
|
||||
import net.minecraft.client.renderer.ShaderDefines;
|
||||
import net.minecraft.client.renderer.oit.OitPipelineSet;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* Every pipeline the game can compile, as pairs of shader stages. The game's own pipelines come
|
||||
* from {@link RenderPipelines}, which registers them all in its static initializer; post effects
|
||||
* are built from their JSON files at run time, on {@link RenderPipelines#POST_PROCESSING_SNIPPET},
|
||||
* so each pass of each file in the jar is one more pipeline here.
|
||||
*/
|
||||
final class PipelineCatalog {
|
||||
|
||||
/**
|
||||
* One pipeline's two stages, and the defines both are compiled with.
|
||||
*
|
||||
* @param wireframe whether it draws outlines (a debug view; WebGL2 needs WEBGL_polygon_mode)
|
||||
*/
|
||||
record Pipeline(
|
||||
String name, ShaderStageKey vertex, ShaderStageKey fragment, ShaderDefines defines, boolean wireframe) {}
|
||||
|
||||
private PipelineCatalog() {}
|
||||
|
||||
static List<Pipeline> collect(GameShaderFiles files) throws ShaderException {
|
||||
BuildPlatform.install();
|
||||
// The registry keeps one pipeline per location, and some pipelines share one (the item
|
||||
// pipelines with and without glint), so the ones it drops are found among its fields.
|
||||
Set<RenderPipeline> seen = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
List<RenderPipeline> all = new ArrayList<>();
|
||||
all.addAll(RenderPipelines.requiredPipelines());
|
||||
all.addAll(RenderPipelines.optionalPipelines());
|
||||
all.addAll(declaredPipelines());
|
||||
List<Pipeline> pipelines = new ArrayList<>();
|
||||
for (RenderPipeline pipeline : all) {
|
||||
if (seen.add(pipeline)) {
|
||||
pipelines.add(of(pipeline));
|
||||
}
|
||||
}
|
||||
for (Map.Entry<String, String> effect : files.postEffects().entrySet()) {
|
||||
pipelines.addAll(postEffect(effect.getKey(), effect.getValue()));
|
||||
}
|
||||
return pipelines;
|
||||
}
|
||||
|
||||
/** Every pipeline {@link RenderPipelines} holds in a static field, directly or in an OIT set. */
|
||||
private static List<RenderPipeline> declaredPipelines() throws ShaderException {
|
||||
List<RenderPipeline> pipelines = new ArrayList<>();
|
||||
for (Field field : RenderPipelines.class.getDeclaredFields()) {
|
||||
if (!Modifier.isStatic(field.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
Object value;
|
||||
try {
|
||||
field.setAccessible(true);
|
||||
value = field.get(null);
|
||||
} catch (ReflectiveOperationException | RuntimeException e) {
|
||||
throw new ShaderException("Can't read RenderPipelines." + field.getName() + ": " + e);
|
||||
}
|
||||
if (value instanceof RenderPipeline pipeline) {
|
||||
pipelines.add(pipeline);
|
||||
} else if (value instanceof OitPipelineSet set) {
|
||||
pipelines.add(set.depthBoundsPipeline());
|
||||
pipelines.add(set.transmittancePipeline());
|
||||
pipelines.add(set.accumulatePipeline());
|
||||
}
|
||||
}
|
||||
return pipelines;
|
||||
}
|
||||
|
||||
private static Pipeline of(RenderPipeline pipeline) {
|
||||
Map<ShaderType, Identifier> shaders = pipeline.getShaders();
|
||||
// RenderPipeline.Builder refuses to build a pipeline without both stages.
|
||||
Identifier vertex = Objects.requireNonNull(shaders.get(ShaderType.VERTEX));
|
||||
Identifier fragment = Objects.requireNonNull(shaders.get(ShaderType.FRAGMENT));
|
||||
return new Pipeline(
|
||||
pipeline.getLocation().toString(),
|
||||
ShaderStageKey.of(ShaderType.VERTEX, vertex, pipeline.getShaderDefines()),
|
||||
ShaderStageKey.of(ShaderType.FRAGMENT, fragment, pipeline.getShaderDefines()),
|
||||
pipeline.getShaderDefines(),
|
||||
pipeline.getPolygonMode() == PolygonMode.WIREFRAME);
|
||||
}
|
||||
|
||||
/** The passes of one post effect, built the way the game builds them (only the shaders matter). */
|
||||
private static List<Pipeline> postEffect(String id, String json) throws ShaderException {
|
||||
List<Pipeline> passes = new ArrayList<>();
|
||||
JsonElement passList = JsonParser.parseString(json).getAsJsonObject().get("passes");
|
||||
if (passList == null) {
|
||||
return passes;
|
||||
}
|
||||
int index = 0;
|
||||
for (JsonElement element : passList.getAsJsonArray()) {
|
||||
JsonObject pass = element.getAsJsonObject();
|
||||
Identifier vertex = parse(id, pass, "vertex_shader");
|
||||
Identifier fragment = parse(id, pass, "fragment_shader");
|
||||
RenderPipeline pipeline = RenderPipeline.builder(RenderPipelines.POST_PROCESSING_SNIPPET)
|
||||
.withVertexShader(vertex)
|
||||
.withFragmentShader(fragment)
|
||||
.withLocation(Identifier.parse(id).withSuffix("/" + index))
|
||||
.build();
|
||||
passes.add(of(pipeline));
|
||||
index++;
|
||||
}
|
||||
return passes;
|
||||
}
|
||||
|
||||
private static Identifier parse(String effect, JsonObject pass, String field) throws ShaderException {
|
||||
JsonElement value = pass.get(field);
|
||||
if (value == null) {
|
||||
throw new ShaderException("Post effect " + effect + " has a pass without " + field);
|
||||
}
|
||||
return Identifier.parse(value.getAsString());
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
/** A shader that couldn't be compiled, translated or validated; the message says which and why. */
|
||||
final class ShaderException extends Exception {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
ShaderException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Map;
|
||||
import org.lwjgl.util.shaderc.Shaderc;
|
||||
|
||||
/**
|
||||
* GLSL to SPIR-V with shaderc, set up as the game sets it up for its own devices: Vulkan 1.2
|
||||
* semantics, uniforms bound automatically, debug info kept (SPIRV-Cross needs the names back), no
|
||||
* optimization. The browser's device reports depth as -1 to 1 and no draw parameters, so none of
|
||||
* the game's device-dependent macros are defined; only the pipeline's own defines are.
|
||||
*
|
||||
* <p>One compiler for the whole run; not thread-safe.
|
||||
*/
|
||||
final class SpirvCompiler implements AutoCloseable {
|
||||
|
||||
private final long compiler = Shaderc.shaderc_compiler_initialize();
|
||||
|
||||
/** Compiles an include-expanded source; the SPIR-V words are copied out of shaderc's result. */
|
||||
int[] compile(String name, String source, ShaderType type, Map<String, String> defines) throws ShaderException {
|
||||
long options = Shaderc.shaderc_compile_options_initialize();
|
||||
try {
|
||||
Shaderc.shaderc_compile_options_set_source_language(options, Shaderc.shaderc_source_language_glsl);
|
||||
Shaderc.shaderc_compile_options_set_target_env(
|
||||
options, Shaderc.shaderc_target_env_vulkan, Shaderc.shaderc_env_version_vulkan_1_2);
|
||||
Shaderc.shaderc_compile_options_set_auto_bind_uniforms(options, true);
|
||||
Shaderc.shaderc_compile_options_set_generate_debug_info(options);
|
||||
Shaderc.shaderc_compile_options_set_optimization_level(options, Shaderc.shaderc_optimization_level_zero);
|
||||
for (Map.Entry<String, String> define : defines.entrySet()) {
|
||||
Shaderc.shaderc_compile_options_add_macro_definition(options, define.getKey(), define.getValue());
|
||||
}
|
||||
int kind = type == ShaderType.VERTEX ? Shaderc.shaderc_vertex_shader : Shaderc.shaderc_fragment_shader;
|
||||
long result = Shaderc.shaderc_compile_into_spv(compiler, source, kind, name, "main", options);
|
||||
try {
|
||||
if (Shaderc.shaderc_result_get_compilation_status(result)
|
||||
!= Shaderc.shaderc_compilation_status_success) {
|
||||
throw new ShaderException("shaderc: "
|
||||
+ String.valueOf(Shaderc.shaderc_result_get_error_message(result))
|
||||
.trim());
|
||||
}
|
||||
ByteBuffer bytes = Shaderc.shaderc_result_get_bytes(result);
|
||||
if (bytes == null) {
|
||||
throw new ShaderException("shaderc returned no SPIR-V");
|
||||
}
|
||||
int[] words = new int[bytes.remaining() / 4];
|
||||
bytes.order(java.nio.ByteOrder.LITTLE_ENDIAN).asIntBuffer().get(words);
|
||||
return words;
|
||||
} finally {
|
||||
Shaderc.shaderc_result_release(result);
|
||||
}
|
||||
} finally {
|
||||
Shaderc.shaderc_compile_options_release(options);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
Shaderc.shaderc_compiler_release(compiler);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** The build-time shader translation for the browser build: GLSL to SPIR-V to GLSL ES 3.00. */
|
||||
@NullMarked
|
||||
package incari.tools.shaders;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class EsslRewritesTest {
|
||||
|
||||
@Test
|
||||
void texelFetchesReadTheTwoDimensionalLayout() {
|
||||
String glsl = """
|
||||
#version 300 es
|
||||
#extension GL_OES_texture_buffer : require
|
||||
uniform highp isamplerBuffer CloudFaces;
|
||||
void main()
|
||||
{
|
||||
int a = texelFetch(CloudFaces, (idx * 3) + 1).x;
|
||||
int b = texelFetch(CloudFaces, f(idx, g(2))).x;
|
||||
}
|
||||
""";
|
||||
|
||||
String rewritten = EsslRewrites.texelBuffers(glsl, List.of("CloudFaces"));
|
||||
|
||||
assertThat(rewritten)
|
||||
.doesNotContain("#extension")
|
||||
.contains("uniform highp isampler2D CloudFaces;")
|
||||
.contains("return ivec2(i & 2047, i >> 11);")
|
||||
.contains("texelFetch(CloudFaces, incari_texel_CloudFaces((idx * 3) + 1), 0).x")
|
||||
.contains("texelFetch(CloudFaces, incari_texel_CloudFaces(f(idx, g(2))), 0).x");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shadersWithoutTexelBuffersAreUntouched() {
|
||||
String glsl = "#version 300 es\nvoid main()\n{\n}\n";
|
||||
assertThat(EsslRewrites.texelBuffers(glsl, List.of())).isSameAs(glsl);
|
||||
assertThat(EsslRewrites.fragmentOutputArrays(glsl)).isSameAs(glsl);
|
||||
}
|
||||
|
||||
@Test
|
||||
void outputArraysAreCopiedToOutputsAfterMain() {
|
||||
String glsl = """
|
||||
#version 300 es
|
||||
layout(location = 0) out highp vec4 coeff[2];
|
||||
void main()
|
||||
{
|
||||
coeff[i] = vec4(1.0);
|
||||
}
|
||||
""";
|
||||
|
||||
String rewritten = EsslRewrites.fragmentOutputArrays(glsl);
|
||||
|
||||
assertThat(rewritten)
|
||||
.contains("""
|
||||
layout(location = 0) out highp vec4 incari_out_coeff_0;
|
||||
layout(location = 1) out highp vec4 incari_out_coeff_1;
|
||||
highp vec4 coeff[2];""")
|
||||
.contains("void incari_main()\n{\n coeff[i] = vec4(1.0);\n}")
|
||||
.endsWith("""
|
||||
void main()
|
||||
{
|
||||
incari_main();
|
||||
incari_out_coeff_0 = coeff[0];
|
||||
incari_out_coeff_1 = coeff[1];
|
||||
}
|
||||
|
||||
""");
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class IncludesTest {
|
||||
|
||||
@Test
|
||||
void expandsNestedIncludesInPlace() throws Exception {
|
||||
Map<String, String> includes = Map.of(
|
||||
"minecraft:a.glsl", "float a;\n#include <minecraft:b.glsl>\n",
|
||||
"minecraft:b.glsl", "float b;\n");
|
||||
|
||||
String expanded = Includes.expand("#version 330\n #include <minecraft:a.glsl>\nvoid main() {}", includes);
|
||||
|
||||
assertThat(expanded).isEqualTo("#version 330\nfloat a;\nfloat b;\n\n\nvoid main() {}\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theNamespaceDefaultsToMinecraft() throws Exception {
|
||||
assertThat(Includes.expand("#include \"globals.glsl\"", Map.of("minecraft:globals.glsl", "float g;")))
|
||||
.isEqualTo("float g;\n");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aMissingIncludeIsAnError() {
|
||||
assertThatThrownBy(() -> Includes.expand("#include <minecraft:gone.glsl>", Map.of()))
|
||||
.isInstanceOf(ShaderException.class)
|
||||
.hasMessageContaining("minecraft:gone.glsl");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCycleIsAnError() {
|
||||
Map<String, String> includes = Map.of("minecraft:self.glsl", "#include <minecraft:self.glsl>");
|
||||
assertThatThrownBy(() -> Includes.expand("#include <minecraft:self.glsl>", includes))
|
||||
.isInstanceOf(ShaderException.class)
|
||||
.hasMessageContaining("cycle");
|
||||
}
|
||||
|
||||
@Test
|
||||
void recognizesGlslangsEsOnlyLimits() {
|
||||
String output = """
|
||||
ERROR: /tmp/x/s111.frag:113: 'variable indexing fragment shader output array' : not supported with this profile: es
|
||||
ERROR: /tmp/x/s111.frag:113: '' : compilation terminated
|
||||
""";
|
||||
|
||||
assertThat(GlslangCheck.esLimit(output))
|
||||
.isEqualTo(new GlslangCheck.EsLimit("variable indexing fragment shader output array", false));
|
||||
assertThat(GlslangCheck.esLimit("ERROR: /tmp/x/s1.vert:3: 'foo' : undeclared identifier"))
|
||||
.isNull();
|
||||
}
|
||||
}
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
package incari.tools.shaders;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import com.mojang.renderpearl.api.pipeline.ShaderType;
|
||||
import incari.render.webgl2.shaders.TranslatedStage;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/** Runs shaderc and SPIRV-Cross (LWJGL's natives) on small shaders written for the test. */
|
||||
class TranslationTest {
|
||||
|
||||
private static final String VERTEX = """
|
||||
#version 330
|
||||
#extension GL_ARB_separate_shader_objects : require
|
||||
layout(std140) uniform Projection {
|
||||
mat4 ProjMat;
|
||||
};
|
||||
layout(location = 0) in vec3 Position;
|
||||
layout(location = 1) in ivec2 Id;
|
||||
layout(location = 2) out vec4 tint;
|
||||
void main() {
|
||||
gl_Position = ProjMat * vec4(Position, 1.0);
|
||||
tint = vec4(float(Id.x));
|
||||
}
|
||||
""";
|
||||
|
||||
private static final String FRAGMENT = """
|
||||
#version 330
|
||||
#extension GL_ARB_separate_shader_objects : require
|
||||
layout(std140) uniform Projection {
|
||||
mat4 ProjMat;
|
||||
};
|
||||
uniform sampler2D Sampler0;
|
||||
layout(location = 2) in vec4 color;
|
||||
layout(location = 0) out vec4 fragColor;
|
||||
void main() {
|
||||
fragColor = texture(Sampler0, color.xy) * ProjMat[0][0];
|
||||
}
|
||||
""";
|
||||
|
||||
private static SpirvCompiler compiler;
|
||||
|
||||
@BeforeAll
|
||||
static void start() {
|
||||
compiler = new SpirvCompiler();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stop() {
|
||||
compiler.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void translatesToEsWithWebGlsNaming() throws Exception {
|
||||
TranslatedStage vertex = translate("vertex test:v", VERTEX, ShaderType.VERTEX);
|
||||
TranslatedStage fragment = translate("fragment test:f", FRAGMENT, ShaderType.FRAGMENT);
|
||||
|
||||
assertThat(vertex.glsl()).startsWith("#version 300 es");
|
||||
// Varyings meet by name in ES 3.00, so both sides are named after the location they share,
|
||||
// even though the game's two stages call it tint and color.
|
||||
assertThat(vertex.glsl()).contains("out vec4 incari_io_2;").doesNotContain("tint");
|
||||
assertThat(fragment.glsl()).contains("in vec4 incari_io_2;").doesNotContain(" color;");
|
||||
// Blocks keep their names (the pipeline binds by them), with one instance name in both stages.
|
||||
assertThat(vertex.glsl()).contains("uniform Projection").contains("} incari_ubo_Projection;");
|
||||
assertThat(fragment.glsl()).contains("} incari_ubo_Projection;");
|
||||
assertThat(vertex.uniformBlocks()).containsExactly("Projection");
|
||||
assertThat(fragment.samplers()).containsExactly("Sampler0");
|
||||
assertThat(vertex.attributes())
|
||||
.containsExactlyInAnyOrder(
|
||||
new TranslatedStage.Attribute("Position", 0, false),
|
||||
new TranslatedStage.Attribute("Id", 1, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void texelBuffersBecomeTwoDimensionalTextures() throws Exception {
|
||||
String source = """
|
||||
#version 330
|
||||
uniform isamplerBuffer Faces;
|
||||
layout(location = 0) out vec4 fragColor;
|
||||
void main() {
|
||||
int index = int(gl_FragCoord.x) * 3;
|
||||
fragColor = vec4(texelFetch(Faces, index + 1).r);
|
||||
}
|
||||
""";
|
||||
|
||||
TranslatedStage stage = translate("fragment test:clouds", source, ShaderType.FRAGMENT);
|
||||
|
||||
assertThat(stage.isSupported()).isTrue();
|
||||
assertThat(stage.glsl()).contains("uniform highp isampler2D Faces;").doesNotContain("samplerBuffer");
|
||||
assertThat(stage.glsl()).containsPattern("texelFetch\\(Faces, incari_texel_Faces\\(.*\\), 0\\)");
|
||||
assertThat(stage.samplers()).containsExactly("Faces");
|
||||
assertValidEs(stage.glsl(), "frag");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fragmentOutputArraysBecomeOutputs() throws Exception {
|
||||
String source = """
|
||||
#version 330
|
||||
layout(location = 0) out vec4 coeff[2];
|
||||
void main() {
|
||||
for (int i = 0; i < 2; i++) {
|
||||
for (int j = 0; j < 4; j++) {
|
||||
coeff[i][j] = float(i * 4 + j);
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
TranslatedStage stage = translate("fragment test:oit", source, ShaderType.FRAGMENT);
|
||||
|
||||
assertThat(stage.glsl())
|
||||
.contains("layout(location = 0) out vec4 incari_out_coeff_0;")
|
||||
.contains("layout(location = 1) out vec4 incari_out_coeff_1;");
|
||||
assertValidEs(stage.glsl(), "frag");
|
||||
}
|
||||
|
||||
/** Compiles {@code glsl} with glslang as GLSL ES, where it's installed (CI requires it). */
|
||||
private static void assertValidEs(String glsl, String stage) throws Exception {
|
||||
java.nio.file.Path validator = GlslangCheck.find();
|
||||
if (validator == null) {
|
||||
return;
|
||||
}
|
||||
java.nio.file.Path file = java.nio.file.Files.createTempFile("incari-test", "." + stage);
|
||||
try {
|
||||
java.nio.file.Files.writeString(file, glsl);
|
||||
Process process = new ProcessBuilder(validator.toString(), file.toString())
|
||||
.redirectErrorStream(true)
|
||||
.start();
|
||||
String output =
|
||||
new String(process.getInputStream().readAllBytes(), java.nio.charset.StandardCharsets.UTF_8);
|
||||
assertThat(process.waitFor()).as(output + "\n" + glsl).isZero();
|
||||
} finally {
|
||||
java.nio.file.Files.delete(file);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void compileErrorsNameTheShader() {
|
||||
assertThatThrownBy(() ->
|
||||
translate("vertex test:broken", "#version 330\nvoid main() { nope(); }\n", ShaderType.VERTEX))
|
||||
.isInstanceOf(ShaderException.class)
|
||||
.hasMessageContaining("shaderc")
|
||||
.hasMessageContaining("nope");
|
||||
}
|
||||
|
||||
private static TranslatedStage translate(String key, String source, ShaderType type) throws ShaderException {
|
||||
int[] spirv = compiler.compile(key, source, type, Map.of());
|
||||
return EsslTranslator.translate(key, "0000000000000000", spirv, type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
# tools/sprites
|
||||
|
||||
- Build-time only; never referenced by code that ships. May use LWJGL and the game freely.
|
||||
- The file format is `client`'s `incari.client.render.SpriteCache`: both sides must agree, and its
|
||||
version goes up with any change.
|
||||
- Make each image with the game's own code (its decoder, `MipmapGenerator`), never a copy of it:
|
||||
the page uses what's here instead of what the game would have made.
|
||||
- Test: `./gradlew :tools:sprites:check`; run for real with `./gradlew :app-web:sprites`.
|
||||
@@ -0,0 +1,23 @@
|
||||
# tools/sprites: vanilla sprites, decoded at build time
|
||||
|
||||
Decodes every vanilla sprite and makes its mip levels at build time, with the game's own code
|
||||
(ADR 0026). `./gradlew :app-web:sprites` writes `app-web/build/web-sprites/sprites.bin` for the
|
||||
asset pack. In the page, `client`'s `SpriteCache` uses these instead of decoding PNGs. The file
|
||||
holds Mojang's textures: build output, never committed or published.
|
||||
|
||||
## How it works
|
||||
|
||||
1. `Main` boots the game on this JVM and opens the vanilla pack as the game does.
|
||||
2. `Sprites` asks each atlas for its sprite sources. Plain, non-animated sprites are decoded with
|
||||
the game's decoder and mipmapped by the game's `MipmapGenerator` (blocks atlas up to level 4).
|
||||
3. The file: little-endian magic, version, count, then each sprite's name, size and RGBA levels.
|
||||
|
||||
Generated sprites (armor trims, sheets) and animated ones are left to the page, as before.
|
||||
|
||||
## Invariants
|
||||
|
||||
- **Nothing here ships.** It runs on the build machine with LWJGL's natives.
|
||||
- **Byte-identical to the game.** `SpritesTest` compares every level through `SpriteCache`; the
|
||||
screenshot diffs compare whole frames.
|
||||
- **The format belongs to `SpriteCache`.** Change both together and raise the version.
|
||||
- **Fewer than 1000 sprites fails the build**, so a moved sprite layout can't ship a useless file.
|
||||
@@ -0,0 +1,57 @@
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
application
|
||||
}
|
||||
|
||||
// Decodes the vanilla sprites and makes their mip levels at build time, with the game's own code,
|
||||
// for the browser build's asset pack (ADR 0026). Runs on a normal JVM with LWJGL's natives
|
||||
// (stb_image decodes the PNGs, as on the desktop). Its output holds Mojang's textures, decoded:
|
||||
// build output, never committed or published.
|
||||
|
||||
dependencies {
|
||||
implementation(project(":client"))
|
||||
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testImplementation(libs.assertj)
|
||||
testRuntimeOnly(libs.junit.launcher)
|
||||
}
|
||||
|
||||
val repoRoot = rootProject.layout.projectDirectory
|
||||
val minecraftVersion: String = Properties().run {
|
||||
repoRoot.file("incari.properties").asFile.reader().use { load(it) }
|
||||
getProperty("minecraft.version")
|
||||
}
|
||||
|
||||
/** This machine's LWJGL natives (stb among them), as `incari fetch` got them. */
|
||||
val nativeJars = run {
|
||||
val root = repoRoot.asFile
|
||||
providers.fileContents(repoRoot.file("work/cache/versions/$minecraftVersion/natives.txt")).asText.map { text ->
|
||||
text.lines().filter { it.isNotBlank() }.map { root.resolve(it.trim()) }
|
||||
}.orElse(emptyList())
|
||||
}
|
||||
|
||||
dependencies {
|
||||
runtimeOnly(files(nativeJars))
|
||||
}
|
||||
|
||||
application {
|
||||
applicationName = "incari-sprites"
|
||||
mainClass = "incari.tools.sprites.Main"
|
||||
applicationDefaultJvmArgs = listOf(
|
||||
"--enable-native-access=ALL-UNNAMED",
|
||||
"-Dorg.lwjgl.system.SharedLibraryExtractPath=${repoRoot.dir("work/natives/lwjgl").asFile}",
|
||||
)
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
// Game classes loaded by tests write logs/ into the working directory; keep that in build/.
|
||||
val runDir = layout.buildDirectory.dir("test-run").get().asFile
|
||||
workingDir = runDir
|
||||
jvmArgs(
|
||||
"--enable-native-access=ALL-UNNAMED",
|
||||
"-Dorg.lwjgl.system.SharedLibraryExtractPath=${repoRoot.dir("work/natives/lwjgl").asFile}",
|
||||
)
|
||||
doFirst { runDir.mkdirs() }
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package incari.tools.sprites;
|
||||
|
||||
import incari.platform.api.Platform;
|
||||
import incari.platform.api.Platforms;
|
||||
import incari.platform.api.threads.PlatformThreads;
|
||||
import java.lang.reflect.Proxy;
|
||||
|
||||
/**
|
||||
* The platform the game sees while this tool decodes its sprites: loading the game's classes runs
|
||||
* {@code Util}'s static initializer, which asks the platform how many background threads to make.
|
||||
* Anything else fails loudly, so a game version that reaches further at class-load time shows up
|
||||
* here rather than half-working.
|
||||
*/
|
||||
final class BuildPlatform {
|
||||
|
||||
private BuildPlatform() {}
|
||||
|
||||
static void install() {
|
||||
if (Platforms.isInstalled()) {
|
||||
return;
|
||||
}
|
||||
PlatformThreads inline = suggested -> 0;
|
||||
Platform platform = (Platform) Proxy.newProxyInstance(
|
||||
Platform.class.getClassLoader(),
|
||||
new Class<?>[] {Platform.class},
|
||||
(proxy, method, args) -> switch (method.getName()) {
|
||||
case "threads" -> inline;
|
||||
case "description" -> "Build-time sprite decoding (no game running)";
|
||||
case "nanoTime" -> System.nanoTime();
|
||||
case "toString" -> "BuildPlatform";
|
||||
default ->
|
||||
throw new UnsupportedOperationException("The sprite tool's platform has no " + method.getName()
|
||||
+ "(); the game reached it while its sprites were decoded");
|
||||
});
|
||||
Platforms.install(platform);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package incari.tools.sprites;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.client.ClientBootstrap;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.packs.PackLocationInfo;
|
||||
import net.minecraft.server.packs.PackResources;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.VanillaPackResourcesBuilder;
|
||||
import net.minecraft.server.packs.repository.KnownPack;
|
||||
import net.minecraft.server.packs.repository.PackSource;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
|
||||
/**
|
||||
* {@code incari-sprites --out <file>}: decodes the vanilla sprites on this JVM, with the game's
|
||||
* resources on the class path (the client jar's, as {@code :client} extracts them), and writes them
|
||||
* in the format {@code SpriteCache} reads.
|
||||
*/
|
||||
public final class Main {
|
||||
|
||||
/** Fewer sprites than this means something went wrong (26.3's atlases hold about 4,000). */
|
||||
private static final int MINIMUM = 1000;
|
||||
|
||||
private Main() {}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
if (args.length != 2 || !args[0].equals("--out")) {
|
||||
System.err.println("usage: incari-sprites --out <file>");
|
||||
System.exit(2);
|
||||
}
|
||||
Path out = Path.of(args[1]);
|
||||
BuildPlatform.install();
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
// The client's own registries: the atlases' sprite source types among them.
|
||||
ClientBootstrap.bootstrap();
|
||||
long start = System.nanoTime();
|
||||
List<Sprites.Sprite> sprites;
|
||||
try (PackResources vanilla = vanillaPack();
|
||||
MultiPackResourceManager resources =
|
||||
new MultiPackResourceManager(PackType.CLIENT_RESOURCES, List.of(vanilla))) {
|
||||
sprites = Sprites.decode(resources);
|
||||
}
|
||||
if (sprites.size() < MINIMUM) {
|
||||
// A game version that moved its sprites, or resources missing from the class path:
|
||||
// fail rather than ship a file that saves nothing.
|
||||
System.err.println("Only " + sprites.size() + " sprites decoded (expected thousands): see the log above");
|
||||
System.exit(1);
|
||||
}
|
||||
Path parent = out.toAbsolutePath().getParent();
|
||||
if (parent != null) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
try (OutputStream file = new BufferedOutputStream(Files.newOutputStream(out), 1 << 20)) {
|
||||
Sprites.write(sprites, file);
|
||||
}
|
||||
sprites.forEach(Sprites.Sprite::close);
|
||||
System.out.printf(
|
||||
"==> %d sprites decoded with their mip levels into %s (%.1f MB) in %d ms%n",
|
||||
sprites.size(), out, Files.size(out) / 1e6, (System.nanoTime() - start) / 1_000_000);
|
||||
}
|
||||
|
||||
/** The vanilla pack as the game makes it: its resources from the class path, by the vanilla pack's id. */
|
||||
static PackResources vanillaPack() {
|
||||
return new VanillaPackResourcesBuilder()
|
||||
.exposeNamespace("minecraft")
|
||||
.pushJarResources()
|
||||
.build(new PackLocationInfo(
|
||||
"vanilla",
|
||||
Component.literal("vanilla"),
|
||||
PackSource.BUILT_IN,
|
||||
Optional.of(KnownPack.vanilla("vanilla"))))
|
||||
.fullResources();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package incari.tools.sprites;
|
||||
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import net.minecraft.client.renderer.texture.MipmapGenerator;
|
||||
import net.minecraft.client.renderer.texture.MipmapStrategy;
|
||||
import net.minecraft.client.renderer.texture.atlas.SpriteResourceLoader;
|
||||
import net.minecraft.client.renderer.texture.atlas.SpriteSource;
|
||||
import net.minecraft.client.renderer.texture.atlas.SpriteSourceList;
|
||||
import net.minecraft.client.resources.metadata.animation.AnimationMetadataSection;
|
||||
import net.minecraft.client.resources.metadata.texture.TextureMetadataSection;
|
||||
import net.minecraft.data.AtlasIds;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.packs.resources.Resource;
|
||||
import net.minecraft.server.packs.resources.ResourceManager;
|
||||
import net.minecraft.util.Mth;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The vanilla atlases' sprites, decoded, with the mip levels the game would make of them:
|
||||
* what {@code client}'s {@code SpriteCache} reads in the browser instead of the PNGs.
|
||||
*
|
||||
* <p>Each atlas's sprites are listed by the game's own sprite sources; a sprite that is a single file
|
||||
* of its own and not animated is decoded with the game's decoder and given its levels by the game's
|
||||
* {@code MipmapGenerator}, with the inputs the game's {@code SpriteContents} would give it (its
|
||||
* texture metadata, its transparency). Level 0 is kept as the generator leaves it: for a cut-out
|
||||
* sprite the generator fills the colour of its transparent pixels, which the game uploads. Sprites
|
||||
* made another way (palette permutations, cut from a sheet) and animated ones are left to the game.
|
||||
*/
|
||||
final class Sprites {
|
||||
|
||||
/** The format {@code SpriteCache} reads; the version goes up with any change to either side. */
|
||||
static final int MAGIC = 0x49535031; // "ISP1"
|
||||
|
||||
static final int VERSION = 1;
|
||||
|
||||
/** The game's largest mipmap setting: the blocks atlas's sprites get every level up to it. */
|
||||
static final int MAX_MIP_LEVELS = 4;
|
||||
|
||||
/** The game's atlases, and how many mip levels each makes (only the blocks atlas has any). */
|
||||
private static final Map<Identifier, Integer> ATLASES = new LinkedHashMap<>();
|
||||
|
||||
static {
|
||||
ATLASES.put(AtlasIds.BLOCKS, MAX_MIP_LEVELS);
|
||||
for (Identifier atlas : List.of(
|
||||
AtlasIds.ITEMS,
|
||||
AtlasIds.GUI,
|
||||
AtlasIds.PARTICLES,
|
||||
AtlasIds.PAINTINGS,
|
||||
AtlasIds.BANNER_PATTERNS,
|
||||
AtlasIds.SHIELD_PATTERNS,
|
||||
AtlasIds.CHESTS,
|
||||
AtlasIds.SHULKER_BOXES,
|
||||
AtlasIds.DECORATED_POT,
|
||||
AtlasIds.MAP_DECORATIONS,
|
||||
AtlasIds.CELESTIALS)) {
|
||||
ATLASES.put(atlas, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/** One sprite: its name and its images, level 0 first. */
|
||||
record Sprite(String name, List<NativeImage> levels) implements AutoCloseable {
|
||||
@Override
|
||||
public void close() {
|
||||
levels.forEach(NativeImage::close);
|
||||
}
|
||||
}
|
||||
|
||||
private Sprites() {}
|
||||
|
||||
/** Every vanilla sprite this file can carry, from {@code resources} (the vanilla pack alone). */
|
||||
static List<Sprite> decode(ResourceManager resources) {
|
||||
Map<String, Sprite> sprites = new LinkedHashMap<>();
|
||||
ATLASES.forEach((atlas, mipLevels) -> {
|
||||
SpriteResourceLoader capture = (location, resource) -> {
|
||||
if (!sprites.containsKey(location.toString())) {
|
||||
Sprite sprite = decode(location, resource, mipLevels);
|
||||
if (sprite != null) {
|
||||
sprites.put(sprite.name(), sprite);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
for (SpriteSource.Loader loader :
|
||||
SpriteSourceList.load(resources, atlas).list(resources)) {
|
||||
loader.get(capture);
|
||||
}
|
||||
});
|
||||
return new ArrayList<>(sprites.values());
|
||||
}
|
||||
|
||||
/** {@code location}'s images, or null if the game must make it itself (animated, unreadable). */
|
||||
private static @Nullable Sprite decode(Identifier location, Resource resource, int mipLevels) {
|
||||
Optional<TextureMetadataSection> texture;
|
||||
try {
|
||||
if (resource.metadata().getSection(AnimationMetadataSection.TYPE).isPresent()) {
|
||||
return null;
|
||||
}
|
||||
texture = resource.metadata().getSection(TextureMetadataSection.TYPE);
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
NativeImage image;
|
||||
try (InputStream in = resource.open()) {
|
||||
image = NativeImage.read(in);
|
||||
} catch (IOException e) {
|
||||
return null;
|
||||
}
|
||||
// As far as the game's stitcher can take this sprite: down to a texel of its smallest side.
|
||||
int levels = Math.min(
|
||||
mipLevels,
|
||||
Mth.log2(Math.min(Integer.lowestOneBit(image.getWidth()), Integer.lowestOneBit(image.getHeight()))));
|
||||
NativeImage[] made = MipmapGenerator.generateMipLevels(
|
||||
location,
|
||||
new NativeImage[] {image},
|
||||
levels,
|
||||
texture.map(TextureMetadataSection::mipmapStrategy).orElse(MipmapStrategy.AUTO),
|
||||
texture.map(TextureMetadataSection::alphaCutoffBias).orElse(0.0F),
|
||||
image.computeTransparency());
|
||||
return new Sprite(location.toString(), List.of(made));
|
||||
}
|
||||
|
||||
/** {@code sprites} in {@code SpriteCache}'s format. */
|
||||
static void write(List<Sprite> sprites, OutputStream to) throws IOException {
|
||||
DataOutputStream out = new DataOutputStream(to);
|
||||
ByteBuffer header = ByteBuffer.allocate(12).order(ByteOrder.LITTLE_ENDIAN);
|
||||
header.putInt(MAGIC).putInt(VERSION).putInt(sprites.size());
|
||||
out.write(header.array());
|
||||
for (Sprite sprite : sprites) {
|
||||
byte[] name = sprite.name().getBytes(StandardCharsets.UTF_8);
|
||||
NativeImage first = sprite.levels().getFirst();
|
||||
ByteBuffer entry = ByteBuffer.allocate(2 + name.length + 9).order(ByteOrder.LITTLE_ENDIAN);
|
||||
entry.putShort((short) name.length)
|
||||
.put(name)
|
||||
.putInt(first.getWidth())
|
||||
.putInt(first.getHeight())
|
||||
.put((byte) sprite.levels().size());
|
||||
out.write(entry.array());
|
||||
for (NativeImage level : sprite.levels()) {
|
||||
ByteBuffer pixels = level.getPixelBytes();
|
||||
byte[] bytes = new byte[pixels.remaining()];
|
||||
pixels.get(bytes);
|
||||
out.write(bytes);
|
||||
}
|
||||
}
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** The vanilla sprites decoded at build time, for the browser build's asset pack (ADR 0026). */
|
||||
@NullMarked
|
||||
package incari.tools.sprites;
|
||||
|
||||
import org.jspecify.annotations.NullMarked;
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
package incari.tools.sprites;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import incari.client.render.SpriteCache;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.client.ClientBootstrap;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.server.packs.PackResources;
|
||||
import net.minecraft.server.packs.PackType;
|
||||
import net.minecraft.server.packs.resources.MultiPackResourceManager;
|
||||
import net.minecraft.server.packs.resources.Resource;
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
/**
|
||||
* The vanilla sprites, decoded here and read back through the page's {@link SpriteCache}: the
|
||||
* same pixels and mip levels, for the vanilla pack's resources only.
|
||||
*/
|
||||
class SpritesTest {
|
||||
|
||||
private static PackResources vanilla;
|
||||
private static MultiPackResourceManager resources;
|
||||
private static List<Sprites.Sprite> sprites;
|
||||
private static Map<String, Sprites.Sprite> byName;
|
||||
|
||||
@TempDir
|
||||
static Path directory;
|
||||
|
||||
@BeforeAll
|
||||
static void decode() throws IOException {
|
||||
BuildPlatform.install();
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
ClientBootstrap.bootstrap();
|
||||
vanilla = Main.vanillaPack();
|
||||
resources = new MultiPackResourceManager(PackType.CLIENT_RESOURCES, List.of(vanilla));
|
||||
sprites = Sprites.decode(resources);
|
||||
byName = sprites.stream().collect(Collectors.toMap(Sprites.Sprite::name, Function.identity()));
|
||||
Path file = directory.resolve("sprites.bin");
|
||||
try (OutputStream out = Files.newOutputStream(file)) {
|
||||
Sprites.write(sprites, out);
|
||||
}
|
||||
SpriteCache.install(file);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void close() {
|
||||
sprites.forEach(Sprites.Sprite::close);
|
||||
resources.close();
|
||||
vanilla.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void blockSpritesHaveEveryMipLevelAndOthersNone() {
|
||||
assertThat(sprites).hasSizeGreaterThan(3000);
|
||||
assertThat(byName.get("minecraft:block/stone").levels()).hasSize(5);
|
||||
assertThat(byName.get("minecraft:item/apple").levels()).hasSize(1);
|
||||
// Animated sprites are left to the game.
|
||||
assertThat(byName).doesNotContainKey("minecraft:block/water_still");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCacheGivesBackTheSamePixels() throws IOException {
|
||||
for (String name :
|
||||
List.of("minecraft:block/stone", "minecraft:block/oak_leaves", "minecraft:block/short_grass")) {
|
||||
Identifier location = Identifier.parse(name);
|
||||
Resource resource = resources.getResourceOrThrow(location.withPath(path -> "textures/" + path + ".png"));
|
||||
NativeImage image = SpriteCache.image(location, resource);
|
||||
assertThat(image).as(name).isNotNull();
|
||||
List<NativeImage> expected = byName.get(name).levels();
|
||||
assertThat(bytes(image)).as(name).isEqualTo(bytes(expected.getFirst()));
|
||||
NativeImage[] levels = SpriteCache.mipLevels(image, 4);
|
||||
assertThat(levels).as(name).hasSize(5);
|
||||
for (int level = 0; level < levels.length; level++) {
|
||||
assertThat(bytes(levels[level])).as(name + " level " + level).isEqualTo(bytes(expected.get(level)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void fewerLevelsAreTheFirstOnes() throws IOException {
|
||||
Identifier location = Identifier.parse("minecraft:block/dirt");
|
||||
Resource resource = resources.getResourceOrThrow(Identifier.parse("minecraft:textures/block/dirt.png"));
|
||||
NativeImage image = SpriteCache.image(location, resource);
|
||||
assertThat(image).isNotNull();
|
||||
NativeImage[] levels = SpriteCache.mipLevels(image, 2);
|
||||
assertThat(levels).hasSize(3);
|
||||
assertThat(bytes(levels[2]))
|
||||
.isEqualTo(bytes(byName.get("minecraft:block/dirt").levels().get(2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyTheVanillaPacksResourcesComeFromTheCache() throws IOException {
|
||||
Resource vanillaResource = resources.getResourceOrThrow(Identifier.parse("minecraft:textures/block/sand.png"));
|
||||
Resource fromAPack = new Resource(
|
||||
new net.minecraft.server.packs.PathPackResources(
|
||||
new net.minecraft.server.packs.PackLocationInfo(
|
||||
"some_pack",
|
||||
net.minecraft.network.chat.Component.literal("some pack"),
|
||||
net.minecraft.server.packs.repository.PackSource.DEFAULT,
|
||||
java.util.Optional.empty()),
|
||||
directory),
|
||||
vanillaResource::open);
|
||||
assertThat(SpriteCache.image(Identifier.parse("minecraft:block/sand"), fromAPack))
|
||||
.isNull();
|
||||
}
|
||||
|
||||
private static byte[] bytes(NativeImage image) {
|
||||
ByteBuffer pixels = image.getPixelBytes();
|
||||
byte[] out = new byte[pixels.remaining()];
|
||||
pixels.get(out);
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# tools/survey
|
||||
|
||||
- Runs on exactly JDK 25: `JAVA_HOME=/usr/lib/jvm/java-25-openjdk ./incari survey`.
|
||||
- `docs/port-backlog.md` is generated; change `rules.txt` and rerun (`--reclassify` is seconds),
|
||||
never edit the backlog by hand. It must never contain game code.
|
||||
- Test: `./gradlew :tools:survey:test`.
|
||||
@@ -0,0 +1,47 @@
|
||||
# tools/survey: the TeaVM compile survey
|
||||
|
||||
Compiles the whole client with TeaVM and records everything between it and a browser build:
|
||||
missing classes and members, JDK classes TeaVM lacks, natives and reflection. Each finding is
|
||||
triaged as **stub**, **shim**, **rewrite** or **delete** into
|
||||
[`docs/port-backlog.md`](../../docs/port-backlog.md). `tools/webbuild` uses the same rules.
|
||||
|
||||
```sh
|
||||
./incari fetch # once
|
||||
JAVA_HOME=<JDK 25> ./incari survey # about a minute
|
||||
JAVA_HOME=<JDK 25> ./incari survey --reclassify # re-triage the last run, seconds
|
||||
```
|
||||
|
||||
`INCARI_SURVEY_OPTS=-Xmx20g` raises the heap (default 12 GB).
|
||||
|
||||
## How it works
|
||||
|
||||
1. **Class path:** the client jar plus libraries `rules.txt` marks `keep`. Libraries marked
|
||||
`replace` or `delete` (LWJGL, JNA, OSHI…) stay off, so each call into them is a finding.
|
||||
2. **Roots:** every method of every client class is an entry point (except `no-root` packages such
|
||||
as data generators), since following `main()` misses code behind callbacks.
|
||||
3. **Host JDK hidden,** so JDK classes TeaVM lacks are reported, not silently compiled in.
|
||||
4. **Stub rounds:** missing symbols get default-returning stubs, and it recompiles until nothing new
|
||||
turns up. Stubs are for analysis only; everything stubbed is still a finding.
|
||||
5. **Scan and triage:** a bytecode scan adds reflection and missing-class references; each finding
|
||||
takes the first matching rule in `rules.txt`.
|
||||
|
||||
## Files
|
||||
|
||||
| File | What |
|
||||
| --- | --- |
|
||||
| `rules.txt` | The policy: which libraries compile in, which packages aren't roots, a triage rule per work item |
|
||||
| `Main`, `Roots`, `TeaVmSurvey`, `Stubs`, `BytecodeScanner`, `Backlog` | Orchestration, roots, compile rounds, scan, markdown |
|
||||
| `docs/port-backlog.md` (tracked) | Counts and a table per work item: API and package names only, never game code |
|
||||
| `work/survey/<version>/` (ignored) | Every call site, and the saved result `--reclassify` reuses |
|
||||
|
||||
## Invariants
|
||||
|
||||
- **Exactly JDK 25.** TeaVM can't read Java 26 classes, and "missing" depends on the JDK.
|
||||
- **Deterministic:** sorted, no timestamps.
|
||||
- **Every library has a rule,** and no committed backlog has unclassified findings.
|
||||
|
||||
## How to test
|
||||
|
||||
```sh
|
||||
./gradlew :tools:survey:test # rules, stubs and roots; the full survey runs by hand
|
||||
```
|
||||
@@ -0,0 +1,32 @@
|
||||
plugins {
|
||||
application
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// Reuses the build tool's workspace layout and version pin, so the survey always reads
|
||||
// the same jars `incari fetch` downloaded.
|
||||
implementation(project(":tools:build"))
|
||||
implementation(libs.teavm.tooling)
|
||||
implementation(libs.teavm.core)
|
||||
implementation(libs.teavm.classlib)
|
||||
implementation(libs.asm)
|
||||
implementation(libs.gson)
|
||||
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testImplementation(libs.assertj)
|
||||
testRuntimeOnly(libs.junit.launcher)
|
||||
}
|
||||
|
||||
application {
|
||||
applicationName = "incari-survey"
|
||||
mainClass = "incari.tools.survey.Main"
|
||||
// TeaVM's dependency analysis over the whole client plus its libraries is memory-hungry.
|
||||
// Override with INCARI_SURVEY_OPTS="-Xmx..." on smaller machines.
|
||||
applicationDefaultJvmArgs = listOf("-Xmx12g", "-Dincari.teavm.version=${libs.versions.teavm.get()}")
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
// SurveyRulesTest parses the real rules.txt from the module directory.
|
||||
workingDir = projectDir
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
# TeaVM survey policy. Read by `./incari survey`; see tools/survey/README.md.
|
||||
#
|
||||
# Two kinds of lines:
|
||||
# library <maven coordinate prefix> <keep|replace|delete> <reason>
|
||||
# <stub|shim|rewrite|delete> <selector>=<glob>... <reason: the work item's name in the backlog>
|
||||
#
|
||||
# Triage rules are tried top to bottom; the first match wins, so put narrow rules first.
|
||||
# Selectors: symbol (API used, owner#member), caller (class needing work), origin
|
||||
# (minecraft, or a library's artifact id), kind (missing-class, missing-method, missing-field,
|
||||
# unsupported-method, missing-supertype, native, host-jdk, reflection).
|
||||
# Globs: * stays inside one name segment, ** matches anything.
|
||||
|
||||
# ---------------------------------------------------------------------------------------------
|
||||
# Libraries. Only `keep` libraries are compiled with the game. The rest are left off the
|
||||
# classpath on purpose, so every place the game calls them shows up as its own finding.
|
||||
# Every non-native library in Mojang's version JSON must match one line.
|
||||
# ---------------------------------------------------------------------------------------------
|
||||
|
||||
library org.lwjgl: replace Platform layer: WebGL2, canvas input, Web Audio, fonts
|
||||
library net.java.dev.jna: delete Native interop; only OSHI and OS integration use it
|
||||
library com.github.oshi: delete Hardware and OS telemetry
|
||||
library com.mojang:jtracy: delete Tracy profiler (native)
|
||||
library com.mojang:text2speech: replace Narrator; the browser has the Web Speech API
|
||||
library ca.weblite:java-objc-bridge: delete macOS-only native bridge
|
||||
library com.microsoft.azure:msal4j: delete Microsoft login; the browser build uses offline or Eagler identity
|
||||
library com.azure:azure-json: delete Only used by msal4j
|
||||
library com.ibm.icu:icu4j: replace Bidi text; the browser has Intl, or a minimal shim
|
||||
library org.apache.logging.log4j:log4j-core: replace Console logging shim
|
||||
library org.apache.logging.log4j:log4j-slf4j2-impl: replace Console logging shim
|
||||
library io.netty:netty-buffer: keep FriendlyByteBuf extends ByteBuf; pure Java in heap mode
|
||||
library io.netty:netty-common: keep Needed by netty-buffer
|
||||
library io.netty:netty-transport: keep The game's Connection is a Netty pipeline; it runs over the WebSocket transport (ADR 0008)
|
||||
library io.netty:netty-codec-base: keep The game's packet codecs extend its encoders and decoders
|
||||
library io.netty:netty-handler: keep The read timeout and flow control in the game's pipeline
|
||||
library io.netty:netty-resolver: keep Bootstrap's address resolution; WebSocket addresses need none
|
||||
library io.netty: replace Native transports, compression and HTTP codecs: the browser has none of them
|
||||
library at.yawk.lz4: keep Has a pure-Java implementation
|
||||
library com.google. keep Guava, Gson, failureaccess: pure Java
|
||||
library com.mojang:authlib: keep GameProfile and properties are used everywhere; its HTTP parts get cut
|
||||
library com.mojang: keep Brigadier, DataFixerUpper codecs, logging, blocklist, patchy
|
||||
library commons-codec: keep Pure Java
|
||||
library commons-io: keep Pure Java
|
||||
library org.apache.commons: keep commons-lang3, commons-compress: pure Java
|
||||
library it.unimi.dsi:fastutil: keep Pure Java collections
|
||||
library net.sf.jopt-simple: keep Command-line parsing for Main
|
||||
library org.apache.logging.log4j:log4j-api: keep API only; backed by the console shim
|
||||
library org.slf4j: keep API only; backed by the console shim
|
||||
library org.jcraft:jorbis: keep Pure-Java Ogg Vorbis decoder, useful for Web Audio
|
||||
library org.joml: keep Pure Java math
|
||||
library org.jspecify: keep Annotations only
|
||||
|
||||
# ---------------------------------------------------------------------------------------------
|
||||
# Analysis roots. Every class in the client jar is a root (see Roots.java) except these, which
|
||||
# ship in the jar but never run in the client.
|
||||
# ---------------------------------------------------------------------------------------------
|
||||
|
||||
no-root net.minecraft.data.** Data generators run at Mojang's build time
|
||||
no-root net.minecraft.client.data.** Client-side data generators
|
||||
no-root net.minecraft.gametest.** Automated game tests
|
||||
no-root net.minecraft.server.Main Dedicated server entry point
|
||||
no-root net.minecraft.server.Main$* Dedicated server entry point
|
||||
no-root net.minecraft.server.Eula Dedicated server EULA file
|
||||
no-root net.minecraft.server.ConsoleInput Dedicated server console
|
||||
no-root net.minecraft.server.dedicated.** Dedicated server
|
||||
no-root net.minecraft.server.gui.** Dedicated server Swing GUI
|
||||
no-root net.minecraft.server.rcon.** Dedicated server remote console
|
||||
no-root net.minecraft.server.jsonrpc.** Dedicated server management protocol
|
||||
no-root net.minecraft.server.chase.** Debug tool that mirrors a player between servers
|
||||
|
||||
# ---------------------------------------------------------------------------------------------
|
||||
# Triage. The reason is the work item's name in docs/port-backlog.md; rule lines that share a
|
||||
# reason form one work item. Narrow rules first.
|
||||
# ---------------------------------------------------------------------------------------------
|
||||
|
||||
# --- Delete: features the browser build strips --------------------------------------------
|
||||
|
||||
delete symbol=com.mojang.jtracy.** Tracy profiler hooks
|
||||
delete caller=net.minecraft.util.profiling.jfr.** Java Flight Recorder profiling
|
||||
delete symbol=jdk.jfr.** Java Flight Recorder profiling
|
||||
delete symbol=io.netty.buffer.*Event Java Flight Recorder profiling
|
||||
delete symbol=oshi.** OSHI hardware info (crash reports, telemetry)
|
||||
delete symbol=com.sun.jna.** JNA Windows process inspection (crash reports)
|
||||
delete symbol=ca.weblite.** macOS window integration
|
||||
delete caller=com.mojang.renderpearl.backend.vulkan.** Vulkan backend (the browser gets WebGL2, later WebGPU)
|
||||
delete symbol=org.lwjgl.vulkan.** Vulkan backend (the browser gets WebGL2, later WebGPU)
|
||||
delete symbol=org.lwjgl.util.vma.** Vulkan backend (the browser gets WebGL2, later WebGPU)
|
||||
delete symbol=org.lwjgl.sdl.SDLVulkan Vulkan backend (the browser gets WebGL2, later WebGPU)
|
||||
delete caller=com.mojang.realmsclient.** Realms (Mojang's hosting service and its HTTP client)
|
||||
delete caller=net.minecraft.server.dedicated.** Dedicated server code the client reaches (watchdog, properties)
|
||||
delete caller=net.minecraft.server.chase.** Debug tool that mirrors a player between servers
|
||||
delete caller=com.viaversion.viaversion.libs.snakeyaml.** Via's bundled YAML parser: Incari keeps Via's settings in memory (ADR 0017)
|
||||
delete symbol=io.netty.channel.epoll.** Native socket transports (epoll, kqueue)
|
||||
delete symbol=io.netty.channel.kqueue.** Native socket transports (epoll, kqueue)
|
||||
delete symbol=java.net.DatagramSocket LAN world discovery and hosting (UDP multicast, server sockets)
|
||||
delete symbol=java.net.DatagramPacket LAN world discovery and hosting (UDP multicast, server sockets)
|
||||
delete symbol=java.net.MulticastSocket LAN world discovery and hosting (UDP multicast, server sockets)
|
||||
delete symbol=java.net.ServerSocket LAN world discovery and hosting (UDP multicast, server sockets)
|
||||
delete symbol=javax.naming.** DNS SRV lookup of server addresses (JNDI)
|
||||
delete symbol=org.osgi.** Library support for optional runtimes (OSGi, Log4j 1, java.sql)
|
||||
delete symbol=org.apache.log4j.** Library support for optional runtimes (OSGi, Log4j 1, java.sql)
|
||||
delete symbol=java.sql.** Library support for optional runtimes (OSGi, Log4j 1, java.sql)
|
||||
delete symbol=org.lwjgl.system.Configuration Native library loading and LWJGL setup
|
||||
delete symbol=org.lwjgl.system.Platform** Native library loading and LWJGL setup
|
||||
delete symbol=org.lwjgl.system.SharedLibrary Native library loading and LWJGL setup
|
||||
delete symbol=org.lwjgl.system.Library Native library loading and LWJGL setup
|
||||
delete symbol=org.lwjgl.Version Native library loading and LWJGL setup
|
||||
delete symbol=org.lwjgl.util.shaderc.Shaderc#getLibrary Native library loading and LWJGL setup
|
||||
delete symbol=org.lwjgl.util.spvc.Spvc#getLibrary Native library loading and LWJGL setup
|
||||
delete symbol=java.lang.UnsatisfiedLinkError Native library loading and LWJGL setup
|
||||
delete caller=io.netty.util.NetUtil symbol=java.lang.Process** Operating system queries in Netty (somaxconn through sysctl): a page runs no processes
|
||||
delete symbol=javax.management.** JMX server monitoring (MBeans)
|
||||
delete symbol=com.microsoft.aad.** Microsoft account services (login, server chat filter)
|
||||
delete symbol=java.security.** Encryption and signing (Mojang auth, chat signing, key pairs); offline and Eagler modes don't use them
|
||||
delete symbol=javax.security.** Encryption and signing (Mojang auth, chat signing, key pairs); offline and Eagler modes don't use them
|
||||
delete symbol=javax.crypto.** Encryption and signing (Mojang auth, chat signing, key pairs); offline and Eagler modes don't use them
|
||||
|
||||
# --- Rewrite: the platform layer ------------------------------------------------------------
|
||||
|
||||
rewrite caller=com.mojang.renderpearl.backend.opengl.** OpenGL backend: replace with a WebGL2 GpuDevice backend
|
||||
rewrite symbol=org.lwjgl.opengl.** OpenGL backend: replace with a WebGL2 GpuDevice backend
|
||||
rewrite symbol=org.lwjgl.util.shaderc.** Shader toolchain: GLSL to SPIR-V (shaderc) and back (SPIRV-Cross) runs natively; move it to build time
|
||||
rewrite symbol=org.lwjgl.util.spvc.** Shader toolchain: GLSL to SPIR-V (shaderc) and back (SPIRV-Cross) runs natively; move it to build time
|
||||
rewrite symbol=org.lwjgl.BufferUtils Off-heap memory (MemoryUtil, MemoryStack, pointers): rewrite over ArrayBuffer
|
||||
rewrite symbol=org.lwjgl.system.MemoryStack** Off-heap memory (MemoryUtil, MemoryStack, pointers): rewrite over ArrayBuffer
|
||||
rewrite symbol=org.lwjgl.system.MemoryUtil** Off-heap memory (MemoryUtil, MemoryStack, pointers): rewrite over ArrayBuffer
|
||||
rewrite symbol=org.lwjgl.PointerBuffer Off-heap memory (MemoryUtil, MemoryStack, pointers): rewrite over ArrayBuffer
|
||||
rewrite symbol=org.lwjgl.system.** Off-heap memory (MemoryUtil, MemoryStack, pointers): rewrite over ArrayBuffer
|
||||
rewrite symbol=org.lwjgl.sdl.** Window, input, clipboard and events (SDL3): canvas, Pointer Lock and DOM events
|
||||
rewrite symbol=org.lwjgl.openal.** Audio (OpenAL): Web Audio
|
||||
rewrite symbol=javax.sound.** Audio (OpenAL): Web Audio
|
||||
rewrite symbol=org.lwjgl.stb.** Image decode and encode (STB): createImageBitmap or a pure-Java codec
|
||||
rewrite symbol=com.mojang.blaze3d.platform.NativeImage$WriteCallback Image decode and encode (STB): createImageBitmap or a pure-Java codec
|
||||
rewrite symbol=org.lwjgl.util.freetype.** TrueType fonts (FreeType): pre-baked glyph atlases, Canvas2D for pack fonts
|
||||
rewrite caller=io.netty.channel.nio.** symbol=java.nio.** Netty's NIO transport (selectors, socket channels): in the browser, connections are WebSockets on local event loops
|
||||
rewrite caller=io.netty.channel.socket.nio.** symbol=java.nio.** Netty's NIO transport (selectors, socket channels): in the browser, connections are WebSockets on local event loops
|
||||
rewrite caller=io.netty.util.concurrent.FastThreadLocalThread symbol=java.lang.Thread#<init> Netty's own thread class (a ThreadGroup constructor TeaVM lacks): event loops get their threads from the game's factory
|
||||
rewrite symbol=io.netty.** Netty channels and pipeline: WebSocket transport under Connection
|
||||
rewrite symbol=java.net.** Socket addresses, proxies and HTTP: server addresses become WebSocket URLs, HTTP becomes fetch
|
||||
rewrite kind=reflection origin=minecraft Game code using reflection: replace with direct references
|
||||
rewrite kind=reflection origin=log4j-api Logging backend discovery (ServiceLoader, class loading): bind the console logger directly
|
||||
rewrite kind=reflection origin=slf4j-api Logging backend discovery (ServiceLoader, class loading): bind the console logger directly
|
||||
rewrite origin=slf4j-api symbol=java.lang.** Logging backend discovery (ServiceLoader, class loading): bind the console logger directly
|
||||
rewrite symbol=org.apache.logging.log4j.core.** Logging backend discovery (ServiceLoader, class loading): bind the console logger directly
|
||||
rewrite origin=log4j-api Logging backend discovery (ServiceLoader, class loading): bind the console logger directly
|
||||
rewrite kind=reflection origin=gson Gson reflective type adapters: register explicit adapters, or keep Gson on JsonElement trees
|
||||
rewrite kind=reflection Library reflection: steer the library off the reflective path, or declare it for TeaVM
|
||||
rewrite symbol=java.lang.invoke.** VarHandle and MethodHandle (Netty, Guava atomics): the libraries probe for them and fall back when they throw; patch any game caller
|
||||
|
||||
# --- Shim: JDK APIs TeaVM's class library lacks --------------------------------------------
|
||||
|
||||
stub symbol=sun.misc.Unsafe sun.misc.Unsafe in libraries: stub it as unavailable so Netty, Guava and JOML take their safe fallbacks
|
||||
stub symbol=jdk.internal.misc.Unsafe sun.misc.Unsafe in libraries: stub it as unavailable so Netty, Guava and JOML take their safe fallbacks
|
||||
shim symbol=java.util.concurrent.CompletableFuture CompletableFuture (async loading everywhere): a single-threaded implementation over TeaVM coroutines
|
||||
shim symbol=java.util.concurrent.CompletionException CompletableFuture (async loading everywhere): a single-threaded implementation over TeaVM coroutines
|
||||
shim symbol=java.util.concurrent.*Executor* Executors, thread pools and futures: a coroutine scheduler, later Web Workers
|
||||
shim symbol=java.util.concurrent.ForkJoin* Executors, thread pools and futures: a coroutine scheduler, later Web Workers
|
||||
shim symbol=java.util.concurrent.*Future Executors, thread pools and futures: a coroutine scheduler, later Web Workers
|
||||
shim symbol=java.util.concurrent.*Exception Executors, thread pools and futures: a coroutine scheduler, later Web Workers
|
||||
shim symbol=net.minecraft.util.Util$2 Executors, thread pools and futures: a coroutine scheduler, later Web Workers
|
||||
shim symbol=com.google.common.util.concurrent.** Executors, thread pools and futures: a coroutine scheduler, later Web Workers
|
||||
shim symbol=java.util.concurrent.** Locks, atomics and concurrent queues: single-threaded shims
|
||||
shim symbol=com.google.common.cache.LocalCache$Segment Locks, atomics and concurrent queues: single-threaded shims
|
||||
shim symbol=com.google.common.collect.MapMakerInternalMap$Segment Locks, atomics and concurrent queues: single-threaded shims
|
||||
shim symbol=io.netty.util.concurrent.MpscIntQueue** Locks, atomics and concurrent queues: single-threaded shims
|
||||
shim symbol=java.time.** java.time (dates, durations, formatting): compile a java.time implementation for TeaVM
|
||||
shim symbol=java.nio.file.** Filesystem (java.nio.file, channels, locks, watching): an in-memory file system kept in OPFS or IndexedDB (ADR 0011)
|
||||
shim symbol=java.nio.channels.** Filesystem (java.nio.file, channels, locks, watching): an in-memory file system kept in OPFS or IndexedDB (ADR 0011)
|
||||
shim symbol=java.io.FileInputStream#getChannel Filesystem (java.nio.file, channels, locks, watching): an in-memory file system kept in OPFS or IndexedDB (ADR 0011)
|
||||
shim symbol=java.io.File#toPath Filesystem (java.nio.file, channels, locks, watching): an in-memory file system kept in OPFS or IndexedDB (ADR 0011)
|
||||
shim symbol=com.ibm.icu.** Bidi text and localized dates (ICU): the browser's Intl, or a minimal shim
|
||||
shim symbol=com.mojang.text2speech.** Narrator: Web Speech API
|
||||
shim symbol=java.lang.ScopedValue** ScopedValue (Java 25): a thread-local style shim
|
||||
|
||||
# --- Stub: small gaps where a trivial implementation is enough ------------------------------
|
||||
|
||||
stub symbol=java.lang.management.** JVM memory, GC and thread stats (debug overlay, crash reports, watchdog): report browser numbers or zeros
|
||||
stub symbol=java.lang.StackWalker** Caller lookup (StackWalker, modules): return nothing
|
||||
stub symbol=java.lang.Module** Caller lookup (StackWalker, modules): return nothing
|
||||
stub symbol=java.lang.System#exit Process control (exit, shutdown hooks, environment, native libraries): no-ops in a browser tab
|
||||
stub symbol=java.lang.System#getenv Process control (exit, shutdown hooks, environment, native libraries): no-ops in a browser tab
|
||||
stub symbol=java.lang.System#mapLibraryName Process control (exit, shutdown hooks, environment, native libraries): no-ops in a browser tab
|
||||
stub symbol=java.lang.Runtime Process control (exit, shutdown hooks, environment, native libraries): no-ops in a browser tab
|
||||
stub symbol=java.lang.SecurityManager Process control (exit, shutdown hooks, environment, native libraries): no-ops in a browser tab
|
||||
stub symbol=java.lang.RuntimePermission Process control (exit, shutdown hooks, environment, native libraries): no-ops in a browser tab
|
||||
stub symbol=java.lang.Thread Thread details TeaVM lacks (ids, state, onSpinWait): trivial answers under coroutines
|
||||
stub symbol=java.** Small JDK methods and classes TeaVM's class library lacks: add them to the class library
|
||||
stub symbol=javax.** Small JDK methods and classes TeaVM's class library lacks: add them to the class library
|
||||
@@ -0,0 +1,408 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
import incari.tools.build.Log;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Renders {@code docs/port-backlog.md} from the triaged findings.
|
||||
*
|
||||
* <p>The file is tracked, so it holds only API names, package names and counts: never game
|
||||
* code, and never Mojang member names (callers are summarized by package). The output is
|
||||
* sorted and has no timestamp, so rerunning the survey on the same inputs changes nothing.
|
||||
*/
|
||||
final class Backlog {
|
||||
|
||||
private static final int SYMBOLS_PER_ITEM = 12;
|
||||
private static final int PACKAGES_PER_ITEM = 4;
|
||||
|
||||
private final String version;
|
||||
private final String teavmVersion;
|
||||
private final int jdk;
|
||||
private final String entryPoint;
|
||||
private final Set<String> reachableClasses;
|
||||
private final Origins origins;
|
||||
private final List<Main.LibraryDecision> libraries;
|
||||
private final List<Main.Classified> findings;
|
||||
|
||||
Backlog(
|
||||
String version,
|
||||
String teavmVersion,
|
||||
int jdk,
|
||||
String entryPoint,
|
||||
Set<String> reachableClasses,
|
||||
Origins origins,
|
||||
List<Main.LibraryDecision> libraries,
|
||||
List<Main.Classified> findings) {
|
||||
this.version = version;
|
||||
this.teavmVersion = teavmVersion;
|
||||
this.jdk = jdk;
|
||||
this.entryPoint = entryPoint;
|
||||
this.reachableClasses = reachableClasses;
|
||||
this.origins = origins;
|
||||
this.libraries = libraries;
|
||||
this.findings = findings;
|
||||
}
|
||||
|
||||
/** Counts for one category or work item. A call site is one distinct (symbol, caller, line). */
|
||||
private record Tally(int items, long symbols, long sites) {}
|
||||
|
||||
private static Tally tally(List<Main.Classified> group) {
|
||||
long symbols = group.stream().map(c -> c.finding().symbol()).distinct().count();
|
||||
long items = group.stream()
|
||||
.map(c -> c.rule() == null ? null : c.rule().reason())
|
||||
.distinct()
|
||||
.count();
|
||||
return new Tally((int) items, symbols, group.size());
|
||||
}
|
||||
|
||||
String render() {
|
||||
Map<SurveyRules.Category, List<Main.Classified>> byCategory = new LinkedHashMap<>();
|
||||
for (SurveyRules.Category category : SurveyRules.Category.values()) {
|
||||
byCategory.put(category, new ArrayList<>());
|
||||
}
|
||||
List<Main.Classified> unclassified = new ArrayList<>();
|
||||
for (Main.Classified c : findings) {
|
||||
if (c.rule() == null) {
|
||||
unclassified.add(c);
|
||||
} else {
|
||||
byCategory
|
||||
.computeIfAbsent(c.rule().category(), k -> new ArrayList<>())
|
||||
.add(c);
|
||||
}
|
||||
}
|
||||
|
||||
StringBuilder md = new StringBuilder();
|
||||
md.append("# Port backlog: Minecraft ").append(version).append(" under TeaVM\n\n");
|
||||
md.append("Generated by `./incari survey`. Don't edit it by hand: change `")
|
||||
.append(Main.RULES_FILE)
|
||||
.append("` and rerun.\n\n");
|
||||
|
||||
Tally total = tally(findings);
|
||||
md.append("TeaVM ")
|
||||
.append(teavmVersion)
|
||||
.append(" (WebAssembly GC) reaches ")
|
||||
.append(String.format(Locale.ROOT, "%,d", reachableClasses.size()))
|
||||
.append(" classes when every client class is a root (not just what `")
|
||||
.append(entryPoint)
|
||||
.append("` reaches). ")
|
||||
.append(String.format(Locale.ROOT, "%,d", total.sites()))
|
||||
.append(" call sites use ")
|
||||
.append(String.format(Locale.ROOT, "%,d", total.symbols()))
|
||||
.append(" APIs the browser build can't provide as-is, grouped below into ")
|
||||
.append(byCategory.values().stream()
|
||||
.mapToInt(g -> tally(g).items())
|
||||
.sum())
|
||||
.append(" work items.\n\n");
|
||||
|
||||
md.append("## Summary\n\n");
|
||||
md.append("| Category | Meaning | Work items | APIs | Call sites |\n");
|
||||
md.append("| --- | --- | ---: | ---: | ---: |\n");
|
||||
for (Map.Entry<SurveyRules.Category, List<Main.Classified>> entry : byCategory.entrySet()) {
|
||||
Tally t = tally(entry.getValue());
|
||||
md.append("| ")
|
||||
.append(entry.getKey().title())
|
||||
.append(" | ")
|
||||
.append(entry.getKey().meaning())
|
||||
.append(" | ")
|
||||
.append(t.items())
|
||||
.append(" | ")
|
||||
.append(t.symbols())
|
||||
.append(" | ")
|
||||
.append(t.sites())
|
||||
.append(" |\n");
|
||||
}
|
||||
if (!unclassified.isEmpty()) {
|
||||
Tally t = tally(unclassified);
|
||||
md.append("| Unclassified | No rule matched yet. | - | ")
|
||||
.append(t.symbols())
|
||||
.append(" | ")
|
||||
.append(t.sites())
|
||||
.append(" |\n");
|
||||
}
|
||||
md.append("| **Total** | | ")
|
||||
.append(byCategory.values().stream()
|
||||
.mapToInt(g -> tally(g).items())
|
||||
.sum())
|
||||
.append(" | ")
|
||||
.append(total.symbols())
|
||||
.append(" | ")
|
||||
.append(total.sites())
|
||||
.append(" |\n\n");
|
||||
|
||||
md.append("By kind of finding:\n\n");
|
||||
md.append("| Kind | Call sites | What it means |\n| --- | ---: | --- |\n");
|
||||
Map<Finding.Kind, Long> byKind = findings.stream()
|
||||
.collect(Collectors.groupingBy(c -> c.finding().kind(), TreeMap::new, Collectors.counting()));
|
||||
for (Map.Entry<Finding.Kind, Long> entry : byKind.entrySet()) {
|
||||
md.append("| ")
|
||||
.append(entry.getKey().label())
|
||||
.append(" | ")
|
||||
.append(entry.getValue())
|
||||
.append(" | ")
|
||||
.append(kindMeaning(entry.getKey()))
|
||||
.append(" |\n");
|
||||
}
|
||||
md.append('\n');
|
||||
|
||||
for (Map.Entry<SurveyRules.Category, List<Main.Classified>> entry : byCategory.entrySet()) {
|
||||
renderCategory(md, entry.getKey(), entry.getValue());
|
||||
}
|
||||
if (!unclassified.isEmpty()) {
|
||||
md.append("## Unclassified\n\n");
|
||||
md.append("No rule in `")
|
||||
.append(Main.RULES_FILE)
|
||||
.append("` matches these yet. Add rules until this section disappears.\n\n");
|
||||
renderSymbols(md, unclassified, Integer.MAX_VALUE);
|
||||
}
|
||||
|
||||
renderInputs(md);
|
||||
md.append("## Reading this backlog\n\n");
|
||||
md.append("- **It's the first layer.** TeaVM stops following calls at anything it can't resolve, so stubbing"
|
||||
+ " these items uncovers more. Rerun the survey after each round of porting work.\n");
|
||||
md.append("- **Call sites** are distinct (API, calling class, line) triples. Findings TeaVM reported inside JDK"
|
||||
+ " or class-library code are charged to the nearest game or library method that calls into it.\n");
|
||||
md.append("- **JDK classes TeaVM lacks.** Left alone, TeaVM would copy them from the JDK running the compile,"
|
||||
+ " dragging in JDK internals that can't work in a browser. The survey hides the host JDK, so each is"
|
||||
+ " listed where the game uses it.\n");
|
||||
md.append("- **Whole client, not one path.** Every class in the client jar is an analysis root, except the"
|
||||
+ " `no-root` packages in `")
|
||||
.append(Main.RULES_FILE)
|
||||
.append(
|
||||
"` (data generators, dedicated server)."
|
||||
+ " Code only the integrated server runs is included; singleplayer is deferred, but its code ships.\n");
|
||||
md.append("- **Stubs let the analysis continue.** TeaVM stops at anything missing, so the survey compiles in"
|
||||
+ " rounds, stubbing what each round reports, until nothing new appears. Stubbed items are still"
|
||||
+ " findings.\n");
|
||||
md.append("- **Full detail** (every call site with its method and line) is in `work/survey/")
|
||||
.append(version)
|
||||
.append("/findings.json` after a local run. It stays out of git because it names"
|
||||
+ " Mojang methods.\n");
|
||||
return md.toString();
|
||||
}
|
||||
|
||||
/** The reason of the rule that classified {@code c}; category groups hold only classified findings. */
|
||||
private static String ruleReason(Main.Classified c) {
|
||||
SurveyRules.TriageRule rule = c.rule();
|
||||
if (rule == null) {
|
||||
throw new IllegalStateException(
|
||||
"Unclassified finding in a category group: " + c.finding().symbol());
|
||||
}
|
||||
return rule.reason();
|
||||
}
|
||||
|
||||
private void renderCategory(StringBuilder md, SurveyRules.Category category, List<Main.Classified> group) {
|
||||
md.append("## ").append(category.title()).append("\n\n");
|
||||
if (group.isEmpty()) {
|
||||
md.append("Nothing in this category.\n\n");
|
||||
return;
|
||||
}
|
||||
Tally t = tally(group);
|
||||
md.append(category.meaning())
|
||||
.append(' ')
|
||||
.append(t.items())
|
||||
.append(" work items, ")
|
||||
.append(t.symbols())
|
||||
.append(" APIs, ")
|
||||
.append(t.sites())
|
||||
.append(" call sites.\n\n");
|
||||
|
||||
// Several rule lines may share a reason: together they are one work item.
|
||||
Map<String, List<Main.Classified>> byItem = group.stream()
|
||||
.collect(Collectors.groupingBy(Backlog::ruleReason, LinkedHashMap::new, Collectors.toList()));
|
||||
List<Map.Entry<String, List<Main.Classified>>> items = new ArrayList<>(byItem.entrySet());
|
||||
items.sort(Comparator.<Map.Entry<String, List<Main.Classified>>>comparingInt(
|
||||
e -> -e.getValue().size())
|
||||
.thenComparing(Map.Entry::getKey));
|
||||
|
||||
md.append("| Work item | APIs | Call sites | Where the calls are |\n| --- | ---: | ---: | --- |\n");
|
||||
for (Map.Entry<String, List<Main.Classified>> item : items) {
|
||||
Tally it = tally(item.getValue());
|
||||
md.append("| ")
|
||||
.append(escape(item.getKey()))
|
||||
.append(" | ")
|
||||
.append(it.symbols())
|
||||
.append(" | ")
|
||||
.append(it.sites())
|
||||
.append(" | ")
|
||||
.append(callerSummary(item.getValue()))
|
||||
.append(" |\n");
|
||||
}
|
||||
md.append('\n');
|
||||
|
||||
for (Map.Entry<String, List<Main.Classified>> item : items) {
|
||||
md.append("### ").append(escape(item.getKey())).append("\n\n");
|
||||
renderSymbols(md, item.getValue(), SYMBOLS_PER_ITEM);
|
||||
}
|
||||
}
|
||||
|
||||
private void renderSymbols(StringBuilder md, List<Main.Classified> group, int limit) {
|
||||
Map<String, List<Main.Classified>> bySymbol = group.stream()
|
||||
.collect(Collectors.groupingBy(c -> c.finding().symbol(), TreeMap::new, Collectors.toList()));
|
||||
List<Map.Entry<String, List<Main.Classified>>> symbols = new ArrayList<>(bySymbol.entrySet());
|
||||
symbols.sort(Comparator.<Map.Entry<String, List<Main.Classified>>>comparingInt(
|
||||
e -> -e.getValue().size())
|
||||
.thenComparing(Map.Entry::getKey));
|
||||
|
||||
md.append("| API | Kind | Call sites |\n| --- | --- | ---: |\n");
|
||||
int shown = 0;
|
||||
for (Map.Entry<String, List<Main.Classified>> symbol : symbols) {
|
||||
if (shown++ == limit) {
|
||||
int restSites = symbols.subList(limit, symbols.size()).stream()
|
||||
.mapToInt(e -> e.getValue().size())
|
||||
.sum();
|
||||
md.append("| ...and ")
|
||||
.append(symbols.size() - limit)
|
||||
.append(" more | | ")
|
||||
.append(restSites)
|
||||
.append(" |\n");
|
||||
break;
|
||||
}
|
||||
String kinds = symbol.getValue().stream()
|
||||
.map(c -> c.finding().kind().label())
|
||||
.distinct()
|
||||
.sorted()
|
||||
.collect(Collectors.joining(", "));
|
||||
md.append("| `")
|
||||
.append(symbol.getKey())
|
||||
.append("` | ")
|
||||
.append(kinds)
|
||||
.append(" | ")
|
||||
.append(symbol.getValue().size())
|
||||
.append(" |\n");
|
||||
}
|
||||
md.append('\n');
|
||||
}
|
||||
|
||||
/** "net.minecraft.client.renderer (40), guava (3)": where the calls come from, by package. */
|
||||
private String callerSummary(List<Main.Classified> group) {
|
||||
Map<String, Long> counts =
|
||||
group.stream().collect(Collectors.groupingBy(c -> callerArea(c), HashMap::new, Collectors.counting()));
|
||||
List<Map.Entry<String, Long>> sorted = new ArrayList<>(counts.entrySet());
|
||||
sorted.sort(Map.Entry.<String, Long>comparingByValue().reversed().thenComparing(Map.Entry::getKey));
|
||||
String shown = sorted.stream()
|
||||
.limit(PACKAGES_PER_ITEM)
|
||||
.map(e -> "`" + e.getKey() + "` (" + e.getValue() + ")")
|
||||
.collect(Collectors.joining(", "));
|
||||
return sorted.size() > PACKAGES_PER_ITEM
|
||||
? shown + ", +" + (sorted.size() - PACKAGES_PER_ITEM) + " more"
|
||||
: shown;
|
||||
}
|
||||
|
||||
/** A Minecraft caller's package, or a library's name. Never a Mojang class or member name. */
|
||||
private String callerArea(Main.Classified c) {
|
||||
String caller = c.finding().caller();
|
||||
if (caller == null) {
|
||||
return "unknown";
|
||||
}
|
||||
String origin = origins.of(caller);
|
||||
if (!Origins.MINECRAFT.equals(origin)) {
|
||||
return origin;
|
||||
}
|
||||
int dot = caller.lastIndexOf('.');
|
||||
return dot > 0 ? caller.substring(0, dot) : caller;
|
||||
}
|
||||
|
||||
private void renderInputs(StringBuilder md) {
|
||||
md.append("## Inputs\n\n");
|
||||
md.append("- Minecraft ")
|
||||
.append(version)
|
||||
.append(", entry point `")
|
||||
.append(entryPoint)
|
||||
.append("` plus every client class except the `no-root` packages\n");
|
||||
md.append("- TeaVM ")
|
||||
.append(teavmVersion)
|
||||
.append(", WebAssembly GC target, run on JDK ")
|
||||
.append(jdk)
|
||||
.append('\n');
|
||||
Map<String, Long> reachable = reachableClasses.stream()
|
||||
.collect(Collectors.groupingBy(this::originGroup, TreeMap::new, Collectors.counting()));
|
||||
md.append("- Reachable classes by origin: ")
|
||||
.append(reachable.entrySet().stream()
|
||||
.sorted(Map.Entry.<String, Long>comparingByValue()
|
||||
.reversed()
|
||||
.thenComparing(Map.Entry::getKey))
|
||||
.map(e -> e.getKey() + " " + String.format(Locale.ROOT, "%,d", e.getValue()))
|
||||
.collect(Collectors.joining(", ")))
|
||||
.append("\n\n");
|
||||
|
||||
md.append("Libraries, as decided in `")
|
||||
.append(Main.RULES_FILE)
|
||||
.append("`. Only `keep` libraries are compiled;"
|
||||
+ " calls into the others show up above as missing classes at their call sites.\n\n");
|
||||
md.append("| Library | Decision | Why |\n| --- | --- | --- |\n");
|
||||
for (Main.LibraryDecision lib : libraries.stream()
|
||||
.sorted(Comparator.comparing((Main.LibraryDecision l) -> l.action())
|
||||
.thenComparing(Main.LibraryDecision::coordinates))
|
||||
.toList()) {
|
||||
md.append("| `")
|
||||
.append(lib.coordinates())
|
||||
.append("` | ")
|
||||
.append(lib.action().name().toLowerCase(Locale.ROOT))
|
||||
.append(" | ")
|
||||
.append(escape(lib.reason()))
|
||||
.append(" |\n");
|
||||
}
|
||||
md.append('\n');
|
||||
}
|
||||
|
||||
private String originGroup(String className) {
|
||||
if (className.startsWith("incari.survey.")) {
|
||||
return "survey roots";
|
||||
}
|
||||
if (!origins.appClass(className).equals(className)) {
|
||||
return "generated lambda classes";
|
||||
}
|
||||
String origin = origins.of(className);
|
||||
return switch (origin) {
|
||||
case Origins.MINECRAFT -> "Minecraft";
|
||||
case Origins.TEAVM -> "TeaVM class library";
|
||||
case Origins.HOST_JDK -> "stubbed JDK classes";
|
||||
case Origins.ABSENT -> "stubbed library classes";
|
||||
default -> "libraries";
|
||||
};
|
||||
}
|
||||
|
||||
private static String kindMeaning(Finding.Kind kind) {
|
||||
return switch (kind) {
|
||||
case MISSING_CLASS ->
|
||||
"TeaVM can't find the class: not in its class library, or in a library left off the classpath";
|
||||
case MISSING_METHOD -> "The class exists in TeaVM's class library but lacks this method";
|
||||
case MISSING_FIELD -> "The class exists but lacks this field";
|
||||
case UNSUPPORTED_CLASS, UNSUPPORTED_METHOD -> "TeaVM knows it but can't support it on WebAssembly GC";
|
||||
case MISSING_SUPERTYPE -> "A class extends or implements something that isn't on the classpath";
|
||||
case MISSING_BOOTSTRAP -> "An invokedynamic TeaVM can't compile";
|
||||
case NATIVE -> "A JNI method; nothing to call in a browser";
|
||||
case HOST_JDK -> "A JDK class that TeaVM's class library doesn't have; the game or a library uses it here";
|
||||
case REFLECTION -> "Reflective lookup that TeaVM's closed-world compile can't see";
|
||||
case OTHER -> "Any other compiler error";
|
||||
};
|
||||
}
|
||||
|
||||
private static String escape(String text) {
|
||||
return text.replace("|", "\\|");
|
||||
}
|
||||
|
||||
void printSummary() {
|
||||
Map<String, Long> counts = findings.stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
c -> c.rule() == null
|
||||
? "unclassified"
|
||||
: c.rule().category().title().toLowerCase(Locale.ROOT),
|
||||
TreeMap::new,
|
||||
Collectors.counting()));
|
||||
Function<String, Long> get = key -> counts.getOrDefault(key, 0L);
|
||||
Log.info("Call sites: stub " + get.apply("stub") + ", shim " + get.apply("shim") + ", rewrite "
|
||||
+ get.apply("rewrite") + ", delete " + get.apply("delete") + ", unclassified "
|
||||
+ get.apply("unclassified"));
|
||||
}
|
||||
}
|
||||
+242
@@ -0,0 +1,242 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.ClassVisitor;
|
||||
import org.objectweb.asm.Label;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.Type;
|
||||
|
||||
/**
|
||||
* Scans reachable game and library bytecode for two things TeaVM itself doesn't report.
|
||||
*
|
||||
* <ul>
|
||||
* <li><b>Reflection.</b> TeaVM compiles a closed world: it keeps only what it can see being
|
||||
* used. A class loaded by name, or a method looked up by string, is invisible to it
|
||||
* unless declared ahead of time. Each hit is a place to replace with a direct reference.
|
||||
* <li><b>Host-JDK references.</b> Instructions that name a JDK class TeaVM's class library
|
||||
* lacks (see {@link Origins}). TeaVM compiles those from the host JDK, which compiles
|
||||
* but often can't run in a browser. Scanning the declared owner at each instruction
|
||||
* finds exactly the game code that names such a class, with none of the call graph's
|
||||
* virtual-dispatch noise.
|
||||
* </ul>
|
||||
*/
|
||||
public final class BytecodeScanner {
|
||||
|
||||
/** {@code owner -> method names} of reflective entry points. An empty set means "any method". */
|
||||
private static final Map<String, Set<String>> REFLECTIVE = Map.ofEntries(
|
||||
Map.entry(
|
||||
"java/lang/Class",
|
||||
Set.of(
|
||||
"forName",
|
||||
"newInstance",
|
||||
"getDeclaredMethod",
|
||||
"getDeclaredMethods",
|
||||
"getMethod",
|
||||
"getMethods",
|
||||
"getDeclaredField",
|
||||
"getDeclaredFields",
|
||||
"getField",
|
||||
"getFields",
|
||||
"getDeclaredConstructor",
|
||||
"getDeclaredConstructors",
|
||||
"getConstructor",
|
||||
"getConstructors",
|
||||
"getRecordComponents",
|
||||
"getDeclaredClasses",
|
||||
"getAnnotation",
|
||||
"getAnnotations",
|
||||
"getDeclaredAnnotations",
|
||||
"getGenericSuperclass",
|
||||
"getGenericInterfaces")),
|
||||
Map.entry(
|
||||
"java/lang/ClassLoader",
|
||||
Set.of(
|
||||
"loadClass",
|
||||
"getResource",
|
||||
"getResources",
|
||||
"getResourceAsStream",
|
||||
"getSystemClassLoader",
|
||||
"getSystemResource",
|
||||
"getSystemResourceAsStream")),
|
||||
Map.entry("java/lang/reflect/Method", Set.of("invoke")),
|
||||
Map.entry("java/lang/reflect/Constructor", Set.of("newInstance")),
|
||||
Map.entry("java/lang/reflect/Field", Set.of()),
|
||||
Map.entry("java/lang/reflect/Proxy", Set.of("newProxyInstance")),
|
||||
Map.entry("java/lang/reflect/RecordComponent", Set.of("getAccessor")),
|
||||
Map.entry("java/util/ServiceLoader", Set.of("load", "loadInstalled")),
|
||||
Map.entry("java/lang/invoke/MethodHandles", Set.of("lookup", "publicLookup", "privateLookupIn")),
|
||||
// Unsafe isn't listed: it's a host-JDK class, reported as such at every use.
|
||||
Map.entry("java/lang/invoke/MethodHandles$Lookup", Set.of()));
|
||||
|
||||
private BytecodeScanner() {}
|
||||
|
||||
/**
|
||||
* Scans the given app jars, looking only inside {@code reachableMethods}
|
||||
* ({@code owner#name(descriptor)}) so that dead code TeaVM drops anyway doesn't inflate the backlog.
|
||||
*/
|
||||
public static List<Finding> scan(
|
||||
Map<Path, String> jars, Set<String> reachableClasses, Set<String> reachableMethods, Origins origins)
|
||||
throws IOException {
|
||||
List<Finding> findings = new ArrayList<>();
|
||||
for (Path jar : jars.keySet()) {
|
||||
try (JarFile file = new JarFile(jar.toFile())) {
|
||||
Enumeration<JarEntry> entries = file.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
JarEntry entry = entries.nextElement();
|
||||
String name = entry.getName();
|
||||
if (!name.endsWith(".class") || name.startsWith("META-INF/")) {
|
||||
continue;
|
||||
}
|
||||
String className = name.substring(0, name.length() - 6).replace('/', '.');
|
||||
if (!reachableClasses.contains(className)) {
|
||||
continue;
|
||||
}
|
||||
try (InputStream in = file.getInputStream(entry)) {
|
||||
new ClassReader(in)
|
||||
.accept(
|
||||
new Visitor(className, reachableMethods, origins, findings),
|
||||
ClassReader.SKIP_FRAMES);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return findings;
|
||||
}
|
||||
|
||||
private static final class Visitor extends ClassVisitor {
|
||||
private final String className;
|
||||
private final Set<String> reachableMethods;
|
||||
private final Origins origins;
|
||||
private final List<Finding> findings;
|
||||
|
||||
Visitor(String className, Set<String> reachableMethods, Origins origins, List<Finding> findings) {
|
||||
super(Opcodes.ASM9);
|
||||
this.className = className;
|
||||
this.reachableMethods = reachableMethods;
|
||||
this.origins = origins;
|
||||
this.findings = findings;
|
||||
}
|
||||
|
||||
/** A reachable class extending or implementing something TeaVM can't see. */
|
||||
@Override
|
||||
public void visit(
|
||||
int version,
|
||||
int access,
|
||||
String name,
|
||||
@Nullable String signature,
|
||||
@Nullable String superName,
|
||||
String @Nullable [] interfaces) {
|
||||
List<String> supertypes = new ArrayList<>();
|
||||
if (superName != null) {
|
||||
supertypes.add(superName);
|
||||
}
|
||||
if (interfaces != null) {
|
||||
supertypes.addAll(List.of(interfaces));
|
||||
}
|
||||
for (String supertype : supertypes) {
|
||||
String superClass = supertype.replace('/', '.');
|
||||
String origin = origins.of(superClass);
|
||||
if (Origins.ABSENT.equals(origin) || Origins.HOST_JDK.equals(origin)) {
|
||||
Finding.Kind kind =
|
||||
Origins.ABSENT.equals(origin) ? Finding.Kind.MISSING_SUPERTYPE : Finding.Kind.HOST_JDK;
|
||||
findings.add(new Finding(
|
||||
kind, superClass, className + " extends " + superClass, className, null, -1, null));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable MethodVisitor visitMethod(
|
||||
int access,
|
||||
String name,
|
||||
String descriptor,
|
||||
@Nullable String signature,
|
||||
String @Nullable [] exceptions) {
|
||||
if (!reachableMethods.contains(className + "#" + name + descriptor)) {
|
||||
return null;
|
||||
}
|
||||
String callerMethod = name + descriptor;
|
||||
return new MethodVisitor(Opcodes.ASM9) {
|
||||
private int line = -1;
|
||||
|
||||
@Override
|
||||
public void visitLineNumber(int lineNumber, Label start) {
|
||||
line = lineNumber;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitMethodInsn(int opcode, String owner, String method, String desc, boolean isInterface) {
|
||||
Set<String> names = REFLECTIVE.get(owner);
|
||||
if (names != null && (names.isEmpty() || names.contains(method))) {
|
||||
String symbol = owner.replace('/', '.') + "#" + method;
|
||||
findings.add(new Finding(
|
||||
Finding.Kind.REFLECTION, symbol, symbol + desc, className, callerMethod, line, null));
|
||||
}
|
||||
hostJdk(owner, method, desc);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFieldInsn(int opcode, String owner, String field, String desc) {
|
||||
hostJdk(owner, field, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTypeInsn(int opcode, String type) {
|
||||
hostJdk(type, null, null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitLdcInsn(Object value) {
|
||||
if (value instanceof Type type && type.getSort() == Type.OBJECT) {
|
||||
hostJdk(type.getInternalName(), null, null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitTryCatchBlock(Label start, Label end, Label handler, @Nullable String type) {
|
||||
if (type != null) {
|
||||
hostJdk(type, null, null);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Records a reference to a class that isn't compiled from the game's own jars or
|
||||
* TeaVM's class library: either copied from the host JDK, or absent entirely
|
||||
* (a library the rules leave out). TeaVM names an absent class only once, at its
|
||||
* first use; this finds every call site.
|
||||
*/
|
||||
private void hostJdk(String owner, @Nullable String member, @Nullable String desc) {
|
||||
if (owner.startsWith("[")) {
|
||||
return;
|
||||
}
|
||||
String ownerName = owner.replace('/', '.');
|
||||
String origin = origins.of(ownerName);
|
||||
Finding.@Nullable Kind kind =
|
||||
switch (origin) {
|
||||
case Origins.HOST_JDK -> Finding.Kind.HOST_JDK;
|
||||
case Origins.ABSENT -> Finding.Kind.MISSING_CLASS;
|
||||
default -> null;
|
||||
};
|
||||
if (kind == null) {
|
||||
return;
|
||||
}
|
||||
String symbol = member != null ? ownerName + "#" + member : ownerName;
|
||||
String detail = desc != null ? symbol + desc : symbol;
|
||||
findings.add(new Finding(kind, symbol, detail, className, callerMethod, line, null));
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* One place where the client (or a library it keeps) uses something the browser build
|
||||
* can't provide as-is.
|
||||
*
|
||||
* @param kind what went wrong, e.g. a missing method or a reflective call
|
||||
* @param symbol the thing that's missing or used: a class ({@code java.nio.file.Files}),
|
||||
* method ({@code java.nio.file.Files#walk}) or field
|
||||
* @param detail the full descriptor, for the machine-readable report
|
||||
* @param caller the calling class, or {@code null} when TeaVM gives no location
|
||||
* @param callerMethod the calling method's name and descriptor, or {@code null}
|
||||
* @param line source line in the caller, or -1
|
||||
* @param via for findings TeaVM reported inside JDK or class-library code, the method
|
||||
* there that the game's {@code caller} reached it through; otherwise {@code null}
|
||||
*/
|
||||
public record Finding(
|
||||
Kind kind,
|
||||
String symbol,
|
||||
String detail,
|
||||
@Nullable String caller,
|
||||
@Nullable String callerMethod,
|
||||
int line,
|
||||
@Nullable String via) {
|
||||
|
||||
public enum Kind {
|
||||
MISSING_CLASS("missing class"),
|
||||
MISSING_METHOD("missing method"),
|
||||
MISSING_FIELD("missing field"),
|
||||
UNSUPPORTED_CLASS("unsupported on target"),
|
||||
UNSUPPORTED_METHOD("unsupported on target"),
|
||||
MISSING_SUPERTYPE("missing supertype"),
|
||||
MISSING_BOOTSTRAP("unsupported invokedynamic"),
|
||||
NATIVE("native method"),
|
||||
HOST_JDK("JDK class TeaVM lacks"),
|
||||
REFLECTION("reflection"),
|
||||
OTHER("other compiler error");
|
||||
|
||||
private final String label;
|
||||
|
||||
Kind(String label) {
|
||||
this.label = label;
|
||||
}
|
||||
|
||||
public String label() {
|
||||
return label;
|
||||
}
|
||||
|
||||
/** The name rules.txt uses: {@code MISSING_METHOD} -> {@code missing-method}. */
|
||||
public String ruleName() {
|
||||
return name().toLowerCase(java.util.Locale.ROOT).replace('_', '-');
|
||||
}
|
||||
}
|
||||
|
||||
/** The class that owns {@link #symbol}: {@code java.nio.file.Files#walk} → {@code java.nio.file.Files}. */
|
||||
public String owner() {
|
||||
int hash = symbol.indexOf('#');
|
||||
return hash < 0 ? symbol : symbol.substring(0, hash);
|
||||
}
|
||||
|
||||
/** The member part of {@link #symbol}, or {@code null} for a class. */
|
||||
public @Nullable String member() {
|
||||
int hash = symbol.indexOf('#');
|
||||
return hash < 0 ? null : symbol.substring(hash + 1);
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* Hides the running JDK's own class files from TeaVM. When TeaVM's class library has no
|
||||
* replacement for a {@code java.*} class, TeaVM compiles the host JDK's class instead, pulling in
|
||||
* JDK internals that can't run in a browser. Hidden, the gap shows up as a missing class at the
|
||||
* place the game uses it, where Incari can fill it deliberately.
|
||||
*/
|
||||
public final class HostJdkHidingLoader extends ClassLoader {
|
||||
|
||||
private final Origins origins;
|
||||
|
||||
public HostJdkHidingLoader(ClassLoader parent, Origins origins) {
|
||||
super(parent);
|
||||
this.origins = origins;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable URL getResource(String name) {
|
||||
return hidden(name) ? null : super.getResource(name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Enumeration<URL> getResources(String name) throws IOException {
|
||||
return hidden(name) ? Collections.emptyEnumeration() : super.getResources(name);
|
||||
}
|
||||
|
||||
private boolean hidden(String name) {
|
||||
if (!name.endsWith(".class")) {
|
||||
return false;
|
||||
}
|
||||
String className = name.substring(0, name.length() - 6).replace('/', '.');
|
||||
return Origins.HOST_JDK.equals(origins.of(className));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import incari.tools.build.BuildConfig;
|
||||
import incari.tools.build.CliException;
|
||||
import incari.tools.build.FileTrees;
|
||||
import incari.tools.build.GameFiles;
|
||||
import incari.tools.build.Log;
|
||||
import incari.tools.build.Workspace;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* {@code ./incari survey}: the TeaVM compile survey.
|
||||
*
|
||||
* <p>Compiles the pinned client with TeaVM (WebAssembly GC), collects everything that stands
|
||||
* between it and a browser build, triages each finding with {@code tools/survey/rules.txt},
|
||||
* and writes the outputs below. {@code --reclassify} skips the (slow) compile and reuses the
|
||||
* last run's saved TeaVM result, for iterating on the rules.
|
||||
* <ul>
|
||||
* <li>{@code docs/port-backlog.md}: counts per category and one row per work item. Tracked.
|
||||
* It holds API names and counts only, never game code.
|
||||
* <li>{@code work/survey/<version>/findings.json}: every finding with its call site. Git-ignored.
|
||||
* </ul>
|
||||
*/
|
||||
public final class Main {
|
||||
|
||||
static final String ENTRY_POINT = "net.minecraft.client.main.Main";
|
||||
static final String RULES_FILE = "tools/survey/rules.txt";
|
||||
static final String BACKLOG_FILE = "docs/port-backlog.md";
|
||||
|
||||
/**
|
||||
* TeaVM compiles JDK classes it has no replacement for straight from the running JDK, so
|
||||
* the JDK version changes the result. It also can't read class files newer than Java 25.
|
||||
*/
|
||||
static final int REQUIRED_JDK = 25;
|
||||
|
||||
private Main() {}
|
||||
|
||||
public static void main(String[] args) {
|
||||
try {
|
||||
run(List.of(args));
|
||||
} catch (CliException e) {
|
||||
System.err.println("error: " + e.getMessage());
|
||||
System.exit(1);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
System.exit(2);
|
||||
}
|
||||
}
|
||||
|
||||
static void run(List<String> args) throws Exception {
|
||||
boolean reclassify = args.equals(List.of("--reclassify"));
|
||||
if (!args.isEmpty() && !reclassify) {
|
||||
throw new CliException("Usage: ./incari survey [--reclassify]");
|
||||
}
|
||||
int jdk = Runtime.version().feature();
|
||||
if (jdk != REQUIRED_JDK) {
|
||||
throw new CliException(
|
||||
"The survey must run on JDK " + REQUIRED_JDK + " (this is JDK " + jdk + "). TeaVM compiles"
|
||||
+ " missing JDK classes from the running JDK, so another version changes the result.\n"
|
||||
+ "Point JAVA_HOME at a JDK " + REQUIRED_JDK
|
||||
+ ", e.g. JAVA_HOME=/usr/lib/jvm/java-25-openjdk ./incari survey");
|
||||
}
|
||||
|
||||
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(RULES_FILE));
|
||||
|
||||
Map<Path, String> jars = new LinkedHashMap<>();
|
||||
jars.put(game.clientJar(), Origins.MINECRAFT);
|
||||
List<LibraryDecision> libraries = new ArrayList<>();
|
||||
for (GameFiles.LibraryJar lib : game.libraries()) {
|
||||
String name = lib.library().name();
|
||||
SurveyRules.LibraryRule rule = rules.library(name);
|
||||
libraries.add(new LibraryDecision(name, rule.action(), rule.reason()));
|
||||
if (rule.action() == SurveyRules.LibraryAction.KEEP) {
|
||||
jars.put(lib.jar(), name.split(":", -1)[1]);
|
||||
}
|
||||
}
|
||||
|
||||
Origins origins = new Origins(jars, Main.class.getClassLoader());
|
||||
Path outDir = ws.surveyDir(config.minecraftVersion());
|
||||
Files.createDirectories(outDir);
|
||||
|
||||
Path teavmFindings = outDir.resolve("teavm-findings.json");
|
||||
Path reachableClassesFile = outDir.resolve("reachable-classes.txt");
|
||||
Path reachableMethodsFile = outDir.resolve("reachable-methods.txt");
|
||||
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
||||
TeaVmSurvey.Result result;
|
||||
if (reclassify) {
|
||||
if (!Files.isRegularFile(teavmFindings)) {
|
||||
throw new CliException("No saved TeaVM result in " + outDir + ". Run ./incari survey first.");
|
||||
}
|
||||
Log.step("Reusing the saved TeaVM result (--reclassify)");
|
||||
result = new TeaVmSurvey.Result(
|
||||
List.of(gson.fromJson(Files.readString(teavmFindings), Finding[].class)),
|
||||
new java.util.TreeSet<>(Files.readAllLines(reachableClassesFile)),
|
||||
new java.util.HashSet<>(Files.readAllLines(reachableMethodsFile)));
|
||||
} else {
|
||||
Log.step("Compiling " + game.version().id() + " with TeaVM " + teavmVersion()
|
||||
+ " (WebAssembly GC, in rounds; about a minute)");
|
||||
long start = System.nanoTime();
|
||||
Path rootsDir = outDir.resolve("roots");
|
||||
FileTrees.deleteRecursively(rootsDir);
|
||||
int rooted = Roots.generate(game.clientJar(), rules::isRooted, ENTRY_POINT, rootsDir);
|
||||
Log.info("Rooting " + rooted + " client classes, so the whole client is analysed, not only what"
|
||||
+ " main() reaches");
|
||||
result = TeaVmSurvey.run(Roots.ENTRY, jars, rootsDir, origins, outDir);
|
||||
Log.info("TeaVM analysis took " + (System.nanoTime() - start) / 1_000_000_000 + "s, "
|
||||
+ result.reachableClasses().size() + " reachable classes");
|
||||
Files.write(reachableClassesFile, result.reachableClasses());
|
||||
Files.write(
|
||||
reachableMethodsFile,
|
||||
result.reachableAppMethods().stream().sorted().toList());
|
||||
Files.writeString(teavmFindings, gson.toJson(result.findings()));
|
||||
}
|
||||
|
||||
Log.step("Scanning reachable code for reflection and host-JDK references");
|
||||
List<Finding> scanned =
|
||||
BytecodeScanner.scan(jars, result.reachableClasses(), result.reachableAppMethods(), origins);
|
||||
// For classes TeaVM can't see (libraries left off the classpath, host-JDK classes), the
|
||||
// scan lists every call site in reachable game code, while TeaVM names each one once
|
||||
// (or, once stubbed, per member).
|
||||
// Keep TeaVM's entries only where the scan can't see: callers outside the game's jars.
|
||||
Set<Finding> findings = new LinkedHashSet<>();
|
||||
for (Finding f : result.findings()) {
|
||||
if (f.caller() != null && f.caller().startsWith("incari.survey.roots.")) {
|
||||
continue; // raised by the synthetic roots' own calls; the scan covers the real callers
|
||||
}
|
||||
boolean coveredByScan =
|
||||
switch (f.kind()) {
|
||||
case MISSING_CLASS, MISSING_METHOD, MISSING_FIELD ->
|
||||
TeaVmSurvey.stubbedAsClass(origins, f.owner())
|
||||
&& f.caller() != null
|
||||
&& origins.isApp(f.caller());
|
||||
// TeaVM reports these without the extending class; the scan names every one.
|
||||
case MISSING_SUPERTYPE -> true;
|
||||
default -> false;
|
||||
};
|
||||
if (!coveredByScan) {
|
||||
findings.add(f);
|
||||
}
|
||||
}
|
||||
findings.addAll(scanned);
|
||||
|
||||
List<Classified> classified = new ArrayList<>();
|
||||
for (Finding finding : findings) {
|
||||
@Nullable String origin = finding.caller() != null ? origins.of(finding.caller()) : null;
|
||||
classified.add(new Classified(
|
||||
finding, origin, rules.classify(finding, finding.kind().ruleName(), origin)));
|
||||
}
|
||||
|
||||
List<Map<String, Object>> json = new ArrayList<>();
|
||||
for (Classified c : classified) {
|
||||
Map<String, Object> entry = new LinkedHashMap<>();
|
||||
entry.put(
|
||||
"category",
|
||||
c.rule() != null ? c.rule().category().name().toLowerCase(java.util.Locale.ROOT) : "unclassified");
|
||||
entry.put("rule", c.rule() != null ? c.rule().reason() : null);
|
||||
entry.put("origin", c.origin());
|
||||
entry.put("finding", c.finding());
|
||||
json.add(entry);
|
||||
}
|
||||
Files.writeString(outDir.resolve("findings.json"), gson.toJson(json));
|
||||
Backlog backlog = new Backlog(
|
||||
game.version().id(),
|
||||
teavmVersion(),
|
||||
jdk,
|
||||
ENTRY_POINT,
|
||||
result.reachableClasses(),
|
||||
origins,
|
||||
libraries,
|
||||
classified);
|
||||
Files.writeString(ws.repoRoot().resolve(BACKLOG_FILE), backlog.render());
|
||||
|
||||
Log.step("Wrote " + BACKLOG_FILE + " and work/survey/" + game.version().id() + "/findings.json");
|
||||
backlog.printSummary();
|
||||
}
|
||||
|
||||
record LibraryDecision(String coordinates, SurveyRules.LibraryAction action, String reason) {}
|
||||
|
||||
/** A finding with its caller's origin and the rule that triaged it ({@code null}: unclassified). */
|
||||
record Classified(Finding finding, @Nullable String origin, SurveyRules.@Nullable TriageRule rule) {}
|
||||
|
||||
/** Set by the Gradle build from the version catalog; TeaVM's jars don't record their own version. */
|
||||
static String teavmVersion() {
|
||||
return System.getProperty("incari.teavm.version", "unknown");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
|
||||
/**
|
||||
* Knows where each class comes from: the Minecraft client jar, one of its libraries, TeaVM's
|
||||
* browser class library, or (the case worth flagging) the JDK running the survey.
|
||||
*
|
||||
* <p>That last one matters because TeaVM compiles a {@code java.*} class straight from the
|
||||
* host JDK when its own class library has no replacement, dragging in JDK internals
|
||||
* ({@code jdk.internal.*}, {@code sun.*}) that were never meant to run in a browser. The
|
||||
* survey hides those classes from TeaVM and reports each use instead.
|
||||
*/
|
||||
public final class Origins {
|
||||
|
||||
public static final String MINECRAFT = "minecraft";
|
||||
public static final String TEAVM = "teavm-classlib";
|
||||
public static final String HOST_JDK = "host-jdk";
|
||||
/** Nowhere: a library the rules leave off the classpath, or a class nobody ships. */
|
||||
public static final String ABSENT = "absent";
|
||||
|
||||
private final Map<String, String> appClasses = new HashMap<>();
|
||||
private final Map<String, Boolean> classlibCache = new HashMap<>();
|
||||
private final Map<String, Boolean> jdkCache = new HashMap<>();
|
||||
private final ClassLoader teavmLoader;
|
||||
|
||||
/**
|
||||
* @param jars each app jar (client and kept libraries) mapped to its origin name
|
||||
* @param teavmLoader a loader that can see TeaVM's class library
|
||||
*/
|
||||
public Origins(Map<Path, String> jars, ClassLoader teavmLoader) throws IOException {
|
||||
this.teavmLoader = teavmLoader;
|
||||
for (Map.Entry<Path, String> jar : jars.entrySet()) {
|
||||
try (JarFile file = new JarFile(jar.getKey().toFile())) {
|
||||
Enumeration<JarEntry> entries = file.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
String name = entries.nextElement().getName();
|
||||
if (name.endsWith(".class") && !name.startsWith("META-INF/")) {
|
||||
appClasses.putIfAbsent(
|
||||
name.substring(0, name.length() - 6).replace('/', '.'), jar.getValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** {@link #MINECRAFT}, a library name, {@link #TEAVM}, {@link #HOST_JDK} or {@link #ABSENT}. */
|
||||
public String of(String className) {
|
||||
String app = appClasses.get(appClass(className));
|
||||
if (app != null) {
|
||||
return app;
|
||||
}
|
||||
if (isInClasslib(className)) {
|
||||
return TEAVM;
|
||||
}
|
||||
return isInJdk(className) ? HOST_JDK : ABSENT;
|
||||
}
|
||||
|
||||
/** True for code Incari compiles as part of the game: the client and its kept libraries. */
|
||||
public boolean isApp(String className) {
|
||||
return appClasses.containsKey(appClass(className));
|
||||
}
|
||||
|
||||
/**
|
||||
* The jar class behind a name. TeaVM compiles lambdas into synthetic classes named after
|
||||
* their enclosing class ({@code net.minecraft.util.Util$makeIoExecutor$lambda$_20_0}) that
|
||||
* exist in no jar; those belong to the enclosing class.
|
||||
*/
|
||||
public String appClass(String className) {
|
||||
if (appClasses.containsKey(className)) {
|
||||
return className;
|
||||
}
|
||||
int lambda = className.indexOf("$lambda$");
|
||||
if (lambda > 0) {
|
||||
String outer = className.substring(0, lambda);
|
||||
for (int dollar = outer.length(); dollar > 0; dollar = outer.lastIndexOf('$', dollar - 1)) {
|
||||
String candidate = outer.substring(0, dollar);
|
||||
if (appClasses.containsKey(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
return className;
|
||||
}
|
||||
|
||||
private boolean isInJdk(String className) {
|
||||
return jdkCache.computeIfAbsent(
|
||||
className,
|
||||
name -> ClassLoader.getPlatformClassLoader().getResource(name.replace('.', '/') + ".class") != null);
|
||||
}
|
||||
|
||||
private boolean isInClasslib(String className) {
|
||||
if (className.startsWith("org.teavm.")) {
|
||||
return true;
|
||||
}
|
||||
String outer = className.contains("$") ? className.substring(0, className.indexOf('$')) : className;
|
||||
return classlibCache.computeIfAbsent(outer, name -> {
|
||||
// TeaVM's naming scheme: java.util.ArrayList -> org.teavm.classlib.java.util.TArrayList.
|
||||
// Internal helpers skip the T (org.teavm.classlib.java.util.TemplateCollections).
|
||||
int dot = name.lastIndexOf('.');
|
||||
String dir = "org/teavm/classlib/" + name.substring(0, dot + 1).replace('.', '/');
|
||||
String simple = name.substring(dot + 1);
|
||||
return teavmLoader.getResource(dir + "T" + simple + ".class") != null
|
||||
|| teavmLoader.getResource(dir + simple + ".class") != null;
|
||||
});
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.ClassVisitor;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
/**
|
||||
* How the game's bytecode uses classes it doesn't ship: which members it touches, whether
|
||||
* each is static, and which types it treats as interfaces.
|
||||
*
|
||||
* <p>The auto-stubber needs this to fake a missing class convincingly enough for TeaVM's
|
||||
* analysis to continue. TeaVM's own error says only "method X not found", not whether X is
|
||||
* static or lives on an interface.
|
||||
*/
|
||||
final class ReferenceIndex {
|
||||
|
||||
/** A member reference as seen at a call site. {@code nameAndDesc} is e.g. {@code "foo(I)V"} or {@code "bar:I"}. */
|
||||
record Member(String owner, String nameAndDesc, boolean method, boolean isStatic) {}
|
||||
|
||||
private final Map<String, Map<String, Member>> byOwner = new HashMap<>();
|
||||
private final Set<String> interfaces = new HashSet<>();
|
||||
private final Set<String> superclasses = new HashSet<>();
|
||||
|
||||
static ReferenceIndex build(Iterable<Path> jars) throws IOException {
|
||||
ReferenceIndex index = new ReferenceIndex();
|
||||
for (Path jar : jars) {
|
||||
try (JarFile file = new JarFile(jar.toFile())) {
|
||||
Enumeration<JarEntry> entries = file.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
JarEntry entry = entries.nextElement();
|
||||
if (!entry.getName().endsWith(".class") || entry.getName().startsWith("META-INF/")) {
|
||||
continue;
|
||||
}
|
||||
try (InputStream in = file.getInputStream(entry)) {
|
||||
new ClassReader(in)
|
||||
.accept(index.new Visitor(), ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
/** Every member of {@code owner} (dotted name) the game references. */
|
||||
Iterable<Member> membersOf(String owner) {
|
||||
Map<String, Member> members = byOwner.get(owner);
|
||||
return members != null ? members.values() : Set.of();
|
||||
}
|
||||
|
||||
/** The recorded static-ness of a member, or {@code null} if the game never references it. */
|
||||
@Nullable
|
||||
Boolean isStatic(String owner, String nameAndDesc) {
|
||||
Map<String, Member> members = byOwner.get(owner);
|
||||
Member member = members != null ? members.get(nameAndDesc) : null;
|
||||
return member != null ? member.isStatic() : null;
|
||||
}
|
||||
|
||||
boolean usedAsInterface(String owner) {
|
||||
return interfaces.contains(owner) && !superclasses.contains(owner);
|
||||
}
|
||||
|
||||
private void add(String internalOwner, String nameAndDesc, boolean method, boolean isStatic) {
|
||||
String owner = internalOwner.replace('/', '.');
|
||||
byOwner.computeIfAbsent(owner, k -> new HashMap<>())
|
||||
.putIfAbsent(nameAndDesc, new Member(owner, nameAndDesc, method, isStatic));
|
||||
}
|
||||
|
||||
private final class Visitor extends ClassVisitor {
|
||||
Visitor() {
|
||||
super(Opcodes.ASM9);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(
|
||||
int version,
|
||||
int access,
|
||||
String name,
|
||||
@Nullable String signature,
|
||||
@Nullable String superName,
|
||||
String @Nullable [] ifaces) {
|
||||
if (superName != null) {
|
||||
superclasses.add(superName.replace('/', '.'));
|
||||
}
|
||||
if (ifaces != null) {
|
||||
for (String iface : ifaces) {
|
||||
interfaces.add(iface.replace('/', '.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public MethodVisitor visitMethod(
|
||||
int access, String name, String descriptor, String signature, String[] exceptions) {
|
||||
return new MethodVisitor(Opcodes.ASM9) {
|
||||
@Override
|
||||
public void visitMethodInsn(int opcode, String owner, String method, String desc, boolean isInterface) {
|
||||
if (owner.startsWith("[")) {
|
||||
return;
|
||||
}
|
||||
add(owner, method + desc, true, opcode == Opcodes.INVOKESTATIC);
|
||||
if (isInterface) {
|
||||
interfaces.add(owner.replace('/', '.'));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visitFieldInsn(int opcode, String owner, String field, String desc) {
|
||||
add(owner, field + ":" + desc, false, opcode == Opcodes.GETSTATIC || opcode == Opcodes.PUTSTATIC);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.ClassVisitor;
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.Type;
|
||||
|
||||
/**
|
||||
* Generates a synthetic entry point that calls every method of every client class.
|
||||
*
|
||||
* <p>Following the game from {@code main} alone reaches only part of it: TeaVM resolves a
|
||||
* virtual call by the types that actually flow to it, so a screen created in an async
|
||||
* callback, or a packet handler behind the network layer, looks unreachable once those are
|
||||
* stubbed. The survey is meant to scope the whole client, so every method is made a root:
|
||||
* static methods by {@code invokestatic}, constructors by {@code new}, everything else by
|
||||
* {@code invokespecial} on a null receiver. TeaVM doesn't verify bytecode, so this links
|
||||
* each method directly, private ones included, whatever its runtime receiver would be.
|
||||
*
|
||||
* <p>Each client class gets its own root method, so a call TeaVM decides never returns only
|
||||
* hides the rest of that one class.
|
||||
*/
|
||||
final class Roots {
|
||||
|
||||
static final String ENTRY = "incari.survey.roots.Entry";
|
||||
private static final String PACKAGE = "incari/survey/roots/";
|
||||
/** Keeps each generated class well inside the constant-pool and method-count limits. */
|
||||
private static final int CLASSES_PER_HOLDER = 150;
|
||||
|
||||
private Roots() {}
|
||||
|
||||
/**
|
||||
* Writes the roots for {@code jar} into {@code dir}. {@code rooted} decides which classes
|
||||
* become roots; {@code mainClass} is still called first, as the real entry point.
|
||||
*
|
||||
* @return the number of classes rooted
|
||||
*/
|
||||
static int generate(Path jar, Predicate<String> rooted, String mainClass, Path dir) throws IOException {
|
||||
List<byte[]> classes = new ArrayList<>();
|
||||
try (JarFile file = new JarFile(jar.toFile())) {
|
||||
Enumeration<JarEntry> entries = file.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
JarEntry entry = entries.nextElement();
|
||||
String name = entry.getName();
|
||||
if (!name.endsWith(".class")
|
||||
|| name.startsWith("META-INF/")
|
||||
|| name.endsWith("package-info.class")
|
||||
|| name.endsWith("module-info.class")) {
|
||||
continue;
|
||||
}
|
||||
if (!rooted.test(name.substring(0, name.length() - 6).replace('/', '.'))) {
|
||||
continue;
|
||||
}
|
||||
try (InputStream in = file.getInputStream(entry)) {
|
||||
classes.add(in.readAllBytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<String> holders = new ArrayList<>();
|
||||
for (int start = 0; start < classes.size(); start += CLASSES_PER_HOLDER) {
|
||||
String holder = PACKAGE + "Roots" + holders.size();
|
||||
byte[] bytes = holder(holder, classes.subList(start, Math.min(start + CLASSES_PER_HOLDER, classes.size())));
|
||||
write(dir, holder, bytes);
|
||||
holders.add(holder);
|
||||
}
|
||||
write(dir, ENTRY.replace('.', '/'), entry(mainClass, holders));
|
||||
return classes.size();
|
||||
}
|
||||
|
||||
private static byte[] entry(String mainClass, List<String> holders) {
|
||||
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
|
||||
cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, ENTRY.replace('.', '/'), null, "java/lang/Object", null);
|
||||
MethodVisitor mv =
|
||||
cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
|
||||
mv.visitCode();
|
||||
mv.visitVarInsn(Opcodes.ALOAD, 0);
|
||||
mv.visitMethodInsn(Opcodes.INVOKESTATIC, mainClass.replace('.', '/'), "main", "([Ljava/lang/String;)V", false);
|
||||
for (String holder : holders) {
|
||||
mv.visitMethodInsn(Opcodes.INVOKESTATIC, holder, "run", "()V", false);
|
||||
}
|
||||
mv.visitInsn(Opcodes.RETURN);
|
||||
mv.visitMaxs(0, 0);
|
||||
mv.visitEnd();
|
||||
cw.visitEnd();
|
||||
return cw.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] holder(String name, List<byte[]> classes) {
|
||||
// Straight-line code with no branches needs no stack map frames, so COMPUTE_MAXS is enough.
|
||||
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
|
||||
cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, name, null, "java/lang/Object", null);
|
||||
MethodVisitor run = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "run", "()V", null, null);
|
||||
run.visitCode();
|
||||
for (int i = 0; i < classes.size(); i++) {
|
||||
String method = "c" + i;
|
||||
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC, method, "()V", null, null);
|
||||
mv.visitCode();
|
||||
ClassReader reader = new ClassReader(classes.get(i));
|
||||
reader.accept(new CallEveryMethod(mv, reader.getClassName()), ClassReader.SKIP_CODE);
|
||||
mv.visitInsn(Opcodes.RETURN);
|
||||
mv.visitMaxs(0, 0);
|
||||
mv.visitEnd();
|
||||
run.visitMethodInsn(Opcodes.INVOKESTATIC, name, method, "()V", false);
|
||||
}
|
||||
run.visitInsn(Opcodes.RETURN);
|
||||
run.visitMaxs(0, 0);
|
||||
run.visitEnd();
|
||||
cw.visitEnd();
|
||||
return cw.toByteArray();
|
||||
}
|
||||
|
||||
/** Emits one call per method of the visited class into {@code out}. */
|
||||
private static final class CallEveryMethod extends ClassVisitor {
|
||||
private final MethodVisitor out;
|
||||
private final String owner;
|
||||
private boolean isInterface;
|
||||
private boolean isAbstract;
|
||||
|
||||
CallEveryMethod(MethodVisitor out, String owner) {
|
||||
super(Opcodes.ASM9);
|
||||
this.out = out;
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void visit(
|
||||
int version,
|
||||
int access,
|
||||
String name,
|
||||
@Nullable String signature,
|
||||
@Nullable String superName,
|
||||
String @Nullable [] interfaces) {
|
||||
isInterface = (access & Opcodes.ACC_INTERFACE) != 0;
|
||||
isAbstract = (access & Opcodes.ACC_ABSTRACT) != 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public @Nullable MethodVisitor visitMethod(
|
||||
int access,
|
||||
String name,
|
||||
String descriptor,
|
||||
@Nullable String signature,
|
||||
String @Nullable [] exceptions) {
|
||||
if (name.equals("<clinit>") || (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) != 0) {
|
||||
return null;
|
||||
}
|
||||
boolean isStatic = (access & Opcodes.ACC_STATIC) != 0;
|
||||
boolean constructor = name.equals("<init>");
|
||||
if (constructor && !isAbstract) {
|
||||
// Instantiating also puts the class's type into circulation for virtual calls.
|
||||
out.visitTypeInsn(Opcodes.NEW, owner);
|
||||
out.visitInsn(Opcodes.DUP);
|
||||
pushDefaults(descriptor);
|
||||
out.visitMethodInsn(Opcodes.INVOKESPECIAL, owner, name, descriptor, false);
|
||||
out.visitInsn(Opcodes.POP);
|
||||
return null;
|
||||
}
|
||||
if (!isStatic) {
|
||||
out.visitInsn(Opcodes.ACONST_NULL);
|
||||
}
|
||||
pushDefaults(descriptor);
|
||||
out.visitMethodInsn(
|
||||
isStatic ? Opcodes.INVOKESTATIC : Opcodes.INVOKESPECIAL, owner, name, descriptor, isInterface);
|
||||
Type result = Type.getReturnType(descriptor);
|
||||
if (result.getSize() == 2) {
|
||||
out.visitInsn(Opcodes.POP2);
|
||||
} else if (result.getSize() == 1) {
|
||||
out.visitInsn(Opcodes.POP);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void pushDefaults(String descriptor) {
|
||||
for (Type arg : Type.getArgumentTypes(descriptor)) {
|
||||
switch (arg.getSort()) {
|
||||
case Type.BOOLEAN, Type.CHAR, Type.BYTE, Type.SHORT, Type.INT -> out.visitInsn(Opcodes.ICONST_0);
|
||||
case Type.LONG -> out.visitInsn(Opcodes.LCONST_0);
|
||||
case Type.FLOAT -> out.visitInsn(Opcodes.FCONST_0);
|
||||
case Type.DOUBLE -> out.visitInsn(Opcodes.DCONST_0);
|
||||
default -> out.visitInsn(Opcodes.ACONST_NULL);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void write(Path dir, String internalName, byte[] bytes) throws IOException {
|
||||
Path file = dir.resolve(internalName + ".class");
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.write(file, bytes);
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.teavm.model.AccessLevel;
|
||||
import org.teavm.model.ClassHolder;
|
||||
import org.teavm.model.ClassHolderTransformer;
|
||||
import org.teavm.model.ClassHolderTransformerContext;
|
||||
import org.teavm.model.ElementModifier;
|
||||
import org.teavm.model.FieldHolder;
|
||||
import org.teavm.model.MethodDescriptor;
|
||||
import org.teavm.model.MethodHolder;
|
||||
import org.teavm.model.ValueType;
|
||||
import org.teavm.model.emit.ProgramEmitter;
|
||||
|
||||
/**
|
||||
* Adds stub members to existing classes as TeaVM loads them (see {@link Stubs}).
|
||||
*
|
||||
* <p>TeaVM instantiates transformers by class name with a no-argument constructor, so the
|
||||
* current round's members are handed over through a static field. The survey runs one
|
||||
* compile at a time, so there's never more than one set in play.
|
||||
*/
|
||||
public final class StubTransformer implements ClassHolderTransformer {
|
||||
|
||||
static volatile Map<String, Set<Stubs.ExtraMember>> members = Map.of();
|
||||
|
||||
@Override
|
||||
public void transformClass(ClassHolder cls, ClassHolderTransformerContext context) {
|
||||
Set<Stubs.ExtraMember> extra = members.get(cls.getName());
|
||||
if (extra == null) {
|
||||
return;
|
||||
}
|
||||
for (Stubs.ExtraMember member : extra) {
|
||||
if (member.method()) {
|
||||
MethodDescriptor descriptor = MethodDescriptor.parse(member.nameAndDesc());
|
||||
if (cls.getMethod(descriptor) != null) {
|
||||
continue;
|
||||
}
|
||||
MethodHolder method = new MethodHolder(descriptor);
|
||||
method.setLevel(AccessLevel.PUBLIC);
|
||||
if (member.isStatic()) {
|
||||
method.getModifiers().add(ElementModifier.STATIC);
|
||||
}
|
||||
ProgramEmitter pe = ProgramEmitter.create(method, context.getHierarchy());
|
||||
if (descriptor.getResultType() == ValueType.VOID) {
|
||||
pe.exit();
|
||||
} else {
|
||||
pe.defaultValue(descriptor.getResultType()).returnValue();
|
||||
}
|
||||
cls.addMethod(method);
|
||||
} else {
|
||||
String[] parts = member.nameAndDesc().split(":", 2);
|
||||
if (cls.getField(parts[0]) != null) {
|
||||
continue;
|
||||
}
|
||||
FieldHolder field = new FieldHolder(parts[0]);
|
||||
field.setType(ValueType.parse(parts[1]));
|
||||
field.setLevel(AccessLevel.PUBLIC);
|
||||
if (member.isStatic()) {
|
||||
field.getModifiers().add(ElementModifier.STATIC);
|
||||
}
|
||||
cls.addField(field);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.objectweb.asm.Type;
|
||||
import org.teavm.model.FieldReference;
|
||||
import org.teavm.model.MethodReference;
|
||||
|
||||
/**
|
||||
* Stand-ins that let TeaVM's analysis continue past things that are missing.
|
||||
*
|
||||
* <p>TeaVM treats a call to a missing method as a throw, and its optimizer then drops
|
||||
* everything after the call. One missing {@code Runtime.addShutdownHook} in {@code main}
|
||||
* hides the entire game from the survey. So the survey runs in rounds: whatever TeaVM
|
||||
* reports missing gets a stub that returns a default value, and the compile runs again,
|
||||
* until nothing new turns up.
|
||||
*
|
||||
* <p>The stubs are only an analysis device. Everything stubbed is still reported as a
|
||||
* finding; nothing here says the stub is the right fix.
|
||||
*
|
||||
* <p>Two kinds of stub:
|
||||
* <ul>
|
||||
* <li>classes TeaVM can't see (from libraries the rules leave out, or host-JDK classes its
|
||||
* class library lacks) are generated as class files, with every member the game
|
||||
* references, on a directory added to TeaVM's classpath;
|
||||
* <li>members missing from classes that do exist (TeaVM's class library, the host JDK) are
|
||||
* added by {@link StubTransformer} as TeaVM loads each class.
|
||||
* </ul>
|
||||
*/
|
||||
final class Stubs {
|
||||
|
||||
/** A member to add to an existing class. {@code nameAndDesc}: {@code "foo(I)V"} or {@code "bar:I"}. */
|
||||
record ExtraMember(String nameAndDesc, boolean method, boolean isStatic) {}
|
||||
|
||||
private final ReferenceIndex index;
|
||||
private final Map<String, Set<ReferenceIndex.Member>> absentClasses = new LinkedHashMap<>();
|
||||
private final Map<String, Set<ExtraMember>> extraMembers = new HashMap<>();
|
||||
|
||||
Stubs(ReferenceIndex index) {
|
||||
this.index = index;
|
||||
}
|
||||
|
||||
int absentClassCount() {
|
||||
return absentClasses.size();
|
||||
}
|
||||
|
||||
int extraMemberCount() {
|
||||
return extraMembers.values().stream().mapToInt(Set::size).sum();
|
||||
}
|
||||
|
||||
Map<String, Set<ExtraMember>> extraMembers() {
|
||||
return extraMembers;
|
||||
}
|
||||
|
||||
/** Stubs an absent class with every member the game references on it. Returns true if new. */
|
||||
boolean addAbsentClass(String className) {
|
||||
if (absentClasses.containsKey(className)) {
|
||||
return false;
|
||||
}
|
||||
Set<ReferenceIndex.Member> members = new LinkedHashSet<>();
|
||||
index.membersOf(className).forEach(members::add);
|
||||
absentClasses.put(className, members);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Adds a method TeaVM reported missing. Returns true if it wasn't stubbed yet. */
|
||||
boolean addMethod(MethodReference method, boolean ownerAbsent) {
|
||||
String nameAndDesc = method.getName() + method.getDescriptor().signatureToString();
|
||||
return addMember(method.getClassName(), nameAndDesc, true, ownerAbsent);
|
||||
}
|
||||
|
||||
boolean addField(FieldReference field, boolean ownerAbsent) {
|
||||
return addMember(field.getClassName(), field.getFieldName() + ":" + fieldDescriptor(field), false, ownerAbsent);
|
||||
}
|
||||
|
||||
/** TeaVM's error doesn't carry the field's type: take it from a call site, else the JDK. */
|
||||
private String fieldDescriptor(FieldReference field) {
|
||||
String prefix = field.getFieldName() + ":";
|
||||
for (ReferenceIndex.Member member : index.membersOf(field.getClassName())) {
|
||||
if (!member.method() && member.nameAndDesc().startsWith(prefix)) {
|
||||
return member.nameAndDesc().substring(prefix.length());
|
||||
}
|
||||
}
|
||||
try {
|
||||
Class<?> cls = Class.forName(field.getClassName(), false, ClassLoader.getPlatformClassLoader());
|
||||
return Type.getDescriptor(cls.getDeclaredField(field.getFieldName()).getType());
|
||||
} catch (ClassNotFoundException | NoSuchFieldException | LinkageError e) {
|
||||
return "Ljava/lang/Object;";
|
||||
}
|
||||
}
|
||||
|
||||
private boolean addMember(String owner, String nameAndDesc, boolean method, boolean ownerAbsent) {
|
||||
boolean isStatic = isStatic(owner, nameAndDesc, method);
|
||||
if (ownerAbsent) {
|
||||
boolean added = addAbsentClass(owner);
|
||||
Set<ReferenceIndex.Member> members = absentClasses.get(owner);
|
||||
if (members == null) {
|
||||
throw new IllegalStateException("addAbsentClass didn't register " + owner);
|
||||
}
|
||||
return members.add(new ReferenceIndex.Member(owner, nameAndDesc, method, isStatic)) || added;
|
||||
}
|
||||
return extraMembers
|
||||
.computeIfAbsent(owner, k -> new LinkedHashSet<>())
|
||||
.add(new ExtraMember(nameAndDesc, method, isStatic));
|
||||
}
|
||||
|
||||
/** Static-ness from the game's call sites, else from the host JDK's real class, else instance. */
|
||||
private boolean isStatic(String owner, String nameAndDesc, boolean method) {
|
||||
Boolean fromIndex = index.isStatic(owner, nameAndDesc);
|
||||
if (fromIndex != null) {
|
||||
return fromIndex;
|
||||
}
|
||||
try {
|
||||
Class<?> cls = Class.forName(owner, false, ClassLoader.getPlatformClassLoader());
|
||||
if (method) {
|
||||
for (Method m : cls.getDeclaredMethods()) {
|
||||
if (nameAndDesc.equals(m.getName() + Type.getMethodDescriptor(m))) {
|
||||
return Modifier.isStatic(m.getModifiers());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
String name = nameAndDesc.substring(0, nameAndDesc.indexOf(':'));
|
||||
return Modifier.isStatic(cls.getDeclaredField(name).getModifiers());
|
||||
}
|
||||
} catch (ClassNotFoundException | NoSuchFieldException | LinkageError e) {
|
||||
// Not a JDK class, or not a member of it: fall through to the default.
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Writes every absent-class stub as a class file under {@code dir}. */
|
||||
void writeClasses(Path dir) throws IOException {
|
||||
for (Map.Entry<String, Set<ReferenceIndex.Member>> entry : absentClasses.entrySet()) {
|
||||
byte[] bytes = generate(entry.getKey(), entry.getValue());
|
||||
Path file = dir.resolve(entry.getKey().replace('.', '/') + ".class");
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.write(file, bytes);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] generate(String className, Set<ReferenceIndex.Member> members) {
|
||||
boolean isInterface = isInterface(className);
|
||||
String internal = className.replace('.', '/');
|
||||
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES) {
|
||||
@Override
|
||||
protected String getCommonSuperClass(String type1, String type2) {
|
||||
return "java/lang/Object"; // stubs never merge types; avoid loading anything
|
||||
}
|
||||
};
|
||||
int access = Opcodes.ACC_PUBLIC | (isInterface ? Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT : 0);
|
||||
cw.visit(Opcodes.V17, access, internal, null, "java/lang/Object", null);
|
||||
|
||||
boolean hasDefaultConstructor = false;
|
||||
for (ReferenceIndex.Member member : members) {
|
||||
if (!member.method()) {
|
||||
String[] parts = member.nameAndDesc().split(":", 2);
|
||||
int fieldAccess = Opcodes.ACC_PUBLIC | (member.isStatic() || isInterface ? Opcodes.ACC_STATIC : 0);
|
||||
cw.visitField(fieldAccess, parts[0], parts[1], null, null).visitEnd();
|
||||
continue;
|
||||
}
|
||||
int paren = member.nameAndDesc().indexOf('(');
|
||||
String name = member.nameAndDesc().substring(0, paren);
|
||||
String desc = member.nameAndDesc().substring(paren);
|
||||
if (name.equals("<clinit>")) {
|
||||
continue;
|
||||
}
|
||||
boolean constructor = name.equals("<init>");
|
||||
if (constructor && isInterface) {
|
||||
continue;
|
||||
}
|
||||
hasDefaultConstructor |= constructor && desc.equals("()V");
|
||||
int methodAccess = Opcodes.ACC_PUBLIC | (member.isStatic() && !constructor ? Opcodes.ACC_STATIC : 0);
|
||||
MethodVisitor mv = cw.visitMethod(methodAccess, name, desc, null, null);
|
||||
mv.visitCode();
|
||||
if (constructor) {
|
||||
mv.visitVarInsn(Opcodes.ALOAD, 0);
|
||||
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
|
||||
}
|
||||
returnDefault(mv, Type.getReturnType(desc));
|
||||
mv.visitMaxs(0, 0);
|
||||
mv.visitEnd();
|
||||
}
|
||||
if (!isInterface && !hasDefaultConstructor) {
|
||||
// Subclasses of a stubbed class call some super constructor; give them one to find.
|
||||
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
|
||||
mv.visitCode();
|
||||
mv.visitVarInsn(Opcodes.ALOAD, 0);
|
||||
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
|
||||
mv.visitInsn(Opcodes.RETURN);
|
||||
mv.visitMaxs(0, 0);
|
||||
mv.visitEnd();
|
||||
}
|
||||
cw.visitEnd();
|
||||
return cw.toByteArray();
|
||||
}
|
||||
|
||||
/** The real JDK class's shape when there is one; otherwise how the game uses the name. */
|
||||
private boolean isInterface(String className) {
|
||||
try {
|
||||
return Class.forName(className, false, ClassLoader.getPlatformClassLoader())
|
||||
.isInterface();
|
||||
} catch (ClassNotFoundException | LinkageError e) {
|
||||
return index.usedAsInterface(className);
|
||||
}
|
||||
}
|
||||
|
||||
private static void returnDefault(MethodVisitor mv, Type type) {
|
||||
switch (type.getSort()) {
|
||||
case Type.VOID -> mv.visitInsn(Opcodes.RETURN);
|
||||
case Type.BOOLEAN, Type.CHAR, Type.BYTE, Type.SHORT, Type.INT -> {
|
||||
mv.visitInsn(Opcodes.ICONST_0);
|
||||
mv.visitInsn(Opcodes.IRETURN);
|
||||
}
|
||||
case Type.LONG -> {
|
||||
mv.visitInsn(Opcodes.LCONST_0);
|
||||
mv.visitInsn(Opcodes.LRETURN);
|
||||
}
|
||||
case Type.FLOAT -> {
|
||||
mv.visitInsn(Opcodes.FCONST_0);
|
||||
mv.visitInsn(Opcodes.FRETURN);
|
||||
}
|
||||
case Type.DOUBLE -> {
|
||||
mv.visitInsn(Opcodes.DCONST_0);
|
||||
mv.visitInsn(Opcodes.DRETURN);
|
||||
}
|
||||
default -> {
|
||||
mv.visitInsn(Opcodes.ACONST_NULL);
|
||||
mv.visitInsn(Opcodes.ARETURN);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
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.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
/**
|
||||
* The survey's policy file ({@code tools/survey/rules.txt}): which libraries are compiled
|
||||
* with the game, and how each finding is triaged.
|
||||
*
|
||||
* <p>Three kinds of lines. Library lines decide the classpath:
|
||||
* <pre>
|
||||
* library org.lwjgl: replace Platform layer: graphics, windowing, input, audio
|
||||
* </pre>
|
||||
* {@code keep} compiles the library with the game. {@code replace} and {@code delete} leave it
|
||||
* off the classpath, so every call into it shows up as a missing symbol at its call site.
|
||||
*
|
||||
* <p>No-root lines keep parts of the client jar that never run in the client (data
|
||||
* generators, the dedicated server) out of the analysis roots (see {@link Roots}):
|
||||
* <pre>
|
||||
* no-root net.minecraft.data.** Data generators run at Mojang's build time
|
||||
* </pre>
|
||||
*
|
||||
* <p>Triage lines sort findings. The first rule whose selectors all match wins:
|
||||
* <pre>
|
||||
* delete caller=net.minecraft.util.profiling.jfr.** JFR profiling, stripped
|
||||
* shim symbol=java.nio.file.** Virtual filesystem over OPFS
|
||||
* stub kind=reflection symbol=java.lang.Class#getGenericSuperclass ...
|
||||
* </pre>
|
||||
* Selectors: {@code symbol} (the missing or used thing, {@code owner#member}),
|
||||
* {@code caller} (the class that needs work), {@code origin} ({@code minecraft} or a
|
||||
* library name), {@code kind} ({@code reflection}, {@code native}, {@code host-jdk}, or a
|
||||
* TeaVM problem such as {@code missing-method}). Globs: {@code *} matches within one name
|
||||
* segment, {@code **} matches anything.
|
||||
*/
|
||||
public record SurveyRules(List<LibraryRule> libraries, List<NoRootRule> noRoots, List<TriageRule> triage) {
|
||||
|
||||
public enum Category {
|
||||
STUB("Stub", "A no-op or trivial implementation is enough."),
|
||||
SHIM("Shim", "Needs a real implementation, over a browser API or simpler Java."),
|
||||
REWRITE("Rewrite", "The calling code has to change: a patch or a replacement class."),
|
||||
DELETE("Delete", "The feature is stripped from the browser build.");
|
||||
|
||||
private final String title;
|
||||
private final String meaning;
|
||||
|
||||
Category(String title, String meaning) {
|
||||
this.title = title;
|
||||
this.meaning = meaning;
|
||||
}
|
||||
|
||||
public String title() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public String meaning() {
|
||||
return meaning;
|
||||
}
|
||||
}
|
||||
|
||||
public enum LibraryAction {
|
||||
KEEP,
|
||||
REPLACE,
|
||||
DELETE
|
||||
}
|
||||
|
||||
public record NoRootRule(Pattern classes, String reason) {}
|
||||
|
||||
/** Matches Maven coordinates by prefix, e.g. {@code "org.lwjgl:"} or {@code "io.netty:netty-buffer:"}. */
|
||||
public record LibraryRule(String coordinatePrefix, LibraryAction action, String reason) {}
|
||||
|
||||
public record TriageRule(
|
||||
Category category,
|
||||
@Nullable Pattern symbol,
|
||||
@Nullable Pattern caller,
|
||||
@Nullable Pattern origin,
|
||||
@Nullable String kind,
|
||||
String reason,
|
||||
int line) {
|
||||
|
||||
boolean matches(Finding finding, String kindName, @Nullable String origin) {
|
||||
return (symbol == null
|
||||
|| symbol.matcher(finding.symbol()).matches()
|
||||
|| (finding.member() != null
|
||||
&& symbol.matcher(finding.owner()).matches()
|
||||
&& !symbol.pattern().contains("#")))
|
||||
&& (caller == null
|
||||
|| (finding.caller() != null
|
||||
&& caller.matcher(finding.caller()).matches()))
|
||||
&& (this.origin == null
|
||||
|| (origin != null && this.origin.matcher(origin).matches()))
|
||||
&& (kind == null || kind.equals(kindName));
|
||||
}
|
||||
}
|
||||
|
||||
public static SurveyRules load(Path file) throws IOException {
|
||||
return parse(Files.readAllLines(file), file.getFileName().toString());
|
||||
}
|
||||
|
||||
static SurveyRules parse(List<String> lines, String origin) {
|
||||
List<LibraryRule> libraries = new ArrayList<>();
|
||||
List<NoRootRule> noRoots = new ArrayList<>();
|
||||
List<TriageRule> triage = new ArrayList<>();
|
||||
for (int i = 0; i < lines.size(); i++) {
|
||||
String raw = lines.get(i);
|
||||
int hash = raw.indexOf(" #");
|
||||
String line = (raw.startsWith("#") ? "" : hash >= 0 ? raw.substring(0, hash) : raw).strip();
|
||||
if (line.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
String where = origin + ":" + (i + 1);
|
||||
String[] words = line.split("\\s+");
|
||||
if (words[0].equals("library")) {
|
||||
if (words.length < 4) {
|
||||
throw new CliException(
|
||||
where + ": expected: library <coordinate prefix> <keep|replace|delete> <reason>");
|
||||
}
|
||||
LibraryAction action = parseEnum(LibraryAction.class, words[2], where);
|
||||
libraries.add(new LibraryRule(words[1], action, rest(words, 3)));
|
||||
continue;
|
||||
}
|
||||
if (words[0].equals("no-root")) {
|
||||
if (words.length < 3) {
|
||||
throw new CliException(where + ": expected: no-root <class glob> <reason>");
|
||||
}
|
||||
noRoots.add(new NoRootRule(glob(words[1]), rest(words, 2)));
|
||||
continue;
|
||||
}
|
||||
Category category = parseEnum(Category.class, words[0], where);
|
||||
@Nullable Pattern symbol = null;
|
||||
@Nullable Pattern caller = null;
|
||||
@Nullable Pattern originPattern = null;
|
||||
@Nullable String kind = null;
|
||||
int w = 1;
|
||||
for (; w < words.length && words[w].contains("="); w++) {
|
||||
String[] kv = words[w].split("=", 2);
|
||||
switch (kv[0]) {
|
||||
case "symbol" -> symbol = glob(kv[1]);
|
||||
case "caller" -> caller = glob(kv[1]);
|
||||
case "origin" -> originPattern = glob(kv[1]);
|
||||
case "kind" -> kind = kv[1];
|
||||
default -> throw new CliException(where + ": unknown selector '" + kv[0] + "'");
|
||||
}
|
||||
}
|
||||
if (w == 1) {
|
||||
throw new CliException(where + ": a triage rule needs at least one selector");
|
||||
}
|
||||
if (w >= words.length) {
|
||||
throw new CliException(where + ": a triage rule needs a reason after its selectors");
|
||||
}
|
||||
triage.add(new TriageRule(category, symbol, caller, originPattern, kind, rest(words, w), i + 1));
|
||||
}
|
||||
return new SurveyRules(List.copyOf(libraries), List.copyOf(noRoots), List.copyOf(triage));
|
||||
}
|
||||
|
||||
/** The action for a library; libraries with no rule are an error, so none slips in unreviewed. */
|
||||
public LibraryRule library(String coordinates) {
|
||||
for (LibraryRule rule : libraries) {
|
||||
if (coordinates.startsWith(rule.coordinatePrefix())) {
|
||||
return rule;
|
||||
}
|
||||
}
|
||||
throw new CliException("No library rule in rules.txt covers " + coordinates
|
||||
+ ". Decide whether the browser build keeps, replaces or deletes it.");
|
||||
}
|
||||
|
||||
/** Whether a client class becomes an analysis root (see {@link Roots}). */
|
||||
public boolean isRooted(String className) {
|
||||
for (NoRootRule rule : noRoots) {
|
||||
if (rule.classes().matcher(className).matches()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The first matching rule, or {@code null} when nothing matches (reported as unclassified). */
|
||||
public @Nullable TriageRule classify(Finding finding, String kindName, @Nullable String origin) {
|
||||
for (TriageRule rule : triage) {
|
||||
if (rule.matches(finding, kindName, origin)) {
|
||||
return rule;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static Pattern glob(String glob) {
|
||||
StringBuilder regex = new StringBuilder();
|
||||
for (int i = 0; i < glob.length(); i++) {
|
||||
char c = glob.charAt(i);
|
||||
if (c == '*' && i + 1 < glob.length() && glob.charAt(i + 1) == '*') {
|
||||
regex.append(".*");
|
||||
i++;
|
||||
} else if (c == '*') {
|
||||
regex.append("[^.#]*");
|
||||
} else {
|
||||
regex.append(Pattern.quote(String.valueOf(c)));
|
||||
}
|
||||
}
|
||||
return Pattern.compile(regex.toString());
|
||||
}
|
||||
|
||||
private static String rest(String[] words, int from) {
|
||||
return String.join(" ", java.util.Arrays.copyOfRange(words, from, words.length));
|
||||
}
|
||||
|
||||
private static <E extends Enum<E>> E parseEnum(Class<E> type, String value, String where) {
|
||||
try {
|
||||
return Enum.valueOf(type, value.toUpperCase(Locale.ROOT));
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new CliException(where + ": unknown " + type.getSimpleName() + " '" + value + "'", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
import incari.tools.build.FileTrees;
|
||||
import incari.tools.build.Log;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import org.teavm.dependency.DependencyInfo;
|
||||
import org.teavm.diagnostics.DefaultProblemTextConsumer;
|
||||
import org.teavm.diagnostics.Problem;
|
||||
import org.teavm.model.CallLocation;
|
||||
import org.teavm.model.ClassReader;
|
||||
import org.teavm.model.ElementModifier;
|
||||
import org.teavm.model.FieldReference;
|
||||
import org.teavm.model.MethodReader;
|
||||
import org.teavm.model.MethodReference;
|
||||
import org.teavm.model.TextLocation;
|
||||
import org.teavm.tooling.TeaVMTargetType;
|
||||
import org.teavm.tooling.TeaVMTool;
|
||||
import org.teavm.tooling.TeaVMToolException;
|
||||
import org.teavm.tooling.TeaVMToolLog;
|
||||
import org.teavm.vm.TeaVMOptimizationLevel;
|
||||
|
||||
/**
|
||||
* Runs TeaVM's WebAssembly GC compile over the client and turns what it learns into findings.
|
||||
*
|
||||
* <p>Two sources from one compile: TeaVM's own errors (classes, methods and fields its class
|
||||
* library doesn't have), and native (JNI) methods reachable in the game or its libraries,
|
||||
* which TeaVM only rejects at code generation, a stage it never reaches while errors remain.
|
||||
* It also returns the reachable game methods, so {@link BytecodeScanner} looks only at code
|
||||
* that will actually be compiled.
|
||||
*
|
||||
* <p>Errors TeaVM reports inside JDK code it copied from the host (see {@link Origins}) keep
|
||||
* that JDK class as their caller. Walking them up the call graph to game code doesn't work:
|
||||
* virtual dispatch through {@code Object.hashCode()} and friends links almost everything to
|
||||
* everything.
|
||||
*
|
||||
* <p>TeaVM doesn't follow calls into code it can't find, so this is the first layer: stubbing
|
||||
* these items will uncover more behind them. Rerun the survey after each round.
|
||||
*/
|
||||
public final class TeaVmSurvey {
|
||||
|
||||
/**
|
||||
* What the compile rounds found, and what TeaVM will compile.
|
||||
*
|
||||
* @param reachableAppMethods game and library methods TeaVM will compile, as
|
||||
* {@code owner#name(descriptor)}; the bytecode scan only looks inside these
|
||||
*/
|
||||
public record Result(List<Finding> findings, Set<String> reachableClasses, Set<String> reachableAppMethods) {}
|
||||
|
||||
/** Rounds are cheap early and grow as more of the game becomes reachable; this is a safety net. */
|
||||
private static final int MAX_ROUNDS = 40;
|
||||
|
||||
private TeaVmSurvey() {}
|
||||
|
||||
/**
|
||||
* Compiles in rounds, stubbing whatever each round reports missing, until a round finds
|
||||
* nothing new (see {@link Stubs}). Findings accumulate across rounds; reachability and
|
||||
* natives come from the last, most complete round.
|
||||
*/
|
||||
public static Result run(String mainClass, Map<Path, String> appJars, Path rootsDir, Origins origins, Path workDir)
|
||||
throws IOException, TeaVMToolException {
|
||||
Stubs stubs = new Stubs(ReferenceIndex.build(appJars.keySet()));
|
||||
Set<Finding> findings = new LinkedHashSet<>();
|
||||
Path stubDir = workDir.resolve("stubs");
|
||||
Analysis last = null;
|
||||
for (int round = 1; ; round++) {
|
||||
FileTrees.deleteRecursively(stubDir);
|
||||
Files.createDirectories(stubDir);
|
||||
stubs.writeClasses(stubDir);
|
||||
StubTransformer.members = Map.copyOf(stubs.extraMembers());
|
||||
|
||||
List<Path> classpath = new ArrayList<>(appJars.keySet());
|
||||
classpath.add(rootsDir);
|
||||
classpath.add(stubDir);
|
||||
long start = System.nanoTime();
|
||||
last = compile(mainClass, classpath, origins, workDir.resolve("teavm-out"));
|
||||
findings.addAll(last.findings);
|
||||
|
||||
int added = 0;
|
||||
for (Problem problem : last.problems) {
|
||||
added += stubFor(problem, stubs, origins) ? 1 : 0;
|
||||
}
|
||||
// TeaVM names a missing class once; stub every one that reachable code uses.
|
||||
for (Finding f : BytecodeScanner.scan(appJars, last.reachableClasses, last.reachableAppMethods, origins)) {
|
||||
if (f.kind() == Finding.Kind.MISSING_CLASS || f.kind() == Finding.Kind.HOST_JDK) {
|
||||
added += stubs.addAbsentClass(f.owner()) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
Log.info(String.format(
|
||||
Locale.ROOT,
|
||||
"round %d: %,d reachable classes, %d problems, %d new stubs (%ds)",
|
||||
round,
|
||||
last.reachableClasses.size(),
|
||||
last.problems.size(),
|
||||
added,
|
||||
(System.nanoTime() - start) / 1_000_000_000));
|
||||
if (added == 0) {
|
||||
break;
|
||||
}
|
||||
if (round == MAX_ROUNDS) {
|
||||
Log.warn("Stopped after " + MAX_ROUNDS
|
||||
+ " rounds with stubs still being added; the survey is incomplete.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
findings.addAll(last.natives);
|
||||
Log.info("Stubbed " + stubs.absentClassCount() + " absent classes and " + stubs.extraMemberCount()
|
||||
+ " missing members to reach this point");
|
||||
return new Result(
|
||||
List.copyOf(findings), new TreeSet<>(last.reachableClasses), Set.copyOf(last.reachableAppMethods));
|
||||
}
|
||||
|
||||
/** Registers a stub for what {@code problem} reports missing. True if it's new. */
|
||||
private static boolean stubFor(Problem problem, Stubs stubs, Origins origins) {
|
||||
Object[] params = problem.getParams();
|
||||
String text = problem.getText();
|
||||
if (text.contains("which is missing in the classpath")
|
||||
&& params.length > 1
|
||||
&& params[1] instanceof String cls) {
|
||||
return stubs.addAbsentClass(cls);
|
||||
}
|
||||
if (params.length == 0) {
|
||||
return false;
|
||||
}
|
||||
return switch (params[0]) {
|
||||
case String cls when text.startsWith("Class {{c0}} was not found") -> stubs.addAbsentClass(cls);
|
||||
case MethodReference method
|
||||
when text.startsWith("Method {{m0}} was not found") ->
|
||||
stubs.addMethod(method, stubbedAsClass(origins, method.getClassName()));
|
||||
case FieldReference field
|
||||
when text.startsWith("Field {{f0}} was not found") ->
|
||||
stubs.addField(field, stubbedAsClass(origins, field.getClassName()));
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
/** Classes TeaVM can't see at all get generated stub class files, not transformer members. */
|
||||
static boolean stubbedAsClass(Origins origins, String className) {
|
||||
String origin = origins.of(className);
|
||||
return Origins.ABSENT.equals(origin) || Origins.HOST_JDK.equals(origin);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hides the host JDK's class files from TeaVM.
|
||||
*
|
||||
* <p>Left visible, TeaVM compiles any JDK class its class library lacks straight from the
|
||||
* running JDK, and follows it into JDK internals (security, JMX, {@code jdk.internal}).
|
||||
* That analysis is huge (tens of thousands of classes) and says nothing useful: the work
|
||||
* item is the game's use of the missing class, not everything behind it. Hidden, each such
|
||||
* class is reported missing and stubbed like any other. Class loading (TeaVM's own plugins)
|
||||
* is untouched; only bytecode reads are filtered.
|
||||
*/
|
||||
private static Analysis compile(String mainClass, List<Path> classpath, Origins origins, Path outputDir)
|
||||
throws IOException, TeaVMToolException {
|
||||
URL[] urls = new URL[classpath.size()];
|
||||
for (int i = 0; i < urls.length; i++) {
|
||||
urls[i] = classpath.get(i).toUri().toURL();
|
||||
}
|
||||
// Parent = the survey's own loader, which carries TeaVM's class library (the
|
||||
// browser-side java.* implementations the game will actually run against), minus the
|
||||
// host JDK's class files (see HostJdkHidingLoader).
|
||||
ClassLoader parent = new HostJdkHidingLoader(TeaVmSurvey.class.getClassLoader(), origins);
|
||||
try (URLClassLoader loader = new URLClassLoader(urls, parent)) {
|
||||
TeaVMTool tool = new TeaVMTool();
|
||||
tool.setTargetType(TeaVMTargetType.WEBASSEMBLY_GC);
|
||||
tool.setMainClass(mainClass);
|
||||
tool.setClassLoader(loader);
|
||||
tool.setTargetDirectory(outputDir.toFile());
|
||||
tool.setOptimizationLevel(TeaVMOptimizationLevel.SIMPLE);
|
||||
tool.setIncremental(false);
|
||||
// Every client method is already a root (see Roots), so precise per-variable type
|
||||
// flow adds little, and on the whole client it needs well over 20 GB. The fast mode
|
||||
// resolves virtual calls by class hierarchy instead.
|
||||
tool.setFastDependencyAnalysis(true);
|
||||
tool.setLog(new QuietLog());
|
||||
tool.getTransformers().add(StubTransformer.class.getName());
|
||||
tool.generate();
|
||||
|
||||
DependencyInfo deps = tool.getDependencyInfo();
|
||||
if (deps == null) {
|
||||
throw new IllegalStateException("TeaVM produced no dependency information");
|
||||
}
|
||||
Analysis analysis = new Analysis(deps, origins);
|
||||
for (Problem problem : tool.getProblemProvider().getProblems()) {
|
||||
analysis.addProblem(problem);
|
||||
}
|
||||
analysis.scanReachableMethods();
|
||||
return analysis;
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Analysis {
|
||||
private final DependencyInfo deps;
|
||||
private final Origins origins;
|
||||
private final List<Problem> problems = new ArrayList<>();
|
||||
private final Set<Finding> findings = new LinkedHashSet<>();
|
||||
private final Set<Finding> natives = new LinkedHashSet<>();
|
||||
private final Set<String> reachableAppMethods = new HashSet<>();
|
||||
private final Set<String> reachableClasses;
|
||||
|
||||
Analysis(DependencyInfo deps, Origins origins) {
|
||||
this.deps = deps;
|
||||
this.origins = origins;
|
||||
this.reachableClasses = new HashSet<>(deps.getReachableClasses());
|
||||
}
|
||||
|
||||
void addProblem(Problem problem) {
|
||||
problems.add(problem);
|
||||
findings.add(toFinding(problem));
|
||||
}
|
||||
|
||||
/** Finds reachable natives, and records which game methods are reachable at all. */
|
||||
void scanReachableMethods() {
|
||||
for (MethodReference method : deps.getReachableMethods()) {
|
||||
String owner = method.getClassName();
|
||||
if (!origins.isApp(owner)) {
|
||||
continue;
|
||||
}
|
||||
reachableAppMethods.add(
|
||||
owner + "#" + method.getName() + method.getDescriptor().signatureToString());
|
||||
if (isNative(method)) {
|
||||
natives.add(new Finding(
|
||||
Finding.Kind.NATIVE,
|
||||
owner + "#" + method.getName(),
|
||||
method.toString(),
|
||||
owner,
|
||||
method.getDescriptor().toString(),
|
||||
-1,
|
||||
null));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isNative(MethodReference method) {
|
||||
ClassReader cls = deps.getClassSource().get(method.getClassName());
|
||||
MethodReader reader = cls != null ? cls.getMethod(method.getDescriptor()) : null;
|
||||
return reader != null && reader.hasModifier(ElementModifier.NATIVE);
|
||||
}
|
||||
}
|
||||
|
||||
static Finding toFinding(Problem problem) {
|
||||
String text = problem.getText();
|
||||
Object[] params = problem.getParams();
|
||||
Object first = params.length > 0 ? params[0] : null;
|
||||
|
||||
Finding.Kind kind;
|
||||
if (text.startsWith("Class {{c0}} was not found")) {
|
||||
kind = Finding.Kind.MISSING_CLASS;
|
||||
} else if (text.startsWith("Method {{m0}} was not found")) {
|
||||
kind = Finding.Kind.MISSING_METHOD;
|
||||
} else if (text.startsWith("Field {{f0}} was not found")) {
|
||||
kind = Finding.Kind.MISSING_FIELD;
|
||||
} else if (text.startsWith("Class {{c0}} is not supported")) {
|
||||
kind = Finding.Kind.UNSUPPORTED_CLASS;
|
||||
} else if (text.startsWith("Method {{m0}} is not supported")) {
|
||||
kind = Finding.Kind.UNSUPPORTED_METHOD;
|
||||
} else if (text.contains("which is missing in the classpath")) {
|
||||
kind = Finding.Kind.MISSING_SUPERTYPE;
|
||||
// The interesting symbol is the missing supertype, not the class extending it.
|
||||
first = params.length > 1 ? params[1] : first;
|
||||
} else if (text.startsWith("Bootstrap method {{m0}} was not found")) {
|
||||
kind = Finding.Kind.MISSING_BOOTSTRAP;
|
||||
} else {
|
||||
kind = Finding.Kind.OTHER;
|
||||
}
|
||||
|
||||
String symbol;
|
||||
String detail;
|
||||
switch (first) {
|
||||
case MethodReference method -> {
|
||||
symbol = method.getClassName() + "#" + method.getName();
|
||||
detail = method.toString();
|
||||
}
|
||||
case FieldReference field -> {
|
||||
symbol = field.getClassName() + "#" + field.getFieldName();
|
||||
detail = field.toString();
|
||||
}
|
||||
case String className -> {
|
||||
symbol = className;
|
||||
detail = className;
|
||||
}
|
||||
case null, default -> {
|
||||
symbol = kind == Finding.Kind.OTHER ? render(problem) : String.valueOf(first);
|
||||
detail = render(problem);
|
||||
}
|
||||
}
|
||||
|
||||
CallLocation location = problem.getLocation();
|
||||
MethodReference callerMethod = location != null ? location.getMethod() : null;
|
||||
TextLocation source = location != null ? location.getSourceLocation() : null;
|
||||
return new Finding(
|
||||
kind,
|
||||
symbol,
|
||||
detail,
|
||||
callerMethod != null ? callerMethod.getClassName() : null,
|
||||
callerMethod != null ? callerMethod.getDescriptor().toString() : null,
|
||||
source != null && !source.isEmpty() ? source.getLine() : -1,
|
||||
null);
|
||||
}
|
||||
|
||||
private static String render(Problem problem) {
|
||||
DefaultProblemTextConsumer consumer = new DefaultProblemTextConsumer();
|
||||
problem.render(consumer);
|
||||
return consumer.getText();
|
||||
}
|
||||
|
||||
/** TeaVM's progress chatter is noise here; its problems are collected separately. */
|
||||
private static final class QuietLog implements TeaVMToolLog {
|
||||
@Override
|
||||
public void info(String text) {}
|
||||
|
||||
@Override
|
||||
public void debug(String text) {}
|
||||
|
||||
@Override
|
||||
public void warning(String text) {}
|
||||
|
||||
@Override
|
||||
public void error(String text) {}
|
||||
|
||||
@Override
|
||||
public void info(String text, Throwable e) {}
|
||||
|
||||
@Override
|
||||
public void debug(String text, Throwable e) {}
|
||||
|
||||
@Override
|
||||
public void warning(String text, Throwable e) {
|
||||
Log.warn("TeaVM: " + text + ": " + e);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void error(String text, Throwable e) {
|
||||
Log.warn("TeaVM error: " + text + ": " + e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
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.jar.JarEntry;
|
||||
import java.util.jar.JarOutputStream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.objectweb.asm.ClassReader;
|
||||
import org.objectweb.asm.ClassVisitor;
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
|
||||
class RootsTest {
|
||||
|
||||
@TempDir
|
||||
Path dir;
|
||||
|
||||
@Test
|
||||
void everyMethodOfEveryRootedClassIsCalledAndExcludedClassesAreNot() throws Exception {
|
||||
Path jar = dir.resolve("client.jar");
|
||||
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
|
||||
add(out, "game/Screen", Opcodes.ACC_PUBLIC, cw -> {
|
||||
method(cw, Opcodes.ACC_PUBLIC, "<init>", "()V");
|
||||
method(cw, Opcodes.ACC_PUBLIC, "render", "(IF)V");
|
||||
method(cw, Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC, "helper", "(J)Ljava/lang/String;");
|
||||
cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, "skipped", "()V", null, null)
|
||||
.visitEnd();
|
||||
});
|
||||
add(
|
||||
out,
|
||||
"game/data/Generator",
|
||||
Opcodes.ACC_PUBLIC,
|
||||
cw -> method(cw, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "run", "()V"));
|
||||
}
|
||||
|
||||
int rooted = Roots.generate(jar, name -> !name.startsWith("game.data."), "game.Main", dir.resolve("roots"));
|
||||
|
||||
assertThat(rooted).isEqualTo(1);
|
||||
List<String> calls = calls(dir.resolve("roots/incari/survey/roots/Roots0.class"));
|
||||
assertThat(calls)
|
||||
.contains("game/Screen.<init>", "game/Screen.render", "game/Screen.helper")
|
||||
.doesNotContain("game/Screen.skipped", "game/data/Generator.run");
|
||||
assertThat(calls(dir.resolve("roots/incari/survey/roots/Entry.class")))
|
||||
.containsExactly("game/Main.main", "incari/survey/roots/Roots0.run");
|
||||
}
|
||||
|
||||
private static List<String> calls(Path classFile) throws IOException {
|
||||
List<String> calls = new ArrayList<>();
|
||||
new ClassReader(Files.readAllBytes(classFile))
|
||||
.accept(
|
||||
new ClassVisitor(Opcodes.ASM9) {
|
||||
@Override
|
||||
public MethodVisitor visitMethod(
|
||||
int access, String name, String desc, String sig, String[] exceptions) {
|
||||
return new MethodVisitor(Opcodes.ASM9) {
|
||||
@Override
|
||||
public void visitMethodInsn(
|
||||
int opcode, String owner, String method, String d, boolean itf) {
|
||||
if (!owner.startsWith("incari/survey/roots/Roots") || method.equals("run")) {
|
||||
calls.add(owner + "." + method);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
},
|
||||
0);
|
||||
return calls;
|
||||
}
|
||||
|
||||
private static void add(JarOutputStream out, String name, int access, java.util.function.Consumer<ClassWriter> body)
|
||||
throws IOException {
|
||||
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
|
||||
cw.visit(Opcodes.V17, access, name, null, "java/lang/Object", null);
|
||||
body.accept(cw);
|
||||
cw.visitEnd();
|
||||
out.putNextEntry(new JarEntry(name + ".class"));
|
||||
out.write(cw.toByteArray());
|
||||
out.closeEntry();
|
||||
}
|
||||
|
||||
private static void method(ClassWriter cw, int access, String name, String desc) {
|
||||
MethodVisitor mv = cw.visitMethod(access, name, desc, null, null);
|
||||
mv.visitCode();
|
||||
mv.visitInsn(Opcodes.RETURN);
|
||||
mv.visitMaxs(0, 0);
|
||||
mv.visitEnd();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarOutputStream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.objectweb.asm.ClassWriter;
|
||||
import org.objectweb.asm.MethodVisitor;
|
||||
import org.objectweb.asm.Opcodes;
|
||||
import org.teavm.model.MethodDescriptor;
|
||||
import org.teavm.model.MethodReference;
|
||||
|
||||
/** Stub generation for absent classes, checked by loading the generated classes on the real JVM. */
|
||||
class StubsTest {
|
||||
|
||||
@TempDir
|
||||
Path dir;
|
||||
|
||||
@Test
|
||||
void absentClassStubsCarryEveryReferencedMemberAndLoad() throws Exception {
|
||||
// A "game" class that uses an absent library class three ways.
|
||||
Path jar = jarWith("game/User", cw -> {
|
||||
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "use", "()V", null, null);
|
||||
mv.visitCode();
|
||||
mv.visitMethodInsn(Opcodes.INVOKESTATIC, "lib/Gl", "glDraw", "(II)I", false);
|
||||
mv.visitInsn(Opcodes.POP);
|
||||
mv.visitFieldInsn(Opcodes.GETSTATIC, "lib/Gl", "GL_TRIANGLES", "I");
|
||||
mv.visitInsn(Opcodes.POP);
|
||||
mv.visitTypeInsn(Opcodes.NEW, "lib/Window");
|
||||
mv.visitInsn(Opcodes.DUP);
|
||||
mv.visitLdcInsn("title");
|
||||
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "lib/Window", "<init>", "(Ljava/lang/String;)V", false);
|
||||
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "lib/Window", "title", "()Ljava/lang/String;", false);
|
||||
mv.visitInsn(Opcodes.POP);
|
||||
mv.visitInsn(Opcodes.RETURN);
|
||||
mv.visitMaxs(0, 0);
|
||||
mv.visitEnd();
|
||||
});
|
||||
|
||||
Stubs stubs = new Stubs(ReferenceIndex.build(java.util.List.of(jar)));
|
||||
assertThat(stubs.addAbsentClass("lib.Gl")).isTrue();
|
||||
assertThat(stubs.addAbsentClass("lib.Gl")).isFalse();
|
||||
stubs.addAbsentClass("lib.Window");
|
||||
// A member TeaVM reports later, which the game's own bytecode never showed.
|
||||
stubs.addMethod(new MethodReference("lib.Window", MethodDescriptor.parse("close()V")), true);
|
||||
stubs.writeClasses(dir);
|
||||
|
||||
try (URLClassLoader loader = new URLClassLoader(new URL[] {dir.toUri().toURL()}, null)) {
|
||||
Class<?> gl = loader.loadClass("lib.Gl");
|
||||
Method draw = gl.getMethod("glDraw", int.class, int.class);
|
||||
assertThat(Modifier.isStatic(draw.getModifiers())).isTrue();
|
||||
assertThat(draw.invoke(null, 1, 2)).isEqualTo(0);
|
||||
assertThat(Modifier.isStatic(gl.getField("GL_TRIANGLES").getModifiers()))
|
||||
.isTrue();
|
||||
|
||||
Class<?> window = loader.loadClass("lib.Window");
|
||||
Object instance = window.getConstructor(String.class).newInstance("x");
|
||||
assertThat(window.getMethod("title").invoke(instance)).isNull();
|
||||
window.getMethod("close").invoke(instance);
|
||||
// Always a no-arg constructor, for subclasses whose super call the index missed.
|
||||
assertThat(window.getConstructor()).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingMembersOfExistingClassesGoToTheTransformerWithJdkStaticness() {
|
||||
Stubs stubs = new Stubs(emptyIndex());
|
||||
stubs.addMethod(new MethodReference("java.lang.System", MethodDescriptor.parse("exit(I)V")), false);
|
||||
stubs.addMethod(
|
||||
new MethodReference(
|
||||
"java.lang.Runtime", MethodDescriptor.parse("addShutdownHook(Ljava/lang/Thread;)V")),
|
||||
false);
|
||||
|
||||
assertThat(stubs.extraMembers().get("java.lang.System"))
|
||||
.containsExactly(new Stubs.ExtraMember("exit(I)V", true, true));
|
||||
assertThat(stubs.extraMembers().get("java.lang.Runtime"))
|
||||
.containsExactly(new Stubs.ExtraMember("addShutdownHook(Ljava/lang/Thread;)V", true, false));
|
||||
assertThat(stubs.absentClassCount()).isZero();
|
||||
}
|
||||
|
||||
private ReferenceIndex emptyIndex() {
|
||||
try {
|
||||
return ReferenceIndex.build(java.util.List.of());
|
||||
} catch (IOException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private Path jarWith(String internalName, java.util.function.Consumer<ClassWriter> body) throws IOException {
|
||||
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
|
||||
cw.visit(Opcodes.V17, Opcodes.ACC_PUBLIC, internalName, null, "java/lang/Object", null);
|
||||
body.accept(cw);
|
||||
cw.visitEnd();
|
||||
Path jar = dir.resolve("game.jar");
|
||||
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
|
||||
out.putNextEntry(new JarEntry(internalName + ".class"));
|
||||
out.write(cw.toByteArray());
|
||||
out.closeEntry();
|
||||
}
|
||||
return jar;
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
package incari.tools.survey;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import incari.tools.build.CliException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SurveyRulesTest {
|
||||
|
||||
private static Finding finding(Finding.Kind kind, String symbol, String caller) {
|
||||
return new Finding(kind, symbol, symbol, caller, "m()V", 1, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void globsDistinguishOneSegmentFromAnything() {
|
||||
assertThat(SurveyRules.glob("java.nio.file.*")
|
||||
.matcher("java.nio.file.Files")
|
||||
.matches())
|
||||
.isTrue();
|
||||
assertThat(SurveyRules.glob("java.nio.file.*")
|
||||
.matcher("java.nio.file.spi.FileSystemProvider")
|
||||
.matches())
|
||||
.isFalse();
|
||||
assertThat(SurveyRules.glob("java.nio.**")
|
||||
.matcher("java.nio.file.spi.FileSystemProvider#x")
|
||||
.matches())
|
||||
.isTrue();
|
||||
assertThat(SurveyRules.glob("java.lang.Thread#set*")
|
||||
.matcher("java.lang.Thread#setPriority")
|
||||
.matches())
|
||||
.isTrue();
|
||||
assertThat(SurveyRules.glob("a$b").matcher("a$b").matches()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstMatchingRuleWinsAndAllSelectorsMustMatch() {
|
||||
SurveyRules rules = SurveyRules.parse(
|
||||
List.of(
|
||||
"delete caller=net.minecraft.util.profiling.** Profiler",
|
||||
"stub kind=missing-method symbol=java.lang.Thread#setPriority Thread priorities",
|
||||
"shim symbol=java.lang.Thread Threads as coroutines"),
|
||||
"rules.txt");
|
||||
|
||||
Finding priorityInProfiler = finding(
|
||||
Finding.Kind.MISSING_METHOD, "java.lang.Thread#setPriority", "net.minecraft.util.profiling.Profiler");
|
||||
Finding priority = finding(Finding.Kind.MISSING_METHOD, "java.lang.Thread#setPriority", "net.minecraft.Util");
|
||||
Finding reflectivePriority =
|
||||
finding(Finding.Kind.REFLECTION, "java.lang.Thread#setPriority", "net.minecraft.Util");
|
||||
|
||||
assertThat(rules.classify(priorityInProfiler, "missing-method", "minecraft")
|
||||
.reason())
|
||||
.isEqualTo("Profiler");
|
||||
assertThat(rules.classify(priority, "missing-method", "minecraft").reason())
|
||||
.isEqualTo("Thread priorities");
|
||||
// A pattern without '#' matches every member of that class.
|
||||
assertThat(rules.classify(reflectivePriority, "reflection", "minecraft").reason())
|
||||
.isEqualTo("Threads as coroutines");
|
||||
assertThat(rules.classify(finding(Finding.Kind.MISSING_METHOD, "java.util.X#y", "a.B"), "missing-method", "x"))
|
||||
.isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void originSelectorMatchesTheCallersJar() {
|
||||
SurveyRules rules = SurveyRules.parse(List.of("shim origin=guava kind=host-jdk Guava's JDK internals"), "r");
|
||||
Finding f = finding(Finding.Kind.HOST_JDK, "sun.misc.Unsafe#getUnsafe", "com.google.common.X");
|
||||
assertThat(rules.classify(f, "host-jdk", "guava")).isNotNull();
|
||||
assertThat(rules.classify(f, "host-jdk", "minecraft")).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void libraryRulesMatchByPrefixAndEveryLibraryNeedsOne() {
|
||||
SurveyRules rules = SurveyRules.parse(
|
||||
List.of(
|
||||
"library io.netty:netty-buffer: keep Pure Java",
|
||||
"library io.netty: replace WebSocket transport"),
|
||||
"r");
|
||||
assertThat(rules.library("io.netty:netty-buffer:4.2.16.Final").action())
|
||||
.isEqualTo(SurveyRules.LibraryAction.KEEP);
|
||||
assertThat(rules.library("io.netty:netty-handler:4.2.16.Final").action())
|
||||
.isEqualTo(SurveyRules.LibraryAction.REPLACE);
|
||||
assertThatThrownBy(() -> rules.library("org.example:new:1.0"))
|
||||
.isInstanceOf(CliException.class)
|
||||
.hasMessageContaining("org.example:new:1.0");
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedLinesNameTheirLocation() {
|
||||
assertThatThrownBy(() -> SurveyRules.parse(List.of("fix symbol=a.B reason"), "r"))
|
||||
.hasMessageContaining("r:1");
|
||||
assertThatThrownBy(() -> SurveyRules.parse(List.of("stub symbol=a.B"), "r"))
|
||||
.hasMessageContaining("reason");
|
||||
assertThatThrownBy(() -> SurveyRules.parse(List.of("stub nope=a.B x"), "r"))
|
||||
.hasMessageContaining("unknown selector");
|
||||
assertThatThrownBy(() -> SurveyRules.parse(List.of("library a:"), "r"))
|
||||
.hasMessageContaining("expected: library");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCheckedInRulesFileParses() throws Exception {
|
||||
SurveyRules rules =
|
||||
SurveyRules.load(Path.of(System.getProperty("user.dir")).resolve("rules.txt"));
|
||||
assertThat(rules.libraries()).isNotEmpty();
|
||||
assertThat(rules.triage()).isNotEmpty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# tools/teavm-patches
|
||||
|
||||
- TeaVM's code under its Apache 2.0 header. Change only what a fix needs; describe it in README.md.
|
||||
- Never put Incari code in `src/main`; it's excluded from formatting and lint. The tests in
|
||||
`src/test` are Incari code, formatted and linted as usual.
|
||||
- Test class library fixes against the JDK's behaviour: `./gradlew :tools:teavm-patches:check`.
|
||||
@@ -0,0 +1,79 @@
|
||||
# tools/teavm-patches: fixes to TeaVM
|
||||
|
||||
Fixes to TeaVM 0.16.0 the browser build needs before a TeaVM release has them. Each file is TeaVM's
|
||||
own source (Apache-2.0, header kept), with the change described in its header. `tools/webbuild`
|
||||
puts this module ahead of TeaVM on its class path, and checks at start-up that these classes won.
|
||||
Nothing here ships except through TeaVM's compiler.
|
||||
|
||||
## Fixes
|
||||
|
||||
All are worth reporting upstream (konsoletyper/teavm). Probes run with `app-web/probes/run.sh <Name>`;
|
||||
tests run on the JVM.
|
||||
|
||||
| Class | Bug | What it broke | Check |
|
||||
| --- | --- | --- | --- |
|
||||
| `CoroutineTransformation` | Blocks around suspensions used non-null types for values restored as nullable | Module failed to validate (`BanListEntry.serialize`) | — |
|
||||
| `CoroutineTransformation` | Non-nullable locals read before any set on the save path | "uninitialized non-defaultable local" in reflection callers | `SuspendingReflectionProbe` |
|
||||
| `ClassInitializerInsertionTransformer` | Subclass initialized before its superclass (against JLS 12.4.2) | "Duplicate id value" creating the player | `InitOrderProbe` |
|
||||
| `TObject` | Interrupted `wait()` didn't retake the monitor | Crash when joining a world (sound thread) | `InterruptedWaitProbe` |
|
||||
| `TArrayDeque` | Iterator `remove()` skipped the shifted element; removal shifted in a loop | Crash on the first expired particle; slow removals | `ArrayDequeProbe` |
|
||||
| `TZipFile` | Inflater got no trailing byte at an entry's end | 638 textures lost from a community pack | `ZipFileProbe` |
|
||||
| `TTemplateCollections` | Empty immutable map divided by zero in `get()` | Crash entering the End | `EmptyTemplateMapTest` |
|
||||
| `TTemplateCollections` | `Set.of`/`Map.of` lookups compared every element | Slow lookups (ADR 0034) | `ImmutableCollectionsProbe` |
|
||||
| `TCollections` | `unmodifiableCollection` scanned every element for `contains` | Slow model discovery (sets and maps fixed in 0.16.0) | `UnmodifiableViewsTest` |
|
||||
| `StringConcatFactorySubstitutor` | Concatenation called `toString` virtually | Every concatenation, so every exception, became a coroutine | — |
|
||||
| `WasmGCReferenceQueueDependency` | Polled references typed as plain `WeakReference` | Null trap in Guava's weak maps (Optimize World) | `WeakQueueProbe` |
|
||||
| `WeakReferenceIntrinsic` | `new WeakReference<>(null)` reached `new WeakRef(null)` | Uncatchable `TypeError` | — |
|
||||
| `TPath` | `Path.of(URI)` failed for any `file:` URI but `file:///` | The game couldn't find its built-in packs | — |
|
||||
| `ClassInitElimination` | Interface method calls counted as initializing the interface | A `catch` saw null for an interface constant | — |
|
||||
| `TDefaultPath` | `resolve` from an empty path, or after the root | Listing resource packs | — |
|
||||
| `TByteBufferImpl`, `TByteBufferNative` | Absolute `getLong(int)` moved the position | Every PNG read skipped 8 bytes | — |
|
||||
| `TByteBuffer` | Absolute bulk `put` copied nothing when the source had no bytes after its position | Zero projection matrix; blank sprites | `AbsoluteBulkPutTest` |
|
||||
| `TByteBuffer` | `allocateDirect` memory not zeroed | Region files read chunks from garbage offsets | — |
|
||||
| `TFormatter` | `%%` and `%n` consumed arguments; `MIN_VALUE` printed `--` | F3 screen crashed | `FormatterTest` |
|
||||
| `TSortedStreamImpl`, `TSimpleStreamImpl` | Sorted stream kept the source's size estimate | Tab list crashed in multiplayer | `StreamToArrayTest` |
|
||||
| `WasmGCJsoCommonGenerator` | Functions given to JavaScript weren't exported | Binaryen's `--closed-world` deleted `main` (ADR 0034) | — |
|
||||
| `WasmGCSupertypeFunctionGenerator` | `instanceof` and casts walked every tag range of a widely implemented interface | Slow type checks at start-up (ADR 0026) | — |
|
||||
| `CoroutineFunctions`, `WasmGCDependencies` | 0.16.0's coroutines check the fiber with static `isPresentAndSuspending(fiber)`, twice the code of 0.15's `isSuspending()` and called after every call that may suspend; V8 then inlined less of the game | Compatible build 17% slower in the lobby at 4x throttle (ADR 0064) | — |
|
||||
| `ReflectionMetadataGenerator`, `WasmGCModuleGenerator` | Reflection setup and start function were single huge functions | V8's optimizer ran out of memory and Chrome killed the tab (ADR 0042) | — |
|
||||
|
||||
## JSPI: the Fast build
|
||||
|
||||
Not a fix, but a second way to run threads (ADR 0036). TeaVM compiles 81% of this program as
|
||||
coroutines, which run about 1.5x slower (`CoroutineCostProbe`). JSPI lets the browser keep the
|
||||
suspended stack instead.
|
||||
|
||||
- `AsyncMethodFinder`: with `incari.jspi` set (only in a `--jspi` build), finds no async methods,
|
||||
so nothing is compiled as a coroutine.
|
||||
- `Fiber`: adds `Fiber.Jspi`. Each fiber runs through `WebAssembly.promising`; `suspend` awaits a
|
||||
promise through a `WebAssembly.Suspending` import (`app-web`'s `jspi.ts`). `tools/webbuild`'s
|
||||
`JspiTransformer` routes `Fiber.suspend` and `Fiber.start` there.
|
||||
|
||||
Differences from coroutines:
|
||||
|
||||
- A woken thread resumes from a microtask, not inside the call that woke it.
|
||||
- A JavaScript callback into Java still must not suspend (JSPI traps).
|
||||
- V8 never frees a suspended stack. So on `pagehide`, `jspi.ts` resumes each waiting fiber with an
|
||||
order to end, and it unwinds by trapping, with no Java code run. Without this, every reload
|
||||
leaked the whole game.
|
||||
|
||||
`JspiProbe` checks threads behave the same in both builds.
|
||||
|
||||
## Fixed upstream
|
||||
|
||||
TeaVM 0.16.0 has these, so the patches went (ADR 0064): `WasmTypeInference`; `CoroutineTransformation`'s
|
||||
type after a suspending `c ? a : b`; `TThrowable`'s suppressed array; `Heap` growth; `instanceof Item[]`
|
||||
(`WasmGCInstructionGenerationVisitor`, `WasmGCSupertypeFunctionGenerator`); the absolute bulk `put` in
|
||||
`TByteBufferImpl` and `TByteBufferNative`; `TCollections`' set and map views; `TDefaultPath`'s
|
||||
`iterator` and `equals`. Their probes still run.
|
||||
|
||||
## Invariants
|
||||
|
||||
- One class per fix, as close to upstream as possible, the change described here and in the file.
|
||||
- Drop a patch when the pinned TeaVM has the fix.
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
./gradlew :tools:teavm-patches:check
|
||||
```
|
||||
@@ -0,0 +1,37 @@
|
||||
import net.ltgt.gradle.errorprone.errorprone
|
||||
|
||||
plugins {
|
||||
`java-library`
|
||||
}
|
||||
|
||||
// Fixes to TeaVM classes, shadowing TeaVM's own on the web build's class path (README.md).
|
||||
// TeaVM's code (Apache License 2.0), kept in its own style: not reformatted, not linted.
|
||||
// The tests are Incari code and follow the usual rules.
|
||||
|
||||
dependencies {
|
||||
compileOnly(libs.teavm.core)
|
||||
compileOnly(libs.teavm.classlib)
|
||||
compileOnly(libs.teavm.jso)
|
||||
compileOnly(libs.teavm.jso.impl)
|
||||
// The JSO generator's JavaScript bodies are Rhino trees (TeaVM's relocated copy).
|
||||
compileOnly("org.teavm:teavm-relocated-libs-rhino:${libs.versions.teavm.get()}")
|
||||
|
||||
// Class library fixes run on the JVM in the tests, checked against the JDK's own behaviour.
|
||||
testImplementation(libs.teavm.classlib)
|
||||
testImplementation(platform(libs.junit.bom))
|
||||
testImplementation(libs.junit.jupiter)
|
||||
testImplementation(libs.assertj)
|
||||
testRuntimeOnly(libs.junit.launcher)
|
||||
}
|
||||
|
||||
tasks.named<JavaCompile>("compileJava") {
|
||||
options.compilerArgs.removeAll { it.startsWith("-Xlint") || it == "-Werror" }
|
||||
options.errorprone.enabled = false
|
||||
}
|
||||
|
||||
configure<com.diffplug.gradle.spotless.SpotlessExtension> {
|
||||
java {
|
||||
// Third-party code keeps its upstream formatting.
|
||||
targetExclude("src/main/**/*.java")
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
/*
|
||||
* Copyright 2024 Alexey Andreev.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
* Modified for Incari (tools/teavm-patches/README.md): the start function, teavm@initializer,
|
||||
* is split where its operand stack is empty into functions of about CHUNK_INSTRUCTIONS
|
||||
* instructions each, which it calls in turn (5 MB of code in the game's build, run once by each
|
||||
* instance; V8 sent it to its optimizing compiler once enough instances had, which took gigabytes
|
||||
* of memory on it: ADR 0042).
|
||||
*/
|
||||
package org.teavm.backend.wasm;
|
||||
|
||||
import org.teavm.backend.wasm.generate.WasmGCDeclarationsGenerator;
|
||||
import org.teavm.backend.wasm.model.WasmFunction;
|
||||
import org.teavm.backend.wasm.model.WasmGlobal;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmBranch;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmBreak;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmInstruction;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmInstructionList;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmIntBinaryOperation;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmIntType;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmReturn;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmSwitch;
|
||||
import org.teavm.backend.wasm.model.instruction.WasmTypeInference;
|
||||
import org.teavm.backend.wasm.runtime.StringInternPool;
|
||||
import org.teavm.interop.Address;
|
||||
import org.teavm.model.MethodReference;
|
||||
import org.teavm.model.ValueType;
|
||||
import org.teavm.runtime.heap.Heap;
|
||||
|
||||
public class WasmGCModuleGenerator {
|
||||
private WasmGCDeclarationsGenerator declarationsGenerator;
|
||||
private WasmFunction initializer;
|
||||
private static final int CHUNK_INSTRUCTIONS = 4000;
|
||||
|
||||
public WasmGCModuleGenerator(WasmGCDeclarationsGenerator declarationsGenerator) {
|
||||
this.declarationsGenerator = declarationsGenerator;
|
||||
}
|
||||
|
||||
public void generate() {
|
||||
declarationsGenerator.generate();
|
||||
createInitializer();
|
||||
}
|
||||
|
||||
public void initBuffersHeap(WasmGlobal offset, int minSize, WasmGlobal heapLimit) {
|
||||
var target = declarationsGenerator.functions().forStaticMethod(new MethodReference(Heap.class,
|
||||
"init", Address.class, int.class, int.class, void.class));
|
||||
var builder = new WasmInstructionList().builder();
|
||||
builder
|
||||
.getGlobal(offset)
|
||||
.i32Const(minSize)
|
||||
.getGlobal(heapLimit)
|
||||
.getGlobal(offset)
|
||||
.intBinary(WasmIntType.INT32, WasmIntBinaryOperation.SUB)
|
||||
.call(target);
|
||||
initializer.getBody().transferFrom(builder.list);
|
||||
}
|
||||
|
||||
public WasmFunction generateReportGarbageCollectedStringFunction() {
|
||||
var entryType = ValueType.object(StringInternPool.class.getName() + "$Entry");
|
||||
return declarationsGenerator.functions().forStaticMethod(new MethodReference(
|
||||
StringInternPool.class.getName(),
|
||||
"remove",
|
||||
entryType,
|
||||
ValueType.VOID
|
||||
));
|
||||
}
|
||||
|
||||
private void createInitializer() {
|
||||
var functionType = declarationsGenerator.functionTypes.of(null);
|
||||
initializer = new WasmFunction(functionType);
|
||||
initializer.setName("teavm@initializer");
|
||||
declarationsGenerator.module.functions.add(initializer);
|
||||
declarationsGenerator.module.setStartFunction(initializer);
|
||||
declarationsGenerator.contributeToInitializer(initializer);
|
||||
splitInitializer();
|
||||
}
|
||||
|
||||
private void splitInitializer() {
|
||||
if (!initializer.getLocalVariables().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
// Where to split: after an instruction that leaves the stack empty, once a chunk is full.
|
||||
var inference = new WasmTypeInference();
|
||||
var ends = new java.util.HashSet<WasmInstruction>();
|
||||
int size = 0;
|
||||
int total = 0;
|
||||
try {
|
||||
for (var insn : initializer.getBody()) {
|
||||
if (insn instanceof WasmReturn || insn instanceof WasmBranch || insn instanceof WasmBreak
|
||||
|| insn instanceof WasmSwitch) {
|
||||
return;
|
||||
}
|
||||
insn.acceptVisitor(inference);
|
||||
size++;
|
||||
total++;
|
||||
if (size >= CHUNK_INSTRUCTIONS && inference.typeStack.isEmpty()) {
|
||||
ends.add(insn);
|
||||
size = 0;
|
||||
}
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
return;
|
||||
}
|
||||
if (ends.isEmpty() || !inference.typeStack.isEmpty() || total <= CHUNK_INSTRUCTIONS) {
|
||||
return;
|
||||
}
|
||||
var body = initializer.getBody();
|
||||
var calls = new java.util.ArrayList<WasmFunction>();
|
||||
WasmFunction chunk = null;
|
||||
while (body.getFirst() != null) {
|
||||
var insn = body.getFirst();
|
||||
insn.delete();
|
||||
if (chunk == null) {
|
||||
chunk = new WasmFunction(declarationsGenerator.functionTypes.of(null));
|
||||
chunk.setName("teavm@initializer$" + calls.size());
|
||||
declarationsGenerator.module.functions.add(chunk);
|
||||
calls.add(chunk);
|
||||
}
|
||||
chunk.getBody().add(insn);
|
||||
if (ends.contains(insn)) {
|
||||
chunk = null;
|
||||
}
|
||||
}
|
||||
var builder = body.builder();
|
||||
for (var function : calls) {
|
||||
builder.call(function);
|
||||
}
|
||||
}
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
/*
|
||||
* Copyright 2026 Alexey Andreev.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*
|
||||
* Modified for Incari (tools/teavm-patches/README.md): also links Fiber's instance checks
|
||||
* isResuming() and isSuspending(), which tools/teavm-patches' CoroutineFunctions has coroutines
|
||||
* call, as TeaVM 0.15 did.
|
||||
*/
|
||||
package org.teavm.backend.wasm.dependencies;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import org.teavm.backend.wasm.WasmRuntime;
|
||||
import org.teavm.backend.wasm.runtime.WasmGCSupport;
|
||||
import org.teavm.dependency.AbstractDependencyListener;
|
||||
import org.teavm.dependency.DependencyAgent;
|
||||
import org.teavm.dependency.DependencyAnalyzer;
|
||||
import org.teavm.interop.Address;
|
||||
import org.teavm.model.MethodReader;
|
||||
import org.teavm.model.MethodReference;
|
||||
import org.teavm.model.ValueType;
|
||||
import org.teavm.runtime.EventQueue;
|
||||
import org.teavm.runtime.Fiber;
|
||||
import org.teavm.runtime.heap.Heap;
|
||||
|
||||
public class WasmGCDependencies {
|
||||
private DependencyAnalyzer analyzer;
|
||||
|
||||
public WasmGCDependencies(DependencyAnalyzer analyzer) {
|
||||
this.analyzer = analyzer;
|
||||
}
|
||||
|
||||
public void contribute() {
|
||||
analyzer.linkClass("java.lang.Class");
|
||||
contributeWasmRuntime();
|
||||
contributeMathUtils();
|
||||
contributeExceptionUtils();
|
||||
contributeInitializerUtils();
|
||||
contributeString();
|
||||
contributeBuffers();
|
||||
contributeFiber();
|
||||
analyzer.addDependencyListener(new WasmGCReferenceQueueDependency());
|
||||
analyzer.addDependencyListener(new WasmGCResourceDependency());
|
||||
analyzer.addDependencyListener(new SystemArrayCopyDependencySupport());
|
||||
analyzer.addDependencyListener(new WasmGCSignatureDependencyListener());
|
||||
analyzer.addDependencyListener(new WasmGCExportDependencyListener());
|
||||
}
|
||||
|
||||
public void contributeStandardExports() {
|
||||
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "createStringArray", int.class, String[].class))
|
||||
.use();
|
||||
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "createStringBuilder", StringBuilder.class))
|
||||
.use();
|
||||
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "setToStringArray", String[].class,
|
||||
int.class, String.class, void.class))
|
||||
.propagate(1, analyzer.getType(ValueType.arrayOf(ValueType.object("java.lang.String"))))
|
||||
.propagate(3, analyzer.getClassType("java.lang.String"))
|
||||
.use();
|
||||
analyzer.linkMethod(new MethodReference(StringBuilder.class, "append", char.class, StringBuilder.class))
|
||||
.propagate(0, analyzer.getClassType("java.lang.StringBuilder"))
|
||||
.use();
|
||||
analyzer.linkMethod(new MethodReference(StringBuilder.class, "toString", String.class))
|
||||
.propagate(0, analyzer.getClassType("java.lang.StringBuilder"))
|
||||
.use();
|
||||
analyzer.linkMethod(new MethodReference(String.class, "length", int.class))
|
||||
.propagate(0, analyzer.getClassType("java.lang.String"))
|
||||
.use();
|
||||
analyzer.linkMethod(new MethodReference(String.class, "charAt", int.class, char.class))
|
||||
.propagate(0, analyzer.getClassType("java.lang.String"))
|
||||
.use();
|
||||
}
|
||||
|
||||
private void contributeWasmRuntime() {
|
||||
for (var cls : List.of(int.class, long.class, float.class, double.class)) {
|
||||
analyzer.linkMethod(new MethodReference(WasmRuntime.class, "lt", cls, cls, boolean.class)).use();
|
||||
analyzer.linkMethod(new MethodReference(WasmRuntime.class, "gt", cls, cls, boolean.class)).use();
|
||||
}
|
||||
for (var cls : List.of(int.class, long.class)) {
|
||||
analyzer.linkMethod(new MethodReference(WasmRuntime.class, "ltu", cls, cls, boolean.class)).use();
|
||||
analyzer.linkMethod(new MethodReference(WasmRuntime.class, "gtu", cls, cls, boolean.class)).use();
|
||||
}
|
||||
for (var cls : List.of(float.class, double.class)) {
|
||||
analyzer.linkMethod(new MethodReference(WasmRuntime.class, "min", cls, cls, cls)).use();
|
||||
analyzer.linkMethod(new MethodReference(WasmRuntime.class, "max", cls, cls, cls)).use();
|
||||
}
|
||||
}
|
||||
|
||||
private void contributeMathUtils() {
|
||||
for (var type : Arrays.asList(int.class, long.class, float.class, double.class)) {
|
||||
var method = new MethodReference(WasmRuntime.class, "compare", type, type, int.class);
|
||||
analyzer.linkMethod(method).use();
|
||||
}
|
||||
for (var type : Arrays.asList(float.class, double.class)) {
|
||||
var method = new MethodReference(WasmRuntime.class, "compareLess", type, type, int.class);
|
||||
analyzer.linkMethod(method).use();
|
||||
}
|
||||
for (var type : Arrays.asList(int.class, long.class)) {
|
||||
var method = new MethodReference(WasmRuntime.class, "compareUnsigned", type, type, int.class);
|
||||
analyzer.linkMethod(method).use();
|
||||
}
|
||||
|
||||
for (var type : Arrays.asList(float.class, double.class)) {
|
||||
var method = new MethodReference(WasmRuntime.class, "remainder", type, type, type);
|
||||
analyzer.linkMethod(method).use();
|
||||
}
|
||||
}
|
||||
|
||||
private void contributeExceptionUtils() {
|
||||
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "npe", NullPointerException.class))
|
||||
.use();
|
||||
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "aiiobe", ArrayIndexOutOfBoundsException.class))
|
||||
.use();
|
||||
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "cce", ClassCastException.class)).use();
|
||||
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "throwCloneNotSupportedException",
|
||||
void.class)).use();
|
||||
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "defaultClone", Object.class, Object.class)).use();
|
||||
analyzer.linkMethod(new MethodReference(NullPointerException.class, "<init>", void.class)).use();
|
||||
analyzer.linkMethod(new MethodReference(Throwable.class, "getMessage", String.class))
|
||||
.propagate(0, Throwable.class).use();
|
||||
|
||||
analyzer.addDependencyListener(new AbstractDependencyListener() {
|
||||
@Override
|
||||
public void classReached(DependencyAgent agent, String className) {
|
||||
if (className.equals(Throwable.class.getName())) {
|
||||
agent.linkMethod(new MethodReference(Throwable.class, "getMessage", String.class))
|
||||
.propagate(0, Throwable.class)
|
||||
.use();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void contributeInitializerUtils() {
|
||||
analyzer.linkMethod(new MethodReference(WasmGCSupport.class, "nextCharArray", char[].class)).use();
|
||||
}
|
||||
|
||||
private void contributeString() {
|
||||
analyzer.addDependencyListener(new StringInternDependencySupport());
|
||||
}
|
||||
|
||||
private void contributeBuffers() {
|
||||
analyzer.linkMethod(new MethodReference(Heap.class, "init", Address.class, int.class, int.class,
|
||||
void.class)).use();
|
||||
}
|
||||
|
||||
private void contributeFiber() {
|
||||
analyzer.linkMethod(new MethodReference(Fiber.class, "isPresentAndResuming", Fiber.class, boolean.class))
|
||||
.propagate(1, Fiber.class)
|
||||
.use();
|
||||
analyzer.linkMethod(new MethodReference(Fiber.class, "isPresentAndSuspending", Fiber.class, boolean.class))
|
||||
.propagate(1, Fiber.class)
|
||||
.use();
|
||||
// Incari: what coroutines call (CoroutineFunctions).
|
||||
analyzer.linkMethod(new MethodReference(Fiber.class, "isResuming", boolean.class)).use();
|
||||
analyzer.linkMethod(new MethodReference(Fiber.class, "isSuspending", boolean.class)).use();
|
||||
analyzer.linkMethod(new MethodReference(Fiber.class, "current", Fiber.class)).use();
|
||||
analyzer.linkMethod(new MethodReference(Thread.class, "setCurrentThread", Thread.class,
|
||||
void.class)).use();
|
||||
|
||||
var offerMethod = analyzer.linkMethod(new MethodReference(EventQueue.class, "offer", EventQueue.Event.class,
|
||||
long.class, int.class));
|
||||
var runEventMethod = analyzer.linkMethod(new MethodReference(EventQueue.class, "run", EventQueue.Event.class,
|
||||
void.class));
|
||||
|
||||
offerMethod.getVariable(1).addConsumer(type -> {
|
||||
runEventMethod.getVariable(1).propagate(type);
|
||||
runEventMethod.use();
|
||||
});
|
||||
|
||||
var fiberClass = analyzer.getClassSource().get(Fiber.class.getName());
|
||||
for (MethodReader method : fiberClass.getMethods()) {
|
||||
if (method.getName().startsWith("pop")) {
|
||||
analyzer.linkMethod(method.getReference())
|
||||
.propagate(0, Fiber.class)
|
||||
.use();
|
||||
} else if (method.getName().equals("reversePush")) {
|
||||
analyzer.linkMethod(method.getReference())
|
||||
.propagate(2, Fiber.class)
|
||||
.use();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user