import bpy import math import json from pathlib import Path from mathutils import Vector from bpy_extras.object_utils import world_to_camera_view OUT = Path('/Users/yanchenyu/Documents/WebApps/PerfetCoffee/model_assets/coffee_machine') TEX = OUT / 'textures' OUT.mkdir(parents=True, exist_ok=True) TEX.mkdir(parents=True, exist_ok=True) bpy.ops.wm.read_factory_settings(use_empty=True) bpy.context.preferences.filepaths.save_version = 0 scene = bpy.context.scene scene.unit_settings.system = 'METRIC' scene.unit_settings.length_unit = 'METERS' cm = bpy.data.collections.new('CM_CoffeeMachine_Model') studio = bpy.data.collections.new('Studio_Exclude_From_Export') scene.collection.children.link(cm) scene.collection.children.link(studio) def move_to(obj, collection=cm): for collection_old in list(obj.users_collection): collection_old.objects.unlink(obj) collection.objects.link(obj) return obj def material(name, color, metallic=0.0, roughness=0.45): mat = bpy.data.materials.new(name) mat.use_nodes = True mat.diffuse_color = (*color, 1) bsdf = mat.node_tree.nodes.get('Principled BSDF') bsdf.inputs['Base Color'].default_value = (*color, 1) bsdf.inputs['Metallic'].default_value = metallic bsdf.inputs['Roughness'].default_value = roughness return mat steel = material('CM_Brushed_Steel', (0.48, 0.54, 0.58), 0.82, 0.28) steel_light = material('CM_Satin_Steel', (0.68, 0.73, 0.76), 0.78, 0.25) steel_dark = material('CM_Dark_Steel', (0.16, 0.20, 0.22), 0.72, 0.32) charcoal = material('CM_Charcoal_Panels', (0.035, 0.047, 0.052), 0.32, 0.34) rubber = material('CM_Black_Grip', (0.018, 0.023, 0.025), 0.05, 0.48) ivory = material('CM_Ivory_Dial', (0.88, 0.87, 0.80), 0.05, 0.62) ink = material('CM_Dial_Ink', (0.018, 0.025, 0.028), 0.0, 0.6) red = material('CM_Signal_Red', (0.72, 0.025, 0.018), 0.15, 0.32) orange = material('CM_Temperature_Needle', (0.92, 0.15, 0.025), 0.12, 0.32) teal = material('CM_Flow_Needle', (0.02, 0.32, 0.42), 0.18, 0.3) white = material('CM_Label_White', (0.84, 0.88, 0.88), 0.1, 0.5) def assign(obj, mat): if mat: obj.data.materials.append(mat) def bevel(obj, width=0.002, segments=2): if width > 0: mod = obj.modifiers.new('CM_Soft_Edges', 'BEVEL') mod.width = width mod.segments = segments if obj.type == 'MESH': normal = obj.modifiers.new('CM_Weighted_Normals', 'WEIGHTED_NORMAL') normal.keep_sharp = True normal.weight = 40 def box(name, loc, dims, mat, edge=0.002, parent=None): bpy.ops.mesh.primitive_cube_add(size=1, location=loc) obj = bpy.context.object obj.name = name obj.dimensions = dims bpy.ops.object.transform_apply(location=False, rotation=False, scale=True) move_to(obj) assign(obj, mat) bevel(obj, edge, 3 if edge > 0.003 else 2) if parent: parent_keep(obj, parent) return obj def cylinder(name, loc, radius, depth, mat, axis='Z', vertices=24, edge=0.0008, parent=None): bpy.ops.mesh.primitive_cylinder_add(vertices=vertices, radius=radius, depth=depth, location=loc) obj = bpy.context.object obj.name = name if axis == 'Y': obj.rotation_euler[0] = math.pi / 2 elif axis == 'X': obj.rotation_euler[1] = math.pi / 2 move_to(obj) assign(obj, mat) for poly in obj.data.polygons: poly.use_smooth = len(poly.vertices) == 4 bevel(obj, edge, 2) if parent: parent_keep(obj, parent) return obj def torus(name, loc, major, minor, mat, axis='Z', parent=None): rotation = (math.pi / 2, 0, 0) if axis == 'Y' else (0, 0, 0) bpy.ops.mesh.primitive_torus_add( major_segments=32, minor_segments=8, location=loc, rotation=rotation, major_radius=major, minor_radius=minor, ) obj = bpy.context.object obj.name = name move_to(obj) assign(obj, mat) for poly in obj.data.polygons: poly.use_smooth = True if parent: parent_keep(obj, parent) return obj def rod(name, start, end, radius, mat, vertices=16, parent=None): start_v = Vector(start) end_v = Vector(end) direction = end_v - start_v obj = cylinder(name, (start_v + end_v) / 2, radius, direction.length, mat, vertices=vertices, edge=0.0005) obj.rotation_euler = direction.to_track_quat('Z', 'Y').to_euler() if parent: parent_keep(obj, parent) return obj def empty(name, loc=(0, 0, 0), parent=None, size=0.025): obj = bpy.data.objects.new(name, None) cm.objects.link(obj) obj.empty_display_type = 'PLAIN_AXES' obj.empty_display_size = size obj.location = loc bpy.context.view_layer.update() if parent: parent_keep(obj, parent) return obj def parent_keep(obj, parent): bpy.context.view_layer.update() obj.parent = parent obj.matrix_parent_inverse = parent.matrix_world.inverted() def mesh_face(name, vertices, mat, parent=None): mesh = bpy.data.meshes.new(name + '_Mesh') mesh.from_pydata(vertices, [], [list(range(len(vertices)))]) mesh.update() obj = bpy.data.objects.new(name, mesh) cm.objects.link(obj) assign(obj, mat) if parent: parent_keep(obj, parent) return obj def lathe_profile(name, center, profile, mat, segments=48, edge=0.0003, parent=None): x, y, z = center vertices = [] for radius, height in profile: for index in range(segments): angle = index * 2 * math.pi / segments vertices.append((x + radius * math.cos(angle), y + radius * math.sin(angle), z + height)) faces = [] for profile_index in range(len(profile)): next_profile = (profile_index + 1) % len(profile) for index in range(segments): next_index = (index + 1) % segments faces.append((profile_index * segments + index, profile_index * segments + next_index, next_profile * segments + next_index, next_profile * segments + index)) mesh = bpy.data.meshes.new(name + '_Mesh') mesh.from_pydata(vertices, [], faces) mesh.update() obj = bpy.data.objects.new(name, mesh) cm.objects.link(obj) assign(obj, mat) for polygon in mesh.polygons: polygon.use_smooth = True bevel(obj, edge, 2) if parent: parent_keep(obj, parent) return obj def arc_ring(name, center, outer_radius, inner_radius, z_bottom, z_top, start_angle, end_angle, mat, parent=None, edge=0.0003): x, y, z = center segments = max(3, math.ceil((end_angle - start_angle) / (2 * math.pi) * 96)) vertices = [] for index in range(segments + 1): angle = start_angle + (end_angle - start_angle) * index / segments for radius, height in [(outer_radius, z_bottom), (inner_radius, z_bottom), (outer_radius, z_top), (inner_radius, z_top)]: vertices.append((x + radius * math.cos(angle), y + radius * math.sin(angle), z + height)) faces = [] for index in range(segments): a = index * 4 b = (index + 1) * 4 faces.extend([ (a, b, b + 2, a + 2), (a + 1, a + 3, b + 3, b + 1), (a, a + 1, b + 1, b), (a + 2, b + 2, b + 3, a + 3), ]) end = segments * 4 faces.extend([(0, 2, 3, 1), (end, end + 1, end + 3, end + 2)]) mesh = bpy.data.meshes.new(name + '_Mesh') mesh.from_pydata(vertices, [], faces) mesh.update() obj = bpy.data.objects.new(name, mesh) cm.objects.link(obj) assign(obj, mat) for polygon in mesh.polygons: polygon.use_smooth = len(polygon.vertices) == 4 bevel(obj, edge, 2) if parent: parent_keep(obj, parent) return obj def tube_between(name, start, end, outer_radius, inner_radius, mat, parent=None): start_v = Vector(start) end_v = Vector(end) direction = end_v - start_v half = direction.length / 2 obj = lathe_profile(name, (0, 0, 0), [(outer_radius, -half), (outer_radius, half), (inner_radius, half), (inner_radius, -half)], mat, 24, 0.00025) obj.location = (start_v + end_v) / 2 obj.rotation_euler = direction.to_track_quat('Z', 'Y').to_euler() if parent: parent_keep(obj, parent) return obj def horizontal_disc(name, center, radius, mat, parent=None): x, y, z = center segments = 48 vertices = [(x, y, z)] uv_coords = [(0.5, 0.5)] for index in range(segments): angle = index * 2 * math.pi / segments vertices.append((x + radius * math.cos(angle), y + radius * math.sin(angle), z)) uv_coords.append((0.5 + math.cos(angle) / 2, 0.5 + math.sin(angle) / 2)) faces = [(0, index + 1, (index + 1) % segments + 1) for index in range(segments)] mesh = bpy.data.meshes.new(name + '_Mesh') mesh.from_pydata(vertices, [], faces) mesh.update() uv = mesh.uv_layers.new(name='CM_FilterScreen_UV') for loop in mesh.loops: uv.data[loop.index].uv = uv_coords[loop.vertex_index] obj = bpy.data.objects.new(name, mesh) cm.objects.link(obj) assign(obj, mat) if parent: parent_keep(obj, parent) return obj def text(name, body, loc, size, mat, parent=None, align='CENTER'): curve = bpy.data.curves.new(name + '_Font', 'FONT') curve.body = body curve.size = size curve.align_x = align curve.align_y = 'CENTER' curve.space_character = 1.05 curve.resolution_u = 4 obj = bpy.data.objects.new(name, curve) cm.objects.link(obj) obj.location = loc obj.rotation_euler = (math.pi / 2, 0, 0) assign(obj, mat) if parent: parent_keep(obj, parent) return obj def driver(obj, prop, expression, index=1): curve = obj.driver_add('rotation_euler', index) drv = curve.driver drv.type = 'SCRIPTED' var = drv.variables.new() var.name = 'value' var.type = 'SINGLE_PROP' var.targets[0].id = controller var.targets[0].data_path = '["' + prop + '"]' drv.expression = expression root = empty('CM_CoffeeMachine', size=0.06) root['front_direction'] = '-Y in Blender' root['model_version'] = 'v1.0' root['reference'] = 'Original single-group design based on reference 02 proportions' controller = empty('CM_ControlState', parent=root) controller['hot_water_open'] = 0.0 controller['brew_flow'] = 0.0 controller['temperature_c'] = 0.0 for prop in ['hot_water_open', 'brew_flow']: controller.id_properties_ui(prop).update(min=0.0, max=1.0, description='Normalized control value') controller.id_properties_ui('temperature_c').update(min=0.0, max=100.0, description='Displayed outlet temperature') controller['hot_water_max_degrees'] = 270.0 controller['flow_lever_max_degrees'] = 100.0 # Main body and compact single-group housing. body = empty('CM_Body', parent=root) box('CM_Body_MainShell', (0, 0.025, 0.28), (0.46, 0.35, 0.36), steel, 0.012, body) box('CM_Body_FrontPanel', (0, -0.153, 0.29), (0.45, 0.012, 0.305), steel_light, 0.006, body) box('CM_Body_LeftPanel', (-0.229, 0.025, 0.275), (0.012, 0.325, 0.31), charcoal, 0.005, body) box('CM_Body_RightPanel', (0.229, 0.025, 0.275), (0.012, 0.325, 0.31), charcoal, 0.005, body) box('CM_Body_Base', (0, -0.015, 0.092), (0.46, 0.37, 0.035), steel_dark, 0.005, body) box('CM_Body_TopLip', (0, 0.025, 0.458), (0.45, 0.345, 0.016), steel_dark, 0.005, body) for x in [-0.185, 0.185]: for y in [-0.105, 0.13]: cylinder('CM_Body_Foot', (x, y, 0.028), 0.018, 0.045, rubber, vertices=20, edge=0.002, parent=body) for x in [-0.205, 0.205]: rod('CM_CupRail_Side', (x, -0.125, 0.49), (x, 0.155, 0.49), 0.004, steel_light, parent=body) for y in [-0.125, 0.155]: rod('CM_CupRail_Post', (x, y, 0.46), (x, y, 0.49), 0.0035, steel_light, parent=body) rod('CM_CupRail_Back', (-0.205, 0.155, 0.49), (0.205, 0.155, 0.49), 0.004, steel_light, parent=body) rod('CM_CupRail_FrontLeft', (-0.205, -0.125, 0.49), (-0.10, -0.125, 0.49), 0.004, steel_light, parent=body) rod('CM_CupRail_FrontRight', (0.10, -0.125, 0.49), (0.205, -0.125, 0.49), 0.004, steel_light, parent=body) text('CM_Body_Brand', 'PERFECT COFFEE', (0, -0.161, 0.421), 0.014, ink, body) # The fixed brew interface faces down; only its external receiving geometry is modeled. BREW_Y = -0.237 BREW_LIFT = 0.070 BREW_SEAL_Z = 0.2135 + BREW_LIFT group = empty('CM_GroupHead', (0, BREW_Y, 0.2135), parent=root) group['interface_axis'] = 'Z' group['bayonet_notch_degrees'] = 42.0 group['support_arc_count'] = 2 group['spout_owner'] = 'CM_Portafilter' cylinder('CM_GroupHead_Mount', (0, BREW_Y + 0.0435, 0.250), 0.038, 0.073, steel_dark, 'Y', 40, 0.002, group) cylinder('CM_GroupHead_Bell', (0, BREW_Y, 0.241), 0.043, 0.042, steel_light, 'Z', 48, 0.002, group) cylinder('CM_GroupHead_UpperCollar', (0, BREW_Y, 0.268), 0.046, 0.012, steel_light, 'Z', 48, 0.0015, group) lathe_profile('CM_GroupHead_SealingSeat', (0, BREW_Y, 0), [(0.050, 0.2135), (0.050, 0.220), (0.0373, 0.220), (0.0373, 0.2135)], steel, 64, 0.0005, group) for suffix, start, end in [('A', 111, 249), ('B', 291, 429)]: arc_ring('CM_GroupHead_BayonetSupport_' + suffix, (0, BREW_Y, 0), 0.050, 0.039, 0.208, 0.2135, math.radians(start), math.radians(end), steel_light, group, 0.0004) lathe_profile('CM_GroupHead_Gasket', (0, BREW_Y, 0), [(0.0373, 0.2135), (0.0373, 0.2165), (0.0348, 0.2165), (0.0337, 0.2148), (0.0348, 0.2135)], rubber, 64, 0.0001, group) # Two external bayonet lugs, an open bowl and both spouts move with the handle. portafilter = empty('CM_Portafilter', (0, BREW_Y, 0.2135), parent=root) portafilter['connection_axis'] = 'Z' portafilter['insertion_direction'] = '+Z' portafilter['unlock_rotation_degrees'] = -45.0 portafilter['bayonet_lug_count'] = 2 portafilter['seal_contact_z_m'] = BREW_SEAL_Z lathe_profile('CM_Portafilter_Bowl', (0, BREW_Y, 0), [(0.0345, 0.1815), (0.0375, 0.184), (0.0375, 0.2095), (0.0385, 0.2095), (0.0385, 0.2135), (0.0340, 0.2135), (0.0330, 0.2105), (0.0295, 0.1915), (0.0005, 0.1915), (0.0005, 0.1815)], steel_light, 64, 0.0004, portafilter) for suffix, angle in [('A', -45), ('B', 135)]: arc_ring('CM_Portafilter_LockingLug_' + suffix, (0, BREW_Y, 0), 0.0475, 0.0355, 0.205, 0.2079, math.radians(angle - 8), math.radians(angle + 8), steel_light, portafilter, 0.0003) lathe_profile('CM_Portafilter_SpoutCollar', (0, BREW_Y, 0), [(0.0105, 0.1745), (0.0105, 0.1815), (0.0065, 0.1815), (0.0065, 0.1745)], steel_light, 32, 0.0005, portafilter) tube_between('CM_Portafilter_SpoutLeft', (0, BREW_Y, 0.176), (-0.014, BREW_Y, 0.157), 0.005, 0.0032, steel_light, portafilter) tube_between('CM_Portafilter_SpoutRight', (0, BREW_Y, 0.176), (0.014, BREW_Y, 0.157), 0.005, 0.0032, steel_light, portafilter) portafilter['grip_axis'] = '-Y; shared centerline with neck, grip and cap' portafilter['grip_centerline_z_m'] = BREW_SEAL_Z - 0.0185 handle_direction = Vector((0, -1, 0)) handle_start = Vector((0, BREW_Y - 0.034, BREW_SEAL_Z - BREW_LIFT - 0.0185)) handle_segments = [ ('Neck', math.sqrt(0.003317), 0.008, steel_light, 20), ('Grip', math.sqrt(0.019019), 0.014, rubber, 24), ('GripCap', math.sqrt(0.000338), 0.0145, steel_dark, 24), ] for name, length, radius, mat, vertices in handle_segments: if name != 'Neck': handle_start -= handle_direction * 0.003 handle_end = handle_start + handle_direction * length rod('CM_Portafilter_' + name, handle_start, handle_end, radius, mat, vertices, portafilter) handle_start = handle_end # Shallow drip tray: all grille holes are represented by a packed texture. drip = empty('CM_DripTray', parent=root) box('CM_DripTray_Base', (0, -0.16, 0.074), (0.46, 0.30, 0.045), steel_dark, 0.006, drip) for x in [-0.222, 0.222]: box('CM_DripTray_SideFrame', (x, -0.16, 0.099), (0.012, 0.29, 0.014), steel_light, 0.002, drip) for y in [-0.301, -0.019]: box('CM_DripTray_EndFrame', (0, y, 0.099), (0.44, 0.012, 0.014), steel_light, 0.002, drip) def save_generated_image(name, pixels, size, path, non_color=False): image = bpy.data.images.new(name, width=size, height=size, alpha=True) if non_color: image.colorspace_settings.name = 'Non-Color' image.pixels = pixels image.update() image.filepath_raw = str(path) image.file_format = 'PNG' image.save() image.pack() return image size = 256 albedo = [] normal_pixels = [] roughness = [] heights = [] for y in range(size): row = [] for x in range(size): bar_x = x % 32 < 7 bar_y = y % 32 < 5 raised = bar_x or bar_y row.append(1.0 if raised else 0.0) if raised: edge = min(x % 32, 7 - x % 32, y % 32, 5 - y % 32) shade = 0.42 + 0.05 * min(edge, 2) + 0.025 * math.sin(y * 0.7) albedo.extend((shade, shade * 1.04, shade * 1.07, 1)) roughness.extend((0.3, 0.3, 0.3, 1)) else: albedo.extend((0.025, 0.032, 0.036, 1)) roughness.extend((0.72, 0.72, 0.72, 1)) heights.append(row) for y in range(size): for x in range(size): dx = (heights[y][(x + 1) % size] - heights[y][(x - 1) % size]) * 1.7 dy = (heights[(y + 1) % size][x] - heights[(y - 1) % size][x]) * 1.7 vec = Vector((-dx, dy, 1)).normalized() normal_pixels.extend((vec.x * 0.5 + 0.5, vec.y * 0.5 + 0.5, vec.z * 0.5 + 0.5, 1)) tray_albedo = save_generated_image('CM_DripTray_Albedo', albedo, size, TEX / 'drip_tray_albedo.png') tray_normal = save_generated_image('CM_DripTray_Normal', normal_pixels, size, TEX / 'drip_tray_normal.png', True) tray_rough = save_generated_image('CM_DripTray_Roughness', roughness, size, TEX / 'drip_tray_roughness.png', True) filter_pixels = [] for py in range(size): for px in range(size): dx = px % 12 - 5.5 dy = py % 12 - 5.5 if dx * dx + dy * dy <= 4: filter_pixels.extend((0.008, 0.012, 0.014, 1)) else: filter_pixels.extend((0.42, 0.45, 0.47, 1)) filter_image = save_generated_image('CM_FilterScreen_Albedo', filter_pixels, size, TEX / 'filter_screen.png') filter_mat = material('CM_FilterScreen_TexturedSteel', (0.42, 0.45, 0.47), 0.65, 0.4) filter_node = filter_mat.node_tree.nodes.new('ShaderNodeTexImage') filter_node.image = filter_image filter_mat.node_tree.links.new(filter_node.outputs['Color'], filter_mat.node_tree.nodes.get('Principled BSDF').inputs['Base Color']) filter_screen = horizontal_disc('CM_Portafilter_FilterScreen', (0, BREW_Y, 0.192), 0.0285, filter_mat, portafilter) filter_screen['holes_representation'] = 'texture' shower_screen = horizontal_disc('CM_GroupHead_ShowerScreen', (0, BREW_Y, 0.2175), 0.0335, filter_mat, group) shower_screen['holes_representation'] = 'texture' # Lift only after every fixed and detachable child has been attached. group.location.z += BREW_LIFT portafilter.location.z += BREW_LIFT group['cup_clearance_lift_m'] = BREW_LIFT portafilter['cup_clearance_lift_m'] = BREW_LIFT bpy.context.view_layer.update() tray_mat = material('CM_DripTray_Textured_Steel', (0.4, 0.45, 0.48), 0.72, 0.35) nodes = tray_mat.node_tree.nodes links = tray_mat.node_tree.links bsdf = nodes.get('Principled BSDF') for image, socket in [(tray_albedo, 'Base Color'), (tray_rough, 'Roughness')]: node = nodes.new('ShaderNodeTexImage') node.image = image links.new(node.outputs['Color'], bsdf.inputs[socket]) normal_tex = nodes.new('ShaderNodeTexImage') normal_tex.image = tray_normal normal_node = nodes.new('ShaderNodeNormalMap') normal_node.inputs['Strength'].default_value = 0.65 links.new(normal_tex.outputs['Color'], normal_node.inputs['Color']) links.new(normal_node.outputs['Normal'], bsdf.inputs['Normal']) mesh = bpy.data.meshes.new('CM_DripTray_Top_Mesh') mesh.from_pydata([(-0.216, -0.294, 0.098), (0.216, -0.294, 0.098), (0.216, -0.026, 0.098), (-0.216, -0.026, 0.098)], [], [[0, 1, 2, 3]]) mesh.update() uv = mesh.uv_layers.new(name='CM_Tray_UV') for loop, coord in zip(uv.data, [(0, 0), (1, 0), (1, 1), (0, 1)]): loop.uv = coord tray_top = bpy.data.objects.new('CM_DripTray_TextureSurface', mesh) cm.objects.link(tray_top) assign(tray_top, tray_mat) parent_keep(tray_top, drip) # Fixed red reading arrows and gauge construction helpers. def fixed_arrow(name, x, y, z, parent, direction): image = create_arrow_texture(direction, TEX / ('arrow_left.png' if direction < 0 else 'arrow_right.png')) mat = material(name + '_DecalMaterial', (0.72, 0.025, 0.018), 0.0, 0.85) bsdf = mat.node_tree.nodes.get('Principled BSDF') bsdf.inputs['Specular IOR Level'].default_value = 0.0 node = mat.node_tree.nodes.new('ShaderNodeTexImage') node.image = image mat.node_tree.links.new(node.outputs['Color'], bsdf.inputs['Base Color']) mat.node_tree.links.new(node.outputs['Alpha'], bsdf.inputs['Alpha']) if hasattr(mat, 'surface_render_method'): mat.surface_render_method = 'DITHERED' width = 0.028 height = 0.018 mesh = bpy.data.meshes.new(name + '_DecalMesh') mesh.from_pydata([(x - width / 2, y, z - height / 2), (x + width / 2, y, z - height / 2), (x + width / 2, y, z + height / 2), (x - width / 2, y, z + height / 2)], [], [[0, 1, 2, 3]]) mesh.update() uv = mesh.uv_layers.new(name='CM_Decal_UV') for loop, coord in zip(uv.data, [(0, 0), (1, 0), (1, 1), (0, 1)]): loop.uv = coord obj = bpy.data.objects.new(name, mesh) cm.objects.link(obj) assign(obj, mat) parent_keep(obj, parent) if hasattr(obj, 'visible_shadow'): obj.visible_shadow = False obj['representation'] = 'decal_texture' obj['flush_offset_m'] = 0.0003 return obj import sys if str(OUT) not in sys.path: sys.path.insert(0, str(OUT)) from dial_textures import create_dial_texture, create_arrow_texture def face_material(name, image): mat = material(name, (0.88, 0.87, 0.80), 0.0, 0.85) bsdf = mat.node_tree.nodes.get('Principled BSDF') bsdf.inputs['Specular IOR Level'].default_value = 0.0 node = mat.node_tree.nodes.new('ShaderNodeTexImage') node.image = image mat.node_tree.links.new(node.outputs['Color'], bsdf.inputs['Base Color']) mat.node_tree.links.new(node.outputs['Color'], bsdf.inputs['Emission Color']) bsdf.inputs['Emission Strength'].default_value = 0.15 return mat def front_texture(name, center, radius, mat, parent): x, y, z = center segments = 48 vertices = [(x, y, z)] uv_coords = [(0.5, 0.5)] for index in range(segments): angle = index * 2 * math.pi / segments dx = radius * math.cos(angle) dz = radius * math.sin(angle) vertices.append((x + dx, y, z + dz)) uv_coords.append((0.5 + dx / (2 * radius), 0.5 + dz / (2 * radius))) faces = [(0, index + 1, (index + 1) % segments + 1) for index in range(segments)] mesh = bpy.data.meshes.new(name + '_Mesh') mesh.from_pydata(vertices, [], faces) mesh.update() uv = mesh.uv_layers.new(name='CM_Dial_UV') for loop in mesh.loops: uv.data[loop.index].uv = uv_coords[loop.vertex_index] obj = bpy.data.objects.new(name, mesh) cm.objects.link(obj) assign(obj, mat) parent_keep(obj, parent) return obj CONTROL_ATLAS_LABELS = ['0°', '90°', '180°', '270°', '0%', '50%', '100%'] def create_control_label_atlas(filepath): atlas_scene = bpy.data.scenes.new('CM_ControlLabelAtlas_Temp') bpy.context.window.scene = atlas_scene atlas_scene.render.engine = 'CYCLES' atlas_scene.cycles.samples = 8 atlas_scene.cycles.use_denoising = False atlas_scene.render.resolution_x = 2048 atlas_scene.render.resolution_y = 512 atlas_scene.render.resolution_percentage = 100 atlas_scene.render.image_settings.file_format = 'PNG' atlas_scene.render.image_settings.color_mode = 'RGBA' atlas_scene.render.film_transparent = True atlas_scene.render.filepath = str(filepath) atlas_scene.view_settings.view_transform = 'Standard' atlas_scene.view_settings.exposure = 0.0 ink_material = bpy.data.materials.new('CM_ControlLabelAtlas_Ink') ink_material.use_nodes = True nodes = ink_material.node_tree.nodes nodes.clear() emission = nodes.new('ShaderNodeEmission') emission.inputs['Color'].default_value = (0.008, 0.012, 0.015, 1.0) emission.inputs['Strength'].default_value = 1.0 output = nodes.new('ShaderNodeOutputMaterial') ink_material.node_tree.links.new(emission.outputs[0], output.inputs['Surface']) font_curves = [] metrics = {} for index, body in enumerate(CONTROL_ATLAS_LABELS): curve = bpy.data.curves.new('CM_AtlasGlyph_' + str(index), 'FONT') curve.body = body curve.size = 1.0 curve.align_x = 'LEFT' curve.align_y = 'CENTER' curve.resolution_u = 12 font_curves.append(curve) obj = bpy.data.objects.new('CM_AtlasGlyph_' + str(index), curve) atlas_scene.collection.objects.link(obj) curve.materials.append(ink_material) bpy.context.view_layer.update() bounds = [Vector(corner) for corner in obj.bound_box] min_x = min(corner.x for corner in bounds) max_x = max(corner.x for corner in bounds) min_y = min(corner.y for corner in bounds) max_y = max(corner.y for corner in bounds) width = max_x - min_x height = max_y - min_y scale = min(3.6 / width, 1.6 / height) width *= scale height *= scale obj.scale = (scale, scale, scale) obj.location = ( (index % 4 - 1.5) * 4 - (min_x + max_x) * scale / 2, (index // 4 - 0.5) * 2 - (min_y + max_y) * scale / 2, 0, ) metrics[body] = (width, height) camera_data = bpy.data.cameras.new('CM_ControlLabelAtlas_Camera') camera_data.type = 'ORTHO' camera_data.ortho_scale = 16.0 camera_obj = bpy.data.objects.new('CM_ControlLabelAtlas_Camera', camera_data) atlas_scene.collection.objects.link(camera_obj) camera_obj.location = (0, 0, 10) atlas_scene.camera = camera_obj bpy.context.view_layer.update() bpy.ops.render.render(write_still=True, scene=atlas_scene.name) bpy.context.window.scene = scene image = bpy.data.images.load(str(filepath), check_existing=False) image.name = 'CM_ControlLabelAtlas' image.pack() for obj in list(atlas_scene.objects): bpy.data.objects.remove(obj, do_unlink=True) bpy.data.scenes.remove(atlas_scene) for curve in font_curves: if curve.users == 0: bpy.data.curves.remove(curve) if camera_data.users == 0: bpy.data.cameras.remove(camera_data) if ink_material.users == 0: bpy.data.materials.remove(ink_material) return image, metrics def printed_label_material(image): mat = material('CM_PrintedLabel_AtlasMaterial', (0.008, 0.012, 0.015), 0.0, 0.85) bsdf = mat.node_tree.nodes.get('Principled BSDF') bsdf.inputs['Specular IOR Level'].default_value = 0.0 node = mat.node_tree.nodes.new('ShaderNodeTexImage') node.image = image mat.node_tree.links.new(node.outputs['Color'], bsdf.inputs['Base Color']) mat.node_tree.links.new(node.outputs['Alpha'], bsdf.inputs['Alpha']) if hasattr(mat, 'surface_render_method'): mat.surface_render_method = 'DITHERED' if hasattr(mat, 'use_backface_culling'): mat.use_backface_culling = True return mat control_label_atlas, control_label_metrics = create_control_label_atlas(TEX / 'control_label_atlas.png') control_label_material = printed_label_material(control_label_atlas) def printed_labels(prefix, pivot, kind): direction = -1 if kind.startswith('hot') else 1 maximum = 270 if direction < 0 else 100 labels = [(0, '0°'), (90, '90°'), (180, '180°'), (270, '270°')] if direction < 0 else [(0, '0%'), (50, '50%'), (100, '100%')] x, y, z = pivot.location for value, body in labels: atlas_width, atlas_height = control_label_metrics[body] natural_aspect = atlas_width / atlas_height glyph_height = min(0.005, 0.017 / natural_aspect) glyph_width = glyph_height * natural_aspect patch_width = glyph_width * 4.0 / atlas_width patch_height = glyph_height * 2.0 / atlas_height axial_center = 0.014 + glyph_width / 2 radius_center = 0.0348 - 0.009 * axial_center / 0.03 angle_height = patch_height / radius_center center_angle = math.radians(180 + value * 270 / maximum) vertices = [] uv_coords = [] width_segments = 4 height_segments = 8 cell = CONTROL_ATLAS_LABELS.index(body) for ix in range(width_segments + 1): u = ix / width_segments axial = axial_center + direction * (u - 0.5) * patch_width radius = 0.0348 - 0.009 * axial / 0.03 for iy in range(height_segments + 1): v = iy / height_segments angle = center_angle - (v - 0.5) * angle_height normal = Vector((direction * 0.3, math.cos(angle), math.sin(angle))).normalized() point = Vector((x + direction * axial, y + radius * math.cos(angle), z + radius * math.sin(angle))) + normal * 0.00004 vertices.append(point) uv_coords.append(((cell % 4 + u) / 4, (cell // 4 + v) / 2)) faces = [] for ix in range(width_segments): for iy in range(height_segments): a = ix * (height_segments + 1) + iy face = (a, a + height_segments + 1, a + height_segments + 2, a + 1) faces.append(face) mesh = bpy.data.meshes.new(prefix + '_PrintedLabel_' + str(value) + '_Mesh') mesh.from_pydata(vertices, [], faces) mesh.update() uv = mesh.uv_layers.new(name='CM_PrintedLabel_UV') for loop in mesh.loops: uv.data[loop.index].uv = uv_coords[loop.vertex_index] for polygon in mesh.polygons: polygon.use_smooth = True obj = bpy.data.objects.new(prefix + '_PrintedLabel_' + str(value), mesh) cm.objects.link(obj) assign(obj, control_label_material) parent_keep(obj, pivot) if hasattr(obj, 'visible_shadow'): obj.visible_shadow = False obj['representation'] = 'vector_text_uv_decal' obj['printed_text'] = body obj['font'] = 'Blender Bfont' obj['glyph_height_m'] = glyph_height obj['natural_aspect_ratio'] = natural_aspect obj['atlas_cell_aspect_ratio'] = 2.0 obj['surface_offset_m'] = 0.00004 obj['baseline_axis'] = 'X' def conical_dial(prefix, pivot, kind): segments = 64 height = 0.03 bottom_radius = 0.0348 top_radius = 0.0258 direction = -1 if kind.startswith('hot') else 1 x, y, z = pivot.location vertices = [] for radius, axial_offset in [(bottom_radius, 0), (top_radius, direction * height)]: for index in range(segments): angle = index * 2 * math.pi / segments vertices.append((x + axial_offset, y + radius * math.cos(angle), z + radius * math.sin(angle))) faces = [] for index in range(segments): next_index = (index + 1) % segments faces.append((index, next_index, segments + next_index, segments + index)) faces.append(tuple(reversed(range(segments)))) faces.append(tuple(range(segments, segments * 2))) if direction < 0: faces = [tuple(reversed(face)) for face in faces] mesh = bpy.data.meshes.new(prefix + '_ConicalMesh') mesh.from_pydata(vertices, [], faces) mesh.update() image = create_dial_texture(kind, TEX / (kind + '.png')) obj = bpy.data.objects.new(prefix + '_ConicalSide', mesh) cm.objects.link(obj) assign(obj, face_material(prefix + '_TextureMaterial', image)) assign(obj, steel_light) uv = mesh.uv_layers.new(name='CM_Conical_UV') for polygon in mesh.polygons: polygon.material_index = 0 if polygon.index < segments else 1 polygon.use_smooth = polygon.index < segments for loop_index in polygon.loop_indices: vertex_index = mesh.loops[loop_index].vertex_index if polygon.index < segments: segment_index = polygon.index u = segment_index / segments if vertex_index in [segment_index, segments + segment_index] else (segment_index + 1) / segments v = 0.0 if vertex_index < segments else 1.0 uv.data[loop_index].uv = (u, v) else: uv.data[loop_index].uv = (0.5, 0.5) parent_keep(obj, pivot) printed_labels(prefix, pivot, kind) pivot['mount_plane'] = 'YOZ' pivot['mount_side'] = 'left' if kind.startswith('hot') else 'right' pivot['dial_axis'] = 'X' pivot['shape'] = 'frustum' pivot['height_m'] = height pivot['outward_direction'] = direction pivot['arrow_location'] = 'front' prop = 'hot_water_open' if kind.startswith('hot') else 'brew_flow' driver(pivot, prop, f'-value * {math.radians(270)}', index=0) def gauge(prefix, center, radius, needle_mat, label, unit, prop, parent=root): x, y, z = center assembly = empty(prefix, center, parent) cylinder(prefix + '_Case', (x, y + 0.004, z), radius, 0.014, steel_dark, 'Y', 32, 0.0015, assembly) torus(prefix + '_Bezel', (x, y - 0.005, z), radius - 0.002, 0.0025, steel_light, 'Y', assembly) cylinder(prefix + '_Face', (x, y - 0.006, z), radius - 0.005, 0.002, ivory, 'Y', 32, 0.0003, assembly) kind = 'temperature' if label == 'TEMP' else 'flow_gauge' image = create_dial_texture(kind, TEX / (kind + '.png')) front_texture(prefix + '_Texture', (x, y - 0.0072, z), radius - 0.005, face_material(prefix + '_TextureMaterial', image), assembly) needle = empty(prefix + '_Needle', center, assembly, 0.01) mesh_face(prefix + '_NeedleShape', [(x - 0.007, y - 0.0105, z - 0.0015), (x + radius * 0.72, y - 0.0105, z), (x - 0.007, y - 0.0105, z + 0.0015)], needle_mat, needle) cylinder(prefix + '_NeedleHub', (x, y - 0.011, z), 0.0035, 0.002, needle_mat, 'Y', 20, 0.0003, assembly) sweep = math.pi if prop == 'brew_flow' else math.pi / 100 driver(needle, prop, f'(value * {sweep}) - {math.pi}') return assembly def top_control(prefix, pivot, current_degrees, hot=False): x, y, z = pivot.location direction = -1 if hot else 1 angle = math.radians(135 + current_degrees) dy = math.cos(angle) dz = math.sin(angle) cylinder(prefix + '_TopCap', (x + direction * 0.008, y, z), 0.0234, 0.016, steel_dark, 'X', 32, 0.002, pivot) rod(prefix + '_Stem', (x + direction * 0.016, y, z), (x + direction * 0.030, y + dy * 0.040, z + dz * 0.068), 0.0055, steel_light, 20, pivot) rod(prefix + '_Grip', (x + direction * 0.026, y + dy * 0.032, z + dz * 0.058), (x + direction * 0.043, y + dy * 0.072, z + dz * 0.125), 0.0105, rubber, 24, pivot) if hot: rod(prefix + '_RedMarker', (x + direction * 0.017, y, z), (x + direction * 0.017, y + dy * 0.026, z + dz * 0.026), 0.0018, red, 8, pivot) pivot['mount_plane'] = 'YOZ' pivot['mount_side'] = 'left' if hot else 'right' pivot['dial_axis'] = 'X' pivot['connector_radius_m'] = 0.0234 pivot['dial_top_radius_m'] = 0.0258 prop = 'hot_water_open' if hot else 'brew_flow' driver(pivot, prop, f'-value * {math.radians(270)}', index=0) # Left side-mounted frustum, with the narrow top and handle facing outward. hot_dial = empty('CM_HotWaterDial', (-0.235, -0.095, 0.337), root) conical_dial('CM_HotWaterDial', hot_dial, 'hot_water_conical') hot_valve = empty('CM_HotWaterValve', (-0.265, -0.095, 0.337), root) top_control('CM_HotWaterValve', hot_valve, 0.0, hot=True) fixed_arrow('CM_HotWaterValve_FixedArrow', -0.214, -0.1593, 0.337, body, -1) # Two enlarged meters remain on the front panel. temp_gauge = gauge('CM_TempGauge', (-0.112, -0.169, 0.337), 0.048, orange, 'TEMP', '°C', 'temperature_c') flow_gauge = gauge('CM_FlowGauge', (0.112, -0.169, 0.337), 0.048, teal, 'FLOW', '%', 'brew_flow') # Right side-mounted frustum uses the same relationship. flow_dial = empty('CM_FlowDial', (0.235, -0.095, 0.337), root) conical_dial('CM_FlowDial', flow_dial, 'flow_dial_conical') flow_lever = empty('CM_FlowLever', (0.265, -0.095, 0.337), root) top_control('CM_FlowLever', flow_lever, 0.0) fixed_arrow('CM_FlowLever_FixedArrow', 0.214, -0.1593, 0.337, body, 1) # Convert the brand text so the GLB does not depend on font objects. bpy.ops.object.select_all(action='DESELECT') font_objects = [obj for obj in cm.objects if obj.type == 'FONT'] for obj in font_objects: obj.select_set(True) if font_objects: bpy.context.view_layer.objects.active = font_objects[0] bpy.ops.object.convert(target='MESH') bpy.ops.object.select_all(action='DESELECT') scene.frame_set(1) bpy.context.view_layer.update() # Studio setup is intentionally separate from the exported asset. floor_mat = material('Studio_Warm_Background', (0.19, 0.22, 0.23), 0.0, 0.72) bpy.ops.mesh.primitive_plane_add(size=200, location=(0, 0, -0.002)) floor = bpy.context.object floor.name = 'Studio_Floor' move_to(floor, studio) assign(floor, floor_mat) world = bpy.data.worlds.new('Studio_World') scene.world = world world.use_nodes = True world.node_tree.nodes['Background'].inputs['Color'].default_value = (0.16, 0.19, 0.22, 1) world.node_tree.nodes['Background'].inputs['Strength'].default_value = 0.45 def area_light(name, loc, energy, size, color, target=(0, 0, 0.24)): data = bpy.data.lights.new(name, 'AREA') data.energy = energy data.shape = 'DISK' data.size = size data.color = color obj = bpy.data.objects.new(name, data) studio.objects.link(obj) obj.location = loc obj.rotation_euler = (Vector(target) - obj.location).to_track_quat('-Z', 'Y').to_euler() area_light('Studio_Key', (-0.65, -0.8, 1.15), 90, 0.75, (1.0, 0.87, 0.72)) area_light('Studio_Fill', (0.75, -0.45, 0.75), 65, 0.65, (0.72, 0.85, 1.0)) area_light('Studio_Rim', (0.1, 0.65, 1.0), 110, 0.6, (1.0, 0.95, 0.85)) def camera(name, loc, target, scale): data = bpy.data.cameras.new(name) data.type = 'ORTHO' data.ortho_scale = scale data.lens = 60 obj = bpy.data.objects.new(name, data) studio.objects.link(obj) obj.location = loc obj.rotation_euler = (Vector(target) - obj.location).to_track_quat('-Z', 'Y').to_euler() return obj front_camera = camera('Acceptance_Front_0deg', (0, -1.8, 0.25), (0, -0.02, 0.25), 0.68) angle_camera = camera('Acceptance_30deg', (0.8, -1.3856, 1.1738), (0, -0.02, 0.25), 0.78) right_camera = camera('Acceptance_Right_YOZ', (1.8, 0, 0.25), (0, 0, 0.25), 1.02) left_camera = camera('Acceptance_Left_YOZ', (-1.8, 0, 0.25), (0, 0, 0.25), 1.02) controls_camera = camera('Acceptance_Controls_Front_XOZ', (0, -1.8, 0.337), (0, -0.095, 0.337), 0.64) brew_camera = camera('Acceptance_Brew_Interface', (0.32, BREW_Y - 0.398, 0.060 + BREW_LIFT), (0, BREW_Y, 0.174 + BREW_LIFT), 0.25) bowl_camera = camera('Acceptance_Portafilter_Bowl', (0.25, BREW_Y - 0.308, 0.49 + BREW_LIFT), (0, BREW_Y - 0.028, 0.17 + BREW_LIFT), 0.25) scene.render.engine = 'CYCLES' scene.cycles.samples = 40 scene.cycles.use_denoising = True scene.render.resolution_x = 1100 scene.render.resolution_y = 1100 scene.render.resolution_percentage = 100 scene.render.image_settings.file_format = 'PNG' scene.render.image_settings.color_mode = 'RGBA' scene.render.film_transparent = False scene.view_settings.view_transform = 'AgX' scene.view_settings.exposure = -0.35 # Export only the machine collection, with current driven poses and packed textures. bpy.ops.object.select_all(action='DESELECT') for obj in cm.all_objects: obj.select_set(True) bpy.context.view_layer.objects.active = root bpy.ops.export_scene.gltf( filepath=str(OUT / 'PerfectCoffee_CoffeeMachine.glb'), export_format='GLB', use_selection=True, export_apply=True, export_animations=False, export_extras=True, ) bpy.ops.object.select_all(action='DESELECT') scene.camera = front_camera for screen in bpy.data.screens: for area in screen.areas: if area.type == 'VIEW_3D': area.spaces.active.region_3d.view_perspective = 'CAMERA' area.spaces.active.shading.type = 'MATERIAL' bpy.ops.wm.save_as_mainfile(filepath=str(OUT / 'PerfectCoffee_CoffeeMachine.blend')) required = ['CM_Body', 'CM_GroupHead', 'CM_HotWaterValve', 'CM_HotWaterDial', 'CM_TempGauge', 'CM_FlowGauge', 'CM_FlowLever', 'CM_FlowDial', 'CM_Portafilter', 'CM_DripTray'] driver_count = sum(len(obj.animation_data.drivers) for obj in cm.all_objects if obj.animation_data) report = {'required_objects': {}, 'camera_bounds': {}, 'mesh_objects': 0, 'vertices': 0, 'polygons': 0, 'drivers': driver_count} for name in required: obj = bpy.data.objects.get(name) report['required_objects'][name] = obj is not None for obj in cm.all_objects: if obj.type == 'MESH': report['mesh_objects'] += 1 report['vertices'] += len(obj.data.vertices) report['polygons'] += len(obj.data.polygons) for cam, label in [(front_camera, 'front'), (angle_camera, 'angle_30deg'), (right_camera, 'right_yoz'), (left_camera, 'left_yoz')]: scene.camera = cam bpy.context.view_layer.update() coverage = {} for name in required: obj = bpy.data.objects[name] points = [] for child in obj.children_recursive: if child.type == 'MESH': points.extend([child.matrix_world @ Vector(corner) for corner in child.bound_box]) if not points: continue projected = [world_to_camera_view(scene, cam, point) for point in points] bounds = [min(p.x for p in projected), max(p.x for p in projected), min(p.y for p in projected), max(p.y for p in projected)] coverage[name] = {'bounds': [round(v, 4) for v in bounds], 'inside_frame': all(0 <= p.x <= 1 and 0 <= p.y <= 1 and p.z > 0 for p in projected)} report['camera_bounds'][label] = coverage for cam, filename in [(front_camera, 'preview_front.png'), (angle_camera, 'preview_30deg.png'), (right_camera, 'preview_right.png'), (left_camera, 'preview_left.png')]: scene.camera = cam scene.render.filepath = str(OUT / filename) bpy.ops.render.render(write_still=True) scene.camera = controls_camera scene.render.resolution_x = 2400 scene.render.resolution_y = 1000 scene.render.filepath = str(OUT / 'preview_controls_front.png') bpy.ops.render.render(write_still=True) scene.camera = brew_camera scene.render.resolution_x = 1400 scene.render.resolution_y = 1400 scene.render.filepath = str(OUT / 'preview_brew_interface.png') bpy.ops.render.render(write_still=True) portafilter.rotation_euler.z = math.radians(-45) portafilter.location.y -= 0.035 portafilter.location.z -= 0.045 bpy.context.view_layer.update() scene.render.filepath = str(OUT / 'preview_portafilter_detached.png') bpy.ops.render.render(write_still=True) scene.camera = bowl_camera scene.render.filepath = str(OUT / 'preview_portafilter_bowl.png') bpy.ops.render.render(write_still=True) portafilter.rotation_euler.z = 0.0 portafilter.location.y += 0.035 portafilter.location.z += 0.045 bpy.context.view_layer.update() scene.render.resolution_x = 1100 scene.render.resolution_y = 1100 scene.camera = front_camera print('MODEL_VALIDATION=' + json.dumps(report), flush=True) print('MODEL_BUILD_COMPLETE', flush=True)