package com.mojang.blaze3d.platform; import com.mojang.jtracy.MemoryPool; import com.mojang.jtracy.TracyClient; import com.mojang.logging.LogUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.nio.channels.SeekableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.EnumSet; import java.util.Locale; import java.util.Objects; import java.util.Set; import java.util.function.IntUnaryOperator; import net.minecraft.client.gui.font.providers.FreeTypeUtil; import net.minecraft.util.ARGB; import net.minecraft.util.PngInfo; import org.apache.commons.io.IOUtils; import org.jspecify.annotations.Nullable; import org.lwjgl.stb.STBIWriteCallback; import org.lwjgl.stb.STBImage; import org.lwjgl.stb.STBImageResize; import org.lwjgl.stb.STBImageWrite; import org.lwjgl.system.MemoryStack; import org.lwjgl.system.MemoryUtil; import org.lwjgl.util.freetype.FT_Bitmap; import org.lwjgl.util.freetype.FT_Face; import org.lwjgl.util.freetype.FT_GlyphSlot; import org.lwjgl.util.freetype.FreeType; import org.slf4j.Logger; public final class NativeImage implements AutoCloseable { private static final Logger LOGGER = LogUtils.getLogger(); private static final MemoryPool MEMORY_POOL = TracyClient.createMemoryPool("NativeImage"); private static final Set OPEN_OPTIONS = EnumSet.of( StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING ); private final NativeImage.Format format; private final int width; private final int height; private final boolean useStbFree; private long pixels; private final long size; public NativeImage(int i, int j, boolean bl) { this(NativeImage.Format.RGBA, i, j, bl); } public NativeImage(NativeImage.Format format, int i, int j, boolean bl) { if (i > 0 && j > 0) { this.format = formatx; this.width = i; this.height = j; this.size = (long)i * (long)j * (long)formatx.components(); this.useStbFree = false; if (bl) { this.pixels = MemoryUtil.nmemCalloc(1L, this.size); } else { this.pixels = MemoryUtil.nmemAlloc(this.size); } MEMORY_POOL.malloc(this.pixels, (int)this.size); if (this.pixels == 0L) { throw new IllegalStateException("Unable to allocate texture of size " + i + "x" + j + " (" + formatx.components() + " channels)"); } } else { throw new IllegalArgumentException("Invalid texture size: " + i + "x" + j); } } public NativeImage(NativeImage.Format format, int i, int j, boolean bl, long l) { if (i > 0 && j > 0) { this.format = formatx; this.width = i; this.height = j; this.useStbFree = bl; this.pixels = l; this.size = (long)i * (long)j * (long)formatx.components(); } else { throw new IllegalArgumentException("Invalid texture size: " + i + "x" + j); } } @Override public String toString() { return "NativeImage[" + this.format + " " + this.width + "x" + this.height + "@" + this.pixels + (this.useStbFree ? "S" : "N") + "]"; } private boolean isOutsideBounds(int i, int j) { return i < 0 || i >= this.width || j < 0 || j >= this.height; } public static NativeImage read(InputStream inputStream) throws IOException { return read(NativeImage.Format.RGBA, inputStream); } public static NativeImage read(@Nullable NativeImage.Format format, InputStream inputStream) throws IOException { ByteBuffer byteBuffer = null; NativeImage nativeImage; try { byteBuffer = TextureUtil.readResource(inputStream); nativeImage = read(formatx, byteBuffer); } finally { MemoryUtil.memFree(byteBuffer); IOUtils.closeQuietly(inputStream); } return nativeImage; } public static NativeImage read(ByteBuffer byteBuffer) throws IOException { return read(NativeImage.Format.RGBA, byteBuffer); } public static NativeImage read(byte[] b) throws IOException { MemoryStack memoryStack = MemoryStack.stackGet(); int i = memoryStack.getPointer(); if (i < b.length) { ByteBuffer byteBuffer1 = MemoryUtil.memAlloc(b.length); NativeImage nativeImage1; try { nativeImage1 = putAndRead(byteBuffer1, b); } finally { MemoryUtil.memFree(byteBuffer1); } return nativeImage1; } else { MemoryStack memoryStack1 = MemoryStack.stackPush(); NativeImage nativeImage; try { ByteBuffer byteBuffer = memoryStack1.malloc(b.length); nativeImage = putAndRead(byteBuffer, b); } catch (Throwable throwable1) { if (memoryStack1 != null) { try { memoryStack1.close(); } catch (Throwable throwable) { throwable1.addSuppressed(throwable); } } throw throwable1; } if (memoryStack1 != null) { memoryStack1.close(); } return nativeImage; } } private static NativeImage putAndRead(ByteBuffer byteBuffer, byte[] b) throws IOException { byteBuffer.put(b); byteBuffer.rewind(); return read(byteBuffer); } public static NativeImage read(@Nullable NativeImage.Format format, ByteBuffer byteBuffer) throws IOException { if (formatx != null && !formatx.supportedByStb()) { throw new UnsupportedOperationException("Don't know how to read format " + formatx); } else if (MemoryUtil.memAddress(byteBuffer) == 0L) { throw new IllegalArgumentException("Invalid buffer"); } else { PngInfo.validateHeader(byteBuffer); MemoryStack memoryStack = MemoryStack.stackPush(); NativeImage nativeImage; try { IntBuffer intBuffer = memoryStack.mallocInt(1); IntBuffer intBuffer1 = memoryStack.mallocInt(1); IntBuffer intBuffer2 = memoryStack.mallocInt(1); ByteBuffer byteBuffer1 = STBImage.stbi_load_from_memory(byteBuffer, intBuffer, intBuffer1, intBuffer2, formatx == null ? 0 : formatx.components); if (byteBuffer1 == null) { throw new IOException("Could not load image: " + STBImage.stbi_failure_reason()); } long l = MemoryUtil.memAddress(byteBuffer1); MEMORY_POOL.malloc(l, byteBuffer1.limit()); nativeImage = new NativeImage( formatx == null ? NativeImage.Format.getStbFormat(intBuffer2.get(0)) : formatx, intBuffer.get(0), intBuffer1.get(0), true, l ); } catch (Throwable throwable1) { if (memoryStack != null) { try { memoryStack.close(); } catch (Throwable throwable) { throwable1.addSuppressed(throwable); } } throw throwable1; } if (memoryStack != null) { memoryStack.close(); } return nativeImage; } } private void checkAllocated() { if (this.pixels == 0L) { throw new IllegalStateException("Image is not allocated."); } } @Override public void close() { if (this.pixels != 0L) { if (this.useStbFree) { STBImage.nstbi_image_free(this.pixels); } else { MemoryUtil.nmemFree(this.pixels); } MEMORY_POOL.free(this.pixels); } this.pixels = 0L; } public int getWidth() { return this.width; } public int getHeight() { return this.height; } public NativeImage.Format format() { return this.format; } private int getPixelABGR(int i, int j) { if (this.format != NativeImage.Format.RGBA) { throw new IllegalArgumentException(String.format(Locale.ROOT, "getPixelRGBA only works on RGBA images; have %s", this.format)); } else if (this.isOutsideBounds(i, j)) { throw new IllegalArgumentException(String.format(Locale.ROOT, "(%s, %s) outside of image bounds (%s, %s)", i, j, this.width, this.height)); } else { this.checkAllocated(); long l = ((long)i + (long)j * (long)this.width) * 4L; return MemoryUtil.memGetInt(this.pixels + l); } } public int getPixel(int i, int j) { return ARGB.fromABGR(this.getPixelABGR(i, j)); } public void setPixelABGR(int i, int j, int k) { if (this.format != NativeImage.Format.RGBA) { throw new IllegalArgumentException(String.format(Locale.ROOT, "setPixelRGBA only works on RGBA images; have %s", this.format)); } else if (this.isOutsideBounds(i, j)) { throw new IllegalArgumentException(String.format(Locale.ROOT, "(%s, %s) outside of image bounds (%s, %s)", i, j, this.width, this.height)); } else { this.checkAllocated(); long l = ((long)i + (long)j * (long)this.width) * 4L; MemoryUtil.memPutInt(this.pixels + l, k); } } public void setPixel(int i, int j, int k) { this.setPixelABGR(i, j, ARGB.toABGR(k)); } public NativeImage mappedCopy(IntUnaryOperator intUnaryOperator) { if (this.format != NativeImage.Format.RGBA) { throw new IllegalArgumentException(String.format(Locale.ROOT, "function application only works on RGBA images; have %s", this.format)); } else { this.checkAllocated(); NativeImage nativeImage1 = new NativeImage(this.width, this.height, false); int i = this.width * this.height; IntBuffer intBuffer = MemoryUtil.memIntBuffer(this.pixels, i); IntBuffer intBuffer1 = MemoryUtil.memIntBuffer(nativeImage1.pixels, i); for (int j = 0; j < i; j++) { int k = ARGB.fromABGR(intBuffer.get(j)); int l = intUnaryOperator.applyAsInt(k); intBuffer1.put(j, ARGB.toABGR(l)); } return nativeImage1; } } public int[] getPixelsABGR() { if (this.format != NativeImage.Format.RGBA) { throw new IllegalArgumentException(String.format(Locale.ROOT, "getPixels only works on RGBA images; have %s", this.format)); } else { this.checkAllocated(); int[] i = new int[this.width * this.height]; MemoryUtil.memIntBuffer(this.pixels, this.width * this.height).get(i); return i; } } public int[] getPixels() { int[] i = this.getPixelsABGR(); for (int j = 0; j < i.length; j++) { i[j] = ARGB.fromABGR(i[j]); } return i; } public byte getLuminanceOrAlpha(int i, int j) { if (!this.format.hasLuminanceOrAlpha()) { throw new IllegalArgumentException(String.format(Locale.ROOT, "no luminance or alpha in %s", this.format)); } else if (this.isOutsideBounds(i, j)) { throw new IllegalArgumentException(String.format(Locale.ROOT, "(%s, %s) outside of image bounds (%s, %s)", i, j, this.width, this.height)); } else { int k = (i + j * this.width) * this.format.components() + this.format.luminanceOrAlphaOffset() / 8; return MemoryUtil.memGetByte(this.pixels + (long)k); } } @Deprecated public int[] makePixelArray() { if (this.format != NativeImage.Format.RGBA) { throw new UnsupportedOperationException("can only call makePixelArray for RGBA images."); } else { this.checkAllocated(); int[] i = new int[this.getWidth() * this.getHeight()]; for (int j = 0; j < this.getHeight(); j++) { for (int k = 0; k < this.getWidth(); k++) { i[k + j * this.getWidth()] = this.getPixel(k, j); } } return i; } } public void writeToFile(File file) throws IOException { this.writeToFile(file.toPath()); } public boolean copyFromFont(FT_Face fT_Face, int i) { if (this.format.components() != 1) { throw new IllegalArgumentException("Can only write fonts into 1-component images."); } else if (FreeTypeUtil.checkError(FreeType.FT_Load_Glyph(fT_Face, i, 4), "Loading glyph")) { return false; } else { FT_GlyphSlot fT_GlyphSlot = Objects.requireNonNull(fT_Face.glyph(), "Glyph not initialized"); FT_Bitmap fT_Bitmap = fT_GlyphSlot.bitmap(); if (fT_Bitmap.pixel_mode() != 2) { throw new IllegalStateException("Rendered glyph was not 8-bit grayscale"); } else if (fT_Bitmap.width() == this.getWidth() && fT_Bitmap.rows() == this.getHeight()) { int j = fT_Bitmap.width() * fT_Bitmap.rows(); ByteBuffer byteBuffer = Objects.requireNonNull(fT_Bitmap.buffer(j), "Glyph has no bitmap"); MemoryUtil.memCopy(MemoryUtil.memAddress(byteBuffer), this.pixels, (long)j); return true; } else { throw new IllegalArgumentException( String.format( Locale.ROOT, "Glyph bitmap of size %sx%s does not match image of size: %sx%s", fT_Bitmap.width(), fT_Bitmap.rows(), this.getWidth(), this.getHeight() ) ); } } } public void writeToFile(Path path) throws IOException { if (!this.format.supportedByStb()) { throw new UnsupportedOperationException("Don't know how to write format " + this.format); } else { this.checkAllocated(); try (SeekableByteChannel seekableByteChannel = Files.newByteChannel(path, OPEN_OPTIONS)) { if (!this.writeToChannel(seekableByteChannel)) { throw new IOException("Could not write image to the PNG file \"" + path.toAbsolutePath() + "\": " + STBImage.stbi_failure_reason()); } } } } private boolean writeToChannel(WritableByteChannel writableByteChannel) throws IOException { NativeImage.WriteCallback writeCallback = new NativeImage.WriteCallback(writableByteChannel); boolean bl; try { int i = Math.min(this.getHeight(), Integer.MAX_VALUE / this.getWidth() / this.format.components()); if (i < this.getHeight()) { LOGGER.warn("Dropping image height from {} to {} to fit the size into 32-bit signed int", this.getHeight(), i); } if (STBImageWrite.nstbi_write_png_to_func(writeCallback.address(), 0L, this.getWidth(), i, this.format.components(), this.pixels, 0) != 0) { writeCallback.throwIfException(); return true; } bl = false; } finally { writeCallback.free(); } return bl; } public void copyFrom(NativeImage nativeImage1) { if (nativeImage1.format() != this.format) { throw new UnsupportedOperationException("Image formats don't match."); } else { int i = this.format.components(); this.checkAllocated(); nativeImage1.checkAllocated(); if (this.width == nativeImage1.width) { MemoryUtil.memCopy(nativeImage1.pixels, this.pixels, Math.min(this.size, nativeImage1.size)); } else { int j = Math.min(this.getWidth(), nativeImage1.getWidth()); int k = Math.min(this.getHeight(), nativeImage1.getHeight()); for (int l = 0; l < k; l++) { int m = l * nativeImage1.getWidth() * i; int n = l * this.getWidth() * i; MemoryUtil.memCopy(nativeImage1.pixels + (long)m, this.pixels + (long)n, (long)j); } } } } public void fillRect(int i, int j, int k, int l, int m) { for (int n = j; n < j + l; n++) { for (int o = i; o < i + k; o++) { this.setPixel(o, n, m); } } } public void copyRect(int i, int j, int k, int l, int m, int n, boolean bl, boolean bl1) { this.copyRect(this, i, j, i + k, j + l, m, n, bl, bl1); } public void copyRect(NativeImage nativeImage1, int i, int j, int k, int l, int m, int n, boolean bl, boolean bl1) { for (int o = 0; o < n; o++) { for (int p = 0; p < m; p++) { int q = bl ? m - 1 - p : p; int r = bl1 ? n - 1 - o : o; int s = this.getPixelABGR(i + p, j + o); nativeImage1.setPixelABGR(k + q, l + r, s); } } } public void resizeSubRectTo(int i, int j, int k, int l, NativeImage nativeImage1) { this.checkAllocated(); if (nativeImage1.format() != this.format) { throw new UnsupportedOperationException("resizeSubRectTo only works for images of the same format."); } else { int m = this.format.components(); STBImageResize.nstbir_resize_uint8( this.pixels + (long)((i + j * this.getWidth()) * m), k, l, this.getWidth() * m, nativeImage1.pixels, nativeImage1.getWidth(), nativeImage1.getHeight(), 0, m ); } } public void untrack() { DebugMemoryUntracker.untrack(this.pixels); } public long getPointer() { return this.pixels; } public static enum Format { RGBA(4, true, true, true, false, true, 0, 8, 16, 255, 24, true), RGB(3, true, true, true, false, false, 0, 8, 16, 255, 255, true), LUMINANCE_ALPHA(2, false, false, false, true, true, 255, 255, 255, 0, 8, true), LUMINANCE(1, false, false, false, true, false, 0, 0, 0, 0, 255, true); final int components; private final boolean hasRed; private final boolean hasGreen; private final boolean hasBlue; private final boolean hasLuminance; private final boolean hasAlpha; private final int redOffset; private final int greenOffset; private final int blueOffset; private final int luminanceOffset; private final int alphaOffset; private final boolean supportedByStb; private Format( final int j, final boolean bl, final boolean bl1, final boolean bl2, final boolean bl3, final boolean bl4, final int k, final int l, final int m, final int n, final int o, final boolean bl5 ) { this.components = j; this.hasRed = bl; this.hasGreen = bl1; this.hasBlue = bl2; this.hasLuminance = bl3; this.hasAlpha = bl4; this.redOffset = k; this.greenOffset = l; this.blueOffset = m; this.luminanceOffset = n; this.alphaOffset = o; this.supportedByStb = bl5; } public int components() { return this.components; } public boolean hasRed() { return this.hasRed; } public boolean hasGreen() { return this.hasGreen; } public boolean hasBlue() { return this.hasBlue; } public boolean hasLuminance() { return this.hasLuminance; } public boolean hasAlpha() { return this.hasAlpha; } public int redOffset() { return this.redOffset; } public int greenOffset() { return this.greenOffset; } public int blueOffset() { return this.blueOffset; } public int luminanceOffset() { return this.luminanceOffset; } public int alphaOffset() { return this.alphaOffset; } public boolean hasLuminanceOrRed() { return this.hasLuminance || this.hasRed; } public boolean hasLuminanceOrGreen() { return this.hasLuminance || this.hasGreen; } public boolean hasLuminanceOrBlue() { return this.hasLuminance || this.hasBlue; } public boolean hasLuminanceOrAlpha() { return this.hasLuminance || this.hasAlpha; } public int luminanceOrRedOffset() { return this.hasLuminance ? this.luminanceOffset : this.redOffset; } public int luminanceOrGreenOffset() { return this.hasLuminance ? this.luminanceOffset : this.greenOffset; } public int luminanceOrBlueOffset() { return this.hasLuminance ? this.luminanceOffset : this.blueOffset; } public int luminanceOrAlphaOffset() { return this.hasLuminance ? this.luminanceOffset : this.alphaOffset; } public boolean supportedByStb() { return this.supportedByStb; } static NativeImage.Format getStbFormat(int i) { switch (i) { case 1: return LUMINANCE; case 2: return LUMINANCE_ALPHA; case 3: return RGB; case 4: default: return RGBA; } } } static class WriteCallback extends STBIWriteCallback { private final WritableByteChannel output; @Nullable private IOException exception; WriteCallback(WritableByteChannel writableByteChannel) { this.output = writableByteChannel; } public void invoke(long m, long l, int i) { ByteBuffer byteBuffer = getData(l, i); try { this.output.write(byteBuffer); } catch (IOException iOException) { this.exception = iOException; } } public void throwIfException() throws IOException { if (this.exception != null) { throw this.exception; } } } }