This commit is contained in:
1 parent
c11a278050
commit
8bc92b2341
25 files changed
+136
-331
No files matched your search
@@ -0,0 +1,116 @@
|
||||
package xyz.nightsync.skinsg;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class SkinsgConfig {
|
||||
|
||||
public enum Mode { ALL, NONE, SELF, SET }
|
||||
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
public static final int DEFAULT_SPEED = 100;
|
||||
|
||||
public String baseUrl = "";
|
||||
public Mode mode = Mode.ALL;
|
||||
public Set<String> enabled = new LinkedHashSet<>();
|
||||
public Set<String> blocked = new LinkedHashSet<>();
|
||||
public int globalSpeed = DEFAULT_SPEED;
|
||||
public Map<String, Integer> speed = new HashMap<>();
|
||||
|
||||
private transient Path file;
|
||||
|
||||
public static SkinsgConfig load(Path configDir) {
|
||||
Path f = configDir.resolve("skinsg.json");
|
||||
boolean fresh = !Files.exists(f);
|
||||
SkinsgConfig cfg;
|
||||
try {
|
||||
cfg = fresh ? new SkinsgConfig()
|
||||
: GSON.fromJson(Files.readString(f, StandardCharsets.UTF_8), SkinsgConfig.class);
|
||||
if (cfg == null) cfg = new SkinsgConfig();
|
||||
} catch (Exception e) {
|
||||
cfg = new SkinsgConfig();
|
||||
}
|
||||
cfg.normalize();
|
||||
cfg.file = f;
|
||||
if (fresh) cfg.save();
|
||||
return cfg;
|
||||
}
|
||||
|
||||
private void normalize() {
|
||||
if (baseUrl == null) baseUrl = "";
|
||||
baseUrl = baseUrl.trim();
|
||||
while (baseUrl.endsWith("/")) baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
|
||||
if (mode == null) mode = Mode.ALL;
|
||||
if (enabled == null) enabled = new LinkedHashSet<>();
|
||||
if (blocked == null) blocked = new LinkedHashSet<>();
|
||||
if (speed == null) speed = new HashMap<>();
|
||||
if (globalSpeed <= 0) globalSpeed = DEFAULT_SPEED;
|
||||
}
|
||||
|
||||
public boolean hasBaseUrl() {
|
||||
return baseUrl != null && !baseUrl.isEmpty();
|
||||
}
|
||||
|
||||
public synchronized void save() {
|
||||
if (file == null) return;
|
||||
try {
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, GSON.toJson(this), StandardCharsets.UTF_8);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
public boolean shouldAnimate(UUID player, UUID self) {
|
||||
if (blocked.contains(player.toString())) return false;
|
||||
return switch (mode) {
|
||||
case ALL -> true;
|
||||
case NONE -> false;
|
||||
case SELF -> self != null && self.equals(player);
|
||||
case SET -> enabled.contains(player.toString());
|
||||
};
|
||||
}
|
||||
|
||||
public int speedFor(UUID player) {
|
||||
Integer s = speed.get(player.toString());
|
||||
return s != null && s > 0 ? s : globalSpeed;
|
||||
}
|
||||
|
||||
public synchronized void setNone() { mode = Mode.NONE; enabled.clear(); blocked.clear(); save(); }
|
||||
|
||||
public synchronized void setAll() { mode = Mode.ALL; enabled.clear(); blocked.clear(); save(); }
|
||||
|
||||
public synchronized void setSelf() { mode = Mode.SELF; enabled.clear(); blocked.clear(); save(); }
|
||||
|
||||
public synchronized void enableFor(Set<UUID> players) {
|
||||
for (UUID u : players) blocked.remove(u.toString());
|
||||
if (mode == Mode.NONE || mode == Mode.SELF) mode = Mode.SET;
|
||||
if (mode == Mode.SET) for (UUID u : players) enabled.add(u.toString());
|
||||
save();
|
||||
}
|
||||
|
||||
public synchronized void disableFor(Set<UUID> players) {
|
||||
for (UUID u : players) { blocked.add(u.toString()); enabled.remove(u.toString()); }
|
||||
if (mode == Mode.SET && enabled.isEmpty()) mode = Mode.NONE;
|
||||
save();
|
||||
}
|
||||
|
||||
public synchronized void setSpeed(UUID player, int percent) {
|
||||
if (percent <= 0) speed.remove(player.toString());
|
||||
else speed.put(player.toString(), percent);
|
||||
save();
|
||||
}
|
||||
|
||||
public synchronized void setGlobalSpeed(int percent) {
|
||||
globalSpeed = percent > 0 ? percent : DEFAULT_SPEED;
|
||||
save();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package xyz.nightsync.skinsg.client;
|
||||
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.renderer.texture.AbstractTexture;
|
||||
import net.minecraft.client.renderer.texture.DynamicTexture;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import xyz.nightsync.skinsg.SkinsgConfig;
|
||||
import xyz.nightsync.skinsg.gif.GifDecoder;
|
||||
import xyz.nightsync.skinsg.gif.GifImage;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URI;
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Fetches a player's GIF cape once, decodes it whole, then advances frames each tick by copying a
|
||||
* pre-composited buffer into a dynamic texture. Players that policy excludes are dropped so the
|
||||
* vanilla (static) cape shows and no memory is held.
|
||||
*
|
||||
* @author Nghtly
|
||||
*/
|
||||
public final class CapeManager {
|
||||
|
||||
private static final String MODID = "skinsg";
|
||||
private static final int MAX_CACHE = 96;
|
||||
private static final int MAX_BYTES = 12 * 1024 * 1024;
|
||||
|
||||
private static SkinsgConfig config;
|
||||
private static Supplier<UUID> selfProvider = () -> null;
|
||||
|
||||
private static final GifDecoder.Limits LIMITS = new GifDecoder.Limits();
|
||||
|
||||
private static final ExecutorService IO = Executors.newFixedThreadPool(2, r -> {
|
||||
Thread t = new Thread(r, "skinsg-cape-io");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
|
||||
private static final Map<UUID, Entry> CACHE = Collections.synchronizedMap(
|
||||
new LinkedHashMap<>(64, 0.75f, true) {
|
||||
@Override
|
||||
protected boolean removeEldestEntry(Map.Entry<UUID, Entry> e) {
|
||||
if (size() > MAX_CACHE) {
|
||||
e.getValue().release();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
private CapeManager() {}
|
||||
|
||||
public static void init(SkinsgConfig cfg, Supplier<UUID> self) {
|
||||
config = cfg;
|
||||
selfProvider = self;
|
||||
}
|
||||
|
||||
public static ResourceLocation getCape(UUID uuid) {
|
||||
if (config == null || uuid == null || !config.hasBaseUrl()) return null;
|
||||
if (!config.shouldAnimate(uuid, selfProvider.get())) {
|
||||
releaseIfPresent(uuid);
|
||||
return null;
|
||||
}
|
||||
return CACHE.computeIfAbsent(uuid, CapeManager::startLoad).texture;
|
||||
}
|
||||
|
||||
public static void clientTick() {
|
||||
if (config == null) return;
|
||||
long now = System.currentTimeMillis();
|
||||
UUID self = selfProvider.get();
|
||||
synchronized (CACHE) {
|
||||
for (Map.Entry<UUID, Entry> en : CACHE.entrySet()) {
|
||||
if (config.shouldAnimate(en.getKey(), self)) {
|
||||
en.getValue().tick(now, config.speedFor(en.getKey()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void releaseAll() {
|
||||
synchronized (CACHE) {
|
||||
for (Entry e : CACHE.values()) e.release();
|
||||
CACHE.clear();
|
||||
}
|
||||
}
|
||||
|
||||
public static void releaseIfPresent(UUID uuid) {
|
||||
Entry e = CACHE.remove(uuid);
|
||||
if (e != null) e.release();
|
||||
}
|
||||
|
||||
private static Entry startLoad(UUID uuid) {
|
||||
Entry entry = new Entry(uuid);
|
||||
IO.submit(() -> {
|
||||
try {
|
||||
byte[] bytes = httpGet(config.baseUrl + "/api/minecraft/cape/" + uuid + "?gif");
|
||||
if (bytes == null || bytes.length < 6 || !isGif(bytes)) {
|
||||
entry.noAnimation = true;
|
||||
return;
|
||||
}
|
||||
buildTexture(entry, GifDecoder.decode(bytes, LIMITS));
|
||||
} catch (Throwable t) {
|
||||
entry.noAnimation = true;
|
||||
}
|
||||
});
|
||||
return entry;
|
||||
}
|
||||
|
||||
private static void buildTexture(Entry entry, GifImage gif) {
|
||||
RenderSystem.recordRenderCall(() -> {
|
||||
try {
|
||||
DynamicTexture tex = new DynamicTexture(gif.width, gif.height, true);
|
||||
((AbstractTexture) tex).setFilter(false, false);
|
||||
ResourceLocation id = new ResourceLocation(MODID, "cape/" + entry.uuid + "/anim");
|
||||
Minecraft.getInstance().getTextureManager().register(id, tex);
|
||||
entry.attach(gif, tex, id);
|
||||
} catch (Throwable t) {
|
||||
entry.noAnimation = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static boolean isGif(byte[] b) {
|
||||
return b[0] == 'G' && b[1] == 'I' && b[2] == 'F';
|
||||
}
|
||||
|
||||
private static byte[] httpGet(String url) throws IOException {
|
||||
HttpURLConnection c = (HttpURLConnection) URI.create(url).toURL().openConnection();
|
||||
c.setConnectTimeout(7000);
|
||||
c.setReadTimeout(10000);
|
||||
c.setRequestProperty("User-Agent", MODID + "/1.0");
|
||||
if (c.getResponseCode() != 200) return null;
|
||||
int len = c.getContentLength();
|
||||
if (len > MAX_BYTES) return null;
|
||||
try (InputStream in = c.getInputStream()) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(1024, Math.min(Math.max(len, 0), MAX_BYTES)));
|
||||
byte[] buf = new byte[8192];
|
||||
int r, total = 0;
|
||||
while ((r = in.read(buf)) != -1) {
|
||||
total += r;
|
||||
if (total > MAX_BYTES) return null;
|
||||
out.write(buf, 0, r);
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
private static final class Entry {
|
||||
final UUID uuid;
|
||||
volatile boolean noAnimation;
|
||||
|
||||
private GifImage gif;
|
||||
private DynamicTexture tex;
|
||||
private volatile ResourceLocation texture;
|
||||
private int frame = -1;
|
||||
private long nextAt;
|
||||
|
||||
Entry(UUID uuid) { this.uuid = uuid; }
|
||||
|
||||
void attach(GifImage gif, DynamicTexture tex, ResourceLocation id) {
|
||||
this.gif = gif;
|
||||
this.tex = tex;
|
||||
this.texture = id;
|
||||
this.frame = -1;
|
||||
this.nextAt = 0L;
|
||||
}
|
||||
|
||||
void tick(long now, int speedPercent) {
|
||||
if (gif == null || tex == null) return;
|
||||
if (frame != -1 && now < nextAt) return;
|
||||
frame = (frame + 1) % gif.frameCount();
|
||||
|
||||
int[] src = gif.framesAbgr[frame];
|
||||
NativeImage px = tex.getPixels();
|
||||
if (px != null && px.getWidth() == gif.width && px.getHeight() == gif.height) {
|
||||
int i = 0;
|
||||
for (int y = 0; y < gif.height; y++) {
|
||||
for (int x = 0; x < gif.width; x++) {
|
||||
px.setPixelRGBA(x, y, src[i++]);
|
||||
}
|
||||
}
|
||||
RenderSystem.recordRenderCall(tex::upload);
|
||||
}
|
||||
|
||||
int base = gif.delaysMs[frame];
|
||||
long dur = speedPercent > 0 ? (long) base * 100L / speedPercent : base;
|
||||
nextAt = now + Math.max(20L, dur);
|
||||
}
|
||||
|
||||
void release() {
|
||||
ResourceLocation id = texture;
|
||||
if (id != null) {
|
||||
RenderSystem.recordRenderCall(() -> {
|
||||
try {
|
||||
Minecraft.getInstance().getTextureManager().release(id);
|
||||
} catch (Throwable ignored) {
|
||||
}
|
||||
});
|
||||
}
|
||||
texture = null;
|
||||
tex = null;
|
||||
gif = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package xyz.nightsync.skinsg.commands;
|
||||
|
||||
import com.mojang.brigadier.arguments.ArgumentType;
|
||||
import com.mojang.brigadier.arguments.IntegerArgumentType;
|
||||
import com.mojang.brigadier.arguments.StringArgumentType;
|
||||
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
|
||||
import com.mojang.brigadier.builder.RequiredArgumentBuilder;
|
||||
import com.mojang.brigadier.context.CommandContext;
|
||||
import com.mojang.brigadier.suggestion.SuggestionProvider;
|
||||
import net.minecraft.client.Minecraft;
|
||||
@@ -14,9 +16,6 @@ import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
import static com.mojang.brigadier.builder.LiteralArgumentBuilder.literal;
|
||||
import static com.mojang.brigadier.builder.RequiredArgumentBuilder.argument;
|
||||
|
||||
/**
|
||||
* Loader-agnostic client command tree, built with RAW Brigadier builders so it is
|
||||
* generic over the command source type {@code S}. Fabric client commands use
|
||||
@@ -46,23 +45,31 @@ public final class SkinsgCommands {
|
||||
return b.buildFuture();
|
||||
};
|
||||
|
||||
return literal("skinsg")
|
||||
.then(literal("playgif")
|
||||
return SkinsgCommands.<S>literal("skinsg")
|
||||
.then(SkinsgCommands.<S>literal("playgif")
|
||||
.executes(c -> { cfg.setNone(); CapeManager.releaseAll(); return ok(fb, c, "GIF capes: off"); })
|
||||
.then(argument("target", StringArgumentType.word()).suggests(targets)
|
||||
.then(SkinsgCommands.<S, String>argument("target", StringArgumentType.word()).suggests(targets)
|
||||
.executes(c -> playgif(fb, cfg, c))))
|
||||
.then(literal("stopgif")
|
||||
.then(SkinsgCommands.<S>literal("stopgif")
|
||||
.executes(c -> { cfg.setNone(); CapeManager.releaseAll(); return ok(fb, c, "GIF capes: off"); })
|
||||
.then(argument("target", StringArgumentType.word()).suggests(targets)
|
||||
.then(SkinsgCommands.<S, String>argument("target", StringArgumentType.word()).suggests(targets)
|
||||
.executes(c -> stopgif(fb, cfg, c))))
|
||||
.then(literal("self")
|
||||
.then(SkinsgCommands.<S>literal("self")
|
||||
.executes(c -> { cfg.setSelf(); CapeManager.releaseAll(); return ok(fb, c, "GIF capes: self only"); }))
|
||||
.then(literal("speed")
|
||||
.then(argument("target", StringArgumentType.word()).suggests(targets)
|
||||
.then(argument("percent", IntegerArgumentType.integer(1, 2000))
|
||||
.then(SkinsgCommands.<S>literal("speed")
|
||||
.then(SkinsgCommands.<S, String>argument("target", StringArgumentType.word()).suggests(targets)
|
||||
.then(SkinsgCommands.<S, Integer>argument("percent", IntegerArgumentType.integer(1, 2000))
|
||||
.executes(c -> speed(fb, cfg, c)))));
|
||||
}
|
||||
|
||||
private static <S> LiteralArgumentBuilder<S> literal(String name) {
|
||||
return LiteralArgumentBuilder.literal(name);
|
||||
}
|
||||
|
||||
private static <S, T> RequiredArgumentBuilder<S, T> argument(String name, ArgumentType<T> type) {
|
||||
return RequiredArgumentBuilder.argument(name, type);
|
||||
}
|
||||
|
||||
private static <S> int playgif(Feedback<S> fb, SkinsgConfig cfg, CommandContext<S> c) {
|
||||
String target = StringArgumentType.getString(c, "target");
|
||||
if (ALL.equals(target)) { cfg.setAll(); return ok(fb, c, "GIF capes: everyone"); }
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
package xyz.nightsync.skinsg.gif;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Decodes a GIF87a/89a in one pass into pre-composited ABGR frames (disposal already applied),
|
||||
* so playback is a plain buffer copy instead of per-frame LZW + compositing. Streaming-safe with
|
||||
* hard size limits.
|
||||
*
|
||||
* @author Nghtly
|
||||
*/
|
||||
public final class GifDecoder {
|
||||
|
||||
public static final class GifException extends Exception {
|
||||
public GifException(String message) { super(message); }
|
||||
}
|
||||
|
||||
public static final class Limits {
|
||||
public int maxDimension = 2048;
|
||||
public int maxFrames = 240;
|
||||
public long maxTotalPixels = 128L * 1024 * 1024;
|
||||
public int minDelayMs = 20;
|
||||
public int maxDelayMs = 10_000;
|
||||
}
|
||||
|
||||
private final byte[] d;
|
||||
private int p;
|
||||
private final Limits lim;
|
||||
|
||||
private int width, height;
|
||||
private int[] gct;
|
||||
private int bgIndex;
|
||||
|
||||
private int disposal = 0;
|
||||
private int transparentIndex = -1;
|
||||
private int delayCs = 0;
|
||||
|
||||
private GifDecoder(byte[] data, Limits limits) {
|
||||
this.d = data;
|
||||
this.lim = limits;
|
||||
}
|
||||
|
||||
public static GifImage decode(byte[] data, Limits limits) throws GifException {
|
||||
return new GifDecoder(data, limits).run();
|
||||
}
|
||||
|
||||
private int u8() throws GifException {
|
||||
if (p >= d.length) throw new GifException("unexpected EOF");
|
||||
return d[p++] & 0xFF;
|
||||
}
|
||||
|
||||
private int u16() throws GifException {
|
||||
int lo = u8(), hi = u8();
|
||||
return lo | (hi << 8);
|
||||
}
|
||||
|
||||
private void skip(int n) throws GifException {
|
||||
if (p + n > d.length) throw new GifException("unexpected EOF");
|
||||
p += n;
|
||||
}
|
||||
|
||||
private int[] readColorTable(int size) throws GifException {
|
||||
int[] table = new int[size];
|
||||
for (int i = 0; i < size; i++) {
|
||||
int r = u8(), g = u8(), b = u8();
|
||||
table[i] = (r << 16) | (g << 8) | b;
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
private byte[] readSubBlocks() throws GifException {
|
||||
int start = p;
|
||||
int total = 0;
|
||||
while (true) {
|
||||
int size = u8();
|
||||
if (size == 0) break;
|
||||
skip(size);
|
||||
total += size;
|
||||
}
|
||||
byte[] out = new byte[total];
|
||||
int op = 0, rp = start;
|
||||
while (true) {
|
||||
int size = d[rp++] & 0xFF;
|
||||
if (size == 0) break;
|
||||
System.arraycopy(d, rp, out, op, size);
|
||||
op += size;
|
||||
rp += size;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private void skipSubBlocks() throws GifException {
|
||||
while (true) {
|
||||
int size = u8();
|
||||
if (size == 0) break;
|
||||
skip(size);
|
||||
}
|
||||
}
|
||||
|
||||
private GifImage run() throws GifException {
|
||||
if (d.length < 13) throw new GifException("too small");
|
||||
if (!(d[0] == 'G' && d[1] == 'I' && d[2] == 'F')) throw new GifException("not a GIF");
|
||||
p = 6;
|
||||
width = u16();
|
||||
height = u16();
|
||||
if (width < 1 || height < 1 || width > lim.maxDimension || height > lim.maxDimension) {
|
||||
throw new GifException("bad dimensions " + width + "x" + height);
|
||||
}
|
||||
int packed = u8();
|
||||
bgIndex = u8();
|
||||
u8();
|
||||
if ((packed & 0x80) != 0) {
|
||||
gct = readColorTable(2 << (packed & 0x07));
|
||||
}
|
||||
|
||||
final long area = (long) width * height;
|
||||
final int frameCap = (int) Math.max(1, Math.min(lim.maxFrames, lim.maxTotalPixels / Math.max(1, area)));
|
||||
|
||||
List<int[]> frames = new ArrayList<>();
|
||||
List<Integer> delays = new ArrayList<>();
|
||||
|
||||
int[] canvas = new int[(int) area];
|
||||
int[] saved = null;
|
||||
int prevDisposal = 0;
|
||||
int prevX = 0, prevY = 0, prevW = 0, prevH = 0;
|
||||
|
||||
boolean done = false;
|
||||
while (!done) {
|
||||
int block = u8();
|
||||
switch (block) {
|
||||
case 0x3B:
|
||||
done = true;
|
||||
break;
|
||||
case 0x21:
|
||||
handleExtension();
|
||||
break;
|
||||
case 0x2C: {
|
||||
int ix = u16(), iy = u16(), iw = u16(), ih = u16();
|
||||
int ipacked = u8();
|
||||
int[] lct = null;
|
||||
if ((ipacked & 0x80) != 0) lct = readColorTable(2 << (ipacked & 0x07));
|
||||
boolean interlaced = (ipacked & 0x40) != 0;
|
||||
int minCode = u8();
|
||||
byte[] lzw = readSubBlocks();
|
||||
|
||||
if (ix < 0 || iy < 0 || iw < 0 || ih < 0 || ix + iw > width || iy + ih > height) {
|
||||
throw new GifException("frame rect out of bounds");
|
||||
}
|
||||
|
||||
if (prevDisposal == 2) {
|
||||
clearRect(canvas, prevX, prevY, prevW, prevH);
|
||||
} else if (prevDisposal == 3 && saved != null) {
|
||||
System.arraycopy(saved, 0, canvas, 0, canvas.length);
|
||||
}
|
||||
if (disposal == 3) {
|
||||
if (saved == null) saved = new int[canvas.length];
|
||||
System.arraycopy(canvas, 0, saved, 0, canvas.length);
|
||||
}
|
||||
|
||||
if (frames.size() < frameCap && iw > 0 && ih > 0) {
|
||||
int[] palette = lct != null ? lct : gct;
|
||||
if (palette == null) throw new GifException("no color table");
|
||||
byte[] indices = LzwDecoder.decode(lzw, minCode, iw * ih);
|
||||
drawFrame(canvas, ix, iy, iw, ih, interlaced, indices, palette, transparentIndex);
|
||||
frames.add(canvas.clone());
|
||||
delays.add(clampDelay(delayCs));
|
||||
}
|
||||
|
||||
prevDisposal = disposal;
|
||||
prevX = ix; prevY = iy; prevW = iw; prevH = ih;
|
||||
transparentIndex = -1;
|
||||
disposal = 0;
|
||||
delayCs = 0;
|
||||
if (frames.size() >= frameCap) done = true;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new GifException("bad block 0x" + Integer.toHexString(block));
|
||||
}
|
||||
}
|
||||
|
||||
if (frames.isEmpty()) throw new GifException("no frames");
|
||||
int[][] arr = frames.toArray(new int[0][]);
|
||||
int[] del = new int[delays.size()];
|
||||
for (int i = 0; i < del.length; i++) del[i] = delays.get(i);
|
||||
return new GifImage(width, height, arr, del);
|
||||
}
|
||||
|
||||
private void handleExtension() throws GifException {
|
||||
int label = u8();
|
||||
if (label == 0xF9) {
|
||||
int size = u8();
|
||||
int flags = u8();
|
||||
disposal = (flags >> 2) & 0x07;
|
||||
delayCs = u16();
|
||||
int tIndex = u8();
|
||||
transparentIndex = (flags & 0x01) != 0 ? tIndex : -1;
|
||||
if (size > 4) skip(size - 4);
|
||||
int term = u8();
|
||||
if (term != 0) skipSubBlocks();
|
||||
} else {
|
||||
skipSubBlocks();
|
||||
}
|
||||
}
|
||||
|
||||
private int clampDelay(int cs) {
|
||||
int ms = cs * 10;
|
||||
if (ms <= 0) ms = 100;
|
||||
return Math.max(lim.minDelayMs, Math.min(lim.maxDelayMs, ms));
|
||||
}
|
||||
|
||||
private void clearRect(int[] canvas, int x, int y, int w, int h) {
|
||||
for (int row = 0; row < h; row++) {
|
||||
int base = (y + row) * width + x;
|
||||
Arrays.fill(canvas, base, base + w, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private void drawFrame(int[] canvas, int fx, int fy, int fw, int fh, boolean interlaced,
|
||||
byte[] indices, int[] palette, int tIndex) {
|
||||
int pal = palette.length;
|
||||
for (int row = 0; row < fh; row++) {
|
||||
int dstY = interlaced ? interlacedRow(row, fh) : row;
|
||||
int dst = (fy + dstY) * width + fx;
|
||||
int src = row * fw;
|
||||
for (int col = 0; col < fw; col++) {
|
||||
int idx = indices[src + col] & 0xFF;
|
||||
if (idx == tIndex || idx >= pal) continue;
|
||||
int rgb = palette[idx];
|
||||
int r = (rgb >> 16) & 0xFF, g = (rgb >> 8) & 0xFF, b = rgb & 0xFF;
|
||||
canvas[dst + col] = 0xFF000000 | (b << 16) | (g << 8) | r;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int interlacedRow(int row, int h) {
|
||||
int p1 = (h + 7) / 8;
|
||||
int p2 = (h + 3) / 8;
|
||||
int p3 = (h + 1) / 4;
|
||||
if (row < p1) return row * 8;
|
||||
row -= p1;
|
||||
if (row < p2) return row * 8 + 4;
|
||||
row -= p2;
|
||||
if (row < p3) return row * 4 + 2;
|
||||
row -= p3;
|
||||
return row * 2 + 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package xyz.nightsync.skinsg.gif;
|
||||
|
||||
public final class GifImage {
|
||||
|
||||
public final int width;
|
||||
public final int height;
|
||||
public final int[][] framesAbgr;
|
||||
public final int[] delaysMs;
|
||||
|
||||
GifImage(int width, int height, int[][] framesAbgr, int[] delaysMs) {
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.framesAbgr = framesAbgr;
|
||||
this.delaysMs = delaysMs;
|
||||
}
|
||||
|
||||
public int frameCount() {
|
||||
return framesAbgr.length;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package xyz.nightsync.skinsg.gif;
|
||||
|
||||
/**
|
||||
* GIF variable-width LZW decompressor; returns one palette index per pixel.
|
||||
*
|
||||
* @author Nghtly
|
||||
*/
|
||||
final class LzwDecoder {
|
||||
|
||||
private LzwDecoder() {}
|
||||
|
||||
private static final int MAX_CODES = 4096;
|
||||
|
||||
static byte[] decode(byte[] data, int minCodeSize, int pixelCount) throws GifDecoder.GifException {
|
||||
if (minCodeSize < 2 || minCodeSize > 8) throw new GifDecoder.GifException("bad LZW code size");
|
||||
|
||||
final int clearCode = 1 << minCodeSize;
|
||||
final int endCode = clearCode + 1;
|
||||
|
||||
final int[] prefix = new int[MAX_CODES];
|
||||
final int[] suffix = new int[MAX_CODES];
|
||||
final byte[] stack = new byte[MAX_CODES + 1];
|
||||
|
||||
final byte[] out = new byte[pixelCount];
|
||||
int outPos = 0;
|
||||
|
||||
int codeSize = minCodeSize + 1;
|
||||
int codeMask = (1 << codeSize) - 1;
|
||||
int available = clearCode + 2;
|
||||
|
||||
for (int i = 0; i < clearCode; i++) {
|
||||
prefix[i] = 0;
|
||||
suffix[i] = i;
|
||||
}
|
||||
|
||||
int bitBuffer = 0, bitCount = 0, dataPos = 0;
|
||||
int oldCode = -1, firstByte = 0;
|
||||
|
||||
while (outPos < pixelCount) {
|
||||
while (bitCount < codeSize) {
|
||||
if (dataPos >= data.length) return out;
|
||||
bitBuffer |= (data[dataPos++] & 0xFF) << bitCount;
|
||||
bitCount += 8;
|
||||
}
|
||||
int code = bitBuffer & codeMask;
|
||||
bitBuffer >>>= codeSize;
|
||||
bitCount -= codeSize;
|
||||
|
||||
if (code == clearCode) {
|
||||
codeSize = minCodeSize + 1;
|
||||
codeMask = (1 << codeSize) - 1;
|
||||
available = clearCode + 2;
|
||||
oldCode = -1;
|
||||
continue;
|
||||
}
|
||||
if (code == endCode) break;
|
||||
|
||||
int sp = 0;
|
||||
int inCode;
|
||||
if (oldCode == -1) {
|
||||
out[outPos++] = (byte) suffix[code];
|
||||
oldCode = code;
|
||||
firstByte = code;
|
||||
continue;
|
||||
}
|
||||
if (code < available) {
|
||||
inCode = code;
|
||||
} else {
|
||||
stack[sp++] = (byte) firstByte;
|
||||
inCode = oldCode;
|
||||
}
|
||||
while (inCode >= clearCode) {
|
||||
stack[sp++] = (byte) suffix[inCode];
|
||||
inCode = prefix[inCode];
|
||||
}
|
||||
firstByte = suffix[inCode];
|
||||
stack[sp++] = (byte) firstByte;
|
||||
|
||||
if (available < MAX_CODES) {
|
||||
prefix[available] = oldCode;
|
||||
suffix[available] = firstByte;
|
||||
available++;
|
||||
if ((available & codeMask) == 0 && available < MAX_CODES) {
|
||||
codeSize++;
|
||||
codeMask += available;
|
||||
}
|
||||
}
|
||||
oldCode = code;
|
||||
|
||||
while (sp > 0 && outPos < pixelCount) {
|
||||
out[outPos++] = stack[--sp];
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package xyz.nightsync.skinsg.mixin;
|
||||
|
||||
import com.mojang.authlib.GameProfile;
|
||||
import net.minecraft.client.player.AbstractClientPlayer;
|
||||
import net.minecraft.resources.ResourceLocation;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
import xyz.nightsync.skinsg.client.CapeManager;
|
||||
|
||||
@Mixin(AbstractClientPlayer.class)
|
||||
public abstract class CapeMagicMixin {
|
||||
|
||||
@Inject(method = "getCloakTextureLocation", at = @At("RETURN"), cancellable = true)
|
||||
private void skinsg$overrideCape(CallbackInfoReturnable<ResourceLocation> cir) {
|
||||
GameProfile profile = ((AbstractClientPlayer) (Object) this).getGameProfile();
|
||||
ResourceLocation animated = CapeManager.getCape(profile.getId());
|
||||
if (animated != null) cir.setReturnValue(animated);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package xyz.nightsync.skinsg.mixin;
|
||||
|
||||
import com.mojang.blaze3d.platform.NativeImage;
|
||||
import net.minecraft.client.renderer.texture.HttpTexture;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Shadow;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
/**
|
||||
* Rewrites the vanilla legacy-skin conversion so it scales from {@code s = w/8} instead of a fixed
|
||||
* 64px grid, giving HD skins (up to 2048) the same 32->64 layer expansion and alpha fixes.
|
||||
* Non-matching proportions are left to vanilla/other mods.
|
||||
*
|
||||
* @author Nghtly
|
||||
*/
|
||||
@Mixin(HttpTexture.class)
|
||||
public abstract class SkinMagicMixin {
|
||||
|
||||
@Shadow
|
||||
private static void setNoAlpha(NativeImage img, int x1, int y1, int x2, int y2) {}
|
||||
|
||||
@Shadow
|
||||
private static void doNotchTransparencyHack(NativeImage img, int x1, int y1, int x2, int y2) {}
|
||||
|
||||
@Inject(method = "processLegacySkin", at = @At("HEAD"), cancellable = true)
|
||||
private void skinsg$processLegacySkin(NativeImage image, CallbackInfoReturnable<@Nullable NativeImage> cir) {
|
||||
final int h = image.getHeight();
|
||||
final int w = image.getWidth();
|
||||
|
||||
final int s = w / 8;
|
||||
final int x64 = s * 8;
|
||||
final int x32 = s * 4;
|
||||
final int x16 = s * 2;
|
||||
final int x8 = s;
|
||||
final int x4 = s / 2;
|
||||
final int x12 = x8 + x4;
|
||||
final int x48 = s * 6;
|
||||
final int x44 = s * 5;
|
||||
final int x52 = x48 + x4;
|
||||
final int x48m4 = x48 - x4;
|
||||
|
||||
if (w != x64 || (h != x32 && h != x64)) {
|
||||
return;
|
||||
}
|
||||
|
||||
final boolean legacy = h == x32;
|
||||
if (legacy) {
|
||||
NativeImage newImg = new NativeImage(x64, x64, true);
|
||||
newImg.copyFrom(image);
|
||||
image.close();
|
||||
image = newImg;
|
||||
|
||||
newImg.fillRect(0, x32, x64, x32, 0);
|
||||
|
||||
newImg.copyRect(x4, x16, x16, x32, x4, x4, true, false);
|
||||
newImg.copyRect(x8, x16, x16, x32, x4, x4, true, false);
|
||||
newImg.copyRect(0, x16 + x4 + x8, x16 + x8, x32, x4, x12, true, false);
|
||||
newImg.copyRect(x4, x16 + x4 + x8, x16, x32, x4, x12, true, false);
|
||||
newImg.copyRect(x8, x16 + x4 + x8, x8, x32, x4, x12, true, false);
|
||||
newImg.copyRect(x12, x16 + x4 + x8, x16, x32, x4, x12, true, false);
|
||||
|
||||
newImg.copyRect(x48m4, x16, -x8, x32, x4, x4, true, false);
|
||||
newImg.copyRect(x48, x16, -x8, x32, x4, x4, true, false);
|
||||
|
||||
newImg.copyRect(x44, x16 + x4 + x8, 0, x32, x4, x12, true, false);
|
||||
newImg.copyRect(x48m4, x16 + x4 + x8, -x8, x32, x4, x12, true, false);
|
||||
newImg.copyRect(x48, x16 + x4 + x8, -x16, x32, x4, x12, true, false);
|
||||
newImg.copyRect(x52, x16 + x4 + x8, -x8, x32, x4, x12, true, false);
|
||||
}
|
||||
|
||||
setNoAlpha(image, 0, 0, x32, x16);
|
||||
if (legacy) {
|
||||
doNotchTransparencyHack(image, x32, 0, x64, x32);
|
||||
}
|
||||
setNoAlpha(image, 0, x16, x64, x32);
|
||||
setNoAlpha(image, x16, x52 - x4, x52 - x4, x64);
|
||||
|
||||
cir.setReturnValue(image);
|
||||
cir.cancel();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"required": true,
|
||||
"minVersion": "0.8",
|
||||
"compatibilityLevel": "JAVA_17",
|
||||
"package": "xyz.nightsync.skinsg.mixin",
|
||||
"refmap": "skinsg.refmap.json",
|
||||
"client": [
|
||||
"SkinMagicMixin",
|
||||
"CapeMagicMixin"
|
||||
],
|
||||
"injectors": {
|
||||
"defaultRequire": 1
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user