Files
PerfectCoffee/model_assets/labels/milk/apply_milk_label.py
T
Yanchen 0f9e127162 feat: track remaining production assets, playtest scenes and references
Close the gaps left open after the LFS migration: 177 files that were
sitting untracked now enter version control, with every binary going
through Git LFS.

- labels: milk and orange-juice wrap artwork (SVG/PNG), Seedream sources,
  prompts and Dreamina job records
- orange juice 2L: bottle, cap, empty state and three label variants
  (blend + glb each)
- cup contents: desktop and mobile-optimised variants plus 3 textures
- milk 2L: empty and packaged variants with their glb exports
- milk frother: low-poly assembly and split base/jug parts
- tamper: model, glb and fit test
- juicer: seven assembly-part review scenes and their export scripts
- playtests: extraction animation scene and grinding/tamping whitebox
- reference: Minex page candidates, user review screenshots, sequence
  analysis frames and tamper STLs
- docs: item design draft, bean research notes, region reference and the
  model-asset audit report

Re-renderable preview/check frames stay untracked on purpose.
2026-11-22 10:26:53 +08:00

345 lines
15 KiB
Python

import hashlib
import json
from pathlib import Path
import bpy
from mathutils import Vector
from mathutils.bvhtree import BVHTree
OUT = Path(__file__).resolve().parent
ROOT = OUT.parents[1]
ASSET = ROOT / "milk_2l"
SOURCE = ASSET / "PerfectCoffee_milk_2l.blend"
BLEND = ASSET / "PerfectCoffee_milk_2l_Packaged.blend"
GLB = BLEND.with_suffix(".glb")
TEXTURE = OUT / "milk_wrap.png"
LABEL_Z_MIN = 0.025
LABEL_Z_MAX = 0.115
LABEL_OFFSET = 0.00012
HANDLE_BOTTOM = 0.122
def sha256(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def mesh_objects():
return [obj for obj in bpy.context.scene.objects if obj.type == "MESH" and not obj.name.startswith("Studio_")]
def triangle_count(objects):
total = 0
for obj in objects:
obj.data.calc_loop_triangles()
total += len(obj.data.loop_triangles)
return total
def clip_polygon(points, threshold, keep_above):
result = []
for first, second in zip(points, points[1:] + points[:1]):
first_inside = first.z >= threshold if keep_above else first.z <= threshold
second_inside = second.z >= threshold if keep_above else second.z <= threshold
if first_inside:
result.append(first.copy())
if first_inside != second_inside:
amount = (threshold - first.z) / (second.z - first.z)
result.append(first.lerp(second, amount))
return result
def cross_2d(origin, first, second):
return (first[0] - origin[0]) * (second[1] - origin[1]) - (first[1] - origin[1]) * (second[0] - origin[0])
def convex_hull(points):
points = sorted(set((round(point[0], 7), round(point[1], 7)) for point in points))
lower = []
for point in points:
while len(lower) >= 2 and cross_2d(lower[-2], lower[-1], point) <= 0:
lower.pop()
lower.append(point)
upper = []
for point in reversed(points):
while len(upper) >= 2 and cross_2d(upper[-2], upper[-1], point) <= 0:
upper.pop()
upper.append(point)
return lower[:-1] + upper[:-1]
def perimeter_mapping(points):
hull = convex_hull(points)
back_index = max(range(len(hull)), key=lambda i: (hull[i][1] + hull[(i + 1) % len(hull)][1]) / 2)
first = Vector(hull[back_index])
second = Vector(hull[(back_index + 1) % len(hull)])
start = (first + second) / 2
outline = [start] + [Vector(hull[i]) for i in range(back_index + 1, len(hull))]
outline += [Vector(hull[i]) for i in range(back_index + 1)] + [start]
lengths = [(second - first).length for first, second in zip(outline[:-1], outline[1:])]
total = sum(lengths)
def map_point(point):
point = Vector(point)
best_distance = None
best_length = 0.0
accumulated = 0.0
for first, second, length in zip(outline[:-1], outline[1:], lengths):
edge = second - first
amount = max(0.0, min(1.0, (point - first).dot(edge) / edge.length_squared))
nearest = first + amount * edge
distance = (point - nearest).length_squared
if best_distance is None or distance < best_distance:
best_distance = distance
best_length = accumulated + amount * length
accumulated += length
return best_length / total
return map_point, total
def create_label(body, root):
polygons = []
for polygon in body.data.polygons:
if abs(polygon.normal.z) > 0.1:
continue
if polygon.center.x * polygon.normal.x + polygon.center.y * polygon.normal.y <= 0:
continue
points = [body.data.vertices[index].co.copy() for index in polygon.vertices]
if max(point.z for point in points) < LABEL_Z_MIN or min(point.z for point in points) > LABEL_Z_MAX:
continue
clipped = clip_polygon(clip_polygon(points, LABEL_Z_MIN, True), LABEL_Z_MAX, False)
if len(clipped) >= 3:
polygons.append(clipped)
vertices = []
faces = []
vertex_map = {}
for polygon in polygons:
face = []
for point in polygon:
key = tuple(round(value, 7) for value in point)
if key not in vertex_map:
vertex_map[key] = len(vertices)
vertices.append(tuple(point))
face.append(vertex_map[key])
faces.append(tuple(face))
assert len(faces) >= 8, f"Unexpected milk label face count: {len(faces)}"
mesh = bpy.data.meshes.new("Milk_Label_Surface_Mesh")
mesh.from_pydata(vertices, [], faces)
mesh.update()
label = bpy.data.objects.new("Milk_Label_Surface", mesh)
bpy.data.collections["Model"].objects.link(label)
label.parent = root
map_point, perimeter = perimeter_mapping(vertices)
uv = mesh.uv_layers.new(name="UVMap_TightLabel")
for polygon in mesh.polygons:
values = []
for loop_index in polygon.loop_indices:
vertex = mesh.vertices[mesh.loops[loop_index].vertex_index].co
u = map_point((vertex.x, vertex.y))
v = (vertex.z - LABEL_Z_MIN) / (LABEL_Z_MAX - LABEL_Z_MIN)
values.append((loop_index, u, v))
if max(value[1] for value in values) - min(value[1] for value in values) > 0.5:
values = [(index, u + 1 if u < 0.5 else u, v) for index, u, v in values]
for loop_index, u, v in values:
uv.data[loop_index].uv = (u, v)
image = bpy.data.images.load(str(TEXTURE), check_existing=True)
image.name = "Milk_LowPoly_MeadowLabel"
image.colorspace_settings.name = "sRGB"
image.use_fake_user = True
image.pack()
material = bpy.data.materials.new("Milk_Label_Meadow")
material.use_nodes = True
material.use_backface_culling = False
shader = material.node_tree.nodes.get("Principled BSDF")
texture = material.node_tree.nodes.new("ShaderNodeTexImage")
texture.name = "Image Texture"
texture.image = image
texture.extension = "REPEAT"
texture.interpolation = "Linear"
shader.inputs["Roughness"].default_value = 0.66
material.node_tree.links.new(texture.outputs["Color"], shader.inputs["Base Color"])
material.node_tree.links.new(shader.outputs["BSDF"], material.node_tree.nodes["Material Output"].inputs["Surface"])
mesh.materials.append(material)
modifier = label.modifiers.new("Tight_To_Bottle", "SHRINKWRAP")
modifier.target = body
modifier.wrap_method = "NEAREST_SURFACEPOINT"
modifier.wrap_mode = "OUTSIDE_SURFACE"
modifier.offset = LABEL_OFFSET
label["label_surface_offset_m"] = LABEL_OFFSET
label["label_z_range_m"] = [LABEL_Z_MIN, LABEL_Z_MAX]
label["below_handle"] = True
label["texture_contains_percentage_claim"] = False
root["label_fit_method"] = "Surface-cut geometry with shrinkwrap to the actual milk bottle exterior"
return label, perimeter, len(polygons)
def surface_gaps(body, label):
bpy.context.view_layer.update()
depsgraph = bpy.context.evaluated_depsgraph_get()
tree = BVHTree.FromObject(body, depsgraph)
evaluated = label.evaluated_get(depsgraph)
mesh = evaluated.to_mesh()
inverse = body.matrix_world.inverted()
gaps = []
for vertex in mesh.vertices:
point = inverse @ (label.matrix_world @ vertex.co)
nearest, normal, _, _ = tree.find_nearest(point)
gaps.append((point - nearest).dot(normal))
evaluated.to_mesh_clear()
return [min(gaps) * 1000, max(gaps) * 1000]
def export_collection():
collection = bpy.data.collections["Model"]
bpy.ops.object.select_all(action="DESELECT")
for obj in collection.all_objects:
obj.select_set(True)
bpy.context.view_layer.objects.active = bpy.data.objects["Milk_Label_Surface"]
bpy.ops.export_scene.gltf(
filepath=str(GLB), export_format="GLB", use_selection=True,
export_yup=True, export_apply=True, export_texcoords=True,
export_cameras=False, export_lights=False,
)
source_hash = sha256(SOURCE)
bpy.ops.wm.open_mainfile(filepath=str(SOURCE))
bpy.context.preferences.filepaths.save_version = 0
assert {obj.name for obj in mesh_objects()} == {"Milk_Bottle_Body", "Milk_Cap"}
body = bpy.data.objects["Milk_Bottle_Body"]
root = bpy.data.objects["Milk2L_Root"]
cap = bpy.data.objects["Milk_Cap"]
assert triangle_count(mesh_objects()) == 906
assert cap.parent == bpy.data.objects["Milk_Cap_Pivot"]
reference_images = [image.name for image in bpy.data.images if image.name.startswith("REFERENCE_")]
for image in list(bpy.data.images):
if image.name in reference_images:
bpy.data.images.remove(image)
label, perimeter, source_face_count = create_label(body, root)
root.name = "Milk2L_Packaged_Root"
root["label_design"] = "Original low-poly dairy cow and meadow in a rounded arch, with a cream and navy text card"
root["label_artwork_origin"] = "Seedream 5.5 text-to-image illustration without image inputs; original SVG layout"
root["reference_usage"] = "General ivory, blue, sky and pasture inspiration only; no brand graphics or packaging layout reproduced"
root["seedream_prompt"] = "model_assets/labels/milk/seedream55_meadow_prompt.txt"
root["label_below_handle"] = True
root["percentage_purity_claims_present"] = False
source_triangles = triangle_count(mesh_objects())
assert source_triangles <= 1000
export_collection()
scene = bpy.context.scene
camera = scene.camera
camera.location = (0.20, -0.28, 0.18)
camera.rotation_euler = (Vector((0, 0, 0.14)) - camera.location).to_track_quat("-Z", "Y").to_euler()
camera.data.ortho_scale = 0.325
scene.render.filepath = str(ASSET / "preview_packaged.png")
bpy.ops.render.render(write_still=True)
for name, position in (("front", (0, -0.55, 0.18)), ("back", (0, 0.55, 0.18)), ("fit", (0.20, -0.28, 0.16))):
camera.location = position
target = Vector((0, 0, 0.14 if name != "fit" else 0.075))
camera.rotation_euler = (target - camera.location).to_track_quat("-Z", "Y").to_euler()
camera.data.ortho_scale = 0.325 if name != "fit" else 0.205
scene.render.resolution_x = 900
scene.render.resolution_y = 900
scene.render.filepath = str(ASSET / f"preview_packaged_{name}.png")
bpy.ops.render.render(write_still=True)
camera.location = (0.20, -0.28, 0.18)
camera.rotation_euler = (Vector((0, 0, 0.14)) - camera.location).to_track_quat("-Z", "Y").to_euler()
camera.data.ortho_scale = 0.325
scene.render.resolution_x = 720
scene.render.resolution_y = 720
scene.render.filepath = str(ASSET / "preview_packaged.png")
assert sha256(SOURCE) == source_hash
bpy.ops.wm.save_as_mainfile(filepath=str(BLEND), compress=True)
bpy.ops.wm.open_mainfile(filepath=str(BLEND))
body = bpy.data.objects["Milk_Bottle_Body"]
label = bpy.data.objects["Milk_Label_Surface"]
native_triangles = triangle_count(mesh_objects())
native_gaps = surface_gaps(body, label)
native_texture = bpy.data.materials["Milk_Label_Meadow"].node_tree.nodes["Image Texture"]
native_alpha = bpy.data.materials["Milk_HDPE"].node_tree.nodes["Principled BSDF"].inputs["Alpha"].default_value
native_ok = (
native_triangles == source_triangles and native_triangles <= 1000
and len(mesh_objects()) == 3
and len(body.data.polygons) == 682 and len(bpy.data.objects["Milk_Cap"].data.polygons) == 128
and abs(native_alpha - 1.0) < 0.00001
and bpy.data.objects["Milk_Cap"].parent == bpy.data.objects["Milk_Cap_Pivot"]
and label.modifiers["Tight_To_Bottle"].target == body
and bool(label.data.uv_layers)
and native_texture.image.name == "Milk_LowPoly_MeadowLabel"
and list(native_texture.image.size) == [3584, 768]
and native_texture.image.packed_file is not None
and bpy.data.images.get("REFERENCE_milk_2l_woolworths") is None
and max(native_gaps) <= 0.121 and min(native_gaps) > 0
and LABEL_Z_MAX < HANDLE_BOTTOM
)
bpy.ops.wm.read_factory_settings(use_empty=True)
bpy.ops.import_scene.gltf(filepath=str(GLB))
imported_objects = mesh_objects()
body = bpy.data.objects["Milk_Bottle_Body"]
label = bpy.data.objects["Milk_Label_Surface"]
glb_triangles = triangle_count(imported_objects)
glb_gaps = surface_gaps(body, label)
glb_texture = bpy.data.materials["Milk_Label_Meadow"].node_tree.nodes["Image Texture"]
glb_alpha = bpy.data.materials["Milk_HDPE"].node_tree.nodes["Principled BSDF"].inputs["Alpha"].default_value
glb_ok = (
glb_triangles == native_triangles and len(imported_objects) == 3
and abs(glb_alpha - 1.0) < 0.00001
and bool(label.data.uv_layers)
and glb_texture is not None and list(glb_texture.image.size) == [3584, 768]
and max(glb_gaps) <= 0.121 and min(glb_gaps) > 0
and bpy.data.objects["Milk_Cap"].parent is not None
)
assert native_ok and glb_ok, "Milk packaged label validation failed"
assert sha256(SOURCE) == source_hash
report = {
"asset": "Milk2L_Packaged_Root",
"source_model": "model_assets/milk_2l/PerfectCoffee_milk_2l.blend",
"source_unchanged": True,
"source_sha256": source_hash,
"design_id": "premade_milk_packaged_low_poly_meadow",
"release_role": "Packaged variant of the approved 2L milk bottle; original model retained separately",
"artwork": "Original low-poly dairy cow and meadow with ivory and navy SVG packaging",
"seedream_model": "seedream_5.5",
"seedream_node": "node_3090jfx4nz",
"seedream_resource": "1bc79bf5-fc06-4942-b349-a90b8b358f6c",
"seedream_reference_images_used": False,
"seedream_asset": "model_assets/labels/milk/seedream55_meadow.png",
"seedream_prompt": "model_assets/labels/milk/seedream55_meadow_prompt.txt",
"reference_usage": "Ivory and navy palette, sky and pasture subject only; no brand, barcode, nutrition panel or full-cream claim",
"brand_logo_present": False,
"percentage_purity_claim_present": False,
"reference_photo_packed": False,
"label_texture": "model_assets/labels/milk/milk_wrap.png",
"body_opacity": native_alpha,
"native_triangles": native_triangles,
"glb_triangles": glb_triangles,
"triangle_limit": 1000,
"cap_independent": True,
"cap_color": "blue",
"label_method": "Clipped bottle-surface mesh with shrinkwrap",
"label_z_range_m": [LABEL_Z_MIN, LABEL_Z_MAX],
"handle_bottom_z_m": HANDLE_BOTTOM,
"label_below_handle": True,
"label_nominal_offset_mm": LABEL_OFFSET * 1000,
"native_surface_gap_mm": native_gaps,
"glb_surface_gap_mm": glb_gaps,
"label_source_face_count": source_face_count,
"label_perimeter_m": perimeter,
"texture_dimensions": [3584, 768],
"native_reopen_passed": native_ok,
"glb_reimport_passed": glb_ok,
"technical_validation_passed": True,
"visual_review_passed": False,
"godot_validation_performed": False,
"passed": False,
"blend": BLEND.name,
"glb": GLB.name,
"preview": "preview_packaged.png",
"preview_front": "preview_packaged_front.png",
"preview_back": "preview_packaged_back.png",
"preview_fit": "preview_packaged_fit.png",
}
(ASSET / "validation_packaged.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
print(json.dumps(report, ensure_ascii=False, indent=2))