convert_color: save mip-mapped image for mip levels

This commit is contained in:
Zack Buhman 2025-04-26 01:04:26 -05:00
parent 12e35fd2a0
commit 99856aa1b9

View File

@ -84,32 +84,33 @@ def pack_indices(f, indices):
f.write(struct.pack("<B", value)) f.write(struct.pack("<B", value))
def mip_levels(n): def mip_levels(n):
while True: while n > 0:
n = n >> 1
yield n yield n
if n == 1: n = n >> 1
break
def resize(im, l):
new = im.resize(
size=(l, l),
resample=Image.Resampling.LANCZOS,
)
new.save(f"{l:03}.png")
return new
def generate_mips(im): def generate_mips(im):
w, h = im.size w, h = im.size
assert w == h and npot(w) == w, (w, h) assert w == h and npot(w) == w, (w, h)
assert w >= 8, (w, h) assert w >= 8, (w, h)
images = [im] + [ images = [im] + [resize(im, l) for l in mip_levels(w >> 1)]
im.resize(
size=(l, l),
resample=Image.Resampling.LANCZOS,
)
for l in mip_levels(w)
]
return list(reversed(images)) return list(reversed(images))
def write_mip(f, mip: Image, is_twiddled: bool, convert): def write_mip(f, mip: Image, is_twiddled: bool, convert):
width, height = mip.size width, height = mip.size
print("mip", width, "offset", f"{f.tell():06x}") #print("mip", width, "offset", f"{f.tell():06x}")
pixels = list(im.convert("RGBA").getdata()) pixels = list(mip.convert("RGBA").getdata())
colors = list(convert_colors(convert, pixels)) colors = list(convert_colors(convert, pixels))
assert len(colors) == width * height, len(colors)
if is_twiddled: if is_twiddled:
new_colors = [0] * width * height new_colors = [0] * width * height
max_twiddle_ix = twiddle_texture(new_colors, colors, width, height) max_twiddle_ix = twiddle_texture(new_colors, colors, width, height)
@ -121,7 +122,7 @@ def write_mips(f, im: Image, is_twiddled: bool, convert):
for mip in generate_mips(im): for mip in generate_mips(im):
write_mip(f, mip, is_twiddled, convert) write_mip(f, mip, is_twiddled, convert)
if __name__ == "__main__": def main():
in_file = sys.argv[1] in_file = sys.argv[1]
format = sys.argv[2] format = sys.argv[2]
assert sys.argv[3] in {"twiddled", "non_twiddled"} assert sys.argv[3] in {"twiddled", "non_twiddled"}
@ -145,6 +146,7 @@ if __name__ == "__main__":
else: else:
write_mip(f, im, is_twiddled, convert) write_mip(f, im, is_twiddled, convert)
else: else:
assert False
pixels = list(im.convert("P").getdata()) pixels = list(im.convert("P").getdata())
palette = list(im.palette.colors) palette = list(im.palette.colors)
indices = list(convert_indices(palette, pixels)) indices = list(convert_indices(palette, pixels))
@ -160,3 +162,6 @@ if __name__ == "__main__":
with open(out_file, 'wb') as f: with open(out_file, 'wb') as f:
pack_indices(f, indices) pack_indices(f, indices)
if __name__ == "__main__":
main()