Files
FreeCADWasmDev/web/tools/line-course/sample-material-colors.py

112 lines
4.2 KiB
Python

#!/usr/bin/env python3
"""Samples embedded GLB base-color textures to representative sRGB colours.
Most line GLBs reference a baseColorTexture without a baseColorFactor, so the
material colour cannot be read from the JSON alone. This script decodes each
embedded image with Pillow, averages it (after downsampling), multiplies by the
factor when present, and writes material-colors.json for build-line-spec.mjs.
Usage: python3 -I sample-material-colors.py [sourceDir] [outFile]
"""
import io
import json
import os
import struct
import sys
from PIL import Image
here = os.path.dirname(os.path.abspath(__file__))
source_dir = sys.argv[1] if len(sys.argv) > 1 else "/home/mes123456/FreeCADWasmDev/working/GLTFmodel"
out_file = sys.argv[2] if len(sys.argv) > 2 else os.path.join(here, "material-colors.json")
def read_glb(path):
with open(path, "rb") as handle:
handle.read(12)
gltf = None
binary = b""
while True:
header = handle.read(8)
if len(header) < 8:
break
length, kind = struct.unpack("<II", header)
payload = handle.read(length)
if kind == 0x4E4F534A:
gltf = json.loads(payload.decode("utf-8"))
elif kind == 0x004E4942:
binary = payload
return gltf, binary
def image_bytes(gltf, binary, image_index):
image = gltf.get("images", [])[image_index]
if "bufferView" in image:
view = gltf["bufferViews"][image["bufferView"]]
start = view.get("byteOffset", 0)
return binary[start:start + view["byteLength"]]
uri = image.get("uri", "")
if uri.startswith("data:"):
import base64
return base64.b64decode(uri.split(",", 1)[1])
return b""
def average_srgb(payload):
with Image.open(io.BytesIO(payload)) as image:
image = image.convert("RGB")
image.thumbnail((64, 64))
pixels = list(image.getdata())
count = max(1, len(pixels))
rgb = [sum(pixel[channel] for pixel in pixels) / count for channel in range(3)]
return [round(value / 255.0, 4) for value in rgb]
def material_color(gltf, binary, index):
material = gltf.get("materials", [])[index]
pbr = material.get("pbrMetallicRoughness", {})
factor = pbr.get("baseColorFactor", [1.0, 1.0, 1.0, 1.0])[:3]
texture_info = pbr.get("baseColorTexture")
if texture_info is not None:
texture = gltf.get("textures", [])[texture_info["index"]]
image_index = texture.get("source")
if image_index is not None:
try:
sampled = average_srgb(image_bytes(gltf, binary, image_index))
return {
"srgb": [round(sampled[channel] * factor[channel], 4) for channel in range(3)],
"source": "textureAvg",
}
except Exception as error: # noqa: BLE001 - record and fall back
return {"srgb": [round(value, 4) for value in factor], "source": "factorFallback",
"error": str(error)[:120]}
return {"srgb": [round(value, 4) for value in factor], "source": "baseColorFactor"}
def main():
result = {}
failures = []
for name in sorted(os.listdir(source_dir)):
if not name.lower().endswith(".glb"):
continue
try:
gltf, binary = read_glb(os.path.join(source_dir, name))
except Exception as error: # noqa: BLE001
failures.append({"file": name, "error": str(error)[:120]})
continue
entry = {}
for index in range(len(gltf.get("materials", []))):
entry[str(index)] = material_color(gltf, binary, index)
result[name] = entry
with open(out_file, "w", encoding="utf-8") as handle:
json.dump({"schema": "freecad-web-line-course/material-colors/v1",
"sourceDir": source_dir, "files": result, "failures": failures},
handle, ensure_ascii=False, indent=1)
print(json.dumps({"ok": True, "outFile": out_file, "files": len(result),
"materials": sum(len(value) for value in result.values()),
"failures": len(failures)}, ensure_ascii=False))
if __name__ == "__main__":
main()