745 lines
33 KiB
Python
745 lines
33 KiB
Python
import bpy
|
|
import bmesh
|
|
import json
|
|
import math
|
|
import sys
|
|
from pathlib import Path
|
|
from mathutils import Matrix, Vector
|
|
|
|
ROOT = Path(__file__).resolve().parent
|
|
REFERENCE = ROOT / "reference" / "consumables"
|
|
MAX_TRIANGLES = 1000
|
|
TAU = math.tau
|
|
MANIFEST = []
|
|
|
|
|
|
def material(name, color, roughness=0.6, alpha=1.0):
|
|
mat = bpy.data.materials.new(name)
|
|
mat.diffuse_color = (*color, alpha)
|
|
mat.use_nodes = True
|
|
bsdf = mat.node_tree.nodes.get("Principled BSDF")
|
|
bsdf.inputs["Base Color"].default_value = (*color, alpha)
|
|
bsdf.inputs["Roughness"].default_value = roughness
|
|
bsdf.inputs["Alpha"].default_value = alpha
|
|
if alpha < 1.0:
|
|
bsdf.inputs["IOR"].default_value = 1.45
|
|
mat.surface_render_method = "DITHERED"
|
|
mat.use_backface_culling = False
|
|
return mat
|
|
|
|
|
|
def reset():
|
|
bpy.ops.object.select_all(action="SELECT")
|
|
bpy.ops.object.delete(use_global=False)
|
|
for collection in list(bpy.data.collections):
|
|
bpy.data.collections.remove(collection)
|
|
scene = bpy.context.scene
|
|
scene.unit_settings.system = "METRIC"
|
|
scene.unit_settings.length_unit = "METERS"
|
|
scene.unit_settings.scale_length = 1.0
|
|
scene.render.engine = "BLENDER_EEVEE"
|
|
scene.render.resolution_x = 720
|
|
scene.render.resolution_y = 720
|
|
scene.render.resolution_percentage = 100
|
|
scene.render.image_settings.file_format = "PNG"
|
|
scene.render.film_transparent = False
|
|
scene.world.color = (0.3, 0.3, 0.3)
|
|
scene.world.use_nodes = True
|
|
scene.world.node_tree.nodes["Background"].inputs[0].default_value = (0.72, 0.78, 0.82, 1)
|
|
scene.world.node_tree.nodes["Background"].inputs[1].default_value = 0.30
|
|
scene.view_settings.view_transform = "AgX"
|
|
scene.view_settings.look = "AgX - Medium High Contrast"
|
|
scene.view_settings.exposure = -0.4
|
|
bpy.context.preferences.filepaths.save_version = 0
|
|
collection = bpy.data.collections.new("Model")
|
|
scene.collection.children.link(collection)
|
|
root = bpy.data.objects.new("Asset_Root", None)
|
|
root.empty_display_type = "PLAIN_AXES"
|
|
root.empty_display_size = 0.03
|
|
collection.objects.link(root)
|
|
return collection, root
|
|
|
|
|
|
def link_mesh(collection, root, name, vertices, faces, mats, indices=None, smooth=False):
|
|
mesh = bpy.data.meshes.new(name + "_Mesh")
|
|
mesh.from_pydata(vertices, [], faces)
|
|
mesh.update()
|
|
bm = bmesh.new()
|
|
bm.from_mesh(mesh)
|
|
bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
|
|
bm.to_mesh(mesh)
|
|
bm.free()
|
|
obj = bpy.data.objects.new(name, mesh)
|
|
collection.objects.link(obj)
|
|
obj.parent = root
|
|
for mat in mats:
|
|
mesh.materials.append(mat)
|
|
for index, polygon in enumerate(mesh.polygons):
|
|
polygon.use_smooth = smooth
|
|
if indices:
|
|
polygon.material_index = indices[index]
|
|
return obj
|
|
|
|
|
|
def merge_geometry(objects, name, collection, root):
|
|
vertices = []
|
|
faces = []
|
|
mats = []
|
|
indices = []
|
|
for obj in objects:
|
|
offset = len(vertices)
|
|
matrix = obj.matrix_world
|
|
vertices.extend(tuple(matrix @ v.co) for v in obj.data.vertices)
|
|
object_mats = list(obj.data.materials)
|
|
mat_map = {}
|
|
for index, mat in enumerate(object_mats):
|
|
if mat.name not in [m.name for m in mats]:
|
|
mats.append(mat)
|
|
mat_map[index] = [m.name for m in mats].index(mat.name)
|
|
for polygon in obj.data.polygons:
|
|
faces.append(tuple(offset + i for i in polygon.vertices))
|
|
indices.append(mat_map[polygon.material_index])
|
|
merged = link_mesh(collection, root, name, vertices, faces, mats, indices, True)
|
|
for obj in objects:
|
|
mesh = obj.data
|
|
bpy.data.objects.remove(obj, do_unlink=True)
|
|
if mesh.users == 0:
|
|
bpy.data.meshes.remove(mesh)
|
|
return merged
|
|
|
|
|
|
def loft(name, profile, segments, mat, collection, root, smooth=True, cap_ribs=False):
|
|
vertices = []
|
|
rings = []
|
|
for entry in profile:
|
|
radius, z = entry[0], entry[1]
|
|
cx = entry[2] if len(entry) > 2 else 0.0
|
|
cy = entry[3] if len(entry) > 3 else 0.0
|
|
aspect = entry[4] if len(entry) > 4 else 1.0
|
|
power = entry[5] if len(entry) > 5 else 2.0
|
|
if radius == 0:
|
|
rings.append([len(vertices)])
|
|
vertices.append((cx, cy, z))
|
|
continue
|
|
ring = []
|
|
for i in range(segments):
|
|
angle = TAU * i / segments
|
|
c, s = math.cos(angle), math.sin(angle)
|
|
x = math.copysign(abs(c) ** (2.0 / power), c) * radius
|
|
y = math.copysign(abs(s) ** (2.0 / power), s) * radius * aspect
|
|
if cap_ribs:
|
|
rib = 1.0 + 0.035 * math.cos(angle * segments / 2)
|
|
x *= rib
|
|
y *= rib
|
|
ring.append(len(vertices))
|
|
vertices.append((cx + x, cy + y, z))
|
|
rings.append(ring)
|
|
faces = []
|
|
for first, second in zip(rings[:-1], rings[1:]):
|
|
for i in range(segments):
|
|
j = (i + 1) % segments
|
|
if len(first) == 1 and len(second) == 1:
|
|
continue
|
|
if len(first) == 1:
|
|
faces.append((first[0], second[j], second[i]))
|
|
elif len(second) == 1:
|
|
faces.append((first[i], first[j], second[0]))
|
|
else:
|
|
faces.append((first[i], first[j], second[j], second[i]))
|
|
return link_mesh(collection, root, name, vertices, faces, [mat], smooth=smooth)
|
|
|
|
|
|
def prism(name, outline, bottom, top, mat, collection, root, slope=0.0):
|
|
count = len(outline)
|
|
vertices = [(x, y, bottom) for x, y in outline]
|
|
vertices += [(x, y, top + slope * y) for x, y in outline]
|
|
faces = [tuple(reversed(range(count))), tuple(range(count, 2 * count))]
|
|
for i in range(count):
|
|
j = (i + 1) % count
|
|
faces.append((i, j, count + j, count + i))
|
|
return link_mesh(collection, root, name, vertices, faces, [mat])
|
|
|
|
|
|
def box(name, location, scale, mat, collection, root, angle=0.0):
|
|
verts = []
|
|
for z in (-0.5, 0.5):
|
|
for x, y in ((-0.5, -0.5), (0.5, -0.5), (0.5, 0.5), (-0.5, 0.5)):
|
|
xx, yy = x * scale[0], y * scale[1]
|
|
verts.append((location[0] + xx * math.cos(angle) - yy * math.sin(angle),
|
|
location[1] + xx * math.sin(angle) + yy * math.cos(angle),
|
|
location[2] + z * scale[2]))
|
|
faces = [(3, 2, 1, 0), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)]
|
|
return link_mesh(collection, root, name, verts, faces, [mat])
|
|
|
|
|
|
def ellipsoid(name, center, radii, mat, collection, root, segments=8):
|
|
profile = [(0, -1.0)]
|
|
for j in range(1, 4):
|
|
theta = -math.pi / 2 + math.pi * j / 4
|
|
profile.append((math.cos(theta), math.sin(theta)))
|
|
profile.append((0, 1.0))
|
|
obj = loft(name, [(r, z) for r, z in profile], segments, mat, collection, root)
|
|
for vertex in obj.data.vertices:
|
|
vertex.co.x = center[0] + vertex.co.x * radii[0]
|
|
vertex.co.y = center[1] + vertex.co.y * radii[1]
|
|
vertex.co.z = center[2] + vertex.co.z * radii[2]
|
|
obj.data.update()
|
|
return obj
|
|
|
|
|
|
def tube(name, points, radius, sides, mat, collection, root):
|
|
vertices = []
|
|
for i, point in enumerate(points):
|
|
p = Vector(point)
|
|
if i == 0:
|
|
tangent = Vector(points[1]) - p
|
|
elif i == len(points) - 1:
|
|
tangent = p - Vector(points[i - 1])
|
|
else:
|
|
tangent = Vector(points[i + 1]) - Vector(points[i - 1])
|
|
tangent.normalize()
|
|
normal = tangent.cross(Vector((0, 1, 0))).normalized()
|
|
if normal.length < 0.1:
|
|
normal = tangent.cross(Vector((1, 0, 0))).normalized()
|
|
other = tangent.cross(normal).normalized()
|
|
for j in range(sides):
|
|
a = TAU * j / sides
|
|
q = p + radius * (math.cos(a) * normal + math.sin(a) * other)
|
|
vertices.append(tuple(q))
|
|
faces = [tuple(reversed(range(sides)))]
|
|
for i in range(len(points) - 1):
|
|
for j in range(sides):
|
|
k = (j + 1) % sides
|
|
faces.append((i * sides + j, i * sides + k, (i + 1) * sides + k, (i + 1) * sides + j))
|
|
faces.append(tuple(range((len(points) - 1) * sides, len(points) * sides)))
|
|
return link_mesh(collection, root, name, vertices, faces, [mat], smooth=True)
|
|
|
|
|
|
def add_reference(root, filename):
|
|
image = bpy.data.images.load(str(REFERENCE / filename), check_existing=True)
|
|
image.name = "REFERENCE_" + Path(filename).stem
|
|
image.use_fake_user = True
|
|
image.pack()
|
|
root["reference_photo"] = filename
|
|
root["reference_usage"] = "Shape and proportion only; no label or photographic texture"
|
|
|
|
|
|
def volume_ml(obj):
|
|
bm = bmesh.new()
|
|
bm.from_mesh(obj.data)
|
|
value = abs(bm.calc_volume(signed=True)) * 1000000
|
|
bm.free()
|
|
return value
|
|
|
|
|
|
def section_solid(name, sections, segments, mat, collection, root):
|
|
vertices = []
|
|
for z, half_x, half_y, corner, cx, cy, circular in sections:
|
|
for i in range(segments):
|
|
angle = TAU * i / segments
|
|
c, s = math.cos(angle), math.sin(angle)
|
|
if circular:
|
|
x, y = half_x * c, half_y * s
|
|
else:
|
|
tx = half_x / max(abs(c), 1e-10)
|
|
ty = half_y / max(abs(s), 1e-10)
|
|
diagonal = (half_x + half_y - corner) / max(abs(c) + abs(s), 1e-10)
|
|
distance = min(tx, ty, diagonal)
|
|
x, y = distance * c, distance * s
|
|
vertices.append((cx + x, cy + y, z))
|
|
faces = [tuple(reversed(range(segments))), tuple(range((len(sections) - 1) * segments, len(sections) * segments))]
|
|
for ring in range(len(sections) - 1):
|
|
for i in range(segments):
|
|
j = (i + 1) % segments
|
|
faces.append((ring * segments + i, ring * segments + j,
|
|
(ring + 1) * segments + j, (ring + 1) * segments + i))
|
|
return link_mesh(collection, root, name, vertices, faces, [mat])
|
|
|
|
|
|
def apply_difference(body, cutter):
|
|
bpy.context.view_layer.objects.active = body
|
|
modifier = body.modifiers.new("Integral_Construction", "BOOLEAN")
|
|
modifier.operation = "DIFFERENCE"
|
|
modifier.solver = "EXACT"
|
|
modifier.object = cutter
|
|
bpy.ops.object.modifier_apply(modifier=modifier.name)
|
|
mesh = cutter.data
|
|
bpy.data.objects.remove(cutter, do_unlink=True)
|
|
if mesh.users == 0:
|
|
bpy.data.meshes.remove(mesh)
|
|
|
|
|
|
def make_rectangular_milk_body(collection, root, mat):
|
|
outer_sections = [
|
|
(0.002, 0.052, 0.052, 0.006, 0, 0, False),
|
|
(0.006, 0.058, 0.058, 0.006, 0, 0, False),
|
|
(0.018, 0.060, 0.060, 0.005, 0, 0, False),
|
|
(0.210, 0.060, 0.060, 0.005, 0, 0, False),
|
|
(0.222, 0.060, 0.060, 0.005, 0, 0, False),
|
|
(0.230, 0.055, 0.055, 0.006, 0, 0, False),
|
|
(0.242, 0.040, 0.040, 0.007, 0, 0, False),
|
|
(0.252, 0.026, 0.026, 0.007, 0, 0, False),
|
|
(0.260, 0.021, 0.021, 0, 0, 0, True),
|
|
(0.266, 0.018, 0.018, 0, 0, 0, True),
|
|
(0.278, 0.018, 0.018, 0, 0, 0, True),
|
|
]
|
|
cavity_sections = [
|
|
(0.006, 0.053, 0.053, 0.004, 0, 0, False),
|
|
(0.018, 0.055, 0.055, 0.004, 0, 0, False),
|
|
(0.112, 0.055, 0.055, 0.004, 0, 0, False),
|
|
(0.122, 0.055, 0.055, 0.062, 0, 0, False),
|
|
(0.214, 0.055, 0.055, 0.062, 0, 0, False),
|
|
(0.218, 0.055, 0.055, 0.004, 0, 0, False),
|
|
(0.230, 0.050, 0.050, 0.004, 0, 0, False),
|
|
(0.242, 0.035, 0.035, 0.004, 0, 0, False),
|
|
(0.252, 0.021, 0.021, 0.004, 0, 0, False),
|
|
(0.260, 0.015, 0.015, 0, 0, 0, True),
|
|
(0.279, 0.015, 0.015, 0, 0, 0, True),
|
|
]
|
|
body = section_solid("Milk_Bottle_Body", outer_sections, 12, mat, collection, root)
|
|
cavity = section_solid("Milk_Interior_Cavity", cavity_sections, 12, mat, collection, root)
|
|
cavity_volume = volume_ml(cavity)
|
|
control = [Vector(point) for point in [(0.080, -0.024), (0.068, -0.006), (0.044, 0.023), (0.032, 0.044), (0.006, 0.068)]]
|
|
curve = []
|
|
for segment in range(len(control) - 1):
|
|
p0 = control[max(0, segment - 1)]
|
|
p1, p2 = control[segment], control[segment + 1]
|
|
p3 = control[min(len(control) - 1, segment + 2)]
|
|
for step in range(3):
|
|
t = step / 3
|
|
point = 0.5 * ((2 * p1) + (-p0 + p2) * t
|
|
+ (2 * p0 - 5 * p1 + 4 * p2 - p3) * t * t
|
|
+ (-p0 + 3 * p1 - 3 * p2 + p3) * t * t * t)
|
|
curve.append(point)
|
|
curve.append(control[-1])
|
|
left, right = [], []
|
|
for i, point in enumerate(curve):
|
|
tangent = curve[min(i + 1, len(curve) - 1)] - curve[max(0, i - 1)]
|
|
tangent.normalize()
|
|
normal = Vector((-tangent.y, tangent.x))
|
|
left.append(point + normal * 0.0085)
|
|
right.append(point - normal * 0.0085)
|
|
tangent = (curve[-1] - curve[-2]).normalized()
|
|
normal = Vector((-tangent.y, tangent.x))
|
|
for i in range(1, 7):
|
|
angle = math.pi * i / 6
|
|
left.append(curve[-1] + tangent * (0.0085 * math.sin(angle)) + normal * (0.0085 * math.cos(angle)))
|
|
outline = [tuple(point) for point in left + list(reversed(right[:-1]))]
|
|
count = len(outline)
|
|
vertices, faces = [], []
|
|
for z, scale in [(0.122, 0.96), (0.128, 1.0), (0.208, 1.0), (0.214, 0.96)]:
|
|
for x, y in outline:
|
|
vertices.append((0.040 + (x - 0.040) * scale, 0.030 + (y - 0.030) * scale, z))
|
|
faces = [tuple(reversed(range(count))), tuple(range(3 * count, 4 * count))]
|
|
for ring in range(3):
|
|
for i in range(count):
|
|
j = (i + 1) % count
|
|
faces.append((ring * count + i, ring * count + j, (ring + 1) * count + j, (ring + 1) * count + i))
|
|
cutter = link_mesh(collection, root, "Milk_Corner_Handle_Pocket", vertices, faces, [mat])
|
|
probe = cutter.copy()
|
|
probe.data = cutter.data.copy()
|
|
collection.objects.link(probe)
|
|
bpy.context.view_layer.objects.active = probe
|
|
modifier = probe.modifiers.new("Cavity_Clearance", "BOOLEAN")
|
|
modifier.operation = "INTERSECT"
|
|
modifier.solver = "EXACT"
|
|
modifier.object = cavity
|
|
bpy.ops.object.modifier_apply(modifier=modifier.name)
|
|
overlap = volume_ml(probe)
|
|
bpy.data.objects.remove(probe, do_unlink=True)
|
|
if overlap > 0.001:
|
|
raise RuntimeError(f"Handle pocket intersects liquid cavity: {overlap} mL")
|
|
apply_difference(body, cavity)
|
|
apply_difference(body, cutter)
|
|
bm = bmesh.new()
|
|
bm.from_mesh(body.data)
|
|
bmesh.ops.dissolve_limit(bm, angle_limit=math.radians(0.5), use_dissolve_boundaries=False)
|
|
bmesh.ops.triangulate(bm, faces=list(bm.faces))
|
|
bmesh.ops.dissolve_degenerate(bm, dist=0.00000001, edges=list(bm.edges))
|
|
bmesh.ops.recalc_face_normals(bm, faces=list(bm.faces))
|
|
non_manifold = sum(not edge.is_manifold for edge in bm.edges)
|
|
bm.to_mesh(body.data)
|
|
bm.free()
|
|
for polygon in body.data.polygons:
|
|
polygon.use_smooth = polygon.center.z > 0.243 or polygon.normal.z > 0.1
|
|
body.data.update()
|
|
if non_manifold:
|
|
raise RuntimeError(f"Milk bottle has {non_manifold} non-manifold edges")
|
|
factor = math.sqrt(2150 / cavity_volume)
|
|
root["interior_capacity_ml"] = cavity_volume * factor * factor
|
|
root["body_profile"] = "Chamfered square lower cuboid; centered shrinking upper segment; circular centered mouth"
|
|
root["lower_segment_square"] = True
|
|
root["lower_segment_top_z_m"] = 0.222
|
|
root["shoulder_start_height_ratio"] = 0.222 / 0.278
|
|
root["mouth_center_xy"] = [0.0, 0.0]
|
|
root["shoulder_to_mouth_ratio"] = 0.021 / 0.018
|
|
root["handle_construction"] = "Large arched corner opening from +X toward +Y around an integral vertical grip; central body is not cut through"
|
|
root["handle_path_xy"] = [list(point) for point in curve]
|
|
root["handle_aperture_width_m"] = 0.017
|
|
root["handle_aperture_height_m"] = 0.092
|
|
root["handle_bottom_z_m"] = 0.122
|
|
root["handle_top_z_m"] = 0.214
|
|
root["handle_cavity_overlap_ml"] = overlap
|
|
root["body_non_manifold_edges"] = non_manifold
|
|
root["mouth_z_m"] = 0.278
|
|
root["cap_base_z_m"] = 0.264
|
|
root["neck_outer_radius_m"] = 0.018 * factor
|
|
root["cap_inner_radius_m"] = 0.0196 * factor
|
|
root["cap_radial_clearance_m"] = (0.0196 * 0.965 - 0.018) * factor
|
|
root["cap_top_clearance_m"] = 0.0005
|
|
return body, 0.0, 0.264, factor
|
|
|
|
|
|
def make_bottle(collection, root, kind):
|
|
milk = kind == "milk"
|
|
prefix = "Milk" if milk else "OrangeJuice"
|
|
body_mat = material(prefix + "_HDPE" if milk else prefix + "_ClearPET",
|
|
(0.88, 0.875, 0.78) if milk else (0.93, 0.98, 1.0),
|
|
0.4 if milk else 0.18,
|
|
1.0 if milk else 0.055)
|
|
cap_mat = material(prefix + "_Cap", (0.035, 0.19, 0.48) if milk else (0.025, 0.20, 0.065), 0.46)
|
|
root["design_id"] = "premade_milk" if milk else "bottled_orange_juice"
|
|
root["nominal_capacity_ml"] = 2000
|
|
root["label_packaging"] = "None: unbranded container only"
|
|
root["cap_independent"] = True
|
|
if milk:
|
|
body, neck_y, neck_z, factor = make_rectangular_milk_body(collection, root, body_mat)
|
|
else:
|
|
profile = [
|
|
(0, 0.003), (0.050, 0.003, 0, 0, 0.87, 2.7),
|
|
(0.058, 0.010, 0, 0, 0.87, 2.7), (0.060, 0.023, 0, 0, 0.87, 2.7),
|
|
(0.060, 0.068, 0, 0, 0.87, 2.7), (0.056, 0.073, 0, 0, 0.87, 2.7),
|
|
(0.059, 0.079, 0, 0, 0.87, 2.7), (0.060, 0.113, 0, 0, 0.87, 2.7),
|
|
(0.057, 0.155, 0, 0, 0.87, 2.7), (0.057, 0.180, 0, 0, 0.87, 2.7),
|
|
(0.052, 0.211, 0, 0, 0.87, 2.7), (0.040, 0.240, 0, 0, 0.87, 2.7),
|
|
(0.028, 0.254, 0, 0, 0.90, 2.3), (0.019, 0.263),
|
|
(0.018, 0.267), (0.018, 0.283), (0.014, 0.283),
|
|
(0.014, 0.261), (0, 0.261),
|
|
]
|
|
body = loft(prefix + "_Bottle_Body", profile, 16, body_mat, collection, root)
|
|
juice_mat = material("OrangeJuice_Liquid", (0.95, 0.29, 0.012), 0.36)
|
|
fill = [
|
|
(0, 0.010), (0.049, 0.010, 0, 0, 0.87, 2.7),
|
|
(0.056, 0.020, 0, 0, 0.87, 2.7), (0.0565, 0.150, 0, 0, 0.87, 2.7),
|
|
(0.0545, 0.180, 0, 0, 0.87, 2.7), (0.050, 0.211, 0, 0, 0.87, 2.7),
|
|
(0.039, 0.236, 0, 0, 0.87, 2.7), (0.034, 0.245, 0, 0, 0.87, 2.7),
|
|
(0, 0.245),
|
|
]
|
|
fill_obj = loft(prefix + "_Juice_Fill", fill, 16, juice_mat, collection, root)
|
|
neck_y, neck_z = 0.0, 0.283
|
|
if milk:
|
|
cap_profile = [
|
|
(0, 0.017), (0.019, 0.017), (0.021, 0.014), (0.0215, 0.004),
|
|
(0.0215, 0.002), (0.0208, 0), (0.0196, 0), (0.0196, 0.0145),
|
|
(0, 0.0145),
|
|
]
|
|
else:
|
|
cap_profile = [
|
|
(0, 0), (0.0208, 0), (0.0215, 0.002), (0.0215, 0.004),
|
|
(0.021, 0.005), (0.021, 0.014), (0.019, 0.017), (0, 0.017),
|
|
]
|
|
cap_pivot = bpy.data.objects.new(prefix + "_Cap_Pivot", None)
|
|
collection.objects.link(cap_pivot)
|
|
cap_pivot.parent = root
|
|
cap_pivot.location = (0, neck_y, neck_z)
|
|
cap_pivot.empty_display_size = 0.024
|
|
cap = loft(prefix + "_Cap", cap_profile, 16, cap_mat, collection, cap_pivot, cap_ribs=True)
|
|
cap["detach_axis"] = "Z"
|
|
cap["thread_detail"] = "Omitted for low-poly budget"
|
|
if milk:
|
|
root["volume_calibration"] = "Inner cavity calibrated to nominal 2L with headroom"
|
|
else:
|
|
factor = math.sqrt(2000 / volume_ml(fill_obj))
|
|
root["modeled_liquid_ml"] = 2000.0
|
|
for obj in collection.all_objects:
|
|
if obj.type == "MESH":
|
|
for vertex in obj.data.vertices:
|
|
vertex.co.x *= factor
|
|
vertex.co.y *= factor
|
|
cap_pivot.location.y *= factor
|
|
root["volume_calibration"] = "Geometric volume, not a manufacturing specification"
|
|
return body, cap, cap_pivot
|
|
|
|
|
|
def make_croissant(collection, root):
|
|
mats = [
|
|
material("Croissant_Golden", (0.62, 0.265, 0.060), 0.72),
|
|
material("Croissant_LightLayers", (0.82, 0.435, 0.13), 0.75),
|
|
material("Croissant_Toast", (0.40, 0.135, 0.026), 0.78),
|
|
]
|
|
count, sides = 23, 10
|
|
vertices, faces, indices = [], [], []
|
|
for i in range(count):
|
|
t = -1 + 2 * i / (count - 1)
|
|
x, y = 0.09 * t, 0.052 * abs(t) ** 1.85 - 0.009
|
|
z = 0.026 + 0.004 * (1 - t * t)
|
|
derivative = Vector((0.09, 0.052 * 1.85 * math.copysign(abs(t) ** 0.85, t), 0))
|
|
tangent = derivative.normalized()
|
|
normal = Vector((-tangent.y, tangent.x, 0))
|
|
radius = 0.003 + 0.026 * max(0, 1 - t * t) ** 0.72
|
|
for j in range(sides):
|
|
angle = TAU * j / sides
|
|
layer = 1 + 0.055 * math.cos(t * math.pi * 9 + 0.7 * math.sin(angle))
|
|
p = Vector((x, y, z))
|
|
p += normal * (radius * 0.92 * math.cos(angle) * layer)
|
|
p.z += radius * math.sin(angle) * layer
|
|
vertices.append(tuple(p))
|
|
for i in range(count - 1):
|
|
for j in range(sides):
|
|
k = (j + 1) % sides
|
|
faces.append((i * sides + j, i * sides + k, (i + 1) * sides + k, (i + 1) * sides + j))
|
|
indices.append(1 if i % 5 in (0, 1) else (2 if i % 5 == 3 else 0))
|
|
faces += [tuple(reversed(range(sides))), tuple(range((count - 1) * sides, count * sides))]
|
|
indices += [0, 0]
|
|
obj = link_mesh(collection, root, "Croissant_Rolled_Pastry", vertices, faces, mats, indices, True)
|
|
obj["recognition_features"] = "Crescent, tapered tips, laminated rolled bands"
|
|
root["design_id"] = "croissant"
|
|
|
|
|
|
def make_cake(collection, root):
|
|
chocolate = material("Cake_ChocolateSponge", (0.12, 0.040, 0.019), 0.88)
|
|
cream = material("Cake_VanillaCream", (0.88, 0.78, 0.57), 0.67)
|
|
frosting = material("Cake_Frosting", (0.91, 0.84, 0.70), 0.56)
|
|
red = material("Cake_Strawberry", (0.58, 0.027, 0.020), 0.4)
|
|
green = material("Cake_StrawberryLeaves", (0.095, 0.25, 0.025), 0.72)
|
|
outline = [(0, -0.060), (-0.054, 0.031), (-0.046, 0.044), (-0.027, 0.052),
|
|
(0, 0.055), (0.027, 0.052), (0.046, 0.044), (0.054, 0.031)]
|
|
prism("Cake_Sponge_Lower", outline, 0.001, 0.021, chocolate, collection, root)
|
|
prism("Cake_Cream_Lower", outline, 0.021, 0.027, cream, collection, root)
|
|
prism("Cake_Sponge_Upper", outline, 0.027, 0.046, chocolate, collection, root)
|
|
prism("Cake_Cream_Upper", outline, 0.046, 0.052, cream, collection, root)
|
|
prism("Cake_Frosting_Top", outline, 0.052, 0.059, frosting, collection, root, 0.08)
|
|
ellipsoid("Cake_Strawberry", (0, 0.036, 0.076), (0.014, 0.012, 0.019), red, collection, root)
|
|
for i in range(3):
|
|
a = i * TAU / 3
|
|
link_mesh(collection, root, f"Cake_Leaf_{i + 1}", [
|
|
(0, 0.036, 0.091), (0.014 * math.cos(a - 0.3), 0.036 + 0.014 * math.sin(a - 0.3), 0.092),
|
|
(0.019 * math.cos(a), 0.036 + 0.019 * math.sin(a), 0.090),
|
|
(0.014 * math.cos(a + 0.3), 0.036 + 0.014 * math.sin(a + 0.3), 0.092),
|
|
], [(0, 1, 2), (0, 2, 3)], [green])
|
|
root["design_id"] = "cake_slice"
|
|
|
|
|
|
def make_cream_toast(collection, root):
|
|
crust = material("Toast_Crust", (0.43, 0.18, 0.052), 0.82)
|
|
crumb = material("Toast_Crumb", (0.82, 0.65, 0.38), 0.88)
|
|
cream = material("Toast_PaleYellowCream", (0.94, 0.77, 0.30), 0.48)
|
|
outline = [
|
|
(-0.046, -0.059), (0.046, -0.059), (0.053, -0.055),
|
|
(0.057, -0.048), (0.057, -0.030), (0.055, 0.022),
|
|
(0.054, 0.038), (0.047, 0.050), (0.035, 0.059),
|
|
(0.020, 0.064), (0, 0.061), (-0.020, 0.064),
|
|
(-0.035, 0.059), (-0.047, 0.050), (-0.054, 0.038),
|
|
(-0.055, 0.022), (-0.057, -0.030), (-0.057, -0.048),
|
|
(-0.053, -0.055),
|
|
]
|
|
|
|
def layer(name, rings, mat):
|
|
count = len(outline)
|
|
vertices = [(x * scale, y * scale, z) for scale, z in rings for x, y in outline]
|
|
faces = [tuple(reversed(range(count)))]
|
|
for ring in range(len(rings) - 1):
|
|
for i in range(count):
|
|
j = (i + 1) % count
|
|
a = ring * count
|
|
b = (ring + 1) * count
|
|
faces.append((a + i, a + j, b + j, b + i))
|
|
faces.append(tuple(range((len(rings) - 1) * count, len(rings) * count)))
|
|
obj = link_mesh(collection, root, name, vertices, faces, [mat], smooth=True)
|
|
for polygon in obj.data.polygons:
|
|
polygon.use_smooth = len(polygon.vertices) == 4
|
|
return obj
|
|
|
|
layer("Toast_Bread_Crust", [(0.94, 0.001), (1.0, 0.003), (1.0, 0.0145), (0.965, 0.017)], crust)
|
|
layer("Toast_Inner_Crumb", [(0.90, 0.017), (0.90, 0.01735)], crumb)
|
|
layer("Toast_PaleYellowCream_Layer", [(0.827, 0.01735), (0.845, 0.01775), (0.827, 0.0194)], cream)
|
|
root["design_id"] = "avocado_toast"
|
|
root["presentation"] = "Plain toast with one pale-yellow cream layer; no avocado, chili or other toppings"
|
|
|
|
|
|
def triangle_count(obj, depsgraph=None):
|
|
if depsgraph is None:
|
|
obj.data.calc_loop_triangles()
|
|
return len(obj.data.loop_triangles)
|
|
evaluated = obj.evaluated_get(depsgraph)
|
|
mesh = evaluated.to_mesh()
|
|
mesh.calc_loop_triangles()
|
|
count = len(mesh.loop_triangles)
|
|
evaluated.to_mesh_clear()
|
|
return count
|
|
|
|
|
|
def bounds(objects):
|
|
bpy.context.view_layer.update()
|
|
points = [obj.matrix_world @ vertex.co for obj in objects for vertex in obj.data.vertices]
|
|
return [min(v[i] for v in points) for i in range(3)], [max(v[i] for v in points) for i in range(3)]
|
|
|
|
|
|
def studio(collection, objects, path, positive_y=False):
|
|
scene = bpy.context.scene
|
|
minimum, maximum = bounds(objects)
|
|
center = Vector([(a + b) / 2 for a, b in zip(minimum, maximum)])
|
|
size = max(maximum[i] - minimum[i] for i in range(3))
|
|
floor_mat = material("Studio_Background", (0.68, 0.70, 0.66), 0.86)
|
|
bpy.ops.mesh.primitive_plane_add(size=200, location=(0, 0, min(-0.0002, minimum[2] - 0.0002)))
|
|
floor = bpy.context.object
|
|
floor.name = "Studio_Ground"
|
|
floor.data.materials.append(floor_mat)
|
|
for c in list(floor.users_collection):
|
|
c.objects.unlink(floor)
|
|
collection.objects.link(floor)
|
|
camera_data = bpy.data.cameras.new("Studio_Camera")
|
|
camera = bpy.data.objects.new("Studio_Camera", camera_data)
|
|
collection.objects.link(camera)
|
|
camera.location = center + Vector((size * 1.6, size * 2.3 if positive_y else -size * 2.3, size * 1.65))
|
|
camera.rotation_euler = (center - camera.location).to_track_quat("-Z", "Y").to_euler()
|
|
camera_data.type = "ORTHO"
|
|
camera_data.ortho_scale = size * 1.30
|
|
scene.camera = camera
|
|
for i, (offset, power, light_size) in enumerate([
|
|
((-1.5, -1.8, 3.0), 35, 1.6), ((2.0, -0.3, 1.6), 20, 1.3), ((0.3, 2.0, 2.4), 30, 1.4),
|
|
]):
|
|
data = bpy.data.lights.new(f"Studio_Light_{i + 1}", "AREA")
|
|
data.energy = power * max(0.2, size * 3) * 0.25
|
|
data.shape = "DISK"
|
|
data.size = light_size * size
|
|
obj = bpy.data.objects.new(data.name, data)
|
|
collection.objects.link(obj)
|
|
obj.location = center + Vector(offset) * size
|
|
obj.rotation_euler = (center - obj.location).to_track_quat("-Z", "Y").to_euler()
|
|
scene.render.filepath = str(path)
|
|
bpy.ops.render.render(write_still=True)
|
|
|
|
|
|
def export_model(collection, path):
|
|
bpy.ops.object.select_all(action="DESELECT")
|
|
for obj in collection.all_objects:
|
|
obj.select_set(True)
|
|
bpy.context.view_layer.objects.active = next(obj for obj in collection.all_objects if obj.type == "MESH")
|
|
bpy.ops.export_scene.gltf(filepath=str(path), export_format="GLB", use_selection=True,
|
|
export_yup=True, export_apply=True, export_cameras=False, export_lights=False)
|
|
|
|
|
|
def report_for(root, collection, out, blend, glb, cap=None):
|
|
objects = [obj for obj in collection.all_objects if obj.type == "MESH"]
|
|
depsgraph = bpy.context.evaluated_depsgraph_get()
|
|
components = {obj.name: triangle_count(obj, depsgraph) for obj in objects}
|
|
total = sum(components.values())
|
|
minimum, maximum = bounds(objects)
|
|
report = {
|
|
"asset": root.name,
|
|
"design_id": root.get("design_id"),
|
|
"presentation": root.get("presentation"),
|
|
"blender_version": bpy.app.version_string,
|
|
"units": "meters",
|
|
"axis_convention": "Blender Z up; GLB Y up",
|
|
"triangle_limit": MAX_TRIANGLES,
|
|
"triangles": total,
|
|
"passed_triangle_budget": total <= MAX_TRIANGLES,
|
|
"mesh_components": components,
|
|
"bounds_min_m": minimum,
|
|
"bounds_max_m": maximum,
|
|
"dimensions_m": [maximum[i] - minimum[i] for i in range(3)],
|
|
"reference_photo": root.get("reference_photo"),
|
|
"reference_images_packed": True,
|
|
"labels_or_brand_graphics": False,
|
|
"blend": blend.name,
|
|
"glb": glb.name,
|
|
"preview": "preview.png",
|
|
"native_reopen_passed": None,
|
|
"glb_reimport_passed": None,
|
|
}
|
|
for key in ("nominal_capacity_ml", "cap_independent", "interior_capacity_ml", "modeled_liquid_ml",
|
|
"body_profile", "handle_construction", "body_non_manifold_edges",
|
|
"mouth_z_m", "cap_base_z_m", "neck_outer_radius_m", "cap_inner_radius_m",
|
|
"cap_radial_clearance_m", "cap_top_clearance_m", "lower_segment_square",
|
|
"lower_segment_top_z_m", "shoulder_start_height_ratio", "mouth_center_xy", "shoulder_to_mouth_ratio",
|
|
"handle_bottom_z_m", "handle_top_z_m", "handle_cavity_overlap_ml",
|
|
"handle_aperture_width_m", "handle_aperture_height_m"):
|
|
if key in root:
|
|
report[key] = list(root[key]) if key == "mouth_center_xy" else root[key]
|
|
if cap:
|
|
report["cap_mesh"] = cap.name
|
|
report["cap_triangles"] = components[cap.name]
|
|
report["cap_files"] = [blend.with_name(blend.stem + "_Cap.blend").name,
|
|
glb.with_name(glb.stem + "_Cap.glb").name]
|
|
report["preview_cap_removed"] = "preview_cap_removed.png"
|
|
report["passed"] = report["passed_triangle_budget"]
|
|
(out / "validation.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
|
assert total <= MAX_TRIANGLES, (root.name, total)
|
|
return report
|
|
|
|
|
|
def finalize(root, collection, directory, cap=None, cap_pivot=None):
|
|
out = ROOT / directory
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
blend = out / ("PerfectCoffee_" + out.name + ".blend")
|
|
glb = blend.with_suffix(".glb")
|
|
report = report_for(root, collection, out, blend, glb, cap)
|
|
export_model(collection, glb)
|
|
studio_collection = bpy.data.collections.new("Studio")
|
|
bpy.context.scene.collection.children.link(studio_collection)
|
|
studio(studio_collection, [obj for obj in collection.all_objects if obj.type == "MESH"], out / "preview.png",
|
|
positive_y=root.name == "Milk2L_Root")
|
|
if cap_pivot:
|
|
saved_location = cap_pivot.location.copy()
|
|
cap_pivot.location += Vector((0.045, 0, 0.055))
|
|
bpy.context.scene.render.filepath = str(out / "preview_cap_removed.png")
|
|
bpy.ops.render.render(write_still=True)
|
|
cap_pivot.location = saved_location
|
|
bpy.context.scene.render.filepath = str(out / "preview.png")
|
|
for area in bpy.context.screen.areas if bpy.context.screen else []:
|
|
if area.type == "VIEW_3D":
|
|
area.spaces.active.region_3d.view_distance = 0.5
|
|
bpy.ops.wm.save_as_mainfile(filepath=str(blend), compress=True)
|
|
if cap:
|
|
cap_mesh = cap.data.copy()
|
|
cap_name = cap.name
|
|
cap_only_name = root.name + "_CapOnly"
|
|
reset()
|
|
cap_collection = bpy.data.collections.get("Model")
|
|
cap_root = bpy.data.objects.get("Asset_Root")
|
|
cap_root.name = cap_only_name
|
|
obj = bpy.data.objects.new(cap_name, cap_mesh)
|
|
cap_collection.objects.link(obj)
|
|
obj.parent = cap_root
|
|
cap_root["pivot"] = "Bottom center; local Z is removal axis"
|
|
export_model(cap_collection, glb.with_name(glb.stem + "_Cap.glb"))
|
|
bpy.ops.wm.save_as_mainfile(filepath=str(blend.with_name(blend.stem + "_Cap.blend")), compress=True)
|
|
MANIFEST.append({"directory": directory, "blend": blend.name, "glb": glb.name, "triangles": report["triangles"]})
|
|
print("ASSET_COMPLETE", directory, report["triangles"], flush=True)
|
|
|
|
|
|
ASSETS = [
|
|
("milk_2l", "milk", "milk_2l_woolworths.png", "Milk2L_Root"),
|
|
("orange_juice_2l", "orange_juice", "orange_juice_2l_product.webp", "OrangeJuice2L_Root"),
|
|
("food/bakery_and_cake/Croissant", "croissant", "croissant.jpg", "Croissant_Root"),
|
|
("food/bakery_and_cake/CakeSlice", "cake", "cake_slice.jpg", "CakeSlice_Root"),
|
|
("food/toast_and_wrap/AvocadoToast", "avocado_toast", "cream_toast.jpg", "AvocadoToast_Root"),
|
|
]
|
|
|
|
requested_assets = set(sys.argv[sys.argv.index("--") + 1:]) if "--" in sys.argv else set()
|
|
for directory, kind, reference, root_name in ASSETS:
|
|
if requested_assets and directory not in requested_assets:
|
|
continue
|
|
collection, root = reset()
|
|
root.name = root_name
|
|
add_reference(root, reference)
|
|
cap, cap_pivot = None, None
|
|
if kind in ("milk", "orange_juice"):
|
|
_, cap, cap_pivot = make_bottle(collection, root, kind)
|
|
elif kind == "croissant":
|
|
make_croissant(collection, root)
|
|
elif kind == "cake":
|
|
make_cake(collection, root)
|
|
elif kind == "avocado_toast":
|
|
make_cream_toast(collection, root)
|
|
finalize(root, collection, directory, cap, cap_pivot)
|
|
|
|
if not requested_assets:
|
|
(ROOT / "low_poly_consumables_manifest.json").write_text(json.dumps({
|
|
"triangle_limit_per_asset": MAX_TRIANGLES,
|
|
"assets": MANIFEST,
|
|
}, ensure_ascii=False, indent=2) + "\n")
|
|
print("ALL_ASSETS_COMPLETE", len(MANIFEST), flush=True)
|