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 PROJECT_ROOT = ROOT.parent.parent MACHINE_SOURCE = PROJECT_ROOT / 'model_assets' / 'coffee_machine' / 'PerfectCoffee_CoffeeMachine.blend' CUP_SOURCE = PROJECT_ROOT / 'model_assets' / 'coffee_cup' / 'PerfectCoffee_CupContents.blend' BLEND_OUT = ROOT / 'PerfectCoffee_Extraction_AnimationTest.blend' FPS = 30 FRAME_END = 1350 Q_MAX = 30.0 LEVER_OPEN = 0.30 FLOW = Q_MAX * LEVER_OPEN SATURATION_ML = 60.0 T_START = 2.0 T_SATURATED = (T_START * FPS + round(SATURATION_ML / FLOW * FPS)) / FPS T_CLOSE = 42.0 T_CLOSED = 42.25 BREW_Y = -0.237 TRAY_Z = 0.098 SPOUT_Z = 0.224034 SPOUTS = [(-0.014, 'Left'), (0.014, 'Right')] CUP_PARK_X = 0.145 CUP_INNER_RIM = 0.0405 STREAM_RADIUS = 0.00135 LIQUID_BOTTOM = 0.0022 LIQUID_TOP = 0.1038 LIQUID_BOTTOM_RADIUS = 0.0278 LIQUID_TOP_RADIUS = 0.0392 source_hashes = { 'machine': hashlib.sha256(MACHINE_SOURCE.read_bytes()).hexdigest(), 'cup_contents': hashlib.sha256(CUP_SOURCE.read_bytes()).hexdigest(), } bpy.ops.wm.open_mainfile(filepath=str(MACHINE_SOURCE)) bpy.context.preferences.filepaths.save_version = 0 scene = bpy.context.scene scene.name = 'PerfectCoffee_Extraction_AnimationTest' scene.render.fps = FPS scene.frame_start = 1 scene.frame_end = FRAME_END scene.unit_settings.system = 'METRIC' scene.unit_settings.length_unit = 'METERS' scene.unit_settings.scale_length = 1.0 for obj in list(bpy.data.objects): if obj.type == 'CAMERA': bpy.data.objects.remove(obj, do_unlink=True) rigs = bpy.data.collections.new('AT_01_Godot_Anchors') visuals = bpy.data.collections.new('AT_02_TestOnly_Cutaway_And_Liquid') hud = bpy.data.collections.new('AT_03_TestOnly_HUD') for collection in [rigs, visuals, hud]: scene.collection.children.link(collection) machine = bpy.data.objects['CM_CoffeeMachine'] portafilter = bpy.data.objects['CM_Portafilter'] controller = bpy.data.objects['CM_ControlState'] controller['temperature_c'] = 92.0 controller['hot_water_open'] = 0.60 controller['brew_flow'] = 0.0 def link_object(obj, collection): for old in list(obj.users_collection): old.objects.unlink(obj) collection.objects.link(obj) return obj def parent_keep(obj, parent): bpy.context.view_layer.update() matrix = obj.matrix_world.copy() obj.parent = parent obj.matrix_world = matrix def material(name, color, roughness=0.4, metallic=0.0, emission=False): mat = bpy.data.materials.new(name) mat.use_nodes = True mat.diffuse_color = (*color, 1.0) nodes = mat.node_tree.nodes nodes.clear() output = nodes.new('ShaderNodeOutputMaterial') if emission: shader = nodes.new('ShaderNodeEmission') shader.inputs['Color'].default_value = (*color, 1.0) shader.inputs['Strength'].default_value = 1.0 else: shader = nodes.new('ShaderNodeBsdfPrincipled') shader.inputs['Base Color'].default_value = (*color, 1.0) shader.inputs['Roughness'].default_value = roughness shader.inputs['Metallic'].default_value = metallic mat.node_tree.links.new(shader.outputs[0], output.inputs['Surface']) return mat coffee_mat = material('AT_Coffee_Stream', (0.030, 0.0075, 0.0020), 0.24) coffee_side_mat = material('AT_Coffee_Volume', (0.014, 0.0038, 0.0012), 0.28) crema_mat = material('AT_Crema_Surface', (0.095, 0.031, 0.0065), 0.34) water_mat = material('AT_Preinfusion_Water', (0.08, 0.38, 0.52), 0.18, emission=True) puck_mat = material('AT_Puck_Wetness', (0.20, 0.068, 0.018), 0.88) ripple_mat = material('AT_Ripple', (0.18, 0.065, 0.014), 0.32) white_hud = material('AT_HUD_White', (0.91, 0.95, 0.91), emission=True) muted_hud = material('AT_HUD_Muted', (0.61, 0.72, 0.68), emission=True) accent_hud = material('AT_HUD_Accent', (0.62, 0.88, 0.67), emission=True) dark_hud = material('AT_HUD_Backdrop', (0.014, 0.025, 0.022), emission=True) def smooth(value): value = max(0.0, min(1.0, value)) return value * value * (3.0 - 2.0 * value) def cup_x_at(t): if t < 1.2: return CUP_PARK_X if t < 1.8: return CUP_PARK_X * (1.0 - smooth((t - 1.2) / 0.6)) if t < 15.0: return 0.0 if t < 15.5: return CUP_PARK_X * smooth((t - 15.0) / 0.5) if t < 18.0: return CUP_PARK_X if t < 18.5: return CUP_PARK_X * (1.0 - smooth((t - 18.0) / 0.5)) if t < 42.25: return 0.0 if t < 42.85: return CUP_PARK_X * smooth((t - 42.25) / 0.6) return CUP_PARK_X def lever_at(t): if t < 1.70: return 0.0 if t < T_START: return LEVER_OPEN * (t - 1.70) / (T_START - 1.70) if t <= T_CLOSE: return LEVER_OPEN if t < T_CLOSED: return LEVER_OPEN * (T_CLOSED - t) / (T_CLOSED - T_CLOSE) return 0.0 def machine_flow_at(t): if t < T_START: return 0.0 return Q_MAX * lever_at(t) def machine_volume_at(t): if t <= T_SATURATED: return 0.0 if t <= T_CLOSE: return (t - T_SATURATED) * FLOW full = (T_CLOSE - T_SATURATED) * FLOW if t >= T_CLOSED: return full + FLOW * (T_CLOSED - T_CLOSE) / 2.0 dt = t - T_CLOSE duration = T_CLOSED - T_CLOSE return full + FLOW * (dt - dt * dt / (2.0 * duration)) def catches_at(t): x = cup_x_at(t) result = [] for spout_x, _ in SPOUTS: distance = math.hypot(spout_x - x, 0.0) result.append(distance <= CUP_INNER_RIM - STREAM_RADIUS) return result def frustum_ml(factor): factor = max(0.0, min(1.0, factor)) height = (LIQUID_TOP - LIQUID_BOTTOM) * factor radius = LIQUID_BOTTOM_RADIUS + (LIQUID_TOP_RADIUS - LIQUID_BOTTOM_RADIUS) * factor return math.pi * height * (radius * radius + radius * LIQUID_BOTTOM_RADIUS + LIQUID_BOTTOM_RADIUS * LIQUID_BOTTOM_RADIUS) / 3.0 * 1e6 CUP_MAX_ML = frustum_ml(1.0) def fill_factor(volume_ml): if volume_ml <= 0.0: return 0.0 low = 0.0 high = 1.0 for _ in range(32): middle = (low + high) / 2.0 if frustum_ml(middle) < volume_ml: low = middle else: high = middle return (low + high) / 2.0 states = {} cup_volume = 0.0 for frame in range(1, FRAME_END + 1): t = (frame - 1) / FPS if frame > 1: middle_t = t - 0.5 / FPS middle_q = machine_flow_at(middle_t) if middle_t > T_SATURATED else 0.0 middle_catches = catches_at(middle_t) cup_volume += middle_q * sum(middle_catches) / 2.0 / FPS preinfusion = min(max(0.0, t - T_START), T_SATURATED - T_START) absorbed = min(SATURATION_ML, max(0.0, t - T_START) * FLOW) catches = catches_at(t) q = machine_flow_at(t) states[frame] = { 'time': t, 'cup_x': cup_x_at(t), 'lever': lever_at(t), 'flow': q, 'absorbed': absorbed, 'preinfusion': preinfusion, 'machine_volume': machine_volume_at(t), 'cup_volume': cup_volume, 'catches': catches, 'fill': fill_factor(cup_volume), 'extraction': t >= T_SATURATED, } cup_rig = bpy.data.objects.new('AT_CupRig', None) rigs.objects.link(cup_rig) cup_rig.empty_display_type = 'PLAIN_AXES' cup_rig.empty_display_size = 0.025 cup_rig['purpose'] = 'Move this transform in Godot; bottom remains on the drip tray.' cup_rig['support_z_m'] = TRAY_Z cup_rig['collection_rule'] = 'Each spout integrates flow only while its vertical projection is inside the cup opening.' with bpy.data.libraries.load(str(CUP_SOURCE), link=False) as (data_from, data_to): data_to.objects = ['CC_Cup_Body'] cup_proxy = data_to.objects[0] visuals.objects.link(cup_proxy) cup_proxy.name = 'AT_Cup_CollisionProxy_Full' cup_proxy.parent = cup_rig cup_proxy.location = (0.0, 0.0, 0.0) cup_proxy.rotation_euler = (0.0, 0.0, 0.0) cup_proxy.scale = (1.0, 1.0, 1.0) cup_proxy.hide_render = True cup_proxy.display_type = 'WIRE' cup_proxy.hide_set(True) def cut_front(obj, plane_y): bm = bmesh.new() bm.from_mesh(obj.data) bmesh.ops.bisect_plane( bm, geom=list(bm.verts) + list(bm.edges) + list(bm.faces), dist=0.0000001, plane_co=(0.0, plane_y, 0.0), plane_no=(0.0, 1.0, 0.0), clear_inner=True, clear_outer=False, ) cut_edges = [ edge for edge in bm.edges if edge.is_boundary and all(abs(vertex.co.y - plane_y) < 0.00001 for vertex in edge.verts) ] if cut_edges: bmesh.ops.holes_fill(bm, edges=cut_edges, sides=0) bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces)) bm.to_mesh(obj.data) bm.free() obj.data.update() obj['test_only_cutaway'] = True cup_cutaway = bpy.data.objects.new('AT_Cup_Cutaway', cup_proxy.data.copy()) visuals.objects.link(cup_cutaway) cup_cutaway.parent = cup_rig cut_front(cup_cutaway, 0.0) assert min(vertex.co.y for vertex in cup_cutaway.data.vertices) > -0.00001, 'Cup cutaway kept the wrong half.' for name in [ 'CM_Portafilter_Bowl', 'CM_GroupHead_Bell', 'CM_GroupHead_SealingSeat', 'CM_GroupHead_Gasket', 'CM_GroupHead_ShowerScreen', ]: obj = bpy.data.objects[name] obj.data = obj.data.copy() cut_front(obj, BREW_Y) def half_frustum(name, bottom_z, top_z, bottom_radius, top_radius, collection, materials): count = 20 angles = [math.pi * index / count for index in range(count + 1)] vertices = [] for radius, z in [(bottom_radius, bottom_z), (bottom_radius, bottom_z)]: vertices.extend((radius * math.cos(angle), radius * math.sin(angle), z) for angle in angles) vertices.extend([(0.0, 0.0, bottom_z), (0.0, 0.0, bottom_z)]) bottom_center = len(vertices) - 2 top_center = len(vertices) - 1 top_offset = count + 1 faces = [] material_indices = [] for index in range(count): faces.append((index, index + 1, top_offset + index + 1, top_offset + index)) material_indices.append(0) faces.append((top_center, top_offset + index, top_offset + index + 1)) material_indices.append(min(1, len(materials) - 1)) faces.append((bottom_center, index + 1, index)) material_indices.append(0) faces.extend([ (bottom_center, 0, top_offset, top_center), (bottom_center, top_center, top_offset + count, count), ]) material_indices.extend([0, 0]) mesh = bpy.data.meshes.new(name + '_Mesh') mesh.from_pydata(vertices, [], faces) mesh.update() for mat in materials: mesh.materials.append(mat) for polygon, material_index in zip(mesh.polygons, material_indices): polygon.material_index = material_index polygon.use_smooth = len(polygon.vertices) == 4 and polygon.index < count * 3 and polygon.index % 3 == 0 obj = bpy.data.objects.new(name, mesh) collection.objects.link(obj) bm = bmesh.new() bm.from_mesh(mesh) bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces)) bm.to_mesh(mesh) bm.free() obj.shape_key_add(name='Basis') full = obj.shape_key_add(name='Full') for index, angle in enumerate(angles): full.data[top_offset + index].co = (top_radius * math.cos(angle), top_radius * math.sin(angle), top_z) full.data[top_center].co = (0.0, 0.0, top_z) full.value = 1.0 return obj, full liquid, liquid_fill = half_frustum( 'AT_CupLiquid_Cutaway', LIQUID_BOTTOM, LIQUID_TOP, LIQUID_BOTTOM_RADIUS, LIQUID_TOP_RADIUS, visuals, [coffee_side_mat, crema_mat], ) liquid.parent = cup_rig liquid['volume_to_shape'] = 'Solve frustum volume; Full.value is geometric fill, not extraction time.' liquid['maximum_visual_volume_ml'] = CUP_MAX_ML puck, _ = half_frustum( 'AT_CoffeePuck_Cutaway', 0.0, 0.012, 0.0285, 0.0285, visuals, [puck_mat], ) puck.location = (0.0, BREW_Y, 0.264) parent_keep(puck, portafilter) puck['purpose'] = 'Test-only visual: dry to wet during saturation; no coffee output before W=A.' def cylinder(name, radius, depth, mat, collection, location=(0.0, 0.0, 0.0), vertices=20): bpy.ops.mesh.primitive_cylinder_add(vertices=vertices, radius=radius, depth=depth, location=location) obj = bpy.context.object obj.name = name link_object(obj, collection) obj.data.materials.append(mat) for polygon in obj.data.polygons: polygon.use_smooth = len(polygon.vertices) == 4 return obj streams = {} for spout_x, suffix in SPOUTS: stream = cylinder('AT_CoffeeStream_' + suffix, 1.0, 1.0, coffee_mat, visuals) stream['source_anchor'] = 'AT_Spout' + suffix + '_Anchor' stream['visibility_rule'] = 'Saturated AND brew_flow>0; independent of cup position.' streams[suffix] = stream splash = cylinder('AT_TraySplash_' + suffix, 0.008, 0.00035, coffee_side_mat, visuals, vertices=24) streams[suffix + '_Splash'] = splash bpy.ops.mesh.primitive_torus_add(major_radius=0.0042, minor_radius=0.00042, major_segments=24, minor_segments=6) ripple = bpy.context.object ripple.name = 'AT_CupRipple_' + suffix link_object(ripple, visuals) ripple.data.materials.append(ripple_mat) streams[suffix + '_Ripple'] = ripple inlet = cylinder('AT_Preinfusion_Inlet', 1.0, 1.0, water_mat, visuals) inlet.location = (0.0, BREW_Y, (0.2875 + 0.276) / 2.0) inlet.scale = (0.0015, 0.0015, 0.0115) for name, location, parent in [ ('AT_BrewCenter_Anchor', (0.0, BREW_Y, TRAY_Z), machine), ('AT_SpoutLeft_Anchor', (-0.014, BREW_Y, SPOUT_Z), portafilter), ('AT_SpoutRight_Anchor', (0.014, BREW_Y, SPOUT_Z), portafilter), ]: anchor = bpy.data.objects.new(name, None) rigs.objects.link(anchor) anchor.location = location anchor.empty_display_size = 0.008 parent_keep(anchor, parent) cup_bottom_anchor = bpy.data.objects.new('AT_CupBottom_Anchor', None) rigs.objects.link(cup_bottom_anchor) cup_bottom_anchor.parent = cup_rig cup_bottom_anchor.empty_display_size = 0.008 cup_surface_anchor = bpy.data.objects.new('AT_CupLiquidSurface_Anchor', None) rigs.objects.link(cup_surface_anchor) cup_surface_anchor.parent = cup_rig cup_surface_anchor.empty_display_size = 0.008 for frame, state in states.items(): cup_rig.location = (state['cup_x'], BREW_Y, TRAY_Z) cup_rig.keyframe_insert(data_path='location', frame=frame, group='Cup_Translation') controller['brew_flow'] = state['lever'] controller.keyframe_insert(data_path='["brew_flow"]', frame=frame, group='Brew_Control') liquid_fill.value = state['fill'] liquid_fill.keyframe_insert(data_path='value', frame=frame) liquid_height = LIQUID_BOTTOM + (LIQUID_TOP - LIQUID_BOTTOM) * state['fill'] cup_surface_anchor.location = (0.0, 0.0, liquid_height) cup_surface_anchor.keyframe_insert(data_path='location', frame=frame) wet = state['absorbed'] / SATURATION_ML dry = Vector((0.20, 0.068, 0.018)) soaked = Vector((0.022, 0.0055, 0.0015)) color = dry.lerp(soaked, wet) bsdf = puck_mat.node_tree.nodes.get('Principled BSDF') bsdf.inputs['Base Color'].default_value = (*color, 1.0) bsdf.inputs['Base Color'].keyframe_insert(data_path='default_value', frame=frame) puck_mat.diffuse_color = (*color, 1.0) puck_mat.keyframe_insert(data_path='diffuse_color', frame=frame) inlet_scale = 0.0015 * math.sqrt(state['flow'] / FLOW) if state['flow'] > 0.0 else 0.0 inlet.scale = (inlet_scale, inlet_scale, 0.0115 if state['flow'] > 0.0 else 0.0) inlet.keyframe_insert(data_path='scale', frame=frame) for spout_x, suffix in SPOUTS: caught = state['catches'][0 if suffix == 'Left' else 1] target_z = TRAY_Z + (liquid_height if caught else 0.0004) length = max(0.0001, SPOUT_Z - target_z) pulse = 1.0 + 0.055 * math.sin(state['time'] * 37.0 + (0.0 if suffix == 'Left' else 1.3)) radius = STREAM_RADIUS * math.sqrt(state['flow'] / FLOW) * pulse if state['extraction'] and state['flow'] > 0.0 else 0.0 stream = streams[suffix] stream.location = (spout_x, BREW_Y, target_z + length / 2.0) stream.scale = (radius, radius, length if radius > 0.0 else 0.0) stream.keyframe_insert(data_path='location', frame=frame, group='Coffee_Stream') stream.keyframe_insert(data_path='scale', frame=frame, group='Coffee_Stream') splash = streams[suffix + '_Splash'] splash.location = (spout_x, BREW_Y, TRAY_Z + 0.00035) splash_scale = 1.0 + 0.15 * math.sin(state['time'] * 19.0) if state['extraction'] and state['flow'] > 0.0 and not caught else 0.0 splash.scale = (splash_scale, splash_scale, splash_scale) splash.keyframe_insert(data_path='location', frame=frame) splash.keyframe_insert(data_path='scale', frame=frame) ripple = streams[suffix + '_Ripple'] ripple.location = (spout_x, BREW_Y, TRAY_Z + liquid_height + 0.0003) ripple_scale = 1.0 + 0.18 * math.sin(state['time'] * 23.0) if state['extraction'] and state['flow'] > 0.0 and caught and state['cup_volume'] > 0.0 else 0.0 ripple.scale = (ripple_scale, ripple_scale, ripple_scale) ripple.keyframe_insert(data_path='location', frame=frame) ripple.keyframe_insert(data_path='scale', frame=frame) portafilter_keys = [ (1, True), (37, False), (1297, False), (1336, True), (FRAME_END, True), ] for frame, detached in portafilter_keys: portafilter.location = (0.0, BREW_Y - (0.035 if detached else 0.0), 0.2835 - (0.045 if detached else 0.0)) portafilter.rotation_euler = (0.0, 0.0, math.radians(-45.0) if detached else 0.0) portafilter.keyframe_insert(data_path='location', frame=frame, group='Bayonet_Insert_Remove') portafilter.keyframe_insert(data_path='rotation_euler', frame=frame, group='Bayonet_Insert_Remove') def camera_only(obj): for prop in ['visible_shadow', 'visible_diffuse', 'visible_glossy', 'visible_transmission', 'visible_volume_scatter']: if hasattr(obj, prop): setattr(obj, prop, False) camera_data = bpy.data.cameras.new('AT_TestCamera') camera = bpy.data.objects.new('AT_TestCamera', camera_data) hud.objects.link(camera) camera.location = (0.235, -0.735, 0.365) target = Vector((0.015, BREW_Y, 0.195)) camera.rotation_euler = (target - camera.location).to_track_quat('-Z', 'Y').to_euler() camera_data.type = 'ORTHO' camera_data.ortho_scale = 0.46 camera_data.clip_start = 0.001 camera_data.clip_end = 100.0 scene.camera = camera font_paths = [ Path('/System/Library/Fonts/PingFang.ttc'), Path('/System/Library/Fonts/Hiragino Sans GB.ttc'), Path('/System/Library/Fonts/Supplemental/Arial.ttf'), ] font = None for font_path in font_paths: if font_path.exists(): font = bpy.data.fonts.load(str(font_path)) break def hud_text(name, body, x, y, size, mat=white_hud, align='LEFT'): curve = bpy.data.curves.new(name + '_Font', 'FONT') curve.body = body curve.size = size curve.align_x = align curve.align_y = 'CENTER' curve.resolution_u = 3 if font is not None: curve.font = font obj = bpy.data.objects.new(name, curve) hud.objects.link(obj) obj.parent = camera obj.location = (x, y, -0.06) obj.rotation_euler = (0.0, 0.0, 0.0) obj.data.materials.append(mat) camera_only(obj) return obj def hud_backdrop(name, y, height): mesh = bpy.data.meshes.new(name + '_Mesh') mesh.from_pydata([(-0.215, -height / 2.0, 0.0), (0.215, -height / 2.0, 0.0), (0.215, height / 2.0, 0.0), (-0.215, height / 2.0, 0.0)], [], [(0, 1, 2, 3)]) obj = bpy.data.objects.new(name, mesh) hud.objects.link(obj) obj.parent = camera obj.location = (0.0, y, -0.065) obj.data.materials.append(dark_hud) camera_only(obj) return obj def show_during(obj, start, end): for prop in ['hide_render', 'hide_viewport']: setattr(obj, prop, True) obj.keyframe_insert(data_path=prop, frame=max(1, start - 1)) setattr(obj, prop, False) obj.keyframe_insert(data_path=prop, frame=start) setattr(obj, prop, True) obj.keyframe_insert(data_path=prop, frame=end + 1) first_collection_frame = min(frame for frame, state in states.items() if state['cup_volume'] > 0.000001) show_during(liquid, first_collection_frame, FRAME_END) hud_backdrop('AT_HUD_TopBackdrop', 0.116, 0.033) hud_text('AT_HUD_Title', '完美咖啡|咖啡机动作可行性测试', -0.210, 0.122, 0.0068) hud_text('AT_HUD_Mode', '剖视 · 非流体模拟', 0.210, 0.122, 0.0055, muted_hud, 'RIGHT') stages = [ (1, 36, '01 锁定手柄'), (37, 60, '02 杯子就位'), (61, 260, '03 预浸泡|粉饼吸水,杯中不出液'), (261, 450, '04 萃取|杯子接取咖啡液'), (451, 540, '05 移杯|机器继续出液'), (541, 555, '06 放回杯子|保留已接咖啡'), (556, 1260, '07 继续萃取|杯中液量恢复增长'), (1261, 1296, '08 关水|再移开杯子'), (1297, FRAME_END, '09 取下手柄|结束冲泡'), ] for index, (start, end, label) in enumerate(stages): obj = hud_text('AT_Stage_%02d' % index, label, 0.0, 0.105, 0.0085, accent_hud, 'CENTER') show_during(obj, start, end) sample_frames = set(range(1, FRAME_END + 1, 15)) sample_frames.update([1, 37, 61, 1297, 1336, FRAME_END]) for transition_start, transition_end in [(261, 262), (451, 466), (541, 556), (1261, 1270)]: sample_frames.update(range(transition_start, transition_end + 1)) sample_frames = sorted(sample_frames) for index, start in enumerate(sample_frames): end = sample_frames[index + 1] - 1 if index + 1 < len(sample_frames) else FRAME_END state = states[start] t = state['time'] if t < T_START: first = '水流拨杆 %.0f%% 等待粉饼接触水' % (state['lever'] * 100.0) elif t < T_SATURATED: first = '预浸泡 %.2f s 粉饼吸水 %.1f / 60 mL' % (state['preinfusion'], state['absorbed']) else: extraction_time = min(t, T_CLOSED) - T_SATURATED first = '萃取 %.2f s 机器累计出液 %.1f mL' % (extraction_time, state['machine_volume']) if t < T_SATURATED: second = '杯中 0.0 mL 尚未出液' else: if state['flow'] <= 0.0: collection = '关水暂停' elif all(state['catches']): collection = '两股均接取' elif any(state['catches']): collection = '移杯过渡 · 部分接取' else: collection = '杯子移开 · 液量暂停' second = '杯中 %.1f mL %s 水流 %.1f mL/s' % (state['cup_volume'], collection, state['flow']) white_hud.node_tree.nodes.get('Emission').inputs['Strength'].default_value = 2.0 first_obj = hud_text('AT_ReadoutA_%04d' % start, first, -0.205, -0.111, 0.0065, white_hud) second_obj = hud_text('AT_ReadoutB_%04d' % start, second, -0.205, -0.124, 0.0065, white_hud) show_during(first_obj, start, end) show_during(second_obj, start, end) for name, frame in [ ('01_手柄开始锁定', 1), ('02_杯子开始就位', 37), ('03_首次接触水_预浸泡计时开始', 61), ('04_粉饼饱和_自动进入萃取', 261), ('05_移杯开始', 451), ('06_杯子完全移开', 466), ('07_杯子开始放回', 541), ('08_杯子重新就位', 556), ('09_开始关水', 1261), ('10_水流完全关闭', 1269), ('11_取手柄开始', 1297), ('12_测试结束', FRAME_END), ]: scene.timeline_markers.new(name, frame=frame) notes = '''PERFECT COFFEE — GODOT IMPLEMENTATION NOTES Purpose: animation and spatial feasibility only. The HUD and cutaway meshes are test-only and must not be exported as final art. Godot visual anchors (meters, Blender Z-up): AT_BrewCenter_Anchor = (0, -0.237, 0.098) AT_SpoutLeft_Anchor = (-0.014, -0.237, 0.224034) while attached AT_SpoutRight_Anchor = (0.014, -0.237, 0.224034) while attached AT_CupBottom_Anchor follows AT_CupRig. AT_CupLiquidSurface_Anchor follows collected cup volume, not machine extraction time. Runtime rules: 1. First water contact starts pre-infusion. W integrates q until W=60 mL. Pre-infusion time continues even if q=0. 2. At W=60 mL, immediately enter extraction. No unlock animation or confirmation gate exists. 3. Coffee output requires saturated puck and q>0. Moving the cup never closes the machine valve. 4. Test each spout independently against the cup opening. Integrate collected volume only for the stream segments that enter the cup. 5. When the cup is away, cup liquid and cup collection stop; machine extraction, machine output and total waiting time continue. 6. Replacing the cup resumes collection without clearing existing cup contents. 7. Close flow fully before removing the portafilter. The cup moves aside before removal to preserve physical clearance. Animation versus logic: Do not use AnimationPlayer animation_finished as the extraction state machine. Compute deterministic state in GDScript, then drive stream visibility, liquid shape, gauges and portafilter/cup transforms from that state. Use ray casts or spout/cup opening tests for the visual stream target. Partial cup contact can be handled per spout, as in this test. Test parameters: fps=30; q_max=30 mL/s; lever=0.30; q=9 mL/s; saturation=60 mL; pre-infusion=6.6667 s; B1 reference only. Closing ramp adds 1.125 mL after the 300 mL full-flow point. This video deliberately misses some output while the cup is away and does not claim a perfect score. ''' text_block = bpy.data.texts.new('GODOT_IMPLEMENTATION_NOTES') text_block.write(notes) scene['test_only'] = True scene['source_machine_sha256'] = source_hashes['machine'] scene['source_cup_contents_sha256'] = source_hashes['cup_contents'] scene['q_max_ml_s'] = Q_MAX scene['test_lever_open'] = LEVER_OPEN scene['saturation_ml'] = SATURATION_ML scene['preinfusion_seconds'] = T_SATURATED - T_START scene['full_flow_machine_output_ml'] = 300.0 scene['closing_ramp_output_ml'] = 1.125 scene['cup_max_visual_ml'] = CUP_MAX_ML scene.render.engine = 'BLENDER_EEVEE' if hasattr(scene, 'eevee') and hasattr(scene.eevee, 'taa_render_samples'): scene.eevee.taa_render_samples = 16 scene.render.resolution_x = 1280 scene.render.resolution_y = 720 scene.render.resolution_percentage = 100 scene.render.image_settings.file_format = 'PNG' scene.render.image_settings.color_mode = 'RGB' scene.render.filepath = '//frames/frame_' scene.render.use_file_extension = True scene.view_settings.view_transform = 'AgX' scene.view_settings.exposure = -0.15 brew_light_data = bpy.data.lights.new('AT_Brew_Fill', 'AREA') brew_light_data.energy = 7.0 brew_light_data.shape = 'DISK' brew_light_data.size = 0.18 brew_light = bpy.data.objects.new('AT_Brew_Fill', brew_light_data) visuals.objects.link(brew_light) brew_light.location = (0.0, -0.42, 0.38) brew_light.rotation_euler = (Vector((0.0, BREW_Y, 0.17)) - brew_light.location).to_track_quat('-Z', 'Y').to_euler() def world_bvh(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 BVHTree.FromPolygons(vertices, polygons, all_triangles=False) collision_results = {} for frame, label in [(61, 'centered'), (480, 'parked_right')]: scene.frame_set(frame) bpy.context.view_layer.update() depsgraph = bpy.context.evaluated_depsgraph_get() cup_bvh = world_bvh(cup_proxy, depsgraph) collisions = [] for obj in machine.children_recursive: if obj.type not in {'MESH', 'CURVE', 'FONT'} or obj.name == 'CM_DripTray_TextureSurface': continue if cup_bvh.overlap(world_bvh(obj, depsgraph)): collisions.append(obj.name) collision_results[label] = collisions scene.frame_set(300) bpy.context.view_layer.update() 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' assert states[180]['absorbed'] > 0.0 and states[180]['machine_volume'] == 0.0 and states[180]['cup_volume'] == 0.0 assert abs(states[261]['preinfusion'] - 6.6666666667) < 0.00001 assert states[261]['extraction'] and states[261]['machine_volume'] == 0.0 assert not any(states[480]['catches']) and not any(states[540]['catches']) assert abs(states[540]['cup_volume'] - states[480]['cup_volume']) < 0.00001 assert states[540]['machine_volume'] > states[480]['machine_volume'] assert states[600]['cup_volume'] > states[540]['cup_volume'] assert abs(states[1261]['machine_volume'] - 300.0) < 0.00001 assert 0.0 < states[1261]['cup_volume'] < 300.0 assert states[1270]['flow'] == 0.0 assert all(abs(state['cup_x']) <= CUP_PARK_X for state in states.values()) assert not collision_results['centered'], collision_results assert not collision_results['parked_right'], collision_results assert hashlib.sha256(MACHINE_SOURCE.read_bytes()).hexdigest() == source_hashes['machine'] assert hashlib.sha256(CUP_SOURCE.read_bytes()).hexdigest() == source_hashes['cup_contents'] report = { 'blend': BLEND_OUT.name, 'fps': FPS, 'frames': [1, FRAME_END], 'duration_seconds': FRAME_END / FPS, 'source_files_unchanged': True, 'source_sha256': source_hashes, 'parameters': { 'q_max_ml_s': Q_MAX, 'lever_open': LEVER_OPEN, 'flow_ml_s': FLOW, 'saturation_ml': SATURATION_ML, 'preinfusion_seconds': T_SATURATED - T_START, 'full_flow_machine_output_ml': 300.0, 'closing_ramp_output_ml': 1.125, 'cup_max_visual_ml': CUP_MAX_ML, }, 'key_states': { str(frame): { key: value for key, value in states[frame].items() if key in ['time', 'cup_x', 'flow', 'absorbed', 'preinfusion', 'machine_volume', 'cup_volume', 'catches', 'extraction'] } for frame in [61, 180, 261, 451, 480, 540, 600, 1261, 1270] }, 'cup_collision_free': collision_results, 'godot_notes_text_block': 'GODOT_IMPLEMENTATION_NOTES', 'test_only_collections': [visuals.name, hud.name], 'checks': { 'no_output_during_preinfusion': True, 'automatic_saturation_transition': True, 'cup_away_pauses_only_cup_collection': True, 'cup_return_preserves_and_resumes_collection': True, 'streams_continue_until_valve_closes': True, 'source_assets_not_overwritten': True, }, } (ROOT / 'validation.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8') bpy.ops.file.pack_all() bpy.ops.wm.save_as_mainfile(filepath=str(BLEND_OUT)) preview_dir = ROOT / 'previews' preview_dir.mkdir(exist_ok=True) scene.render.resolution_x = 960 scene.render.resolution_y = 540 for frame, name in [ (37, '01_cup_ready'), (180, '02_preinfusion'), (270, '03_extraction'), (480, '04_cup_away'), (600, '05_cup_returned'), (1261, '06_close'), (1340, '07_handle_removed'), ]: scene.frame_set(frame) scene.render.filepath = str(preview_dir / (name + '.png')) bpy.ops.render.render(write_still=True) print('ANIMATION_TEST_VALIDATION=' + json.dumps(report, ensure_ascii=False), flush=True) print('ANIMATION_TEST_BUILD_COMPLETE', flush=True)