Compress baked PNGs and tighten XPbr shadows with URP quality tweaks.
Add png_compress to the model pipeline and update TownSquare lighting plus MaleExplorer/plaza textures. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -9,6 +9,7 @@
|
||||
-> model_translator:打包为 XPbr 两张图 + .mat/.meta
|
||||
_base.png RGB=Albedo A=AO/透明
|
||||
_mix.png RG=球面法线 B=Metallic A=Roughness
|
||||
写出时 PNG 无损压缩(体积更小,像素不变)
|
||||
```
|
||||
|
||||
## 环境
|
||||
|
||||
@@ -7,6 +7,7 @@ import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from png_compress import compress_png, prepare_blender_png
|
||||
|
||||
DEFAULT_RAY_PCT = 0.02 # 测量失败时回退:低模包围盒对角线 * 2%
|
||||
RAY_SAFETY = 1.5 # 自适应射线安全系数(分离 P99 × 此值)
|
||||
@@ -199,8 +200,10 @@ def _bake_pass(low, high, target_node, name, bake_type, size, colorspace,
|
||||
path = os.path.abspath(os.path.join(outdir, "%s_%s.png" % (stem, name)))
|
||||
img.filepath_raw = path
|
||||
img.file_format = 'PNG'
|
||||
prepare_blender_png(100)
|
||||
img.save()
|
||||
bpy.data.images.remove(img)
|
||||
compress_png(path)
|
||||
return os.path.basename(path)
|
||||
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import numpy as np
|
||||
|
||||
# blender --python 不会把脚本目录加入 sys.path,手动加入以复用 unity_assets(纯 stdlib)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from png_compress import compress_png, prepare_blender_png
|
||||
from unity_assets import safe_name
|
||||
|
||||
AO_NAME_RE = re.compile(r"(ao|occlusion|ambient)", re.I)
|
||||
@@ -269,8 +270,10 @@ def _save_png(path, rgba):
|
||||
img.filepath_raw = path
|
||||
img.file_format = 'PNG'
|
||||
img.alpha_mode = 'CHANNEL_PACKED'
|
||||
prepare_blender_png(100)
|
||||
img.save()
|
||||
bpy.data.images.remove(img)
|
||||
compress_png(path)
|
||||
|
||||
|
||||
def _convert_material(mat, model_name, outdir, max_size, used_snames, src_dir):
|
||||
|
||||
@@ -8,6 +8,7 @@ import os
|
||||
from bl_bake import output_stem
|
||||
from bl_decimate import model_format
|
||||
from mt_run import HERE, find_blender, run_blender_script
|
||||
from png_compress import compress_pngs
|
||||
|
||||
|
||||
def main():
|
||||
@@ -38,6 +39,9 @@ def main():
|
||||
[args.high, args.low, outdir, str(args.size),
|
||||
ray, str(args.samples)],
|
||||
blender_args=("-t", "1"))
|
||||
compress_pngs(
|
||||
os.path.join(outdir, fname) for fname in (s.get("outputs") or {}).values()
|
||||
)
|
||||
print("== %s(高 %d 面 / 低 %d 面,射线距离 %.4f)-> %s" %
|
||||
(s["stem"], s["high_tris"], s["low_tris"], s["ray_distance"], outdir))
|
||||
for name, fname in s["outputs"].items():
|
||||
|
||||
@@ -28,6 +28,7 @@ if str(_HERE) not in sys.path:
|
||||
from bl_bake import output_stem # noqa: E402
|
||||
from bl_decimate import model_format # noqa: E402
|
||||
from mt_run import find_blender, run_blender_script # noqa: E402
|
||||
from png_compress import compress_pngs # noqa: E402
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
@@ -211,6 +212,9 @@ def run_pipeline(
|
||||
],
|
||||
blender_args=("-t", "1"),
|
||||
)
|
||||
compress_pngs(
|
||||
str(bake_dir / fname) for fname in (bake.get("outputs") or {}).values()
|
||||
)
|
||||
|
||||
xpbr_dir = None
|
||||
xpbr_summary = None
|
||||
|
||||
@@ -8,6 +8,7 @@ import sys
|
||||
|
||||
import unity_assets as ua
|
||||
from mt_run import HERE, find_blender, run_blender_script
|
||||
from png_compress import compress_dir_pngs
|
||||
|
||||
|
||||
def write_unity_assets(outdir, summary, max_size):
|
||||
@@ -79,6 +80,7 @@ def translate_fbx(src, outdir, max_size=2048, blender=None):
|
||||
summary = run_blender_script(
|
||||
blender_exe, "bl_convert.py", [src, outdir, str(max_size)]
|
||||
)
|
||||
compress_dir_pngs(outdir, suffixes=("_base.png", "_mix.png"))
|
||||
unity = write_unity_assets(outdir, summary, max_size)
|
||||
return {**summary, "unity": unity}
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Lossless PNG size reduction for bake outputs.
|
||||
|
||||
Blender's default PNG compression is low (~15/100). Final _base/_mix (and
|
||||
bake maps) are rewritten with zlib level 9. Pillow `optimize=True` is used
|
||||
when available (system Python); Blender's interpreter falls back to IDAT
|
||||
recompress via stdlib only. Pixels are unchanged.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import struct
|
||||
import zlib
|
||||
from typing import Dict, Iterable, List, Optional
|
||||
|
||||
PNG_SIG = b"\x89PNG\r\n\x1a\n"
|
||||
|
||||
|
||||
def prepare_blender_png(compression: int = 100) -> None:
|
||||
"""Blender Image.save() uses scene render PNG compression (0-100)."""
|
||||
import bpy
|
||||
|
||||
settings = bpy.context.scene.render.image_settings
|
||||
settings.file_format = "PNG"
|
||||
settings.color_depth = "8"
|
||||
settings.compression = int(compression)
|
||||
|
||||
|
||||
def compress_png(path: str, level: int = 9) -> Dict[str, int]:
|
||||
"""Rewrite `path` in place. Returns {before, after} byte sizes."""
|
||||
path = os.path.abspath(path)
|
||||
before = os.path.getsize(path)
|
||||
after = before
|
||||
tmp = path + ".pngcompress.tmp"
|
||||
try:
|
||||
if _compress_with_pillow(path, tmp, level) or _compress_idat(path, tmp, level):
|
||||
new_size = os.path.getsize(tmp)
|
||||
if new_size < before:
|
||||
os.replace(tmp, path)
|
||||
after = new_size
|
||||
elif os.path.isfile(tmp):
|
||||
os.remove(tmp)
|
||||
finally:
|
||||
if os.path.isfile(tmp):
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
return {"before": before, "after": after}
|
||||
|
||||
|
||||
def compress_pngs(paths: Iterable[str], level: int = 9) -> List[Dict[str, object]]:
|
||||
reports = []
|
||||
for path in paths:
|
||||
if not path or not os.path.isfile(path):
|
||||
continue
|
||||
if os.path.splitext(path)[1].lower() != ".png":
|
||||
continue
|
||||
sizes = compress_png(path, level=level)
|
||||
reports.append({"path": os.path.abspath(path), **sizes})
|
||||
return reports
|
||||
|
||||
|
||||
def compress_dir_pngs(directory: str, suffixes: Optional[Iterable[str]] = None) -> List[Dict[str, object]]:
|
||||
"""Compress PNGs in a directory. `suffixes` like ('_base.png', '_mix.png')."""
|
||||
directory = os.path.abspath(directory)
|
||||
names = sorted(os.listdir(directory)) if os.path.isdir(directory) else []
|
||||
suffix_tuple = tuple(suffixes) if suffixes else None
|
||||
paths = []
|
||||
for name in names:
|
||||
if not name.lower().endswith(".png"):
|
||||
continue
|
||||
if suffix_tuple and not name.endswith(suffix_tuple):
|
||||
continue
|
||||
paths.append(os.path.join(directory, name))
|
||||
return compress_pngs(paths)
|
||||
|
||||
|
||||
def _compress_with_pillow(src: str, dst: str, level: int) -> bool:
|
||||
try:
|
||||
from PIL import Image
|
||||
except ImportError:
|
||||
return False
|
||||
try:
|
||||
with Image.open(src) as im:
|
||||
im.load()
|
||||
im.save(dst, format="PNG", optimize=True, compress_level=level)
|
||||
except Exception:
|
||||
return False
|
||||
return os.path.isfile(dst)
|
||||
|
||||
|
||||
def _write_chunk(buf: bytearray, ctype: bytes, data: bytes) -> None:
|
||||
buf.extend(struct.pack(">I", len(data)))
|
||||
buf.extend(ctype)
|
||||
buf.extend(data)
|
||||
buf.extend(struct.pack(">I", zlib.crc32(ctype + data) & 0xFFFFFFFF))
|
||||
|
||||
|
||||
def _compress_idat(src: str, dst: str, level: int) -> bool:
|
||||
with open(src, "rb") as f:
|
||||
data = f.read()
|
||||
if len(data) < 8 or data[:8] != PNG_SIG:
|
||||
return False
|
||||
pos = 8
|
||||
before_idat: List[tuple] = []
|
||||
after_idat: List[tuple] = []
|
||||
idat_parts: List[bytes] = []
|
||||
seen_idat = False
|
||||
while pos + 12 <= len(data):
|
||||
length = struct.unpack(">I", data[pos : pos + 4])[0]
|
||||
ctype = data[pos + 4 : pos + 8]
|
||||
end = pos + 8 + length
|
||||
if end + 4 > len(data):
|
||||
return False
|
||||
cdata = data[pos + 8 : end]
|
||||
pos = end + 4
|
||||
if ctype == b"IDAT":
|
||||
idat_parts.append(cdata)
|
||||
seen_idat = True
|
||||
continue
|
||||
if seen_idat:
|
||||
after_idat.append((ctype, cdata))
|
||||
else:
|
||||
before_idat.append((ctype, cdata))
|
||||
if ctype == b"IEND":
|
||||
break
|
||||
if not idat_parts:
|
||||
return False
|
||||
raw = zlib.decompress(b"".join(idat_parts))
|
||||
packed = zlib.compress(raw, level)
|
||||
out = bytearray(PNG_SIG)
|
||||
for ctype, cdata in before_idat:
|
||||
_write_chunk(out, ctype, cdata)
|
||||
_write_chunk(out, b"IDAT", packed)
|
||||
for ctype, cdata in after_idat:
|
||||
_write_chunk(out, ctype, cdata)
|
||||
with open(dst, "wb") as f:
|
||||
f.write(out)
|
||||
return True
|
||||
@@ -0,0 +1,31 @@
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from png_compress import compress_png
|
||||
|
||||
|
||||
class CompressPngTests(unittest.TestCase):
|
||||
def test_pixels_unchanged_and_smaller(self):
|
||||
from PIL import Image
|
||||
|
||||
w = h = 64
|
||||
pixels = [(40, 80, 120, 255)] * (w * h)
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
path = os.path.join(d, "a.png")
|
||||
im = Image.new("RGBA", (w, h))
|
||||
im.putdata(pixels)
|
||||
im.save(path, format="PNG", compress_level=0, optimize=False)
|
||||
before = os.path.getsize(path)
|
||||
src_bytes = list(Image.open(path).getdata())
|
||||
sizes = compress_png(path)
|
||||
after_im = Image.open(path)
|
||||
self.assertEqual(list(after_im.getdata()), src_bytes)
|
||||
self.assertLess(sizes["after"], before)
|
||||
self.assertEqual(sizes["before"], before)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user