Files

453 lines
16 KiB
Python

import bpy
import bmesh
import json
import math
from pathlib import Path
from mathutils import Vector
from mathutils.bvhtree import BVHTree
OUT = Path('/Users/yanchenyu/Documents/WebApps/PerfetCoffee/model_assets/coffee_cup')
OUT.mkdir(parents=True, exist_ok=True)
CM = 0.01
SEGMENTS = 24
CUP_HEIGHT = 11.0
CUP_BOTTOM_RADIUS = 3.0
CUP_TOP_RADIUS = 4.25
CUP_THICKNESS = 0.2
LID_BOTTOM = 10.7
LID_TOP = 13.0
LID_BOTTOM_RADIUS = 4.65
LID_TOP_RADIUS = 3.9
LID_THICKNESS = 0.1
DECK_TOP = 12.55
DECK_BOTTOM = DECK_TOP - LID_THICKNESS
OPENING_CENTER_Y = 3.55
OPENING_LENGTH = 1.0
OPENING_WIDTH = 0.5
VENT_CENTER_Y = -2.65
VENT_RADIUS = 0.05
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 = 'CENTIMETERS'
scene.unit_settings.scale_length = 1.0
model_collection = bpy.data.collections.new('CC_CoffeeCup_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('CC_CoffeeCup_Assembly', None)
model_collection.objects.link(root)
root.empty_display_type = 'PLAIN_AXES'
root.empty_display_size = 0.02
root['units'] = 'meters; dimensions documented in centimeters'
root['cup_height_cm'] = CUP_HEIGHT
root['assembled_height_cm'] = LID_TOP
root['lid_height_cm'] = LID_TOP - LID_BOTTOM
root['assembly_overlap_cm'] = CUP_HEIGHT - LID_BOTTOM
root['forward_axis'] = '+Y; XOY is the top view'
root['radial_segments'] = SEGMENTS
def move_to(obj, collection):
for old_collection in list(obj.users_collection):
old_collection.objects.unlink(obj)
collection.objects.link(obj)
return obj
def make_material(name, color, roughness):
mat = bpy.data.materials.new(name)
mat.use_nodes = True
mat.diffuse_color = (*color, 1.0)
bsdf = mat.node_tree.nodes.get('Principled BSDF')
bsdf.inputs['Base Color'].default_value = (*color, 1.0)
bsdf.inputs['Roughness'].default_value = roughness
return mat
paper = make_material('CC_Cup_Paper', (0.82, 0.82, 0.79), 0.68)
accent = make_material('CC_Cup_Accent', (0.82, 0.82, 0.79), 0.68)
lid_white = make_material('CC_Lid_White', (0.70, 0.72, 0.70), 0.42)
def recalculate_normals(mesh):
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()
def shade_mesh(obj):
for polygon in obj.data.polygons:
polygon.use_smooth = abs(polygon.normal.z) < 0.92
def lathe(name, profile_cm, segments=SEGMENTS):
vertices = []
rings = []
for radius, height in profile_cm:
if radius == 0:
rings.append([len(vertices)])
vertices.append((0.0, 0.0, height * CM))
else:
ring = []
for index in range(segments):
angle = 2.0 * math.pi * index / segments
ring.append(len(vertices))
vertices.append((radius * CM * math.cos(angle), radius * CM * math.sin(angle), height * CM))
rings.append(ring)
faces = []
for ring_index, first in enumerate(rings):
second = rings[(ring_index + 1) % len(rings)]
if len(first) == 1 and len(second) == 1:
continue
for index in range(segments):
next_index = (index + 1) % segments
if len(first) == 1:
faces.append((first[0], second[next_index], second[index]))
elif len(second) == 1:
faces.append((first[index], first[next_index], second[0]))
else:
faces.append((first[index], first[next_index], second[next_index], second[index]))
mesh = bpy.data.meshes.new(name + '_Mesh')
mesh.from_pydata(vertices, [], faces)
recalculate_normals(mesh)
obj = bpy.data.objects.new(name, mesh)
model_collection.objects.link(obj)
obj.parent = root
obj.data.materials.append(paper)
shade_mesh(obj)
return obj
BAND_BOTTOM = CUP_HEIGHT * 1.0 / 5.0
BAND_TOP = CUP_HEIGHT * 4.0 / 5.0
def cup_radius_at(height):
return CUP_BOTTOM_RADIUS + (CUP_TOP_RADIUS - CUP_BOTTOM_RADIUS) * height / CUP_HEIGHT
cup_profile = [
(0.0, 0.0),
(CUP_BOTTOM_RADIUS, 0.0),
(cup_radius_at(BAND_BOTTOM), BAND_BOTTOM),
(cup_radius_at(BAND_TOP), BAND_TOP),
(CUP_TOP_RADIUS, CUP_HEIGHT),
(CUP_TOP_RADIUS - CUP_THICKNESS, CUP_HEIGHT),
(cup_radius_at(BAND_TOP) - CUP_THICKNESS, BAND_TOP),
(cup_radius_at(BAND_BOTTOM) - CUP_THICKNESS, BAND_BOTTOM),
(CUP_BOTTOM_RADIUS - CUP_THICKNESS, CUP_THICKNESS),
(0.0, CUP_THICKNESS),
]
cup = lathe('CC_Cup_Body', cup_profile)
cup.data.materials.append(accent)
for polygon in cup.data.polygons:
center_height = polygon.center.z / CM
radial_normal = polygon.center.x * polygon.normal.x + polygon.center.y * polygon.normal.y
if BAND_BOTTOM <= center_height <= BAND_TOP and radial_normal > 0.0:
polygon.material_index = 1
cup['bottom_diameter_cm'] = CUP_BOTTOM_RADIUS * 2.0
cup['top_diameter_cm'] = CUP_TOP_RADIUS * 2.0
cup['wall_thickness_cm'] = CUP_THICKNESS
cup['height_cm'] = CUP_HEIGHT
cup['accent_band_start_cm'] = BAND_BOTTOM
cup['accent_band_end_cm'] = BAND_TOP
lid_profile = [
(LID_BOTTOM_RADIUS, LID_BOTTOM),
(LID_BOTTOM_RADIUS, 10.95),
(4.50, 11.40),
(4.10, 11.40),
(LID_TOP_RADIUS, LID_TOP),
(LID_TOP_RADIUS - LID_THICKNESS, LID_TOP),
(3.82, DECK_TOP),
(0.0, DECK_TOP),
(0.0, DECK_BOTTOM),
(3.82, DECK_BOTTOM),
(4.00, 11.30),
(4.40, 11.30),
(LID_BOTTOM_RADIUS - LID_THICKNESS, LID_BOTTOM),
]
lid = lathe('CC_Lid', lid_profile)
lid.data.materials[0] = lid_white
lid['bottom_diameter_cm'] = LID_BOTTOM_RADIUS * 2.0
lid['top_diameter_cm'] = LID_TOP_RADIUS * 2.0
lid['wall_thickness_cm'] = LID_THICKNESS
lid['height_cm'] = LID_TOP - LID_BOTTOM
lid['sip_opening_cm'] = '1.0 x 0.5; capsule/rounded rectangle; long axis X'
lid['vent_diameter_cm'] = VENT_RADIUS * 2.0
lid['opening_positions_cm'] = f'sip=(0,+{OPENING_CENTER_Y:.2f}), vent=(0,{VENT_CENTER_Y:.2f})'
def capsule_points(length, width, center_y, arc_steps=7):
radius = width / 2.0
straight = (length - width) / 2.0
points = []
for step in range(arc_steps + 1):
angle = -math.pi / 2.0 + math.pi * step / arc_steps
points.append(((straight + radius * math.cos(angle)) * CM, (center_y + radius * math.sin(angle)) * CM))
for step in range(arc_steps + 1):
angle = math.pi / 2.0 + math.pi * step / arc_steps
points.append(((-straight + radius * math.cos(angle)) * CM, (center_y + radius * math.sin(angle)) * CM))
return points
def capsule_solid(name, length, width, center_y, bottom_z, top_z, inner_width=None):
outer = capsule_points(length, width, center_y)
count = len(outer)
if inner_width is None:
vertices = [(x, y, bottom_z * CM) for x, y in outer] + [(x, y, top_z * CM) for x, y in outer]
faces = [tuple(reversed(range(count))), tuple(range(count, count * 2))]
for index in range(count):
next_index = (index + 1) % count
faces.append((index, next_index, count + next_index, count + index))
else:
inner = capsule_points(length - (width - inner_width), inner_width, center_y)
vertices = (
[(x, y, bottom_z * CM) for x, y in outer]
+ [(x, y, bottom_z * CM) for x, y in inner]
+ [(x, y, top_z * CM) for x, y in outer]
+ [(x, y, top_z * CM) for x, y in inner]
)
faces = []
for index in range(count):
next_index = (index + 1) % count
faces.extend([
(index, next_index, 2 * count + next_index, 2 * count + index),
(count + index, 3 * count + index, 3 * count + next_index, count + next_index),
(2 * count + index, 2 * count + next_index, 3 * count + next_index, 3 * count + index),
(index, count + index, count + next_index, next_index),
])
mesh = bpy.data.meshes.new(name + '_Mesh')
mesh.from_pydata(vertices, [], faces)
recalculate_normals(mesh)
obj = bpy.data.objects.new(name, mesh)
model_collection.objects.link(obj)
return obj
def boolean_apply(target, tool, operation):
bpy.context.view_layer.objects.active = target
modifier = target.modifiers.new('CC_' + operation.title(), 'BOOLEAN')
modifier.operation = operation
modifier.solver = 'EXACT'
modifier.object = tool
bpy.ops.object.modifier_apply(modifier=modifier.name)
bpy.data.objects.remove(tool, do_unlink=True)
spout = capsule_solid(
'CC_Sip_Spout_Builder',
OPENING_LENGTH + 2.0 * LID_THICKNESS,
OPENING_WIDTH + 2.0 * LID_THICKNESS,
OPENING_CENTER_Y,
DECK_BOTTOM,
12.90,
inner_width=OPENING_WIDTH,
)
boolean_apply(lid, spout, 'UNION')
sip_cutter = capsule_solid(
'CC_Sip_Opening_Cutter',
OPENING_LENGTH,
OPENING_WIDTH,
OPENING_CENTER_Y,
DECK_BOTTOM - 0.2,
LID_TOP + 0.2,
)
boolean_apply(lid, sip_cutter, 'DIFFERENCE')
bpy.ops.mesh.primitive_cylinder_add(
vertices=16,
radius=VENT_RADIUS * CM,
depth=1.0 * CM,
location=(0.0, VENT_CENTER_Y * CM, DECK_TOP * CM),
)
vent_cutter = bpy.context.object
vent_cutter.name = 'CC_Vent_Cutter'
boolean_apply(lid, vent_cutter, 'DIFFERENCE')
recalculate_normals(lid.data)
shade_mesh(lid)
def point_at(obj, target):
direction = Vector(target) - obj.location
obj.rotation_euler = direction.to_track_quat('-Z', 'Y').to_euler()
def camera(name, location, target, ortho_scale):
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)
studio_collection.objects.link(obj)
obj.location = location
point_at(obj, target)
return obj
def area_light(name, location, energy, size, target=(0.0, 0.0, 0.06)):
data = bpy.data.lights.new(name, 'AREA')
data.energy = energy
data.shape = 'DISK'
data.size = size
obj = bpy.data.objects.new(name, data)
studio_collection.objects.link(obj)
obj.location = location
point_at(obj, target)
return obj
world = bpy.data.worlds.new('Studio_World')
world.use_nodes = True
world.node_tree.nodes['Background'].inputs['Color'].default_value = (0.12, 0.14, 0.17, 1.0)
world.node_tree.nodes['Background'].inputs['Strength'].default_value = 0.20
scene.world = world
area_light('Studio_Key', (0.10, 0.12, 0.24), 2.0, 0.16)
area_light('Studio_Fill', (-0.14, 0.04, 0.13), 0.8, 0.14)
area_light('Studio_Rim', (0.02, -0.14, 0.19), 2.5, 0.12)
assembled_camera = camera('Acceptance_Assembled', (0.18, 0.24, 0.18), (0.0, 0.0, 0.064), 0.185)
top_camera = camera('Acceptance_Top_XOY_Positive_Y_Forward', (0.0, 0.0, 0.32), (0.0, 0.0, 0.0), 0.112)
exploded_camera = camera('Acceptance_Exploded', (0.21, 0.28, 0.27), (0.0, 0.0, 0.082), 0.255)
scene.render.engine = 'CYCLES'
scene.cycles.samples = 48
scene.cycles.use_denoising = True
scene.render.resolution_x = 1000
scene.render.resolution_y = 1000
scene.render.resolution_percentage = 100
scene.render.image_settings.file_format = 'PNG'
scene.render.image_settings.color_mode = 'RGBA'
scene.render.film_transparent = True
scene.view_settings.view_transform = 'AgX'
scene.view_settings.exposure = -0.5
def dimensions_cm(obj):
return [round(value / CM, 5) for value in obj.dimensions]
def 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 ray_hits_lid(x_cm, y_cm):
evaluated = lid.evaluated_get(bpy.context.evaluated_depsgraph_get())
origin = Vector((x_cm * CM, y_cm * CM, (LID_TOP + 1.0) * CM))
return evaluated.ray_cast(origin, Vector((0.0, 0.0, -1.0)))[0]
bpy.context.view_layer.update()
cup_bvh = BVHTree.FromObject(cup, bpy.context.evaluated_depsgraph_get())
lid_bvh = BVHTree.FromObject(lid, bpy.context.evaluated_depsgraph_get())
intersections = cup_bvh.overlap(lid_bvh)
inner_lid_radius_at_cup_top = 4.55 + (4.40 - 4.55) * ((CUP_HEIGHT - LID_BOTTOM) / (11.30 - LID_BOTTOM))
fit_clearance = inner_lid_radius_at_cup_top - CUP_TOP_RADIUS
sip_is_open = not ray_hits_lid(0.0, OPENING_CENTER_Y)
vent_is_open = not ray_hits_lid(0.0, VENT_CENTER_Y)
deck_is_solid = ray_hits_lid(0.0, 0.0)
cup_non_manifold = manifold_count(cup)
lid_non_manifold = manifold_count(lid)
assembly_top = max((obj.matrix_world @ Vector(corner)).z for obj in (cup, lid) for corner in obj.bound_box)
assembly_bottom = min((obj.matrix_world @ Vector(corner)).z for obj in (cup, lid) for corner in obj.bound_box)
assembly_height = (assembly_top - assembly_bottom) / CM
report = {
'radial_segments': SEGMENTS,
'components': {
'CC_Cup_Body': {'dimensions_cm': dimensions_cm(cup), 'non_manifold_edges': cup_non_manifold},
'CC_Lid': {'dimensions_cm': dimensions_cm(lid), 'non_manifold_edges': lid_non_manifold},
},
'assembly': {
'height_cm': round(assembly_height, 5),
'lid_bottom_cm': LID_BOTTOM,
'overlap_cm': CUP_HEIGHT - LID_BOTTOM,
'minimum_radial_fit_clearance_cm': round(fit_clearance, 5),
'mesh_intersections': len(intersections),
},
'features': {
'sip_opening_through_hole': sip_is_open,
'vent_through_hole': vent_is_open,
'deck_solid_at_center': deck_is_solid,
'sip_opening_length_cm': OPENING_LENGTH,
'sip_opening_width_cm': OPENING_WIDTH,
'sip_edge_clearance_cm': round(3.82 - (OPENING_CENTER_Y + OPENING_WIDTH / 2.0), 5),
'vent_diameter_cm': VENT_RADIUS * 2.0,
'vent_center_y_cm': VENT_CENTER_Y,
'forward_axis': '+Y',
'studio_ground_present': bpy.data.objects.get('Studio_Ground') is not None,
},
}
report['passed'] = (
cup_non_manifold == 0
and lid_non_manifold == 0
and abs(assembly_height - 13.0) < 0.0001
and len(intersections) == 0
and fit_clearance > 0.0
and sip_is_open
and vent_is_open
and deck_is_solid
and 0.0 <= 3.82 - (OPENING_CENTER_Y + OPENING_WIDTH / 2.0) <= 0.05
and bpy.data.objects.get('Studio_Ground') is None
)
(OUT / 'validation.json').write_text(json.dumps(report, indent=2), encoding='utf-8')
print('MODEL_VALIDATION=' + json.dumps(report), flush=True)
assert report['passed'], 'Coffee cup validation failed; inspect validation.json'
bpy.ops.object.select_all(action='DESELECT')
root.select_set(True)
cup.select_set(True)
lid.select_set(True)
bpy.context.view_layer.objects.active = root
bpy.ops.export_scene.gltf(
filepath=str(OUT / 'PerfectCoffee_CoffeeCup.glb'),
export_format='GLB',
use_selection=True,
export_apply=True,
export_animations=False,
export_extras=True,
)
for render_camera, filename in [
(assembled_camera, 'preview_assembled.png'),
(top_camera, 'preview_top.png'),
]:
scene.camera = render_camera
scene.render.filepath = str(OUT / filename)
bpy.ops.render.render(write_still=True)
lid.location.z = 0.05
bpy.context.view_layer.update()
scene.camera = exploded_camera
scene.render.filepath = str(OUT / 'preview_exploded.png')
bpy.ops.render.render(write_still=True)
lid.location.z = 0.0
bpy.context.view_layer.update()
scene.camera = assembled_camera
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(OUT / 'PerfectCoffee_CoffeeCup.blend'))
print('MODEL_BUILD_COMPLETE', flush=True)