"""依頼 361: export_361.py が書き出した 形・コマごとの位置と向き を Blender (Cycles) に当てて, 机側・手首を描く. 関節の計算はしない (MuJoCo が出した geom・カメラの 4×4 をそのまま当てるだけ). 歪みは入れない (描いたあと post_361.py で足す). 色の扱い: MuJoCo と同じ「表示の値のまま光を掛ける」形にする (見え方の変換 Raw. 色は appearance_353/355 の値をそのまま, 机の絵も Non-Color). 光の強さは 机の面 (上向き) で MuJoCo と同じになるように: 平行光 = π × MuJoCo の diffuse, 部屋全体の光 = ambient. Blender で初めて入れるもの: 爪・腕・箱の 表面下の散らし (透け), 柔らかい影 (平行光の広がり), 光の跳ね返り (机からの照り返し), ブロックの表面のつや. 使い方 (Blender の中): blender -b --factory-startup --python so101/blender/render_361.py -- --ep ep00 --samples 32,64 [--labels] [--frames 0,5] 書き出す: check_361//bl_s/<コマ>_.png (16 bit・描く大きさのまま)・bl_lab/ (ラベル)・times_bl_.json """ import json import math import sys import time from pathlib import Path import bpy import numpy as np from mathutils import Matrix HERE = Path(__file__).resolve().parent OUT = HERE.parent / "check_361" SCN = OUT / "scene" # ラベル (appearance_337 と同じ番号) L_TABLE, L_ARM, L_SERVO, L_BLOCK, L_BOXF, L_BOXW, L_JAW = 1, 2, 3, 4, 5, 6, 7 # Blender で足す見た目 (自分で決めた出発点. 細かい合わせ込みは次の依頼) SUN_ANGLE_DEG = {0: 15.0, "other": 15.0} # 平行光の広がり (直径). LED パネル (60cm 四方・約 2m) と 上の柔らかい光 SSS = {L_JAW: (0.6, 0.003), L_ARM: (0.15, 0.002), L_BOXW: (1.0, 0.02), L_BOXF: (0.6, 0.004)} # (重み, 長さ m) ROUGH = {L_TABLE: 0.8, L_ARM: 0.55, L_SERVO: 0.45, L_JAW: 0.7, L_BLOCK: 0.3, L_BOXF: 0.5, L_BOXW: 0.5} SPEC = {L_TABLE: 0.1, L_ARM: 0.3, L_SERVO: 0.4, L_JAW: 0.2, L_BLOCK: 0.6, L_BOXF: 0.3, L_BOXW: 0.3} LABEL_RGB = {k: (k / 10.0, 0.0, 0.0) for k in range(8)} # ラベルの絵: 赤 = ラベル ÷ 10 def arg(name, default): a = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] return a[a.index(name) + 1] if name in a else default def flag(name): a = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] return name in a def principled(name, rgb, lab, image=None): m = bpy.data.materials.new(name) m.use_nodes = True nt = m.node_tree b = nt.nodes["Principled BSDF"] b.inputs["Base Color"].default_value = (*rgb, 1) b.inputs["Roughness"].default_value = ROUGH[lab] b.inputs["Specular IOR Level"].default_value = SPEC[lab] if lab in SSS: w, r = SSS[lab] b.inputs["Subsurface Weight"].default_value = w b.inputs["Subsurface Scale"].default_value = r b.inputs["Subsurface Radius"].default_value = (1.0, 1.0, 1.0) if image is not None: tx = nt.nodes.new("ShaderNodeTexImage") tx.image = image tx.interpolation = "Linear" nt.links.new(tx.outputs["Color"], b.inputs["Base Color"]) return m def build(): bpy.ops.wm.read_factory_settings(use_empty=True) sc = bpy.context.scene look = json.loads((SCN / "look.json").read_text()) geoms = json.loads((SCN / "geoms.json").read_text()) meshes = np.load(SCN / "meshes.npz") C = look["colors"] flip_tex = flag("--tex-flip") img = bpy.data.images.load(look["table_texture"]) img.colorspace_settings.name = "Non-Color" mats = { "table": principled("table", C["table_outside"], L_TABLE), "table_tex": principled("table_tex", (1, 1, 1), L_TABLE, image=img), L_ARM: principled("printed", C["printed"], L_ARM), L_SERVO: principled("servo", C["servo"], L_SERVO), L_JAW: principled("jaw", C["jaw_353"], L_JAW), L_BLOCK: principled("block", C["block"], L_BLOCK), L_BOXF: principled("box_floor", C["box_floor"], L_BOXF), L_BOXW: principled("box_wall", C["box_wall_353"], L_BOXW), } objs = {} for r in geoms: nm, lab = r["name"], r["label"] if r["type"] == "mesh": me = bpy.data.meshes.get(r["mesh"]) if me is None: v = meshes[r["mesh"] + "_v"].astype(float) f = meshes[r["mesh"] + "_f"].astype(int) me = bpy.data.meshes.new(r["mesh"]) me.from_pydata(v.tolist(), [], f.tolist()) me.update() me.shade_smooth() me.set_sharp_from_angle(angle=math.radians(30)) scale = (1, 1, 1) elif r["type"] == "box": me = bpy.data.meshes.new(nm) v = [(x, y, z) for x in (-1, 1) for y in (-1, 1) for z in (-1, 1)] f = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)] me.from_pydata(v, [], f) me.update() scale = tuple(r["size"]) else: # 平面 (机に貼る絵) me = bpy.data.meshes.new(nm) me.from_pydata([(-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0)], [], [(0, 1, 2, 3)]) uv = me.uv_layers.new(name="UVMap") for li, vi in enumerate(me.loops): x, y, _ = me.vertices[vi.vertex_index].co vv = (y + 1) / 2 uv.data[li].uv = ((x + 1) / 2, 1 - vv if flip_tex else vv) me.update() scale = (r["size"][0], r["size"][1], 1) o = bpy.data.objects.new(nm, me) sc.collection.objects.link(o) if r["type"] != "mesh" or not o.data.materials: key = nm if nm in ("table", "table_tex") else lab if o.data.materials: o.data.materials[0] = mats[key] else: o.data.materials.append(mats[key]) o.color = (*LABEL_RGB[lab], 1) objs[nm] = (o, Matrix.Diagonal((*scale, 1)), r["group"]) # 光 for j, L in enumerate(look["lights"]): u = L["u"] mx = max(L["rgb"]) ld = bpy.data.lights.new(f"sun{j}", type="SUN") ld.energy = math.pi * mx ld.color = tuple(c / mx for c in L["rgb"]) ld.angle = math.radians(SUN_ANGLE_DEG[0] if j == 0 else SUN_ANGLE_DEG["other"]) ld.use_shadow = bool(L["shadow"]) lo = bpy.data.objects.new(f"sun{j}", ld) z = -np.asarray(u, float) # 光の進む向き = 太陽の -Z zz = -z / np.linalg.norm(z) xx = np.cross([0, 0, 1.0], zz) if abs(zz[2]) < 0.999 else np.array([1.0, 0, 0]) xx /= np.linalg.norm(xx) yy = np.cross(zz, xx) lo.matrix_world = Matrix([[xx[0], yy[0], zz[0], 0], [xx[1], yy[1], zz[1], 0], [xx[2], yy[2], zz[2], 0], [0, 0, 0, 1]]) sc.collection.objects.link(lo) w = bpy.data.worlds.new("room") w.use_nodes = True nt = w.node_tree bg = nt.nodes["Background"] bg.inputs["Color"].default_value = (*look["ambient_rgb"], 1) bg.inputs["Strength"].default_value = 1.0 lp = nt.nodes.new("ShaderNodeLightPath") blk = nt.nodes.new("ShaderNodeBackground") blk.inputs["Color"].default_value = (0, 0, 0, 1) mix = nt.nodes.new("ShaderNodeMixShader") nt.links.new(lp.outputs["Is Camera Ray"], mix.inputs["Fac"]) nt.links.new(bg.outputs["Background"], mix.inputs[1]) nt.links.new(blk.outputs["Background"], mix.inputs[2]) nt.links.new(mix.outputs["Shader"], nt.nodes["World Output"].inputs["Surface"]) sc.world = w # カメラ (MuJoCo のカメラも Blender のカメラも x右・y上・−z前) cams = {} for k, cv in look["cams"].items(): cd = bpy.data.cameras.new(k) cd.sensor_fit = "VERTICAL" cd.sensor_height = 24.0 cd.lens = 12.0 / math.tan(math.radians(cv["fovy_deg"]) / 2) cd.clip_start = 0.001 cd.clip_end = 10.0 co = bpy.data.objects.new(k, cd) sc.collection.objects.link(co) cams[k] = (co, cv["w"], cv["h"]) sc.view_settings.view_transform = "Raw" sc.view_settings.look = "None" sc.render.image_settings.file_format = "PNG" sc.render.image_settings.color_mode = "RGB" sc.render.image_settings.color_depth = "16" sc.render.use_persistent_data = True return sc, objs, cams def set_device(sc): sc.render.engine = "CYCLES" prefs = bpy.context.preferences.addons["cycles"].preferences prefs.compute_device_type = "METAL" prefs.get_devices() for d in prefs.devices: d.use = d.type == "METAL" sc.cycles.device = "GPU" cy = sc.cycles cy.use_adaptive_sampling = False cy.use_denoising = True cy.denoiser = "OPENIMAGEDENOISE" cy.denoising_use_gpu = True cy.max_bounces, cy.diffuse_bounces, cy.glossy_bounces, cy.transmission_bounces = 8, 3, 2, 4 cy.caustics_reflective = cy.caustics_refractive = False return [d.name for d in prefs.devices if d.use] def apply_frame(objs, cams, fr): for nm, (o, S, _) in objs.items(): o.matrix_world = Matrix(np.asarray(fr["geoms"][nm]).reshape(4, 4).tolist()) @ S for k, (co, _, _) in cams.items(): co.matrix_world = Matrix(np.asarray(fr["cams"][k]).reshape(4, 4).tolist()) def render(sc, objs, cams, key, path): co, w, h = cams[key] for o, _, grp in objs.values(): o.hide_render = grp == 4 and key == "wrist" # 手首カメラの台座は 手首の絵では描かない (MuJoCo と同じ) sc.camera = co sc.render.resolution_x, sc.render.resolution_y = w, h sc.render.resolution_percentage = 100 sc.render.filepath = str(path) t0 = time.perf_counter() bpy.ops.render.render(write_still=True) return time.perf_counter() - t0 def label_mode(sc): """ラベルの絵: 物の色 (ラベル ÷ 10) を そのまま光らせる. 1 サンプル・ノイズ除去なし・ぼかしの幅を最小に.""" m = bpy.data.materials.new("label") m.use_nodes = True nt = m.node_tree for n in list(nt.nodes): nt.nodes.remove(n) oi = nt.nodes.new("ShaderNodeObjectInfo") em = nt.nodes.new("ShaderNodeEmission") out = nt.nodes.new("ShaderNodeOutputMaterial") nt.links.new(oi.outputs["Color"], em.inputs["Color"]) nt.links.new(em.outputs["Emission"], out.inputs["Surface"]) bpy.context.view_layer.material_override = m sc.cycles.samples = 1 sc.cycles.use_denoising = False sc.cycles.filter_width = 0.01 sc.world.node_tree.nodes["Background"].inputs["Strength"].default_value = 0.0 def main(): ep = arg("--ep", "ep00") samples = [int(x) for x in arg("--samples", "32,64").split(",") if x] sc, objs, cams = build() used = set_device(sc) P = json.loads((OUT / ep / "poses.json").read_text()) frames = P["frames"] if arg("--frames", ""): want = {int(x) for x in arg("--frames", "").split(",")} frames = [f for f in frames if f["frame"] in want] times = {"ep": ep, "devices": used, "blender": bpy.app.version_string, "samples": {}} tag = arg("--tag", "") for s in samples: sc.cycles.samples = s d = OUT / ep / f"bl{tag}_s{s}" d.mkdir(parents=True, exist_ok=True) ts = {"desk": [], "wrist": []} for fr in frames: apply_frame(objs, cams, fr) for key in ("desk", "wrist"): ts[key].append(round(render(sc, objs, cams, key, d / f"{fr['frame']:03d}_{key}.png"), 3)) print("frame", ep, s, fr["frame"], ts["desk"][-1], ts["wrist"][-1], flush=True) times["samples"][str(s)] = ts if flag("--labels"): label_mode(sc) d = OUT / ep / f"bl{tag}_lab" d.mkdir(parents=True, exist_ok=True) for fr in frames: apply_frame(objs, cams, fr) for key in ("desk", "wrist"): render(sc, objs, cams, key, d / f"{fr['frame']:03d}_{key}.png") (OUT / f"times_bl{tag}_{ep}.json").write_text(json.dumps(times, indent=1)) main()