"""Blender (5.x) script: studio thumbnails for preview GLBs. Run: Blender -b --factory-startup --python tools/blender_thumb.py -- [ ...] One Blender session renders a batch: for each GLB, a three-quarter orthographic view that fills ~85% of the frame, soft studio light, a contact shadow on a shadow-catcher floor, transparent background (the page supplies the backdrop), saved as /.webp. Cycles on the GPU when available (Metal on a Mac), denoised. """ import math import os import sys import bpy import numpy as np from mathutils import Vector args = sys.argv[sys.argv.index("--") + 1:] out_dir, size, glbs = args[0], int(args[1]), args[2:] os.makedirs(out_dir, exist_ok=True) bpy.ops.wm.read_factory_settings(use_empty=True) scene = bpy.context.scene scene.render.engine = "CYCLES" prefs = bpy.context.preferences.addons["cycles"].preferences for kind in ("METAL", "OPTIX", "CUDA", "HIP"): try: prefs.compute_device_type = kind prefs.get_devices() if any(d.type != "CPU" for d in prefs.devices): for d in prefs.devices: d.use = True scene.cycles.device = "GPU" break except TypeError: continue scene.cycles.samples = 96 scene.cycles.use_denoising = True scene.render.film_transparent = True scene.render.resolution_x = scene.render.resolution_y = size scene.render.resolution_percentage = 100 scene.render.image_settings.file_format = "WEBP" scene.render.image_settings.color_mode = "RGBA" scene.render.image_settings.quality = 90 # Khronos PBR Neutral keeps base colours true and rolls off highlights, so white # products keep their shading instead of clipping (Standard clipped them). scene.view_settings.view_transform = os.environ.get("THUMB_VIEW", "Khronos PBR Neutral") scene.view_settings.exposure = float(os.environ.get("THUMB_EXPOSURE", "-0.8")) world = bpy.data.worlds.new("studio") world.use_nodes = True world.node_tree.nodes["Background"].inputs[0].default_value = (0.82, 0.82, 0.84, 1) world.node_tree.nodes["Background"].inputs[1].default_value = 0.2 scene.world = world cam_data = bpy.data.cameras.new("cam") cam_data.type = "ORTHO" cam = bpy.data.objects.new("cam", cam_data) scene.collection.objects.link(cam) scene.camera = cam def area(name, energy_per_m2): data = bpy.data.lights.new(name, "AREA") data.shape = "DISK" obj = bpy.data.objects.new(name, data) scene.collection.objects.link(obj) return obj, energy_per_m2 lights = [area("key", 55), area("fill", 18), area("top", 28)] for _obj, _ in lights[1:]: _obj.visible_glossy = False # fill and top light the object but don't flare on metal floor_mesh = bpy.data.meshes.new("floor") floor_mesh.from_pydata([(-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0)], [], [(0, 1, 2, 3)]) floor = bpy.data.objects.new("floor", floor_mesh) floor.is_shadow_catcher = True scene.collection.objects.link(floor) KEEP = {cam.name, floor.name, *(o.name for o, _ in lights)} def clear_asset(): for o in list(scene.objects): if o.name not in KEEP: bpy.data.objects.remove(o, do_unlink=True) for coll in (bpy.data.meshes, bpy.data.materials, bpy.data.images): for block in list(coll): if block.users == 0 and block.name != "floor": coll.remove(block) AZIMUTH, ELEVATION, FILL = math.radians(35), math.radians(24), 0.88 view = Vector((math.sin(AZIMUTH) * math.cos(ELEVATION), -math.cos(AZIMUTH) * math.cos(ELEVATION), math.sin(ELEVATION))) for glb in glbs: name = os.path.splitext(os.path.basename(glb))[0] clear_asset() bpy.ops.import_scene.gltf(filepath=glb) meshes = [o for o in scene.objects if o.type == "MESH" and o.name not in KEEP] if not meshes: print(f"THUMB_SKIP {name}: no meshes") continue bpy.context.view_layer.update() # frame on the real vertices (box corners overshoot round objects in a 3/4 view) chunks = [] for o in meshes: co = np.empty(len(o.data.vertices) * 3) o.data.vertices.foreach_get("co", co) co = co.reshape(-1, 3) m = np.array(o.matrix_world) chunks.append(co @ m[:3, :3].T + m[:3, 3]) world = np.concatenate(chunks) lo, hi = Vector(world.min(axis=0)), Vector(world.max(axis=0)) center, diag = (lo + hi) / 2, max((hi - lo).length, 1e-3) cam.location = center + view * diag * 3 cam.rotation_euler = (-view).to_track_quat("-Z", "Y").to_euler() cam_data.clip_start, cam_data.clip_end = diag * 0.01, diag * 10 bpy.context.view_layer.update() inv = np.array(cam.matrix_world.inverted()) local = world @ inv[:3, :3].T + inv[:3, 3] lmin, lmax = local.min(axis=0), local.max(axis=0) cam_data.ortho_scale = max(lmax[0] - lmin[0], lmax[1] - lmin[1]) / FILL # shift the camera in its own plane so the silhouette sits in the middle of the frame cam.location = cam.matrix_world @ Vector(((lmin[0] + lmax[0]) / 2, (lmin[1] + lmax[1]) / 2, 0)) floor.scale = (diag * 6, diag * 6, 1) floor.location = (center.x, center.y, lo.z) for (obj, e), (az, el, r) in zip(lights, [(-55, 40, 2.2), (70, 20, 2.4), (10, 80, 2.0)]): a, b = math.radians(az), math.radians(el) d = Vector((math.sin(a) * math.cos(b), -math.cos(a) * math.cos(b), math.sin(b))) obj.location = center + d * diag * r obj.rotation_euler = (-d).to_track_quat("-Z", "Y").to_euler() obj.data.size = diag * 1.6 obj.data.energy = e * (diag * r) ** 2 scene.render.filepath = os.path.join(out_dir, f"{name}.webp") bpy.ops.render.render(write_still=True) print(f"THUMB_OK {name}")