Archive incari-client (client, 26.3, clean)

This commit is contained in:
2026-11-28 00:54:38 -06:00
parent 7a6174687f
commit 12838e838c
2383 changed files with 280266 additions and 0 deletions
@@ -0,0 +1,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() }
}
@@ -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;
@@ -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;
}
}