Files
PerfectCoffee/model_assets/tamper/build_tamper.py
T
Yanchen 0f9e127162 feat: track remaining production assets, playtest scenes and references
Close the gaps left open after the LFS migration: 177 files that were
sitting untracked now enter version control, with every binary going
through Git LFS.

- labels: milk and orange-juice wrap artwork (SVG/PNG), Seedream sources,
  prompts and Dreamina job records
- orange juice 2L: bottle, cap, empty state and three label variants
  (blend + glb each)
- cup contents: desktop and mobile-optimised variants plus 3 textures
- milk 2L: empty and packaged variants with their glb exports
- milk frother: low-poly assembly and split base/jug parts
- tamper: model, glb and fit test
- juicer: seven assembly-part review scenes and their export scripts
- playtests: extraction animation scene and grinding/tamping whitebox
- reference: Minex page candidates, user review screenshots, sequence
  analysis frames and tamper STLs
- docs: item design draft, bean research notes, region reference and the
  model-asset audit report

Re-renderable preview/check frames stay untracked on purpose.
2026-11-22 10:26:53 +08:00

407 lines
17 KiB
Python

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('<II', raw_glb, 12)
assert chunk_type == 0x4E4F534A
gltf = json.loads(raw_glb[20:20 + json_length])
glb_triangles = sum(gltf['accessors'][primitive['indices']]['count'] // 3 for mesh in gltf['meshes'] for primitive in mesh['primitives'])
assert glb_triangles == total_triangles
assert len(gltf['meshes']) == 2 and len(gltf['materials']) == 2 and not gltf.get('images')
report = {
'construction': '24-segment lathe with smooth side normals and flat end caps',
'base': {'triangles': base_triangles, 'profile_rings': len(base_profile), 'diameter_mm': BASE_RADIUS * 2000.0, 'height_mm': base_profile[-1][1] * 1000.0, 'side_wall_height_mm': base_profile[2][1] * 1000.0, 'non_manifold_edges': non_manifold_count(base)},
'handle': {'triangles': handle_triangles, 'profile_rings': len(handle_profile), 'height_mm': (TOTAL_HEIGHT - base_profile[-1][1]) * 1000.0, 'maximum_diameter_mm': max(radius for radius, z in handle_profile) * 2000.0, 'non_manifold_edges': non_manifold_count(handle)},
'total_triangles': total_triangles,
'triangle_budget': 1000,
'budget_passed': total_triangles <= 1000,
'height_mm': TOTAL_HEIGHT * 1000.0,
'origin': 'bottom contact center (0,0,0), Z up',
'flat_bottom': True,
'glb': {'triangles': glb_triangles, 'meshes': len(gltf['meshes']), 'materials': len(gltf['materials']), 'embedded_images': len(gltf.get('images', [])), 'bytes': len(raw_glb)},
'source_portafilter': str(PORTAFILTER),
'source_portafilter_sha256': PORTAFILTER_SHA256,
}
(OUT / 'validation.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
bpy.ops.wm.open_mainfile(filepath=str(PORTAFILTER))
fit_scene = bpy.context.scene
for obj in list(bpy.data.objects):
if obj.type in {'CAMERA', 'LIGHT'}:
bpy.data.objects.remove(obj, do_unlink=True)
fit_collection = bpy.data.collections.new('TAM_Fit_Model')
fit_scene.collection.children.link(fit_collection)
fit_studio = bpy.data.collections.new('TAM_Fit_Studio')
fit_scene.collection.children.link(fit_studio)
with bpy.data.libraries.load(str(BLEND), link=False) as (source, target):
target.objects = ['TAM_Tamper_Assembly', 'TAM_Metal_Base', 'TAM_Wood_Handle']
for obj in target.objects:
fit_collection.objects.link(obj)
fit_root = bpy.data.objects['TAM_Tamper_Assembly']
fit_root.location = (0.0, 0.0, POWDER_TOP + FIT_LIFT)
fit_root['fit_note'] = 'Bottom is 0.02 mm above the powder proxy to avoid treating numerical surface contact as penetration'
def bowl_inner_radius(z):
if z <= 0.2105:
return 0.0295 + (z - 0.1915) * (0.0330 - 0.0295) / (0.2105 - 0.1915)
return 0.0330 + (z - 0.2105) * (0.0340 - 0.0330) / (0.2135 - 0.2105)
powder_mat = material('FIT_ONLY_Ground_Coffee', '#382014', 0.0, 0.92)
powder = lathe_solid(
'FIT_ONLY_PowderProxy_NotFinalAsset',
[(bowl_inner_radius(POWDER_BOTTOM) - 0.00045, POWDER_BOTTOM), (bowl_inner_radius(POWDER_TOP) - 0.00045, POWDER_TOP)],
powder_mat,
fit_collection,
)
powder['not_final_asset'] = True
powder['purpose'] = 'Placement and clearance proxy only; final coffee powder modeling is a separate task'
bpy.context.view_layer.update()
portafilter_meshes = [obj for obj in bpy.data.objects if obj.type == 'MESH' and obj.name.startswith('CM_Portafilter_')]
tamper_meshes = [bpy.data.objects['TAM_Metal_Base'], bpy.data.objects['TAM_Wood_Handle']]
depsgraph = bpy.context.evaluated_depsgraph_get()
def world_bvh(obj):
evaluated = obj.evaluated_get(depsgraph)
mesh = evaluated.to_mesh()
vertices = [evaluated.matrix_world @ vertex.co for vertex in mesh.vertices]
polygons = [tuple(polygon.vertices) for polygon in mesh.polygons]
tree = BVHTree.FromPolygons(vertices, polygons, all_triangles=False, epsilon=0.0)
evaluated.to_mesh_clear()
return tree
collisions = []
for tamper_obj in tamper_meshes:
tamper_bvh = world_bvh(tamper_obj)
for portafilter_obj in portafilter_meshes:
portafilter_bvh = world_bvh(portafilter_obj)
overlap = tamper_bvh.overlap(portafilter_bvh)
if overlap:
collisions.append({'tamper': tamper_obj.name, 'portafilter': portafilter_obj.name, 'triangle_pairs': len(overlap)})
assert not collisions, 'Tamper/portafilter intersections: ' + json.dumps(collisions)
radial_clearance = bowl_inner_radius(POWDER_TOP) - BASE_RADIUS
assert radial_clearance > 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)