aboutsummaryrefslogtreecommitdiff
path: root/src/main/kotlin/util/render/DumpTexture.kt
blob: a7b4e780544d2e39e80841d86e47ecb0158e536e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package moe.nea.firmament.util.render

import com.mojang.blaze3d.buffers.GpuBuffer
import com.mojang.blaze3d.systems.RenderSystem
import com.mojang.blaze3d.textures.GpuTexture
import java.io.File
import net.minecraft.client.texture.NativeImage

fun dumpTexture(gpuTexture: GpuTexture, name: String) {
	val w = gpuTexture.getWidth(0)
	val h = gpuTexture.getHeight(0)
	val buffer = RenderSystem.getDevice()
		.createBuffer(
			{ "Dump Buffer" },
			GpuBuffer.USAGE_COPY_DST or GpuBuffer.USAGE_MAP_READ,
			w * h * gpuTexture.getFormat().pixelSize()
		)
	val commandEncoder = RenderSystem.getDevice().createCommandEncoder()
	commandEncoder.copyTextureToBuffer(
		gpuTexture, buffer, 0, {
			val nativeImage = NativeImage(w, h, false)
			commandEncoder.mapBuffer(buffer, true, false).use { mappedView ->
				for (i in 0..<w) {
					for (j in 0..<h) {
						val color = mappedView.data().getInt((j + i * w) * gpuTexture.format.pixelSize())
						nativeImage.setColor(j, h - i - 1, color)
					}
				}
			}
			buffer.close()
			nativeImage.writeTo(File("$name.png"))
		}, 0
	)
}