import bpy import bmesh import hashlib import json import math import struct from pathlib import Path from mathutils import Vector from mathutils.bvhtree import BVHTree OUT = Path('/Users/yanchenyu/Documents/WebApps/PerfetCoffee/model_assets/tamper') PORTAFILTER = OUT.parent / 'coffee_machine' / 'PerfectCoffee_Portafilter.blend' BLEND = OUT / 'PerfectCoffee_Tamper.blend' GLB = OUT / 'PerfectCoffee_Tamper.glb' FIT_OUT = OUT / 'fit_test' FIT_OUT.mkdir(parents=True, exist_ok=True) PORTAFILTER_SHA256 = hashlib.sha256(PORTAFILTER.read_bytes()).hexdigest() SEGMENTS = 24 POWDER_TOP = 0.203 POWDER_BOTTOM = 0.192 FIT_LIFT = 0.00002 BASE_RADIUS = 0.0311 TOTAL_HEIGHT = 0.085 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 = 'MILLIMETERS' scene.unit_settings.scale_length = 1.0 model_collection = bpy.data.collections.new('TAM_Tamper_Model') studio_collection = bpy.data.collections.new('Studio_Exclude_From_Export') scene.collection.children.link(model_collection) scene.collection.children.link(studio_collection) root = bpy.data.objects.new('TAM_Tamper_Assembly', None) model_collection.objects.link(root) root.empty_display_type = 'PLAIN_AXES' root.empty_display_size = 0.025 root['construction'] = 'Original 24-segment lathe rebuild; no high-poly source vertices reused' root['reference_primary'] = 'https://www.thingiverse.com/thing:4681893 (matism09, CC BY 4.0)' root['reference_secondary'] = 'https://www.thingiverse.com/thing:3356261 (tswaehn, CC BY-SA 4.0)' root['radial_segments'] = SEGMENTS root['triangle_budget'] = 1000 root['base_diameter_mm'] = BASE_RADIUS * 2000.0 root['height_mm'] = TOTAL_HEIGHT * 1000.0 root['bottom_origin'] = 'Base contact center is world (0,0,0); Z up' root['powder_surface_in_portafilter_m'] = POWDER_TOP root['gameplay_simplification'] = 'One vertical press both levels and compresses the powder; no distributor' root['mat'] = 'Use a cloth texture at the tamping station; no separate solid tamping mat' def linear_channel(value): return value / 12.92 if value <= 0.04045 else ((value + 0.055) / 1.055) ** 2.4 def color_from_hex(value): return tuple(linear_channel(int(value[index:index + 2], 16) / 255.0) for index in (1, 3, 5)) + (1.0,) def material(name, hex_color, metallic, roughness): mat = bpy.data.materials.new(name) mat.use_nodes = True color = color_from_hex(hex_color) mat.diffuse_color = color bsdf = mat.node_tree.nodes.get('Principled BSDF') bsdf.inputs['Base Color'].default_value = color bsdf.inputs['Metallic'].default_value = metallic bsdf.inputs['Roughness'].default_value = roughness return mat steel = material('TAM_Brushed_Steel', '#B9C2C7', 0.86, 0.29) wood = material('TAM_Walnut_Handle', '#704326', 0.0, 0.40) def lathe_solid(name, profile, mat, collection, parent=None): vertices = [] for radius, z in profile: for index in range(SEGMENTS): angle = math.tau * index / SEGMENTS vertices.append((radius * math.cos(angle), radius * math.sin(angle), z)) bottom_center = len(vertices) vertices.append((0.0, 0.0, profile[0][1])) top_center = len(vertices) vertices.append((0.0, 0.0, profile[-1][1])) faces = [] for ring_index in range(len(profile) - 1): first = ring_index * SEGMENTS second = first + SEGMENTS for index in range(SEGMENTS): following = (index + 1) % SEGMENTS faces.append((first + index, first + following, second + following, second + index)) top_start = (len(profile) - 1) * SEGMENTS for index in range(SEGMENTS): following = (index + 1) % SEGMENTS faces.append((bottom_center, following, index)) faces.append((top_center, top_start + index, top_start + following)) mesh = bpy.data.meshes.new(name + '_Mesh') mesh.from_pydata(vertices, [], faces) bm = bmesh.new() bm.from_mesh(mesh) bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces)) bm.to_mesh(mesh) bm.free() mesh.update() obj = bpy.data.objects.new(name, mesh) collection.objects.link(obj) obj.parent = parent obj.data.materials.append(mat) for polygon in mesh.polygons: polygon.use_smooth = len(polygon.vertices) == 4 obj['radial_segments'] = SEGMENTS obj['profile_rings'] = len(profile) mesh.calc_loop_triangles() obj['triangles'] = len(mesh.loop_triangles) return obj base_profile = [ (0.0307, 0.0000), (0.0311, 0.0008), (0.0311, 0.0105), (0.0303, 0.0115), (0.0200, 0.0170), (0.0100, 0.0210), ] handle_profile = [ (0.0100, 0.0210), (0.0120, 0.0250), (0.0142, 0.0310), (0.0129, 0.0390), (0.0133, 0.0485), (0.0163, 0.0585), (0.0198, 0.0695), (0.0181, 0.0770), (0.0120, 0.0820), (0.0035, 0.0850), ] base = lathe_solid('TAM_Metal_Base', base_profile, steel, model_collection, root) handle = lathe_solid('TAM_Wood_Handle', handle_profile, wood, model_collection, root) base['bottom_contact_plane_z_m'] = 0.0 base['maximum_radius_m'] = BASE_RADIUS handle['material_note'] = 'Solid walnut-color PBR; no texture or procedural runtime shader required' def non_manifold_count(obj): bm = bmesh.new() bm.from_mesh(obj.data) result = sum(1 for edge in bm.edges if not edge.is_manifold) bm.free() return result def point_at(obj, target): obj.rotation_euler = (Vector(target) - obj.location).to_track_quat('-Z', 'Y').to_euler() def camera(name, location, target, ortho_scale, collection): data = bpy.data.cameras.new(name) data.type = 'ORTHO' data.ortho_scale = ortho_scale data.clip_start = 0.001 data.clip_end = 100.0 obj = bpy.data.objects.new(name, data) collection.objects.link(obj) obj.location = location point_at(obj, target) return obj def area_light(name, location, energy, size, color, target, collection): 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) collection.objects.link(obj) obj.location = location point_at(obj, target) return obj def setup_world(name, strength): world = bpy.data.worlds.new(name) world.use_nodes = True world.node_tree.nodes['Background'].inputs['Color'].default_value = (0.28, 0.32, 0.38, 1.0) world.node_tree.nodes['Background'].inputs['Strength'].default_value = strength return world ground_mat = material('Studio_Warm_Stone', '#A79D8F', 0.0, 0.80) bpy.ops.mesh.primitive_plane_add(size=2.0, location=(0.0, 0.0, -0.00004)) ground = bpy.context.object ground.name = 'Studio_Ground' for collection in list(ground.users_collection): collection.objects.unlink(ground) studio_collection.objects.link(ground) ground.data.materials.append(ground_mat) scene.world = setup_world('Tamper_Studio_World', 0.22) area_light('Studio_Key', (0.09, 0.08, 0.19), 0.85, 0.13, (1.0, 0.89, 0.76), (0.0, 0.0, 0.045), studio_collection) area_light('Studio_Fill', (-0.11, 0.01, 0.12), 0.35, 0.11, (0.80, 0.90, 1.0), (0.0, 0.0, 0.04), studio_collection) area_light('Studio_Rim', (0.01, -0.10, 0.16), 1.0, 0.10, (1.0, 0.95, 0.86), (0.0, 0.0, 0.05), studio_collection) hero_camera = camera('Acceptance_Tamper_Hero', (0.105, 0.155, 0.125), (0.0, 0.0, 0.042), 0.127, studio_collection) side_camera = camera('Acceptance_Tamper_Side_YOZ', (0.0, 0.19, 0.0435), (0.0, 0.0, 0.0435), 0.108, studio_collection) scene.render.engine = 'CYCLES' scene.cycles.samples = 96 scene.cycles.use_denoising = True scene.render.resolution_x = 1400 scene.render.resolution_y = 1400 scene.render.resolution_percentage = 100 scene.render.image_settings.file_format = 'PNG' scene.render.image_settings.color_mode = 'RGB' scene.render.film_transparent = False scene.view_settings.view_transform = 'AgX' scene.view_settings.look = 'AgX - Medium High Contrast' scene.view_settings.exposure = -0.2 base.data.calc_loop_triangles() handle.data.calc_loop_triangles() base_triangles = len(base.data.loop_triangles) handle_triangles = len(handle.data.loop_triangles) total_triangles = base_triangles + handle_triangles assert base_triangles == 288 and handle_triangles == 480 and total_triangles == 768 assert non_manifold_count(base) == 0 and non_manifold_count(handle) == 0 assert all(polygon.use_smooth for polygon in base.data.polygons if len(polygon.vertices) == 4) assert all(polygon.use_smooth for polygon in handle.data.polygons if len(polygon.vertices) == 4) bottom_faces = [polygon for polygon in base.data.polygons if polygon.center.z == 0.0] assert len(bottom_faces) == SEGMENTS assert all(polygon.normal.z < -0.9999 for polygon in bottom_faces) assert abs(max(math.hypot(vertex.co.x, vertex.co.y) for vertex in base.data.vertices) - BASE_RADIUS) < 0.000001 assert abs(min(vertex.co.z for vertex in base.data.vertices)) < 0.000001 assert abs(max(vertex.co.z for vertex in handle.data.vertices) - TOTAL_HEIGHT) < 0.000001 bpy.ops.object.select_all(action='DESELECT') root.select_set(True) base.select_set(True) handle.select_set(True) bpy.context.view_layer.objects.active = root bpy.ops.export_scene.gltf( filepath=str(GLB), export_format='GLB', use_selection=True, export_apply=True, export_animations=False, export_extras=True, export_cameras=False, export_lights=False, ) for cam, filename in [(hero_camera, 'preview_hero.png'), (side_camera, 'preview_side.png')]: scene.camera = cam scene.render.filepath = str(OUT / filename) bpy.ops.render.render(write_still=True) scene.camera = hero_camera scene.render.filepath = str(OUT / 'preview_hero.png') bpy.ops.object.select_all(action='DESELECT') root.select_set(True) bpy.context.view_layer.objects.active = root 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(BLEND)) raw_glb = GLB.read_bytes() json_length, chunk_type = struct.unpack_from(' 0.00045 fit_report = { 'tamper_file': BLEND.name, 'portafilter_source_sha256_before_test': PORTAFILTER_SHA256, 'portafilter_source_sha256_after_test': hashlib.sha256(PORTAFILTER.read_bytes()).hexdigest(), 'portafilter_source_unchanged': hashlib.sha256(PORTAFILTER.read_bytes()).hexdigest() == PORTAFILTER_SHA256, 'powder_surface_z_m': POWDER_TOP, 'powder_thickness_above_filter_mm': (POWDER_TOP - POWDER_BOTTOM) * 1000.0, 'tamper_bottom_clearance_above_powder_mm': FIT_LIFT * 1000.0, 'bowl_inner_diameter_at_powder_surface_mm': bowl_inner_radius(POWDER_TOP) * 2000.0, 'tamper_base_diameter_mm': BASE_RADIUS * 2000.0, 'radial_clearance_mm': radial_clearance * 1000.0, 'collisions': collisions, 'powder_proxy_is_final_asset': False, 'passed': not collisions and radial_clearance > 0.00045, } (FIT_OUT / 'validation.json').write_text(json.dumps(fit_report, ensure_ascii=False, indent=2), encoding='utf-8') portafilter_points = [obj.matrix_world @ vertex.co for obj in portafilter_meshes for vertex in obj.data.vertices] fit_ground_z = min(point.z for point in portafilter_points) - 0.00005 bpy.ops.mesh.primitive_plane_add(size=2.0, location=(0.0, 0.0, fit_ground_z)) fit_ground = bpy.context.object fit_ground.name = 'FIT_Studio_Ground' for collection in list(fit_ground.users_collection): collection.objects.unlink(fit_ground) fit_studio.objects.link(fit_ground) fit_ground_mat = material('FIT_Studio_Warm_Stone', '#A79D8F', 0.0, 0.80) fit_ground.data.materials.append(fit_ground_mat) fit_scene.world = setup_world('Tamper_Fit_World', 0.22) area_light('FIT_Key', (0.10, 0.07, 0.39), 1.0, 0.16, (1.0, 0.89, 0.76), (0.0, -0.02, 0.20), fit_studio) area_light('FIT_Fill', (-0.15, -0.05, 0.28), 0.45, 0.13, (0.80, 0.90, 1.0), (0.0, -0.04, 0.19), fit_studio) area_light('FIT_Rim', (0.0, -0.20, 0.34), 1.2, 0.13, (1.0, 0.95, 0.88), (0.0, -0.03, 0.20), fit_studio) fit_hero = camera('Acceptance_Tamper_Fit', (0.16, 0.24, 0.22), (0.0, -0.065, 0.205), 0.250, fit_studio) fit_top = camera('Acceptance_Tamper_Fit_Top', (0.0, 0.0, 0.49), (0.0, 0.0, 0.20), 0.102, fit_studio) fit_scene.render.engine = 'CYCLES' fit_scene.cycles.samples = 96 fit_scene.cycles.use_denoising = True fit_scene.render.resolution_x = 1400 fit_scene.render.resolution_y = 1400 fit_scene.render.resolution_percentage = 100 fit_scene.render.image_settings.file_format = 'PNG' fit_scene.render.image_settings.color_mode = 'RGB' fit_scene.view_settings.view_transform = 'AgX' fit_scene.view_settings.look = 'AgX - Medium High Contrast' fit_scene.view_settings.exposure = -0.2 for cam, filename in [(fit_hero, 'fit_perspective.png'), (fit_top, 'fit_top.png')]: fit_scene.camera = cam fit_scene.render.filepath = str(FIT_OUT / filename) bpy.ops.render.render(write_still=True) fit_scene.camera = fit_hero fit_scene.render.filepath = str(FIT_OUT / 'fit_perspective.png') bpy.ops.wm.save_as_mainfile(filepath=str(FIT_OUT / 'TamperFit_Test.blend')) print('TAMPER_BUILD_VALIDATION=' + json.dumps(report, ensure_ascii=False), flush=True) print('TAMPER_FIT_VALIDATION=' + json.dumps(fit_report, ensure_ascii=False), flush=True) print('TAMPER_BUILD_COMPLETE', flush=True)