"""Surfaces of the canister station, headless, in place: blender.exe -b ../CanisterStation.blend --python cs_surfaces.py [-- --nobake] The feeder's recipe (models/nutrition-feeder/build/nf_surfaces.py, from the docking arm and the pressure hatch), for the user's rule "realistic with good textures" from the first version: * tiling sets from the user's own Season 2 pack (already in the Unreal project), read in place by relative path from models/vessel-interior/textures/ModSci_Engineer/Textures: ScratchedMetal under the paints, BrushedMetal for the bare metal, Glass_DirtRough as a smudge mask, T_Scratch_Norm for fine scratches on the metal; * one mask map baked from each mesh in Cycles (R occlusion, G edges, B crevices): textures/T_CS_Body_Masks.png (4096) and T_CS_Canister_Masks.png (2048): shade in crevices and deep corners, low wear (the ship is clean); * drawn textures (cs_textures.py): the radiation sign (a decal patch, alpha-masked), the status screen, the glow ring's colours along its circumference. Tints are the picture's colours, sampled from reference/ref_user.png (linear): green panels 0.04 0.07 0.063, black 0.018, the grey head 0.14 lit, cream 0.60 0.55 0.47, the light grey plate and hub disc 0.48. UV layers (order matters for Unreal): UVMap (UV0) a unique unwrap into the mesh's own mask map; the screen, the decal and the glow ring take their own texture's 0..1 (from the build's UV_Special layer, or planar for the screen) UV_Tile (UV1) metres, box-projected, for the tiling sets A paint used on both meshes gets a copy for the canister ("_Can") that reads the canister's mask map. """ import bpy, bmesh, math, os, sys, time, json import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) FOLDER = os.path.dirname(HERE) TEX = os.path.join(FOLDER, "textures") PACK = os.path.normpath(os.path.join(FOLDER, "..", "vessel-interior", "textures", "ModSci_Engineer", "Textures")) SCR = ("Base/ScratchedMetal/T_ScratchedMetal_Diff.png", "Base/ScratchedMetal/T_ScratchedMetal_Rough.png", "Base/ScratchedMetal/T_ScratchedMetal_Normal.png") BRU = ("Base/BrushedMetal/T_BrushedMetal_Diff.png", "Base/BrushedMetal/T_BrushedMetal_Rough.png", "Base/BrushedMetal/T_BrushedMetal_Normal.png") DIRT = "Base/Glass/T_Glass_DirtRough.png" SCRATCH_N = "Base/Glass/T_Scratch_Norm.png" MASKS = {"SM_CanisterStation_Body": ("T_CS_Body_Masks", 4096), "SM_CanisterStation_Canister": ("T_CS_Canister_Masks", 2048)} EDGE_R = 0.004 PAINT = dict(set=SCR, metal=0.0, tile=0.60, shade=(0.96, 1.03), rough=(0.42, 0.30), normal=0.14, dirt=0.04, dirt_tile=1.4, grime=0.18, wear=0.0, wear_col=(0.55, 0.56, 0.57), wear_rough=0.35) SURF = { "M_CS_Green": dict(PAINT, tint=(0.036, 0.063, 0.058)), "M_CS_Black": dict(PAINT, tint=(0.016, 0.016, 0.017), rough=(0.55, 0.42)), "M_CS_Grey": dict(PAINT, tint=(0.085, 0.090, 0.095), rough=(0.50, 0.38)), "M_CS_Cream": dict(PAINT, tint=(0.56, 0.51, 0.44), rough=(0.40, 0.30), grime=0.14), "M_CS_Steel": dict(PAINT, tint=(0.42, 0.425, 0.44), rough=(0.45, 0.34), grime=0.14), "M_CS_PanelDark": dict(PAINT, tint=(0.045, 0.052, 0.052), rough=(0.50, 0.38)), "M_CS_Chrome": dict(set=BRU, tint=(0.70, 0.66, 0.60), metal=1.0, tile=0.10, shade=(0.95, 1.04), rough=(0.24, 0.34), normal=0.25, normal_map=SCRATCH_N, dirt=0.03, dirt_tile=0.6, grime=0.12, wear=0.0), "M_CS_Rubber": dict(PAINT, tint=(0.010, 0.010, 0.011), rough=(0.70, 0.60), normal=0.05, grime=0.0), "M_CS_Gap": dict(set=(None, SCR[1], None), tint=(0.006, 0.006, 0.007), metal=0.0, tile=0.40, shade=(1.0, 1.0), rough=(0.70, 0.55), normal=0.0, dirt=0.0, dirt_tile=1.0, grime=0.0, wear=0.0), } NOBAKE = {"M_CS_Screen", "M_CS_Glow", "M_CS_Decal"} SPECIAL = {"M_CS_Screen", "M_CS_Glow", "M_CS_Decal"} # ------------------------------------------------------------------ UV layers def uv_tile_layer(me): """metres, by the face's dominant axis""" uv = me.uv_layers.get("UV_Tile") or me.uv_layers.new(name="UV_Tile") co = np.zeros(len(me.vertices) * 3, np.float32) me.vertices.foreach_get("co", co) co = co.reshape(-1, 3) out = np.zeros((len(me.loops), 2), np.float32) for p in me.polygons: n = p.normal ax = 0 if abs(n.x) >= abs(n.y) and abs(n.x) >= abs(n.z) else (1 if abs(n.y) >= abs(n.z) else 2) for li in range(p.loop_start, p.loop_start + p.loop_total): c = co[me.loops[li].vertex_index] out[li] = (c[1], c[2]) if ax == 0 else ((c[0], c[2]) if ax == 1 else (c[0], c[1])) uv.data.foreach_set("uv", out.ravel()) def uv_atlas_layer(ob, size): """UVMap: a unique unwrap of the mesh into its own mask map. Faces of the special materials keep their own 0..1: the glow ring and the decal from the build's UV_Special layer, the screen's glass planar over its rectangle.""" me = ob.data keep = {} for l in me.uv_layers: a = np.zeros(len(me.loops) * 2, np.float32) l.data.foreach_get("uv", a) keep[l.name] = a while len(me.uv_layers): me.uv_layers.remove(me.uv_layers[0]) for nm in ("UVMap", "UV_Tile"): me.uv_layers.new(name=nm).data.foreach_set("uv", keep.get(nm, np.zeros(len(me.loops) * 2, np.float32))) me.uv_layers.active = me.uv_layers["UVMap"] me.uv_layers["UVMap"].active_render = True names = [m.name for m in me.materials] special = {i for i, n in enumerate(names) if n in SPECIAL} vl = bpy.context.view_layer for o in vl.objects: o.select_set(False) ob.select_set(True) vl.objects.active = ob for p in me.polygons: p.select = p.material_index not in special bpy.ops.object.mode_set(mode='EDIT') bpy.ops.mesh.select_mode(type='FACE') margin = 6.0 / size bpy.ops.uv.smart_project(angle_limit=math.radians(50), island_margin=margin, area_weight=0.0, correct_aspect=True, scale_to_bounds=False) bpy.ops.uv.select_all(action='SELECT') try: bpy.ops.uv.pack_islands(rotate=True, scale=True, margin_method='FRACTION', margin=margin, shape_method='CONCAVE') except Exception as ex: print("pack skipped", ob.name, ex) bpy.ops.object.mode_set(mode='OBJECT') a = np.zeros(len(me.loops) * 2, np.float32) me.uv_layers["UVMap"].data.foreach_get("uv", a) a = a.reshape(-1, 2) pad = 4.0 / size a = pad + np.clip(a, 0, 1) * (1 - 2 * pad) sp = keep.get("UV_Special") if sp is not None: sp = sp.reshape(-1, 2) scr = [p for p in me.polygons if names[p.material_index] == "M_CS_Screen"] if scr: vs = [me.vertices[i].co for p in scr for i in p.vertices] x0, x1 = min(v.x for v in vs), max(v.x for v in vs) z0, z1 = min(v.z for v in vs), max(v.z for v in vs) for p in me.polygons: n = names[p.material_index] if n not in SPECIAL: continue for li in range(p.loop_start, p.loop_start + p.loop_total): if n == "M_CS_Screen": c = me.vertices[me.loops[li].vertex_index].co a[li] = ((c.x - x0) / (x1 - x0), (c.z - z0) / (z1 - z0)) elif sp is not None: a[li] = sp[li] me.uv_layers["UVMap"].data.foreach_set("uv", a.ravel()) # ------------------------------------------------------------------ bake def use_gpu(): sc = bpy.context.scene sc.render.engine = 'CYCLES' try: prefs = bpy.context.preferences.addons['cycles'].preferences prefs.compute_device_type = 'HIP' prefs.get_devices() for d in prefs.devices: d.use = d.type == 'HIP' sc.cycles.device = 'GPU' return 'HIP' except Exception as ex: print("GPU not set:", ex) sc.cycles.device = 'CPU' return 'CPU' def bake_masks(ob, name, N): """an emit bake of the mesh alone into its own map (occlusion counts only the mesh itself)""" t0 = time.time() kind = use_gpu() sc = bpy.context.scene for im in [i for i in bpy.data.images if i.name.startswith(name)]: bpy.data.images.remove(im) masks = bpy.data.images.new(name, N, N, alpha=False) masks.colorspace_settings.name = 'Non-Color' masks.pixels.foreach_set(np.tile(np.array((1.0, 0.0, 1.0, 1.0), np.float32), N * N)) mm = bpy.data.materials.new("_bake_masks") mm.use_nodes = True nt = mm.node_tree nt.nodes.clear() ao = nt.nodes.new('ShaderNodeAmbientOcclusion'); ao.samples = 24; ao.only_local = True; ao.inputs["Distance"].default_value = 0.20 cv = nt.nodes.new('ShaderNodeAmbientOcclusion'); cv.samples = 16; cv.only_local = True; cv.inputs["Distance"].default_value = 0.018 bv = nt.nodes.new('ShaderNodeBevel'); bv.samples = 8; bv.inputs["Radius"].default_value = EDGE_R geo = nt.nodes.new('ShaderNodeNewGeometry') dot = nt.nodes.new('ShaderNodeVectorMath'); dot.operation = 'DOT_PRODUCT' nt.links.new(bv.outputs["Normal"], dot.inputs[0]); nt.links.new(geo.outputs["Normal"], dot.inputs[1]) inv = nt.nodes.new('ShaderNodeMath'); inv.operation = 'SUBTRACT'; inv.inputs[0].default_value = 1.0 nt.links.new(dot.outputs["Value"], inv.inputs[1]) edg = nt.nodes.new('ShaderNodeMath'); edg.operation = 'MULTIPLY'; edg.inputs[1].default_value = 3.5; edg.use_clamp = True nt.links.new(inv.outputs[0], edg.inputs[0]) cc = nt.nodes.new('ShaderNodeCombineColor') nt.links.new(ao.outputs["AO"], cc.inputs[0]); nt.links.new(edg.outputs[0], cc.inputs[1]); nt.links.new(cv.outputs["AO"], cc.inputs[2]) em = nt.nodes.new('ShaderNodeEmission') nt.links.new(cc.outputs[0], em.inputs["Color"]) om = nt.nodes.new('ShaderNodeOutputMaterial') nt.links.new(em.outputs[0], om.inputs["Surface"]) ti = nt.nodes.new('ShaderNodeTexImage'); ti.image = masks nt.nodes.active = ti sc.cycles.samples = 24 sc.cycles.use_denoising = False sc.render.bake.margin = 6 sc.render.bake.use_clear = False me = ob.data.copy() bm = bmesh.new() bm.from_mesh(me) names = [m.name for m in me.materials] bmesh.ops.delete(bm, geom=[f for f in bm.faces if names[f.material_index] in NOBAKE], context='FACES') for f in bm.faces: f.material_index = 0 bm.to_mesh(me) bm.free() me.materials.clear() me.materials.append(mm) me.uv_layers.active = me.uv_layers["UVMap"] me.uv_layers["UVMap"].active_render = True tmp = bpy.data.objects.new("_bake_" + name, me) sc.collection.objects.link(tmp) tmp.matrix_world = ob.matrix_world for o2 in bpy.context.view_layer.objects: o2.select_set(False) tmp.select_set(True) bpy.context.view_layer.objects.active = tmp try: bpy.ops.object.bake(type='EMIT', margin=6, use_clear=False) finally: bpy.data.objects.remove(tmp) bpy.data.meshes.remove(me) os.makedirs(TEX, exist_ok=True) masks.filepath_raw = os.path.join(TEX, name + ".png") masks.file_format = 'PNG' masks.save() masks.filepath = bpy.path.relpath(masks.filepath_raw) bpy.data.materials.remove(mm) return masks, dict(device=kind, seconds=round(time.time() - t0, 1), size=N) # ------------------------------------------------------------------ materials (node recipe from the docking arm) def tex_image(path, colorspace="sRGB"): path = os.path.normpath(path) for im in bpy.data.images: if im.filepath and os.path.normpath(bpy.path.abspath(im.filepath)) == path: return im im = bpy.data.images.load(path) im.colorspace_settings.name = colorspace try: im.filepath = bpy.path.relpath(path) except Exception: pass return im _RANGE = {} def tex_range(im, lo=3, hi=97): if im.name not in _RANGE: n, ch = im.size[0] * im.size[1], im.channels px = np.empty(n * ch, np.float32) im.pixels.foreach_get(px) px = px.reshape(n, ch) if ch >= 3: c = px[:, :3] if im.colorspace_settings.name == 'sRGB': c = np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4) v = c @ np.array([0.2126, 0.7152, 0.0722], np.float32) else: v = px[:, 0] _RANGE[im.name] = (round(float(np.percentile(v, lo)), 4), round(float(np.percentile(v, hi)), 4)) return _RANGE[im.name] class Tree: def __init__(self, mat): mat.use_nodes = True self.nt = mat.node_tree self.nt.nodes.clear() def node(self, kind, label=None, **props): n = self.nt.nodes.new(kind) if label: n.label = label for k, v in props.items(): setattr(n, k, v) i = len(self.nt.nodes) - 1 n.location = (-2000 + 240 * (i // 4), 500 - 320 * (i % 4)) return n def link(self, a, b): self.nt.links.new(a, b) def put(self, sock, v): if isinstance(v, bpy.types.NodeSocket): self.nt.links.new(v, sock) else: sock.default_value = v def math(self, op, a, b=None, clamp=False, label=None): n = self.node('ShaderNodeMath', label, operation=op, use_clamp=clamp) self.put(n.inputs[0], a) if b is not None: self.put(n.inputs[1], b) return n.outputs[0] def ranged(self, v, lo, hi, label=None, f0=0.0, f1=1.0, smooth=False): n = self.node('ShaderNodeMapRange', label) if smooth: n.interpolation_type = 'SMOOTHSTEP' self.put(n.inputs["Value"], v) n.inputs["From Min"].default_value = f0; n.inputs["From Max"].default_value = f1 n.inputs["To Min"].default_value = lo; n.inputs["To Max"].default_value = hi return n.outputs["Result"] def mixc(self, fac, a, b, label=None): n = self.node('ShaderNodeMix', label, data_type='RGBA') self.put(n.inputs[0], fac) self.put(n.inputs[6], a if isinstance(a, bpy.types.NodeSocket) else tuple(a) + (1.0,)) self.put(n.inputs[7], b if isinstance(b, bpy.types.NodeSocket) else tuple(b) + (1.0,)) return n.outputs[2] def mixf(self, fac, a, b, label=None): n = self.node('ShaderNodeMix', label, data_type='FLOAT') self.put(n.inputs[0], fac); self.put(n.inputs[2], a); self.put(n.inputs[3], b) return n.outputs[0] def uv(self, name): return self.node('ShaderNodeUVMap', uv_map=name).outputs["UV"] def mapped(self, src, scale, label=None): n = self.node('ShaderNodeMapping', label) self.nt.links.new(src, n.inputs["Vector"]) n.inputs["Scale"].default_value = (scale, scale, scale) return n.outputs["Vector"] def tex(self, im, vec, label=None): n = self.node('ShaderNodeTexImage', label, image=im) self.nt.links.new(vec, n.inputs["Vector"]) return n def dress(mat, r, masks=None): """a coated or bare metal surface: a tiling set + smudges; with the baked masks also shade in crevices""" t = Tree(mat) b = t.node('ShaderNodeBsdfPrincipled') out = t.node('ShaderNodeOutputMaterial') t.link(b.outputs[0], out.inputs["Surface"]) u0 = t.uv("UV_Tile") mp = t.mapped(u0, 1.0 / r["tile"], "one repeat = %.2f m" % r["tile"]) diff, rough, normal = r["set"] dirt = t.tex(tex_image(os.path.join(PACK, DIRT), "Non-Color"), t.mapped(u0, 1.0 / r["dirt_tile"]), "smudges and dust").outputs["Color"] ao = edge = crev = None if masks is not None: sep = t.node('ShaderNodeSeparateColor') t.link(t.tex(masks, t.uv("UVMap"), "baked: R occlusion, G edges, B crevices").outputs["Color"], sep.inputs[0]) ao, edge, crev = sep.outputs[0], sep.outputs[1], sep.outputs[2] tint = tuple(r["tint"]) col = tint if diff: im = tex_image(os.path.join(PACK, diff)) lo, hi = tex_range(im) bw = t.node('ShaderNodeRGBToBW') t.link(t.tex(im, mp, "surface, diffuse").outputs["Color"], bw.inputs[0]) sh = t.ranged(bw.outputs[0], r["shade"][0], r["shade"][1], "shade the tint", lo, hi) vm = t.node('ShaderNodeVectorMath', "tint x shade", operation='SCALE') vm.inputs[0].default_value = tint t.link(sh, vm.inputs["Scale"]) col = vm.outputs["Vector"] grime = None if crev is not None and r["grime"] > 0: grime = t.math('MULTIPLY', t.math('POWER', t.math('SUBTRACT', 1.0, crev), 1.4), r["grime"], clamp=True, label="shade in crevices") col = t.mixc(grime, col, (0.02, 0.019, 0.018), "darken crevices") if ao is not None: col = t.mixc(t.ranged(ao, 0.25, 0.0, "occlusion", 0.0, 1.0), col, (0.004, 0.005, 0.006), "occlusion") rim = tex_image(os.path.join(PACK, rough), "Non-Color") rlo, rhi = tex_range(rim) ro = t.tex(rim, mp, "surface, roughness").outputs["Color"] rr = t.ranged(ro, r["rough"][0], r["rough"][1], "roughness range", rlo, rhi) rr = t.math('ADD', rr, t.math('MULTIPLY', dirt, r["dirt"]), clamp=True, label="smudges dull the sheen") if grime is not None: rr = t.math('ADD', rr, t.math('MULTIPLY', grime, 0.30), clamp=True, label="crevices are matte") t.put(b.inputs["Base Color"], col) t.put(b.inputs["Roughness"], rr) t.put(b.inputs["Metallic"], r["metal"]) nm_file = r.get("normal_map") or normal if nm_file and r["normal"] > 0: nd = t.node('ShaderNodeNormalMap', "fine relief", uv_map="UV_Tile") nd.inputs["Strength"].default_value = r["normal"] t.link(t.tex(tex_image(os.path.join(PACK, nm_file), "Non-Color"), mp, "surface, normal").outputs["Color"], nd.inputs["Color"]) t.link(nd.outputs["Normal"], b.inputs["Normal"]) mat.diffuse_color = tuple(r["tint"]) + (1.0,) mat.metallic = r["metal"] def dress_glow(mat, img, strength): """the light ring: its colour from the drawn gradient along the circumference (UV0 u), as emission""" t = Tree(mat) b = t.node('ShaderNodeBsdfPrincipled') out = t.node('ShaderNodeOutputMaterial') t.link(b.outputs[0], out.inputs["Surface"]) tx = t.tex(img, t.uv("UVMap"), "ring colours (cs_textures.py)") t.link(tx.outputs["Color"], b.inputs["Base Color"]) t.link(tx.outputs["Color"], b.inputs["Emission Color"]) b.inputs["Roughness"].default_value = 0.25 b.inputs["Emission Strength"].default_value = strength mat.diffuse_color = (0.4, 0.9, 0.9, 1.0) def dress_decal(mat, img): """the radiation sign: printed paint over the green, alpha from the drawing (masked in Unreal)""" t = Tree(mat) b = t.node('ShaderNodeBsdfPrincipled') out = t.node('ShaderNodeOutputMaterial') t.link(b.outputs[0], out.inputs["Surface"]) tx = t.tex(img, t.uv("UVMap"), "radiation sign (cs_textures.py)") t.link(tx.outputs["Color"], b.inputs["Base Color"]) t.link(tx.outputs["Alpha"], b.inputs["Alpha"]) b.inputs["Roughness"].default_value = 0.36 try: mat.blend_method = 'CLIP' except Exception: pass mat.diffuse_color = (0.9, 0.75, 0.1, 1.0) def dress_screen(mat, img): """the UI under a glass: the texture is the emission""" t = Tree(mat) b = t.node('ShaderNodeBsdfPrincipled') out = t.node('ShaderNodeOutputMaterial') t.link(b.outputs[0], out.inputs["Surface"]) tx = t.tex(img, t.uv("UVMap"), "status screen (cs_textures.py)") b.inputs["Base Color"].default_value = (0.004, 0.006, 0.007, 1) b.inputs["Roughness"].default_value = 0.30 b.inputs["Specular IOR Level"].default_value = 0.25 t.link(tx.outputs["Color"], b.inputs["Emission Color"]) b.inputs["Emission Strength"].default_value = 1.6 mat.diffuse_color = (0.05, 0.25, 0.25, 1) OBJECTS = ["SM_CanisterStation_Body", "SM_CanisterStation_Canister"] def main(bake=True): rep = {} maps = {} for n in OBJECTS: ob = bpy.data.objects[n] uv_tile_layer(ob.data) uv_atlas_layer(ob, MASKS[n][1]) if "UV_Special" in ob.data.uv_layers: ob.data.uv_layers.remove(ob.data.uv_layers["UV_Special"]) for n in OBJECTS: name, size = MASKS[n] if bake: maps[n], rep[name] = bake_masks(bpy.data.objects[n], name, size) else: maps[n] = bpy.data.images.get(name) # a paint on both meshes: the canister gets a copy "_Can" that reads the canister's mask map users = {} for n in OBJECTS: for m in bpy.data.objects[n].data.materials: if m: users.setdefault(m.name.replace("_Can", ""), []).append(n) for mname, objs in users.items(): if mname not in SURF: continue dress(bpy.data.materials[mname], SURF[mname], maps[objs[0]]) for n in objs[1:]: cp = bpy.data.materials.get(mname + "_Can") if cp is None: cp = bpy.data.materials[mname].copy() cp.name = mname + "_Can" me = bpy.data.objects[n].data for i, m in enumerate(me.materials): if m and m.name == mname: me.materials[i] = cp dress(cp, SURF[mname], maps[n]) dress_glow(bpy.data.materials["M_CS_Glow"], tex_image(os.path.join(TEX, "T_CS_GlowRing.png")), 1.1) dress_decal(bpy.data.materials["M_CS_Decal"], tex_image(os.path.join(TEX, "T_CS_Radiation.png"))) dress_screen(bpy.data.materials["M_CS_Screen"], tex_image(os.path.join(TEX, "T_CS_Screen_UI.png"))) for im in bpy.data.images: if im.filepath and not im.filepath.startswith("//"): try: im.filepath = bpy.path.relpath(bpy.path.abspath(im.filepath)) except Exception: pass bpy.ops.wm.save_mainfile() print("SURFACES OK", json.dumps(rep)) if __name__ == "__main__": main(bake="--nobake" not in sys.argv)