Files
PerfectCoffee/model_assets/milk_frother/build_milk_frother.py
T

790 lines
33 KiB
Python

import bpy
import bmesh
import math
import json
from pathlib import Path
from mathutils import Vector
OUT = Path(__file__).resolve().parent
OUT.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'
scene.unit_settings.scale_length = 1.0
model_collection = bpy.data.collections.new('MF_MilkFrother_Model')
studio_collection = bpy.data.collections.new('MF_Studio_Exclude_From_Export')
scene.collection.children.link(model_collection)
scene.collection.children.link(studio_collection)
text_labels = []
def move_to(obj, collection=model_collection):
for previous in list(obj.users_collection):
previous.objects.unlink(obj)
collection.objects.link(obj)
return obj
def parent_keep(obj, parent):
if parent is None:
return
bpy.context.view_layer.update()
obj.parent = parent
obj.matrix_parent_inverse = parent.matrix_world.inverted()
def material(name, color, metallic=0.0, roughness=0.4, coat=0.0):
mat = bpy.data.materials.new(name)
mat.use_nodes = True
mat.diffuse_color = (*color, 1.0)
shader = mat.node_tree.nodes.get('Principled BSDF')
shader.inputs['Base Color'].default_value = (*color, 1.0)
shader.inputs['Metallic'].default_value = metallic
shader.inputs['Roughness'].default_value = roughness
shader.inputs['Coat Weight'].default_value = coat
return mat
white = material('MF_Warm_White_Enamel', (0.83, 0.825, 0.79), 0.0, 0.24, 0.38)
chrome = material('MF_Polished_Chrome', (0.72, 0.76, 0.80), 1.0, 0.16, 0.25)
steel = material('MF_Brushed_Stainless', (0.53, 0.57, 0.60), 1.0, 0.28)
dark = material('MF_Dark_Grey', (0.055, 0.065, 0.07), 0.05, 0.48)
ink = material('MF_Function_Ink', (0.07, 0.08, 0.085), 0.0, 0.6)
scale_ink = material('MF_Measurement_Ink', (0.75, 0.78, 0.80), 0.0, 0.5)
button_face = material('MF_Start_Button_Satin', (0.52, 0.56, 0.60), 0.45, 0.28)
clear = material('MF_Clear_Tritan', (0.94, 0.98, 1.0), 0.0, 0.055)
clear_shader = clear.node_tree.nodes.get('Principled BSDF')
clear_shader.inputs['Transmission Weight'].default_value = 1.0
clear_shader.inputs['IOR'].default_value = 1.46
glass = material('MF_Clear_Single_Wall_Glass', (0.96, 0.985, 1.0))
nodes = glass.node_tree.nodes
nodes.clear()
glass_output = nodes.new('ShaderNodeOutputMaterial')
glass_output.name = 'Material Output'
glass_output.location = (720, 100)
clear_transmission = nodes.new('ShaderNodeBsdfTransparent')
clear_transmission.name = 'Clear transmission'
clear_transmission.location = (-520, 240)
glass_refraction = nodes.new('ShaderNodeBsdfGlass')
glass_refraction.name = 'Physical glass refraction'
glass_refraction.location = (-520, 20)
glass_refraction.inputs['Color'].default_value = (0.98, 0.99, 1.0, 1.0)
glass_refraction.inputs['Roughness'].default_value = 0.005
glass_refraction.inputs['IOR'].default_value = 1.46
thin_wall_mix = nodes.new('ShaderNodeMixShader')
thin_wall_mix.name = 'Clear thin-wall transmission'
thin_wall_mix.location = (-220, 180)
thin_wall_mix.inputs[0].default_value = 0.08
fresnel = nodes.new('ShaderNodeFresnel')
fresnel.name = 'Glass Fresnel IOR 1.46'
fresnel.location = (-220, -100)
fresnel.inputs['IOR'].default_value = 1.46
polished_reflection = nodes.new('ShaderNodeBsdfAnisotropic')
polished_reflection.name = 'Polished glass reflections'
polished_reflection.location = (-220, -320)
polished_reflection.inputs['Color'].default_value = (1.0, 1.0, 1.0, 1.0)
polished_reflection.inputs['Roughness'].default_value = 0.0
fresnel_mix = nodes.new('ShaderNodeMixShader')
fresnel_mix.name = 'Glass Fresnel reflection'
fresnel_mix.location = (340, 120)
links = glass.node_tree.links
links.new(clear_transmission.outputs['BSDF'], thin_wall_mix.inputs[1])
links.new(glass_refraction.outputs['BSDF'], thin_wall_mix.inputs[2])
links.new(thin_wall_mix.outputs['Shader'], fresnel_mix.inputs[1])
links.new(polished_reflection.outputs['BSDF'], fresnel_mix.inputs[2])
links.new(fresnel.outputs['Fac'], fresnel_mix.inputs[0])
links.new(fresnel_mix.outputs['Shader'], glass_output.inputs['Surface'])
export_glass = material('MF_GLTF_Clear_Glass', (0.98, 0.99, 1.0), 0.0, 0.005)
export_glass_shader = export_glass.node_tree.nodes.get('Principled BSDF')
export_glass_shader.inputs['Transmission Weight'].default_value = 1.0
export_glass_shader.inputs['IOR'].default_value = 1.46
def bevel(obj, width=0.001, segments=4, weighted=True):
if width > 0:
mod = obj.modifiers.new('MF_Soft_Edges', 'BEVEL')
mod.width = width
mod.segments = segments
if weighted and obj.type == 'MESH':
normal = obj.modifiers.new('MF_Weighted_Normals', 'WEIGHTED_NORMAL')
normal.keep_sharp = True
normal.weight = 50
def assign(obj, mat):
obj.data.materials.append(mat)
def empty(name, parent=None):
obj = bpy.data.objects.new(name, None)
model_collection.objects.link(obj)
obj.empty_display_type = 'PLAIN_AXES'
obj.empty_display_size = 0.018
parent_keep(obj, parent)
return obj
root = empty('MilkFrother_Root')
root['front_axis'] = '+Y'
root['up_axis'] = '+Z'
root['brand_markings_removed'] = True
root['control_type'] = 'Single press START button; no rotary program selector'
base_root = empty('MF_Base_Assembly', root)
jug_root = empty('MF_Jug_Assembly', root)
lid_root = empty('MF_Lid_Assembly', jug_root)
control_root = empty('MF_Control_Assembly', base_root)
def lathe(name, profile, mat, segments=192, parent=root, close_profile=True):
vertices = []
rings = []
for radius, height in profile:
if radius <= 1e-9:
rings.append([len(vertices)])
vertices.append((0.0, 0.0, height))
else:
ring = []
for index in range(segments):
angle = index * math.tau / segments
ring.append(len(vertices))
vertices.append((radius * math.cos(angle), radius * math.sin(angle), height))
rings.append(ring)
faces = []
for ring_index in range(len(rings) if close_profile else len(rings) - 1):
first = rings[ring_index]
second = rings[(ring_index + 1) % len(rings)]
if len(first) == 1 and len(second) == 1:
continue
for index in range(segments):
next_index = (index + 1) % segments
if len(first) == 1:
faces.append((first[0], second[next_index], second[index]))
elif len(second) == 1:
faces.append((first[index], first[next_index], second[0]))
else:
faces.append((first[index], first[next_index], second[next_index], second[index]))
mesh = bpy.data.meshes.new(name + '_Mesh')
mesh.from_pydata(vertices, [], faces)
mesh.update()
bm = bmesh.new()
bm.from_mesh(mesh)
bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
bm.to_mesh(mesh)
bm.free()
obj = bpy.data.objects.new(name, mesh)
model_collection.objects.link(obj)
assign(obj, mat)
for polygon in mesh.polygons:
polygon.use_smooth = True
parent_keep(obj, parent)
return obj
def box(name, loc, dims, mat, edge=0.001, parent=root, rotation=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)
if rotation is not None:
obj.rotation_euler = rotation
move_to(obj)
assign(obj, mat)
bevel(obj, edge, 5)
parent_keep(obj, parent)
return obj
def cylinder(name, loc, radius, depth, mat, axis='Z', edge=0.0005, parent=root, vertices=96):
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 polygon in obj.data.polygons:
polygon.use_smooth = len(polygon.vertices) == 4
bevel(obj, edge, 4)
parent_keep(obj, parent)
return obj
def torus(name, loc, major, minor, mat, parent=root, axis='Z'):
rotation = (-math.pi / 2, 0, 0) if axis == 'Y' else (0, 0, 0)
bpy.ops.mesh.primitive_torus_add(
major_segments=128,
minor_segments=24,
location=loc,
rotation=rotation,
major_radius=major,
minor_radius=minor,
)
obj = bpy.context.object
obj.name = name
move_to(obj)
assign(obj, mat)
for polygon in obj.data.polygons:
polygon.use_smooth = True
parent_keep(obj, parent)
return obj
def line(name, points, radius, mat, parent=root):
data = bpy.data.curves.new(name + '_Curve', 'CURVE')
data.dimensions = '3D'
data.resolution_u = 12
data.bevel_depth = radius
data.bevel_resolution = 4
spline = data.splines.new('POLY')
spline.points.add(len(points) - 1)
for point, value in zip(spline.points, points):
point.co = (*value, 1.0)
obj = bpy.data.objects.new(name, data)
model_collection.objects.link(obj)
assign(obj, mat)
parent_keep(obj, parent)
return obj
def text_mesh(name, body, loc, size, mat, parent=root):
data = bpy.data.curves.new(name + '_Font', 'FONT')
data.body = body
data.size = size
data.align_x = 'CENTER'
data.align_y = 'CENTER'
data.space_character = 1.05
data.resolution_u = 8
obj = bpy.data.objects.new(name, data)
model_collection.objects.link(obj)
obj.location = loc
obj.rotation_euler = (-math.pi / 2, 0, 0)
obj['marking_text'] = body
assign(obj, mat)
parent_keep(obj, parent)
text_labels.append(body)
bpy.ops.object.select_all(action='DESELECT')
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
bpy.ops.object.convert(target='MESH')
return bpy.context.object
def handle_mesh():
path = []
for index in range(10):
factor = index / 9
path.append((0.055 + 0.037 * factor, 0.218))
for index in range(1, 25):
factor = index / 24
y = (1 - factor) ** 2 * 0.092 + 2 * (1 - factor) * factor * 0.106 + factor ** 2 * 0.106
z = (1 - factor) ** 2 * 0.218 + 2 * (1 - factor) * factor * 0.218 + factor ** 2 * 0.204
path.append((y, z))
for index in range(1, 21):
factor = index / 20
path.append((0.106, 0.204 - 0.049 * factor))
width = 0.010
thickness = 0.006
corner = 0.0016
section = [
(-width / 2 + corner, -thickness / 2), (width / 2 - corner, -thickness / 2),
(width / 2, -thickness / 2 + corner), (width / 2, thickness / 2 - corner),
(width / 2 - corner, thickness / 2), (-width / 2 + corner, thickness / 2),
(-width / 2, thickness / 2 - corner), (-width / 2, -thickness / 2 + corner),
]
vertices = []
for index, (y, z) in enumerate(path):
previous = Vector(path[max(0, index - 1)])
following = Vector(path[min(len(path) - 1, index + 1)])
tangent = (following - previous).normalized()
normal = Vector((-tangent.y, tangent.x))
for x, offset in section:
vertices.append((x, y + normal.x * offset, z + normal.y * offset))
faces = []
section_count = len(section)
for ring in range(len(path) - 1):
for index in range(section_count):
next_index = (index + 1) % section_count
first = ring * section_count
second = (ring + 1) * section_count
faces.append((first + index, first + next_index, second + next_index, second + index))
faces.append(tuple(reversed(range(section_count))))
faces.append(tuple((len(path) - 1) * section_count + index for index in range(section_count)))
mesh = bpy.data.meshes.new('MF_Handle_Frame_Mesh')
mesh.from_pydata(vertices, [], faces)
mesh.update()
bm = bmesh.new()
bm.from_mesh(mesh)
bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
bm.to_mesh(mesh)
bm.free()
obj = bpy.data.objects.new('MF_Handle_Frame', mesh)
model_collection.objects.link(obj)
assign(obj, glass)
for polygon in mesh.polygons:
polygon.use_smooth = True
bevel(obj, 0.00055, 4)
obj['construction'] = 'Open U-shaped grip; single upper mount; free lower end'
parent_keep(obj, jug_root)
return obj
lathe('MF_Chrome_Base', [
(0, 0.007), (0.051, 0.007), (0.059, 0.009), (0.063, 0.014),
(0.0635, 0.022), (0.061, 0.026), (0, 0.026),
], chrome, parent=base_root)
for index, angle in enumerate((45, 135, 225, 315), 1):
radians = math.radians(angle)
box(
f'MF_Base_Foot_{index:02d}',
(0.052 * math.cos(radians), 0.052 * math.sin(radians), 0.0075),
(0.020, 0.023, 0.015), chrome, 0.0035, base_root,
(0, 0, radians),
)
lathe('MF_Base_Seam', [
(0.0598, 0.0245), (0.0610, 0.0245), (0.0610, 0.0260), (0.0598, 0.0260),
], dark, parent=base_root)
lathe('MF_White_Housing', [
(0, 0.020), (0.052, 0.020), (0.058, 0.022), (0.061, 0.028),
(0.0613, 0.037), (0.0606, 0.053), (0.0592, 0.077),
(0.0569, 0.103), (0.0538, 0.128), (0.0515, 0.139), (0, 0.139),
], white, parent=base_root)
lathe('MF_Neck_Collar', [
(0.048, 0.136), (0.052, 0.136), (0.0523, 0.141),
(0.0504, 0.150), (0.0515, 0.153), (0.048, 0.153),
], chrome, parent=base_root)
cylinder('MF_Base_Support_Pad', (0, 0, 0.151), 0.046, 0.004, dark, edge=0.0006, parent=base_root)
jug_body = lathe('MF_Jug_Outer', [
(0, 0.153), (0.042, 0.153), (0.049, 0.154), (0.052, 0.157),
(0.0535, 0.164), (0.0555, 0.217), (0.0560, 0.226), (0.0560, 0.228),
], glass, parent=jug_root, close_profile=False)
glass_wall = jug_body.modifiers.new('MF_Single_Glass_Wall', 'SOLIDIFY')
glass_wall.thickness = 0.0014
glass_wall.offset = -1.0
glass_wall.use_even_offset = True
glass_wall.use_quality_normals = True
jug_body['construction'] = 'Single-wall transparent glass with integral bottom and pouring lip'
jug_body['glass_wall_thickness_m'] = 0.0014
torus('MF_Jug_Rolled_Rim', (0, 0, 0.228), 0.0551, 0.00115, glass, jug_root)
def stretch_spout(obj):
bpy.context.view_layer.update()
matrix = obj.matrix_world.copy()
inverse = matrix.inverted()
maximum_extension = 0.0
for vertex in obj.data.vertices:
point = matrix @ vertex.co
if point.z < 0.202 or math.hypot(point.x, point.y) < 0.02:
continue
angle = math.atan2(point.y, point.x)
delta = math.atan2(math.sin(angle + math.pi / 2), math.cos(angle + math.pi / 2))
angular = max(0.0, 1.0 - abs(delta) / 0.42) ** 1.25
vertical = min(1.0, max(0.0, (point.z - 0.202) / 0.027)) ** 2
weight = angular * vertical
extension = 0.012 * weight
point.y -= extension
point.z += 0.004 * weight
vertex.co = inverse @ point
maximum_extension = max(maximum_extension, extension)
obj.data.update()
obj['spout_construction'] = 'Continuous jug wall and rim stretched into a pouring lip; no separate patch'
return maximum_extension
spout_extension = max(
stretch_spout(bpy.data.objects['MF_Jug_Outer']),
stretch_spout(bpy.data.objects['MF_Jug_Rolled_Rim']),
)
handle_mesh()
box('MF_Handle_Mount_Upper', (0, 0.055, 0.214), (0.014, 0.012, 0.018), chrome, 0.003, jug_root)
cylinder('MF_Lid_Clear_Disk', (0, 0, 0.231), 0.0575, 0.0025, clear, edge=0.0008, parent=lid_root, vertices=192)
torus('MF_Lid_Clear_Rim', (0, 0, 0.231), 0.0565, 0.0013, clear, lid_root)
cylinder('MF_Measuring_Cap', (0, 0, 0.236), 0.022, 0.006, clear, edge=0.0012, parent=lid_root, vertices=128)
torus('MF_Measuring_Cap_Rim', (0, 0, 0.239), 0.017, 0.0016, clear, lid_root)
box('MF_Measuring_Cap_Grip', (0, 0, 0.2405), (0.026, 0.005, 0.003), clear, 0.0013, lid_root)
for side, x in [('Left', -0.058), ('Right', 0.058)]:
box(f'MF_Lid_Tab_{side}', (x, 0, 0.230), (0.008, 0.013, 0.0022), clear, 0.0009, lid_root)
cylinder('MF_Start_Bezel', (0, 0.0600, 0.063), 0.0135, 0.006, chrome, 'Y', 0.0009, control_root, 128)
cylinder('MF_Start_Button', (0, 0.0635, 0.063), 0.0103, 0.0032, button_face, 'Y', 0.0008, control_root, 128)
text_mesh('MF_Start_Label', 'START', (0, 0.06525, 0.063), 0.0028, ink, control_root)
cylinder('MF_Whisk_Central_Pin', (0, 0, 0.168), 0.0038, 0.014, chrome, edge=0.0006, parent=jug_root)
lathe('MF_Whisk_Disk', [
(0, 0.162), (0.014, 0.162), (0.017, 0.163), (0.017, 0.165), (0.014, 0.166), (0, 0.166),
], steel, parent=jug_root)
torus('MF_Whisk_Notched_Ring', (0, 0, 0.166), 0.0125, 0.0020, chrome, jug_root)
for index in range(32):
angle = index * math.tau / 32
box(
f'MF_Whisk_Tooth_{index + 1:02d}',
(0.0155 * math.cos(angle), 0.0155 * math.sin(angle), 0.165),
(0.004, 0.0021, 0.003), chrome, 0.00045, jug_root,
(0, 0, angle),
)
fill_levels = [('Minimum', 0.174), ('Half', 0.192), ('Maximum', 0.211)]
for label, height in fill_levels:
line(f'MF_Fill_Line_{label}_{height:.3f}', [(-0.010, -0.0522, height), (0.006, -0.0522, height)], 0.00016, scale_ink, jug_root)
label_object = text_mesh(f'MF_Fill_Text_{label}_{height:.3f}', label, (0.011, -0.0520, height), 0.0027, scale_ink, jug_root)
label_object.rotation_euler = (math.pi / 2, 0, 0)
for obj in list(model_collection.objects):
if obj.type == 'CURVE':
bpy.ops.object.select_all(action='DESELECT')
obj.select_set(True)
bpy.context.view_layer.objects.active = obj
bpy.ops.object.convert(target='MESH')
scene['reference_product'] = 'MFF11WHEU reference shape; unbranded local reinterpretation'
scene['reference_images'] = 'reference_images/milk_frother/SMEG_MFF11WHEU_01.jpg ... _06.jpg'
scene['front_axis'] = '+Y'
scene['modifications'] = 'No trademarks; one push START button; no rotary functions; handle and button on +Y front; single-wall glass jug body and glass handle; original clear lid retained'
studio = studio_collection
world = bpy.data.worlds.new('MF_Studio_World')
world.use_nodes = True
world.node_tree.nodes['Background'].inputs['Color'].default_value = (0.05, 0.05, 0.05, 1.0)
world.node_tree.nodes['Background'].inputs['Strength'].default_value = 1.0
scene.world = world
def aim(obj, target):
obj.rotation_euler = (Vector(target) - obj.location).to_track_quat('-Z', 'Y').to_euler()
def area_light(name, loc, energy, size, target=(0, 0, 0.12), color=(1, 1, 1)):
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
aim(obj, target)
return obj
area_light('MF_Key_Light', (0.25, 0.32, 0.46), 22, 0.30)
area_light('MF_Fill_Light', (-0.30, 0.15, 0.26), 13, 0.26)
area_light('MF_Rim_Light', (0.10, -0.30, 0.38), 26, 0.24)
area_light('MF_Front_Softbox', (0, 0.40, 0.18), 7, 0.22)
def camera(name, loc, target, ortho):
data = bpy.data.cameras.new(name)
data.type = 'ORTHO'
data.ortho_scale = ortho
data.clip_start = 0.001
data.clip_end = 100
obj = bpy.data.objects.new(name, data)
studio.objects.link(obj)
obj.location = loc
aim(obj, target)
return obj
hero_camera = camera('MF_Preview_Three_Quarter', (0.30, 0.48, 0.32), (0.023, 0.008, 0.122), 0.335)
front_camera = camera('MF_Preview_Front_Positive_Y', (0, 0.60, 0.145), (0.023, 0, 0.122), 0.320)
open_camera = camera('MF_Preview_Open_Lid', (0.16, 0.20, 0.50), (-0.015, 0, 0.155), 0.39)
spout_camera = camera('MF_Preview_Integrated_Spout', (0.12, -0.16, 0.27), (0, -0.057, 0.231), 0.075)
measurement_camera = camera('MF_Preview_Measurements', (0.13, -0.20, 0.245), (0.002, -0.052, 0.193), 0.145)
separated_camera = camera('MF_Preview_Separated', (0.30, 0.48, 0.36), (0, 0, 0.170), 0.43)
scene.camera = hero_camera
scene.render.engine = 'CYCLES'
scene.cycles.samples = 72
scene.cycles.use_denoising = True
scene.render.resolution_x = 1200
scene.render.resolution_y = 1200
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.0
glass_export_slots = []
for obj in model_collection.all_objects:
if obj.type != 'MESH':
continue
for slot in obj.material_slots:
if slot.material == glass:
glass_export_slots.append(slot)
slot.material = export_glass
glass.name = 'MF_Clear_Single_Wall_Glass_Blender'
export_glass.name = 'MF_Clear_Single_Wall_Glass'
bpy.ops.object.select_all(action='DESELECT')
for obj in model_collection.all_objects:
obj.select_set(True)
bpy.context.view_layer.objects.active = root
bpy.ops.export_scene.gltf(
filepath=str(OUT / 'PerfectCoffee_MilkFrother.glb'),
export_format='GLB',
use_selection=True,
export_apply=True,
export_animations=False,
export_extras=True,
)
bpy.ops.object.select_all(action='DESELECT')
def export_assembly(assembly, filename):
bpy.ops.object.select_all(action='DESELECT')
assembly.select_set(True)
for obj in assembly.children_recursive:
obj.select_set(True)
bpy.context.view_layer.objects.active = assembly
bpy.ops.export_scene.gltf(
filepath=str(OUT / filename),
export_format='GLB',
use_selection=True,
export_apply=True,
export_animations=False,
export_extras=True,
)
export_assembly(base_root, 'PerfectCoffee_MilkFrother_Base.glb')
export_assembly(jug_root, 'PerfectCoffee_MilkFrother_Jug.glb')
for slot in glass_export_slots:
slot.material = glass
export_glass.name = 'MF_GLTF_Clear_Glass'
glass.name = 'MF_Clear_Single_Wall_Glass'
bpy.data.materials.remove(export_glass)
bpy.ops.object.select_all(action='DESELECT')
for screen in bpy.data.screens:
for area in screen.areas:
if area.type == 'VIEW_3D':
space = area.spaces.active
space.region_3d.view_perspective = 'CAMERA'
space.region_3d.view_camera_zoom = 0
space.shading.type = 'MATERIAL'
space.shading.studio_light = 'studio.exr'
space.shading.use_scene_lights = True
space.shading.use_scene_world = False
space.overlay.show_overlays = False
for cam, filename in [
(hero_camera, 'preview_three_quarter.png'),
(front_camera, 'preview_front.png'),
]:
scene.camera = cam
scene.render.filepath = str(OUT / filename)
bpy.ops.render.render(write_still=True)
lid_root.location.z += 0.078
lid_root.location.x -= 0.105
bpy.context.view_layer.update()
scene.camera = open_camera
scene.render.filepath = str(OUT / 'preview_open.png')
bpy.ops.render.render(write_still=True)
lid_root.location = (0, 0, 0)
bpy.context.view_layer.update()
scene.camera = spout_camera
for obj in lid_root.children_recursive:
obj.hide_render = True
scene.camera = measurement_camera
scene.render.filepath = str(OUT / 'preview_measurements.png')
bpy.ops.render.render(write_still=True)
scene.camera = spout_camera
scene.render.filepath = str(OUT / 'preview_spout.png')
bpy.ops.render.render(write_still=True)
for obj in lid_root.children_recursive:
obj.hide_render = False
jug_root.location.z += 0.090
bpy.context.view_layer.update()
scene.camera = separated_camera
scene.render.filepath = str(OUT / 'preview_separated.png')
bpy.ops.render.render(write_still=True)
jug_root.location = (0, 0, 0)
bpy.context.view_layer.update()
scene.camera = hero_camera
scene.render.filepath = '//preview_three_quarter.png'
about = bpy.data.texts.new('ABOUT_MilkFrother')
about.write(
'Unbranded high-detail milk frother reference model.\n'
'Front: +Y. Up: +Z. Units: meters.\n'
'Single press START button; no rotary program selector or program icons.\n'
'Fill marks read Minimum, Half, Maximum from bottom to top and face outward for a normal left-to-right view from -Y.\n'
'Handle and START button are centered on the +Y front; the open U-shaped handle has one upper mount.\n'
'The pouring lip is continuously stretched from the jug wall and rim, with no separate patch.\n'
'The jug body is a single 1.4 mm glass wall with an integral bottom; the grip and rim share its glass material.\n'
'Blender glass matches the high-detail grinder: 92 percent transparent, 8 percent glass, plus Fresnel glossy reflection.\n'
'Material Preview uses studio.exr with scene lights enabled and scene world disabled.\n'
'GLB exports use a compatible Principled transmission glass material.\n'
'The lid retains its original clear material.\n'
'Base and jug are independent assemblies sharing assembled coordinates; the lid and handle follow the jug.\n'
'Component files: PerfectCoffee_MilkFrother_Base and PerfectCoffee_MilkFrother_Jug.\n'
'Reference photographs: reference_images/milk_frother/.\n'
)
def bounds(objects):
bpy.context.view_layer.update()
points = [obj.matrix_world @ Vector(corner) for obj in objects for corner in obj.bound_box]
minimum = [min(point[axis] for point in points) for axis in range(3)]
maximum = [max(point[axis] for point in points) for axis in range(3)]
return minimum, maximum
mesh_objects = [obj for obj in model_collection.all_objects if obj.type == 'MESH']
minimum, maximum = bounds(mesh_objects)
triangles = 0
non_manifold = {}
depsgraph = bpy.context.evaluated_depsgraph_get()
for obj in mesh_objects:
evaluated = obj.evaluated_get(depsgraph)
mesh = evaluated.to_mesh()
mesh.calc_loop_triangles()
triangles += len(mesh.loop_triangles)
evaluated.to_mesh_clear()
for name in ['MF_White_Housing', 'MF_Jug_Outer', 'MF_Handle_Frame', 'MF_Start_Button', 'MF_Lid_Clear_Disk']:
obj = bpy.data.objects[name]
evaluated = obj.evaluated_get(depsgraph)
mesh = evaluated.to_mesh()
bm = bmesh.new()
bm.from_mesh(mesh)
non_manifold[name] = sum(not edge.is_manifold for edge in bm.edges)
bm.free()
evaluated.to_mesh_clear()
button = bpy.data.objects['MF_Start_Button']
handle = bpy.data.objects['MF_Handle_Frame']
handle_y = [handle.matrix_world @ Vector(corner) for corner in handle.bound_box]
handle_x = [point.x for point in handle_y]
handle_mount = bpy.data.objects['MF_Handle_Mount_Upper']
support_min, support_max = bounds([bpy.data.objects['MF_Base_Support_Pad']])
jug_min, jug_max = bounds([bpy.data.objects['MF_Jug_Outer']])
report = {
'blend': 'PerfectCoffee_MilkFrother.blend',
'glb': 'PerfectCoffee_MilkFrother.glb',
'blender_version': bpy.app.version_string,
'units': 'meters',
'up_axis': '+Z',
'front_axis': '+Y',
'mesh_objects': len(mesh_objects),
'evaluated_triangles': triangles,
'dimensions_m': [maximum[i] - minimum[i] for i in range(3)],
'bounds_min_m': minimum,
'bounds_max_m': maximum,
'visible_text_labels': text_labels,
'fill_level_labels_bottom_to_top': [label for label, height in fill_levels],
'fill_level_heights_m': [height for label, height in fill_levels],
'fill_text_reading_view': '-Y outside',
'fill_text_up_vector': list(label_object.rotation_euler.to_quaternion() @ Vector((0, 1, 0))),
'fill_text_screen_right_vector': list(label_object.rotation_euler.to_quaternion() @ Vector((1, 0, 0))),
'fill_text_outward_normal': list(label_object.rotation_euler.to_quaternion() @ Vector((0, 0, 1))),
'brand_text_present': any('SMEG' in label.upper() for label in text_labels),
'rotary_program_icons': 0,
'control_type': 'Single press START button; no rotary selector',
'button_location_m': list(button.location),
'button_outward_normal': list(button.rotation_euler.to_quaternion() @ Vector((0, 0, 1))),
'handle_y_range_m': [min(point.y for point in handle_y), max(point.y for point in handle_y)],
'handle_and_button_on_positive_y': button.location.y > 0 and all(point.y > 0 for point in handle_y),
'handle_x_range_m': [min(handle_x), max(handle_x)],
'handle_connection_location_m': list(handle_mount.location),
'handle_centered_on_positive_y': abs((min(handle_x) + max(handle_x)) / 2) < 1e-6 and abs(handle_mount.location.x) < 1e-6 and abs(button.location.x) < 1e-6,
'handle_open_bottom': bpy.data.objects.get('MF_Handle_Mount_Lower') is None,
'handle_mount_count': 1,
'spout_integrated': True,
'spout_max_extension_m': spout_extension,
'separate_spout_patch_present': bpy.data.objects.get('MF_Pour_Spout') is not None,
'jug_seat_z_m': jug_min[2],
'base_support_top_z_m': support_max[2],
'assembly_contact_gap_m': jug_min[2] - support_max[2],
'glass': {
'material': glass.name,
'shader_configuration': 'Grinder-matched thin-wall transparent/glass mix with Fresnel glossy reflection',
'transparent_weight': 1.0 - thin_wall_mix.inputs[0].default_value,
'refraction_weight': thin_wall_mix.inputs[0].default_value,
'ior': glass_refraction.inputs['IOR'].default_value,
'roughness': glass_refraction.inputs['Roughness'].default_value,
'fresnel_ior': fresnel.inputs['IOR'].default_value,
'reflection_roughness': polished_reflection.inputs['Roughness'].default_value,
'fresnel_linked': fresnel_mix.inputs[0].is_linked and fresnel_mix.inputs[0].links[0].from_node == fresnel,
'glb_material_strategy': 'Compatible Principled transmission glass substituted only during export',
'wall_thickness_m': glass_wall.thickness,
'single_wall_modifier_count': sum(mod.type == 'SOLIDIFY' for mod in jug_body.modifiers),
'body_uses_glass': jug_body.data.materials[0] == glass,
'handle_uses_same_glass': handle.data.materials[0] == glass,
'rim_uses_same_glass': bpy.data.objects['MF_Jug_Rolled_Rim'].data.materials[0] == glass,
'lid_material': clear.name,
'lid_material_unchanged': (
clear.name == 'MF_Clear_Tritan'
and math.isclose(clear_shader.inputs['Transmission Weight'].default_value, 1.0, abs_tol=1e-6)
and math.isclose(clear_shader.inputs['IOR'].default_value, 1.46, abs_tol=1e-6)
and math.isclose(clear_shader.inputs['Roughness'].default_value, 0.055, abs_tol=1e-6)
),
},
'component_files': {
'base': ['PerfectCoffee_MilkFrother_Base.blend', 'PerfectCoffee_MilkFrother_Base.glb'],
'jug': ['PerfectCoffee_MilkFrother_Jug.blend', 'PerfectCoffee_MilkFrother_Jug.glb'],
'shared_assembled_coordinates': True,
'lid_and_handle_follow_jug': lid_root.parent == jug_root and handle.parent == jug_root,
},
'required_parts': {
name: bpy.data.objects.get(name) is not None for name in [
'MF_White_Housing', 'MF_Chrome_Base', 'MF_Neck_Collar', 'MF_Jug_Outer',
'MF_Handle_Frame', 'MF_Start_Button', 'MF_Lid_Clear_Disk',
'MF_Measuring_Cap', 'MF_Whisk_Notched_Ring', 'MF_Base_Support_Pad',
]
},
'key_part_non_manifold_edges': non_manifold,
'missing_images': [],
'linked_libraries': [],
'studio_ground_present': bpy.data.objects.get('MF_Studio_Ground') is not None,
'previews': ['preview_three_quarter.png', 'preview_front.png', 'preview_open.png', 'preview_measurements.png', 'preview_spout.png', 'preview_separated.png'],
}
report['passed'] = (
all(report['required_parts'].values())
and not report['brand_text_present']
and report['fill_level_labels_bottom_to_top'] == ['Minimum', 'Half', 'Maximum']
and (Vector(report['fill_text_up_vector']) - Vector((0, 0, 1))).length < 1e-6
and (Vector(report['fill_text_screen_right_vector']) - Vector((1, 0, 0))).length < 1e-6
and (Vector(report['fill_text_outward_normal']) - Vector((0, -1, 0))).length < 1e-6
and report['handle_and_button_on_positive_y']
and report['handle_centered_on_positive_y']
and report['handle_open_bottom']
and report['spout_integrated']
and not report['separate_spout_patch_present']
and report['spout_max_extension_m'] > 0.009
and abs(report['assembly_contact_gap_m']) < 1e-6
and report['component_files']['lid_and_handle_follow_jug']
and math.isclose(report['glass']['transparent_weight'], 0.92, abs_tol=1e-6)
and math.isclose(report['glass']['refraction_weight'], 0.08, abs_tol=1e-6)
and report['glass']['fresnel_linked']
and report['glass']['single_wall_modifier_count'] == 1
and report['glass']['body_uses_glass']
and report['glass']['handle_uses_same_glass']
and report['glass']['rim_uses_same_glass']
and report['glass']['lid_material_unchanged']
and not report['studio_ground_present']
and all(value == 0 for value in non_manifold.values())
)
(OUT / 'validation.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
bpy.ops.wm.save_as_mainfile(filepath=str(OUT / 'PerfectCoffee_MilkFrother.blend'), compress=True)
def save_component(excluded_assembly, filename):
bpy.ops.wm.open_mainfile(filepath=str(OUT / 'PerfectCoffee_MilkFrother.blend'))
excluded = bpy.data.objects[excluded_assembly]
for obj in list(excluded.children_recursive) + [excluded]:
bpy.data.objects.remove(obj, do_unlink=True)
bpy.ops.wm.save_as_mainfile(filepath=str(OUT / filename), compress=True)
save_component('MF_Jug_Assembly', 'PerfectCoffee_MilkFrother_Base.blend')
save_component('MF_Base_Assembly', 'PerfectCoffee_MilkFrother_Jug.blend')
print('MODEL_VALIDATION=' + json.dumps(report), flush=True)
print('MODEL_BUILD_COMPLETE', flush=True)