import bpy import bmesh import hashlib import json import math import re import shutil import struct import subprocess from pathlib import Path from mathutils.bvhtree import BVHTree OUT = Path('/Users/yanchenyu/Documents/WebApps/PerfetCoffee/model_assets/coffee_cup') BASE = OUT / 'PerfectCoffee_CupContents.blend' MOBILE_BLEND = OUT / 'PerfectCoffee_CupContents_Mobile.blend' MOBILE_GLB = OUT / 'PerfectCoffee_CupContents_Mobile.glb' ATLAS = OUT / 'textures' / 'CC_CupContents_Atlas.png' COMPARISONS = OUT / 'optimization' COMPARISONS.mkdir(exist_ok=True) FFMPEG = shutil.which('ffmpeg') assert FFMPEG, 'ffmpeg is required for the existing lossless texture and comparison pipeline' BASE_SHA256 = hashlib.sha256(BASE.read_bytes()).hexdigest() ORIGINAL_TEXTURE_BYTES = sum((OUT / 'textures' / name).stat().st_size for name in ('CC_Coffee_Surface.png', 'CC_Latte_Surface.png')) SEGMENTS = 48 CUP_SEGMENTS = 24 FOAM_BOTTOM = 0.10382 FOAM_EDGE_TOP = 0.10570 FOAM_DOME = 0.00035 FIT_CLEARANCE = 0.00012 def run(command): result = subprocess.run(command, check=True, text=True, capture_output=True) return result.stdout + result.stderr run([ FFMPEG, '-y', '-hide_banner', '-loglevel', 'warning', '-i', str(OUT / 'textures' / 'CC_Coffee_Surface.png'), '-i', str(OUT / 'textures' / 'CC_Latte_Surface.png'), '-filter_complex', '[0:v]scale=512:512:flags=lanczos[a];[1:v]scale=512:512:flags=lanczos[b];[a][b]hstack=inputs=2,format=rgb24[out]', '-map', '[out]', '-frames:v', '1', '-pred', 'mixed', '-compression_level', '9', '-update', '1', str(ATLAS), ]) bpy.ops.wm.open_mainfile(filepath=str(BASE)) bpy.context.preferences.filepaths.save_version = 0 scene = bpy.context.scene root = bpy.data.objects['CC_CupContents_Assembly'] cup = bpy.data.objects['CC_Cup_Body'] liquid = bpy.data.objects['CC_Coffee_Liquid'] foam = bpy.data.objects['CC_Milk_Foam'] coffee_mat = bpy.data.materials['CC_Coffee_Liquid'] foam_mat = bpy.data.materials['CC_Milk_Foam'] original_foam_vertices = len(foam.data.vertices) foam.data.calc_loop_triangles() original_foam_triangles = len(foam.data.loop_triangles) liquid.data.calc_loop_triangles() liquid_triangles = len(liquid.data.loop_triangles) original_foam_bounds = { 'min_z': min(vertex.co.z for vertex in foam.data.vertices), 'max_z': max(vertex.co.z for vertex in foam.data.vertices), 'max_radius': max(math.hypot(vertex.co.x, vertex.co.y) for vertex in foam.data.vertices), } scene.cycles.samples = 96 scene.cycles.use_denoising = True scene.render.resolution_x = 1400 scene.render.resolution_y = 1400 scene.render.resolution_percentage = 100 for camera_name, filename in [ ('Acceptance_Latte_Cycles', 'before_latte.png'), ('Acceptance_Latte_Top_UV', 'before_latte_top.png'), ]: scene.camera = bpy.data.objects[camera_name] scene.render.filepath = str(COMPARISONS / filename) bpy.ops.render.render(write_still=True) atlas_image = bpy.data.images.load(str(ATLAS), check_existing=False) atlas_image.name = 'CC_CupContents_Atlas' atlas_image.colorspace_settings.name = 'sRGB' atlas_image.pack() for material in (coffee_mat, foam_mat): for node in material.node_tree.nodes: if node.type == 'TEX_IMAGE': node.image = atlas_image for image_name in ('CC_Coffee_Surface', 'CC_Latte_Surface'): image = bpy.data.images.get(image_name) if image is not None and image.users == 0: bpy.data.images.remove(image) for obj, offset in ((liquid, 0.0), (foam, 0.5)): uv = obj.data.uv_layers['LiquidSurfaceUV'] for loop_uv in uv.data: loop_uv.uv.x = offset + loop_uv.uv.x * 0.5 obj['uv_map'] = 'LiquidSurfaceUV' obj['atlas_rect'] = [offset, 0.0, 0.5, 1.0] def fitted_radius(z): if z <= 0.022: radius = 0.028 + (z - 0.002) * (0.0305 - 0.028) / 0.020 else: radius = 0.0305 + (z - 0.022) * (0.038 - 0.0305) / 0.066 return radius * math.cos(math.pi / CUP_SEGMENTS) - FIT_CLEARANCE outer_radius = fitted_radius(FOAM_EDGE_TOP) rings = [ (fitted_radius(FOAM_BOTTOM), FOAM_BOTTOM), (outer_radius, FOAM_EDGE_TOP), (outer_radius * 0.55, FOAM_EDGE_TOP + FOAM_DOME * (1.0 - 0.55 * 0.55)), ] vertices = [] for radius, z in rings: for index in range(SEGMENTS): angle = math.tau * index / SEGMENTS vertices.append((radius * math.cos(angle), radius * math.sin(angle), z)) faces = [tuple(reversed(range(SEGMENTS)))] for ring_index in range(len(rings) - 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)) center_index = len(vertices) vertices.append((0.0, 0.0, FOAM_EDGE_TOP + FOAM_DOME)) last = (len(rings) - 1) * SEGMENTS for index in range(SEGMENTS): following = (index + 1) % SEGMENTS faces.append((last + index, last + following, center_index)) mesh = bpy.data.meshes.new('CC_Milk_Foam_Mobile_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() mesh.materials.append(foam_mat) uv = mesh.uv_layers.new(name='LiquidSurfaceUV') for polygon in mesh.polygons: polygon.use_smooth = abs(polygon.normal.z) < 0.995 for loop_index in polygon.loop_indices: vertex = mesh.vertices[mesh.loops[loop_index].vertex_index].co u = 0.5 + vertex.x / (2.0 * outer_radius) v = 0.5 + vertex.y / (2.0 * outer_radius) uv.data[loop_index].uv = (0.5 + u * 0.5, v) mesh.uv_layers.active = uv old_mesh = foam.data foam.data = mesh if old_mesh.users == 0: bpy.data.meshes.remove(old_mesh) foam['radial_segments'] = SEGMENTS foam['radial_surface_rings'] = 2 foam['top_uv_faces'] = SEGMENTS * 2 foam['atlas_rect'] = [0.5, 0.0, 0.5, 1.0] foam['surface_texture'] = ATLAS.name foam['surface_texture_uv'] = 'LiquidSurfaceUV; right half of atlas; original 0-1 liquid UV is remapped to U=0.5-1.0' foam['optimization'] = '96 to 48 segments; seven concentric surface rings to one intermediate ring; thickness and dome preserved' liquid['surface_texture'] = ATLAS.name liquid['surface_texture_uv'] = 'LiquidSurfaceUV; left half of atlas; original 0-1 liquid UV is remapped to U=0-0.5' root['uv_usage'] = 'LiquidSurfaceUV atlas: coffee U=0-0.5; foam U=0.5-1; shared V=0-1; each tile center U=0.25 or 0.75, V=0.5' root['texture_atlas'] = 'CC_CupContents_Atlas.png; left coffee 512x512, right latte 512x512; RGB PNG lossless' root['mobile_baseline_blend'] = BASE.name root['mobile_baseline_sha256'] = BASE_SHA256 root['foam_original_segments'] = 96 root['foam_mobile_segments'] = SEGMENTS def non_manifold_count(obj): bm = bmesh.new() bm.from_mesh(obj.data) count = sum(1 for edge in bm.edges if not edge.is_manifold) bm.free() return count def uv_bounds(obj): uv = obj.data.uv_layers.active return { 'u': [min(loop_uv.uv.x for loop_uv in uv.data), max(loop_uv.uv.x for loop_uv in uv.data)], 'v': [min(loop_uv.uv.y for loop_uv in uv.data), max(loop_uv.uv.y for loop_uv in uv.data)], } def glb_statistics(path): raw = path.read_bytes() json_length, chunk_type = struct.unpack_from('