synclight / scripts /lightmap_io.py
davidserra9's picture
Add generation scripts
1d4b965 verified
Raw History Blame Contribute Delete
2.64 kB
"""Read/write SyncLight differential lightmaps.
A lightmap is a float32 array of shape (H, W, 4) with channels
[activation, L, a, b], all in [-1, 1]:
- activation: -1 = turn the light off, 0 = no change, 1 = set the light to (L, a, b)
- L: target intensity mapped to [-1, 1] (intensity = (L + 1) / 2)
- a, b: target colour as CIELAB a/b divided by 128
The original training code stored them as .npy. The released dataset stores
them as 16-bit RGBA PNGs (R=activation, G=L, B=a, A=b) with the mapping
v = round(x * 32767) + 32768 x = (v - 32768) / 32767
so -1, 0 and 1 are exact and every other value is within 1.6e-5 of the original.
"""
import numpy as np
SCALE = 32767.0
OFFSET = 32768.0
def encode_lightmap(lightmap):
"""float32 (H, W, 4) in [-1, 1] -> uint16 (H, W, 4)."""
x = np.asarray(lightmap, dtype=np.float32)
if x.ndim != 3 or x.shape[-1] != 4:
raise ValueError(f"expected (H, W, 4) lightmap, got {x.shape}")
if not np.isfinite(x).all() or x.min() < -1.0 or x.max() > 1.0:
raise ValueError(f"lightmap values outside [-1, 1]: [{x.min()}, {x.max()}]")
return (np.round(x * SCALE) + OFFSET).astype(np.uint16)
def decode_lightmap(encoded):
"""uint16 (H, W, 4) -> float32 (H, W, 4) in [-1, 1]."""
return ((np.asarray(encoded, dtype=np.float32) - OFFSET) / SCALE).astype(np.float32)
def save_lightmap_png(path, lightmap):
import cv2
ok = cv2.imwrite(str(path), encode_lightmap(lightmap)[..., [2, 1, 0, 3]]) # OpenCV expects BGRA
if not ok:
raise IOError(f"could not write {path}")
def encode_lightmap_png_bytes(lightmap, compression=6):
import cv2
ok, buf = cv2.imencode(".png", encode_lightmap(lightmap)[..., [2, 1, 0, 3]],
[cv2.IMWRITE_PNG_COMPRESSION, compression])
if not ok:
raise IOError("PNG encoding failed")
return buf.tobytes()
def decode_lightmap_png_bytes(data):
import cv2
arr = cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_UNCHANGED)
return _from_bgra(arr)
def load_lightmap(path):
"""Load a lightmap from .png (release format) or .npy (original format)."""
path = str(path)
if path.endswith(".npy"):
return np.load(path).astype(np.float32)
import cv2
arr = cv2.imread(path, cv2.IMREAD_UNCHANGED)
if arr is None:
raise IOError(f"could not read {path}")
return _from_bgra(arr)
def _from_bgra(arr):
if arr.dtype != np.uint16 or arr.ndim != 3 or arr.shape[-1] != 4:
raise ValueError(f"expected 16-bit 4-channel PNG, got {arr.dtype} {arr.shape}")
return decode_lightmap(arr[..., [2, 1, 0, 3]])