feat: establish coffee game and grinder baseline
This commit is contained in:
@@ -0,0 +1,327 @@
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
|
||||
import bmesh
|
||||
import bpy
|
||||
from mathutils import Vector
|
||||
from mathutils.bvhtree import BVHTree
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
SOURCE = ROOT / 'PerfectCoffee_CoffeeMachine.blend'
|
||||
CUP_SOURCE = ROOT.parent / 'coffee_cup' / 'PerfectCoffee_CoffeeCup.blend'
|
||||
OUT = ROOT / 'cup_fit_test'
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
source_hash = hashlib.sha256(SOURCE.read_bytes()).hexdigest()
|
||||
cup_hash = hashlib.sha256(CUP_SOURCE.read_bytes()).hexdigest()
|
||||
|
||||
bpy.ops.wm.open_mainfile(filepath=str(SOURCE))
|
||||
bpy.context.preferences.filepaths.save_version = 0
|
||||
scene = bpy.context.scene
|
||||
scene.name = 'Cup_Placement_Test'
|
||||
machine = bpy.data.objects['CM_CoffeeMachine']
|
||||
group = bpy.data.objects['CM_GroupHead']
|
||||
tray = bpy.data.objects['CM_DripTray_TextureSurface']
|
||||
bpy.context.view_layer.update()
|
||||
brew_xy = Vector((group.matrix_world.translation.x, group.matrix_world.translation.y))
|
||||
support_z = max((tray.matrix_world @ vertex.co).z for vertex in tray.data.vertices)
|
||||
|
||||
with bpy.data.libraries.load(str(CUP_SOURCE), link=False) as (data_from, data_to):
|
||||
data_to.objects = ['CC_Cup_Body']
|
||||
cup = data_to.objects[0]
|
||||
test_collection = bpy.data.collections.new('Cup_Placement_Test_Only')
|
||||
scene.collection.children.link(test_collection)
|
||||
test_collection.objects.link(cup)
|
||||
cup.parent = None
|
||||
cup.matrix_world.identity()
|
||||
cup.rotation_euler = (0, 0, 0)
|
||||
cup.scale = (1, 1, 1)
|
||||
cup.location = (brew_xy.x, brew_xy.y, support_z)
|
||||
cup['test_only'] = True
|
||||
cup['lid_included'] = False
|
||||
cup['support_surface'] = 'CM_DripTray_TextureSurface'
|
||||
cup['support_z_m'] = support_z
|
||||
|
||||
intersection_collection = bpy.data.collections.new('Test_Intersection_Volumes')
|
||||
scene.collection.children.link(intersection_collection)
|
||||
probe_collection = bpy.data.collections.new('Test_Temporary_Probes')
|
||||
scene.collection.children.link(probe_collection)
|
||||
probe = bpy.data.objects.new('Test_Cup_Intersection_Probe', cup.data.copy())
|
||||
probe_collection.objects.link(probe)
|
||||
|
||||
red = bpy.data.materials.new('Test_Collision_Red')
|
||||
red.use_nodes = True
|
||||
red.diffuse_color = (1, 0.015, 0.005, 1)
|
||||
red.node_tree.nodes.get('Principled BSDF').inputs['Base Color'].default_value = (1, 0.015, 0.005, 1)
|
||||
red.node_tree.nodes.get('Principled BSDF').inputs['Roughness'].default_value = 0.5
|
||||
|
||||
|
||||
def world_mesh(obj, depsgraph):
|
||||
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]
|
||||
evaluated.to_mesh_clear()
|
||||
return vertices, polygons
|
||||
|
||||
|
||||
def bvh_from_world(vertices, polygons):
|
||||
return BVHTree.FromPolygons(vertices, polygons, all_triangles=False, epsilon=0.0)
|
||||
|
||||
|
||||
def bounds_of_vertices(vertices):
|
||||
return {
|
||||
'min': [min(vertex[axis] for vertex in vertices) for axis in range(3)],
|
||||
'max': [max(vertex[axis] for vertex in vertices) for axis in range(3)],
|
||||
}
|
||||
|
||||
|
||||
def intersection_volume(target):
|
||||
probe.data = cup.data.copy()
|
||||
probe.matrix_world = cup.matrix_world.copy()
|
||||
bpy.context.view_layer.update()
|
||||
modifier = probe.modifiers.new('Test_Intersection', 'BOOLEAN')
|
||||
modifier.operation = 'INTERSECT'
|
||||
modifier.solver = 'EXACT'
|
||||
modifier.object = target
|
||||
bpy.context.view_layer.objects.active = probe
|
||||
bpy.ops.object.modifier_apply(modifier=modifier.name)
|
||||
bm = bmesh.new()
|
||||
bm.from_mesh(probe.data)
|
||||
volume = abs(bm.calc_volume(signed=True))
|
||||
bm.free()
|
||||
vertices = [probe.matrix_world @ vertex.co for vertex in probe.data.vertices]
|
||||
return volume, vertices
|
||||
|
||||
|
||||
def check_position(position, keep_intersections=False, exact=True):
|
||||
cup.location = (position[0], position[1], support_z)
|
||||
bpy.context.view_layer.update()
|
||||
depsgraph = bpy.context.evaluated_depsgraph_get()
|
||||
vertices, polygons = world_mesh(cup, depsgraph)
|
||||
cup_bvh = bvh_from_world(vertices, polygons)
|
||||
collisions = []
|
||||
contacts = []
|
||||
for target, target_bvh in machine_bvhs:
|
||||
pairs = cup_bvh.overlap(target_bvh)
|
||||
if not pairs:
|
||||
continue
|
||||
if not exact:
|
||||
contacts.append({'machine_part': target.name, 'overlapping_face_pairs': len(pairs)})
|
||||
continue
|
||||
volume, intersection_vertices = intersection_volume(target)
|
||||
entry = {
|
||||
'machine_part': target.name,
|
||||
'overlapping_face_pairs': len(pairs),
|
||||
'intersection_volume_mm3': volume * 1e9,
|
||||
}
|
||||
if intersection_vertices:
|
||||
entry['intersection_bounds_m'] = bounds_of_vertices(intersection_vertices)
|
||||
if volume > 1e-12:
|
||||
collisions.append(entry)
|
||||
if keep_intersections:
|
||||
intersection_mesh = probe.data.copy()
|
||||
intersection_mesh.name = 'Test_Intersection_' + target.name
|
||||
intersection_mesh.materials.clear()
|
||||
intersection_mesh.materials.append(red)
|
||||
intersection_obj = bpy.data.objects.new(intersection_mesh.name, intersection_mesh)
|
||||
intersection_collection.objects.link(intersection_obj)
|
||||
intersection_obj.matrix_world = probe.matrix_world.copy()
|
||||
intersection_obj['test_only'] = True
|
||||
else:
|
||||
contacts.append(entry)
|
||||
return collisions, contacts
|
||||
|
||||
|
||||
bpy.context.view_layer.update()
|
||||
depsgraph = bpy.context.evaluated_depsgraph_get()
|
||||
machine_objects = [
|
||||
obj for obj in machine.children_recursive
|
||||
if obj.type in {'MESH', 'CURVE', 'FONT', 'SURFACE'} and obj != tray
|
||||
]
|
||||
machine_bvhs = []
|
||||
for obj in machine_objects:
|
||||
vertices, polygons = world_mesh(obj, depsgraph)
|
||||
machine_bvhs.append((obj, bvh_from_world(vertices, polygons)))
|
||||
|
||||
centered_collisions, centered_contacts = check_position(brew_xy, keep_intersections=True)
|
||||
spout_objects = [bpy.data.objects['CM_Portafilter_SpoutLeft'], bpy.data.objects['CM_Portafilter_SpoutRight']]
|
||||
outlet_min_z = min(
|
||||
(obj.matrix_world @ Vector(corner)).z
|
||||
for obj in spout_objects for corner in obj.bound_box
|
||||
)
|
||||
cup_bounds = bounds_of_vertices([
|
||||
cup.matrix_world @ vertex.co for vertex in cup.data.vertices
|
||||
])
|
||||
|
||||
|
||||
def circle_overlap_ratio(dx, dy, small=0.0425, large=0.05):
|
||||
distance = math.hypot(dx, dy)
|
||||
if distance >= small + large:
|
||||
return 0.0
|
||||
if distance <= large - small:
|
||||
return 1.0
|
||||
first = math.acos((distance * distance + small * small - large * large) / (2 * distance * small))
|
||||
second = math.acos((distance * distance + large * large - small * small) / (2 * distance * large))
|
||||
area = small * small * first + large * large * second - 0.5 * math.sqrt(
|
||||
(-distance + small + large) * (distance + small - large)
|
||||
* (distance - small + large) * (distance + small + large)
|
||||
)
|
||||
return area / (math.pi * small * small)
|
||||
|
||||
|
||||
candidates = []
|
||||
for ix in range(-32, 33):
|
||||
dx = ix * 0.0025
|
||||
for iy in range(-22, 22):
|
||||
dy = iy * 0.0025
|
||||
position = brew_xy + Vector((dx, dy))
|
||||
overlap = circle_overlap_ratio(dx, dy)
|
||||
if overlap < 0.25:
|
||||
continue
|
||||
collisions, contacts = check_position(position, exact=False)
|
||||
if not collisions and not contacts:
|
||||
candidates.append({
|
||||
'cup_bottom_center_m': [position.x, position.y, support_z],
|
||||
'offset_from_brew_axis_mm': [dx * 1000, dy * 1000],
|
||||
'head_projection_overlap_percent_of_cup': overlap * 100,
|
||||
'penetrations': 0,
|
||||
'surface_contacts_excluding_tray_support': 0,
|
||||
})
|
||||
|
||||
candidates.sort(key=lambda candidate: (
|
||||
-candidate['head_projection_overlap_percent_of_cup'],
|
||||
math.hypot(*candidate['offset_from_brew_axis_mm']),
|
||||
))
|
||||
best = candidates[0] if candidates else None
|
||||
|
||||
scene.render.engine = 'CYCLES'
|
||||
scene.cycles.samples = 40
|
||||
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 = 'RGBA'
|
||||
scene.view_settings.view_transform = 'AgX'
|
||||
|
||||
|
||||
def point_at(obj, target):
|
||||
obj.rotation_euler = (Vector(target) - obj.location).to_track_quat('-Z', 'Y').to_euler()
|
||||
|
||||
|
||||
def test_camera(name, location, target, scale):
|
||||
data = bpy.data.cameras.new(name)
|
||||
data.type = 'ORTHO'
|
||||
data.ortho_scale = scale
|
||||
data.clip_start = 0.001
|
||||
data.clip_end = 100
|
||||
obj = bpy.data.objects.new(name, data)
|
||||
bpy.data.collections['Studio_Exclude_From_Export'].objects.link(obj)
|
||||
obj.location = location
|
||||
point_at(obj, target)
|
||||
return obj
|
||||
|
||||
|
||||
side_camera = test_camera('CupTest_Centered_YOZ', (0.9, brew_xy.y, 0.21), (0, brew_xy.y, 0.18), 0.245)
|
||||
front_camera = test_camera('CupTest_Centered_XOZ', (0, -0.9, 0.215), (0, brew_xy.y, 0.18), 0.245)
|
||||
cup.location = (brew_xy.x, brew_xy.y, support_z)
|
||||
bpy.context.view_layer.update()
|
||||
for camera, filename in [(front_camera, 'centered_front.png'), (side_camera, 'centered_side.png')]:
|
||||
scene.camera = camera
|
||||
scene.render.filepath = str(OUT / filename)
|
||||
bpy.ops.render.render(write_still=True)
|
||||
|
||||
if best:
|
||||
cup.location = best['cup_bottom_center_m']
|
||||
bpy.context.view_layer.update()
|
||||
scene.camera = side_camera
|
||||
scene.render.filepath = str(OUT / 'accepted_side.png')
|
||||
bpy.ops.render.render(write_still=True)
|
||||
|
||||
original_materials = {obj.data: list(obj.data.materials) for obj in machine_objects if obj.type == 'MESH'}
|
||||
ghost = bpy.data.materials.new('Test_Top_Ghost')
|
||||
ghost.use_nodes = True
|
||||
nodes = ghost.node_tree.nodes
|
||||
nodes.clear()
|
||||
transparent = nodes.new('ShaderNodeBsdfTransparent')
|
||||
solid = nodes.new('ShaderNodeBsdfPrincipled')
|
||||
solid.inputs['Base Color'].default_value = (0.42, 0.52, 0.61, 1)
|
||||
solid.inputs['Roughness'].default_value = 0.5
|
||||
mix = nodes.new('ShaderNodeMixShader')
|
||||
mix.inputs[0].default_value = 0.13
|
||||
output = nodes.new('ShaderNodeOutputMaterial')
|
||||
ghost.node_tree.links.new(transparent.outputs[0], mix.inputs[1])
|
||||
ghost.node_tree.links.new(solid.outputs[0], mix.inputs[2])
|
||||
ghost.node_tree.links.new(mix.outputs[0], output.inputs['Surface'])
|
||||
for mesh, materials in original_materials.items():
|
||||
mesh.materials.clear()
|
||||
mesh.materials.append(ghost)
|
||||
top_camera = test_camera('CupTest_Best_XOY_Ghost', (brew_xy.x, brew_xy.y, 0.9), (brew_xy.x, brew_xy.y, 0), 0.30)
|
||||
scene.camera = top_camera
|
||||
scene.render.filepath = str(OUT / 'accepted_top_ghost.png')
|
||||
bpy.ops.render.render(write_still=True)
|
||||
for mesh, materials in original_materials.items():
|
||||
mesh.materials.clear()
|
||||
for material in materials:
|
||||
mesh.materials.append(material)
|
||||
|
||||
cup.location = (brew_xy.x, brew_xy.y, support_z)
|
||||
bpy.context.view_layer.update()
|
||||
probe.hide_render = True
|
||||
probe.hide_viewport = True
|
||||
scene.camera = side_camera
|
||||
scene.render.filepath = str(OUT / 'centered_side.png')
|
||||
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 / 'CupPlacement_Test.blend'))
|
||||
|
||||
assert hashlib.sha256(SOURCE.read_bytes()).hexdigest() == source_hash
|
||||
assert hashlib.sha256(CUP_SOURCE.read_bytes()).hexdigest() == cup_hash
|
||||
report = {
|
||||
'source_machine_unchanged': True,
|
||||
'source_machine_sha256': source_hash,
|
||||
'source_cup_unchanged': True,
|
||||
'source_cup_sha256': cup_hash,
|
||||
'lid_included': False,
|
||||
'layout': {
|
||||
'scheme': 'A',
|
||||
'brew_center_xy_m': list(brew_xy),
|
||||
'group_seal_z_mm': group.matrix_world.translation.z * 1000,
|
||||
'tray_support_z_mm': support_z * 1000,
|
||||
},
|
||||
'cup': {
|
||||
'height_mm': 110,
|
||||
'top_diameter_mm': 85,
|
||||
'bottom_diameter_mm': 60,
|
||||
'bottom_center_m': [brew_xy.x, brew_xy.y, support_z],
|
||||
'bottom_z_mm': cup_bounds['min'][2] * 1000,
|
||||
'bottom_on_tray_surface': abs(cup_bounds['min'][2] - support_z) < 1e-7,
|
||||
'top_z_mm': cup_bounds['max'][2] * 1000,
|
||||
},
|
||||
'lowest_spout_z_mm': outlet_min_z * 1000,
|
||||
'spout_to_tray_clearance_mm': (outlet_min_z - support_z) * 1000,
|
||||
'spout_clearance_above_cup_mm': (outlet_min_z - cup_bounds['max'][2]) * 1000,
|
||||
'centered_head_projection_overlap_percent_of_cup': circle_overlap_ratio(0, 0) * 100,
|
||||
'centered_penetrations': centered_collisions,
|
||||
'centered_surface_contacts_excluding_tray_support': centered_contacts,
|
||||
'centered_passed': not centered_collisions and not centered_contacts,
|
||||
'search': {
|
||||
'xy_step_mm': 2.5,
|
||||
'cup_upright': True,
|
||||
'bottom_remains_on_tray': True,
|
||||
'minimum_projection_overlap_percent_allowed': 25,
|
||||
'tested_collision_free_candidates': len(candidates),
|
||||
'best_valid_position': best,
|
||||
},
|
||||
}
|
||||
(OUT / 'validation.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
assert report['cup']['bottom_on_tray_surface'], 'Cup bottom is not on the tray surface.'
|
||||
assert report['centered_passed'], 'Cup placement still intersects the coffee machine: ' + json.dumps(centered_collisions + centered_contacts)
|
||||
assert best and best['offset_from_brew_axis_mm'] == [0.0, 0.0], 'The centered position is not the best valid position.'
|
||||
print('CUP_PLACEMENT_VALIDATION=' + json.dumps(report, ensure_ascii=False), flush=True)
|
||||
print('CUP_PLACEMENT_TEST_COMPLETE', flush=True)
|
||||
Reference in New Issue
Block a user