feat: add low-poly grinder with instanced bean fill
This commit is contained in:
@@ -0,0 +1,622 @@
|
||||
from pathlib import Path
|
||||
from collections import defaultdict
|
||||
from hashlib import sha256
|
||||
from array import array
|
||||
import json
|
||||
import math
|
||||
import random
|
||||
import struct
|
||||
|
||||
import bpy
|
||||
import bmesh
|
||||
from mathutils import Vector
|
||||
|
||||
OUT = Path(__file__).resolve().parent
|
||||
SOURCE = OUT / 'ElectricCoffeeGrinder.blend'
|
||||
LOW = OUT / 'ElectricCoffeeGrinder_LowPoly.blend'
|
||||
GLB = OUT / 'ElectricCoffeeGrinder_LowPoly.glb'
|
||||
REPORT = OUT / 'low_poly_validation.json'
|
||||
CAPACITY = 14
|
||||
SEGMENTS = 24
|
||||
source_hash = sha256(SOURCE.read_bytes()).hexdigest()
|
||||
bpy.ops.wm.open_mainfile(filepath=str(SOURCE))
|
||||
scene = bpy.context.scene
|
||||
bpy.context.preferences.filepaths.save_version = 0
|
||||
|
||||
|
||||
def activate(obj):
|
||||
bpy.ops.object.select_all(action='DESELECT')
|
||||
obj.select_set(True)
|
||||
bpy.context.view_layer.objects.active = obj
|
||||
|
||||
|
||||
def move_to_collection(obj, collection):
|
||||
for current in list(obj.users_collection):
|
||||
current.objects.unlink(obj)
|
||||
collection.objects.link(obj)
|
||||
|
||||
|
||||
def triangles(obj):
|
||||
obj.data.calc_loop_triangles()
|
||||
return len(obj.data.loop_triangles)
|
||||
|
||||
|
||||
def decimate(obj, target):
|
||||
if triangles(obj) <= target:
|
||||
return
|
||||
for _ in range(2):
|
||||
current = triangles(obj)
|
||||
if current <= target + 2:
|
||||
break
|
||||
modifier = obj.modifiers.new('Low-poly triangle budget', 'DECIMATE')
|
||||
modifier.ratio = target / current
|
||||
modifier.use_collapse_triangulate = True
|
||||
activate(obj)
|
||||
bpy.ops.object.modifier_apply(modifier=modifier.name)
|
||||
|
||||
|
||||
def replace_with_plane(obj, width, height):
|
||||
data = bpy.data.meshes.new(obj.name + '_LowMesh')
|
||||
data.from_pydata([(-width / 2, -height / 2, 0), (width / 2, -height / 2, 0), (width / 2, height / 2, 0), (-width / 2, height / 2, 0)], [], [(0, 1, 2, 3)])
|
||||
data.materials.append(obj.data.materials[0])
|
||||
obj.data = data
|
||||
obj.rotation_euler = (math.pi / 2, 0, 0)
|
||||
|
||||
|
||||
for index in range(1, 6):
|
||||
replace_with_plane(bpy.data.objects[f'Body | rear vent {index}'], 0.052, 0.0035)
|
||||
replace_with_plane(bpy.data.objects['Body | outlet shadow'], 0.028, 0.012)
|
||||
|
||||
old_button = bpy.data.objects['Body | start button']
|
||||
button_material = old_button.data.materials[0]
|
||||
button_location = old_button.location.copy()
|
||||
button_collection = old_button.users_collection[0]
|
||||
bpy.data.objects.remove(old_button, do_unlink=True)
|
||||
bpy.ops.mesh.primitive_cylinder_add(vertices=16, radius=0.006, depth=0.003, end_fill_type='NGON', location=button_location, rotation=(math.pi / 2, 0, 0))
|
||||
button = bpy.context.object
|
||||
button.name = 'Body | start button'
|
||||
move_to_collection(button, button_collection)
|
||||
button.parent = bpy.data.objects['01 | Grinder Body']
|
||||
button.data.materials.append(button_material)
|
||||
for polygon in button.data.polygons:
|
||||
polygon.use_smooth = len(polygon.vertices) == 4
|
||||
|
||||
old_pointer = bpy.data.objects['Slider | white isosceles pointer']
|
||||
pointer_material = old_pointer.data.materials[0]
|
||||
pointer_collection = old_pointer.users_collection[0]
|
||||
bpy.data.objects.remove(old_pointer, do_unlink=True)
|
||||
pointer_mesh = bpy.data.meshes.new('Low triangular pointer')
|
||||
pointer_mesh.from_pydata([
|
||||
(-0.00275, -0.0585, 0.1535), (0.00275, -0.0585, 0.1535), (0, -0.0585, 0.163859),
|
||||
(-0.00275, -0.0565, 0.1535), (0.00275, -0.0565, 0.1535), (0, -0.0565, 0.163859),
|
||||
], [], [(0, 1, 2), (5, 4, 3), (0, 3, 4), (0, 4, 1), (1, 4, 5), (1, 5, 2), (2, 5, 3), (2, 3, 0)])
|
||||
pointer_mesh.materials.append(pointer_material)
|
||||
pointer = bpy.data.objects.new('Slider | white isosceles pointer', pointer_mesh)
|
||||
pointer_collection.objects.link(pointer)
|
||||
pointer.parent = bpy.data.objects['02 | Grind Slider']
|
||||
|
||||
budgets = {
|
||||
'Body | rounded housing': 684,
|
||||
'Body | weighted base': 180,
|
||||
'Body | tapered outlet': 180,
|
||||
'Body | universal slide rail': 100,
|
||||
'Body | fixed hopper socket': 192,
|
||||
'Body | slider slot base': 220,
|
||||
'Hopper | hollow transparent bowl': 1024,
|
||||
'Hopper | removable lid': 256,
|
||||
'Hopper | lid grip': 96,
|
||||
}
|
||||
for name, target in budgets.items():
|
||||
decimate(bpy.data.objects[name], target)
|
||||
for obj in bpy.data.collections['04 | Removable Portafilter Support'].objects:
|
||||
if obj.type == 'MESH':
|
||||
before = [obj.matrix_world @ Vector(corner) for corner in obj.bound_box]
|
||||
before_min = Vector(tuple(min(point[axis] for point in before) for axis in range(3)))
|
||||
before_max = Vector(tuple(max(point[axis] for point in before) for axis in range(3)))
|
||||
decimate(obj, 72)
|
||||
bpy.context.view_layer.update()
|
||||
after = [obj.matrix_world @ Vector(corner) for corner in obj.bound_box]
|
||||
after_min = Vector(tuple(min(point[axis] for point in after) for axis in range(3)))
|
||||
after_max = Vector(tuple(max(point[axis] for point in after) for axis in range(3)))
|
||||
inverse = obj.matrix_world.inverted()
|
||||
for vertex in obj.data.vertices:
|
||||
world = obj.matrix_world @ vertex.co
|
||||
for axis in range(3):
|
||||
extent = after_max[axis] - after_min[axis]
|
||||
if extent > 1e-9:
|
||||
world[axis] = before_min[axis] + (world[axis] - after_min[axis]) * (before_max[axis] - before_min[axis]) / extent
|
||||
vertex.co = inverse @ world
|
||||
obj.data.update()
|
||||
bpy.context.view_layer.update()
|
||||
corrected = [obj.matrix_world @ Vector(corner) for corner in obj.bound_box]
|
||||
for a, b in zip(before, corrected):
|
||||
assert (a - b).length < 0.00002, (obj.name, list(a), list(b))
|
||||
|
||||
bowl = bpy.data.objects['Hopper | hollow transparent bowl']
|
||||
activate(bowl)
|
||||
bpy.ops.mesh.customdata_custom_splitnormals_clear()
|
||||
for polygon in bowl.data.polygons:
|
||||
polygon.use_smooth = True
|
||||
bm = bmesh.new()
|
||||
bm.from_mesh(bowl.data)
|
||||
assert all(edge.is_manifold for edge in bm.edges), 'Decimation damaged the closed hopper shell'
|
||||
bm.free()
|
||||
|
||||
|
||||
def first_wall_hit(z):
|
||||
hit, location, normal, face = bowl.ray_cast(Vector((0, 0.020, z)), Vector((1, 0, 0)))
|
||||
if not hit:
|
||||
raise RuntimeError(f'No inner hopper wall at {z}')
|
||||
return location.x
|
||||
|
||||
|
||||
for z in [0.250, 0.280, 0.300]:
|
||||
inner = first_wall_hit(z)
|
||||
hit, outer, normal, face = bowl.ray_cast(Vector((inner + 0.00001, 0.020, z)), Vector((1, 0, 0)))
|
||||
assert hit
|
||||
thickness = outer.x - inner
|
||||
assert 0.0013 < thickness < 0.0030, (z, thickness)
|
||||
|
||||
glass = bpy.data.materials.new('Low | clear glass')
|
||||
glass.use_nodes = True
|
||||
glass.diffuse_color = (0.88, 0.95, 1.0, 0.22)
|
||||
glass.surface_render_method = 'BLENDED'
|
||||
glass.use_transparent_shadow = True
|
||||
glass.show_transparent_back = False
|
||||
glass.use_backface_culling = True
|
||||
bsdf = glass.node_tree.nodes.get('Principled BSDF')
|
||||
bsdf.inputs['Base Color'].default_value = (0.88, 0.95, 1.0, 1.0)
|
||||
bsdf.inputs['Roughness'].default_value = 0.06
|
||||
bsdf.inputs['IOR'].default_value = 1.46
|
||||
bsdf.inputs['Alpha'].default_value = 0.22
|
||||
bsdf.inputs['Transmission Weight'].default_value = 0.0
|
||||
bowl.data.materials.clear()
|
||||
bowl.data.materials.append(glass)
|
||||
bowl.visible_shadow = False
|
||||
|
||||
old_scale = bpy.data.objects['Body | white 1-8 scale texture'].active_material.node_tree.nodes.get('Image Texture').image
|
||||
small_scale = old_scale.copy()
|
||||
small_scale.name = 'Low_Grind_Scale_512x128'
|
||||
small_scale.unpack(method='REMOVE')
|
||||
small_scale.scale(512, 128)
|
||||
small_scale.filepath_raw = str(OUT / 'grind_scale_low.png')
|
||||
small_scale.file_format = 'PNG'
|
||||
small_scale.save()
|
||||
small_scale.pack()
|
||||
scale_material = bpy.data.objects['Body | white 1-8 scale texture'].active_material
|
||||
scale_material.node_tree.nodes.get('Image Texture').image = small_scale
|
||||
assert sha256(bytes(small_scale.packed_file.data)).digest() == sha256((OUT / 'grind_scale_low.png').read_bytes()).digest()
|
||||
|
||||
random.seed(41)
|
||||
size = 512
|
||||
pixels = array('f', [0.0]) * (size * size * 4)
|
||||
for y in range(size):
|
||||
for x in range(size):
|
||||
value = 0.055 + random.random() * 0.025
|
||||
index = (y * size + x) * 4
|
||||
pixels[index:index + 4] = array('f', (value * 1.35, value * 0.78, value * 0.43, 1.0))
|
||||
for _ in range(170):
|
||||
cx = random.uniform(-20, size + 20)
|
||||
cy = random.uniform(-20, size + 20)
|
||||
major = random.uniform(17, 27)
|
||||
minor = random.uniform(9, 14)
|
||||
angle = random.uniform(0, math.tau)
|
||||
ca, sa = math.cos(angle), math.sin(angle)
|
||||
tone = random.uniform(0.72, 1.22)
|
||||
for yy in range(max(0, int(cy - major - 2)), min(size, int(cy + major + 3))):
|
||||
for xx in range(max(0, int(cx - major - 2)), min(size, int(cx + major + 3))):
|
||||
dx, dy = xx - cx, yy - cy
|
||||
u = (dx * ca + dy * sa) / major
|
||||
v = (-dx * sa + dy * ca) / minor
|
||||
radius2 = u * u + v * v
|
||||
if radius2 > 1:
|
||||
continue
|
||||
groove = abs(v - 0.12 * math.sin(u * 4.0)) < 0.10
|
||||
shade = (0.48 + 0.48 * math.sqrt(1 - radius2)) * tone
|
||||
if groove:
|
||||
shade *= 0.27
|
||||
index = (yy * size + xx) * 4
|
||||
pixels[index:index + 4] = array('f', (0.23 * shade, 0.105 * shade, 0.045 * shade, 1.0))
|
||||
bean_image = bpy.data.images.new('Low_Coffee_Bean_Packed_Texture', width=size, height=size, alpha=True)
|
||||
bean_image.pixels.foreach_set(pixels)
|
||||
bean_image.update()
|
||||
bean_image.filepath_raw = str(OUT / 'beans_low.png')
|
||||
bean_image.file_format = 'PNG'
|
||||
bean_image.save()
|
||||
bean_image.pack()
|
||||
bean_material = bpy.data.materials.new('Low | coffee bean texture')
|
||||
bean_material.use_nodes = True
|
||||
bean_bsdf = bean_material.node_tree.nodes.get('Principled BSDF')
|
||||
bean_bsdf.inputs['Roughness'].default_value = 0.82
|
||||
bean_bsdf.inputs['Specular IOR Level'].default_value = 0.18
|
||||
bean_texture = bean_material.node_tree.nodes.new('ShaderNodeTexImage')
|
||||
bean_texture.image = bean_image
|
||||
bean_material.node_tree.links.new(bean_texture.outputs['Color'], bean_bsdf.inputs['Base Color'])
|
||||
|
||||
beans_collection = bpy.data.collections.new('05 | Coffee Beans')
|
||||
scene.collection.children.link(beans_collection)
|
||||
beans_root = bpy.data.objects.new('05 | Coffee Beans', None)
|
||||
beans_collection.objects.link(beans_root)
|
||||
beans_root.parent = bpy.data.objects['03 | Coffee Bean Hopper']
|
||||
beans_root.empty_display_size = 0.02
|
||||
beans_root['capacity_portions'] = CAPACITY
|
||||
beans_root['consumption'] = 'One fixed portion per completed portafilter. No vibration, rigid bodies or particle simulation.'
|
||||
beans_root['visuals'] = 'One textured core with 15 morph levels and at most 20 GPU-instanced low-poly beans.'
|
||||
scene['bean_capacity_portions'] = CAPACITY
|
||||
scene['bean_remaining_portions'] = CAPACITY
|
||||
scene['beans_per_grind'] = 1
|
||||
|
||||
profile_z = [0.2164, 0.224, 0.236, 0.252, 0.280, 0.312]
|
||||
profile_r = [max(0.005, first_wall_hit(z) - 0.0008) for z in profile_z]
|
||||
|
||||
|
||||
def radius_at(z):
|
||||
if z <= profile_z[0]:
|
||||
return profile_r[0]
|
||||
for index in range(1, len(profile_z)):
|
||||
if z <= profile_z[index]:
|
||||
t = (z - profile_z[index - 1]) / (profile_z[index] - profile_z[index - 1])
|
||||
return profile_r[index - 1] + t * (profile_r[index] - profile_r[index - 1])
|
||||
return profile_r[-1]
|
||||
|
||||
|
||||
def volume_at(z):
|
||||
volume = 0.0
|
||||
for index in range(1, len(profile_z)):
|
||||
lower_z, upper_z = profile_z[index - 1], profile_z[index]
|
||||
if z <= lower_z:
|
||||
break
|
||||
top = min(z, upper_z)
|
||||
t = (top - lower_z) / (upper_z - lower_z)
|
||||
r1 = profile_r[index - 1]
|
||||
r2 = r1 + t * (profile_r[index] - r1)
|
||||
volume += math.pi * (top - lower_z) * (r1 * r1 + r1 * r2 + r2 * r2) / 3
|
||||
if z < upper_z:
|
||||
break
|
||||
return volume
|
||||
|
||||
|
||||
total_volume = volume_at(profile_z[-1])
|
||||
|
||||
|
||||
def fill_height(portions):
|
||||
if portions <= 0:
|
||||
return profile_z[0]
|
||||
target = total_volume * portions / CAPACITY
|
||||
low, high = profile_z[0], profile_z[-1]
|
||||
for _ in range(32):
|
||||
middle = (low + high) / 2
|
||||
if volume_at(middle) < target:
|
||||
low = middle
|
||||
else:
|
||||
high = middle
|
||||
return (low + high) / 2
|
||||
|
||||
|
||||
vertices, faces, face_uvs, ring_starts = [], [], [], []
|
||||
for ring_index, (z, radius) in enumerate(zip(profile_z, profile_r)):
|
||||
ring_starts.append(len(vertices))
|
||||
for segment in range(SEGMENTS):
|
||||
angle = math.tau * segment / SEGMENTS
|
||||
vertices.append((radius * math.cos(angle), 0.020 + radius * math.sin(angle), z))
|
||||
for ring in range(len(profile_z) - 1):
|
||||
for segment in range(SEGMENTS):
|
||||
a = ring_starts[ring] + segment
|
||||
b = ring_starts[ring] + (segment + 1) % SEGMENTS
|
||||
c = ring_starts[ring + 1] + (segment + 1) % SEGMENTS
|
||||
d = ring_starts[ring + 1] + segment
|
||||
faces.append((a, b, c, d))
|
||||
u0, u1 = 2 * segment / SEGMENTS, 2 * (segment + 1) / SEGMENTS
|
||||
v0 = 2 * ring / (len(profile_z) - 1)
|
||||
v1 = 2 * (ring + 1) / (len(profile_z) - 1)
|
||||
face_uvs.append([(u0, v0), (u1, v0), (u1, v1), (u0, v1)])
|
||||
bottom_center = len(vertices)
|
||||
vertices.append((0, 0.020, profile_z[0]))
|
||||
top_center = len(vertices)
|
||||
vertices.append((0, 0.020, profile_z[-1]))
|
||||
for segment in range(SEGMENTS):
|
||||
nxt = (segment + 1) % SEGMENTS
|
||||
faces.append((bottom_center, ring_starts[0] + nxt, ring_starts[0] + segment))
|
||||
face_uvs.append([(0.5, 0.5), (0.5, 0.5), (0.5, 0.5)])
|
||||
faces.append((top_center, ring_starts[-1] + segment, ring_starts[-1] + nxt))
|
||||
uv = []
|
||||
for x, y, z in [vertices[top_center], vertices[ring_starts[-1] + segment], vertices[ring_starts[-1] + nxt]]:
|
||||
uv.append((0.5 + x / (2 * profile_r[-1]), 0.5 + (y - 0.020) / (2 * profile_r[-1])))
|
||||
face_uvs.append(uv)
|
||||
core_mesh = bpy.data.meshes.new('Low bean core mesh')
|
||||
core_mesh.from_pydata(vertices, [], faces)
|
||||
core_mesh.materials.append(bean_material)
|
||||
core_mesh.update()
|
||||
uv_layer = core_mesh.uv_layers.new(name='BeanTextureUV')
|
||||
for polygon, uvs in zip(core_mesh.polygons, face_uvs):
|
||||
for loop_index, uv in zip(polygon.loop_indices, uvs):
|
||||
uv_layer.data[loop_index].uv = uv
|
||||
core = bpy.data.objects.new('Beans | textured volume core', core_mesh)
|
||||
beans_collection.objects.link(core)
|
||||
core.parent = beans_root
|
||||
core.shape_key_add(name='Basis')
|
||||
for level in range(CAPACITY + 1):
|
||||
z = fill_height(level)
|
||||
radius = radius_at(z)
|
||||
key = core.shape_key_add(name=f'Level_{level:02d}')
|
||||
for index, point in enumerate(key.data):
|
||||
original = Vector(vertices[index])
|
||||
if index == top_center:
|
||||
point.co = (0, 0.020, z)
|
||||
elif original.z > z:
|
||||
angle = math.atan2(original.y - 0.020, original.x)
|
||||
point.co = (radius * math.cos(angle), 0.020 + radius * math.sin(angle), z)
|
||||
else:
|
||||
point.co = original
|
||||
driver = key.driver_add('value').driver
|
||||
driver.type = 'SCRIPTED'
|
||||
variable = driver.variables.new()
|
||||
variable.name = 'remaining'
|
||||
variable.type = 'SINGLE_PROP'
|
||||
variable.targets[0].id_type = 'SCENE'
|
||||
variable.targets[0].id = scene
|
||||
variable.targets[0].data_path = '["bean_remaining_portions"]'
|
||||
driver.expression = f'1.0 if remaining == {level} else 0.0'
|
||||
for property_name in ['hide_render', 'hide_viewport']:
|
||||
driver = core.driver_add(property_name).driver
|
||||
variable = driver.variables.new()
|
||||
variable.name = 'remaining'
|
||||
variable.targets[0].id_type = 'SCENE'
|
||||
variable.targets[0].id = scene
|
||||
variable.targets[0].data_path = '["bean_remaining_portions"]'
|
||||
driver.expression = 'remaining <= 0'
|
||||
|
||||
source_collection = bpy.data.collections.new('Low | authoring sources')
|
||||
scene.collection.children.link(source_collection)
|
||||
bpy.ops.mesh.primitive_uv_sphere_add(segments=8, ring_count=3, radius=1)
|
||||
hero = bpy.context.object
|
||||
hero.name = '_Low bean instance source'
|
||||
move_to_collection(hero, source_collection)
|
||||
for vertex in hero.data.vertices:
|
||||
vertex.co.x *= 0.0055
|
||||
vertex.co.y *= 0.0032
|
||||
vertex.co.z *= 0.0022
|
||||
hero.data.materials.append(bean_material)
|
||||
for polygon in hero.data.polygons:
|
||||
polygon.use_smooth = True
|
||||
hero.visible_shadow = False
|
||||
hero.hide_render = True
|
||||
hero_triangles = triangles(hero)
|
||||
assert hero_triangles <= 40, hero_triangles
|
||||
|
||||
point_mesh = bpy.data.meshes.new('Bean instance points')
|
||||
point_mesh.from_pydata([(0, 0.020, 0.312)] * 20, [], [])
|
||||
point_obj = bpy.data.objects.new('Beans | low-poly surface instances', point_mesh)
|
||||
beans_collection.objects.link(point_obj)
|
||||
point_obj.parent = beans_root
|
||||
thresholds = point_mesh.attributes.new(name='min_remaining', type='INT', domain='POINT')
|
||||
rotations = point_mesh.attributes.new(name='instance_rotation', type='FLOAT_VECTOR', domain='POINT')
|
||||
scales = point_mesh.attributes.new(name='instance_scale', type='FLOAT_VECTOR', domain='POINT')
|
||||
placements = []
|
||||
for index in range(8):
|
||||
angle = index * 2.399963
|
||||
radius = 0.010 + 0.030 * math.sqrt((index + 0.5) / 8)
|
||||
placements.append(((radius * math.cos(angle), 0.020 + radius * math.sin(angle), 0.313), 14))
|
||||
for index, level in enumerate([1, 3, 5, 7, 9, 11]):
|
||||
z = fill_height(level) + 0.0005
|
||||
radius = radius_at(z) - 0.0065
|
||||
for side in range(2):
|
||||
angle = -math.pi / 2 + side * 0.65 + index * 0.37
|
||||
placements.append(((radius * math.cos(angle), 0.020 + radius * math.sin(angle), z), level))
|
||||
for index, (position, level) in enumerate(placements):
|
||||
point_mesh.vertices[index].co = position
|
||||
thresholds.data[index].value = level
|
||||
rotations.data[index].vector = (random.uniform(-0.4, 0.4), random.uniform(-0.4, 0.4), random.uniform(0, math.tau))
|
||||
factor = random.uniform(0.88, 1.12)
|
||||
scales.data[index].vector = (factor, factor, factor)
|
||||
|
||||
group = bpy.data.node_groups.new('Low bean GPU instances', 'GeometryNodeTree')
|
||||
group.interface.new_socket(name='Geometry', in_out='INPUT', socket_type='NodeSocketGeometry')
|
||||
group.interface.new_socket(name='Geometry', in_out='OUTPUT', socket_type='NodeSocketGeometry')
|
||||
remaining_socket = group.interface.new_socket(name='Remaining Portions', in_out='INPUT', socket_type='NodeSocketInt')
|
||||
remaining_socket.default_value = CAPACITY
|
||||
remaining_socket.min_value = 0
|
||||
remaining_socket.max_value = CAPACITY
|
||||
nodes, links = group.nodes, group.links
|
||||
group_input = nodes.new('NodeGroupInput')
|
||||
group_output = nodes.new('NodeGroupOutput')
|
||||
threshold = nodes.new('GeometryNodeInputNamedAttribute')
|
||||
threshold.data_type = 'INT'
|
||||
threshold.inputs['Name'].default_value = 'min_remaining'
|
||||
above = nodes.new('ShaderNodeMath')
|
||||
above.operation = 'GREATER_THAN'
|
||||
links.new(threshold.outputs['Attribute'], above.inputs[0])
|
||||
links.new(group_input.outputs['Remaining Portions'], above.inputs[1])
|
||||
delete = nodes.new('GeometryNodeDeleteGeometry')
|
||||
delete.domain = 'POINT'
|
||||
links.new(group_input.outputs['Geometry'], delete.inputs['Geometry'])
|
||||
links.new(above.outputs[0], delete.inputs['Selection'])
|
||||
object_info = nodes.new('GeometryNodeObjectInfo')
|
||||
object_info.inputs['Object'].default_value = hero
|
||||
object_info.inputs['As Instance'].default_value = True
|
||||
instance = nodes.new('GeometryNodeInstanceOnPoints')
|
||||
links.new(delete.outputs['Geometry'], instance.inputs['Points'])
|
||||
links.new(object_info.outputs['Geometry'], instance.inputs['Instance'])
|
||||
for name, socket, attribute in [('Rotation', 'rotation', 'instance_rotation'), ('Scale', 'scale', 'instance_scale')]:
|
||||
attribute_node = nodes.new('GeometryNodeInputNamedAttribute')
|
||||
attribute_node.data_type = 'FLOAT_VECTOR'
|
||||
attribute_node.inputs['Name'].default_value = attribute
|
||||
links.new(attribute_node.outputs['Attribute'], instance.inputs[name])
|
||||
links.new(instance.outputs['Instances'], group_output.inputs['Geometry'])
|
||||
modifier = point_obj.modifiers.new('Low-cost bean instances', 'NODES')
|
||||
modifier.node_group = group
|
||||
remaining_input = getattr(modifier.properties.inputs, remaining_socket.identifier)
|
||||
remaining_input.value = CAPACITY
|
||||
driver = remaining_input.driver_add('value').driver
|
||||
variable = driver.variables.new()
|
||||
variable.name = 'remaining'
|
||||
variable.targets[0].id_type = 'SCENE'
|
||||
variable.targets[0].id = scene
|
||||
variable.targets[0].data_path = '["bean_remaining_portions"]'
|
||||
driver.expression = 'remaining'
|
||||
for property_name in ['hide_render', 'hide_viewport']:
|
||||
driver = point_obj.driver_add(property_name).driver
|
||||
variable = driver.variables.new()
|
||||
variable.name = 'remaining'
|
||||
variable.targets[0].id_type = 'SCENE'
|
||||
variable.targets[0].id = scene
|
||||
variable.targets[0].data_path = '["bean_remaining_portions"]'
|
||||
driver.expression = 'remaining <= 0'
|
||||
point_obj['instance_count'] = 20
|
||||
point_obj['triangles_per_instance'] = hero_triangles
|
||||
|
||||
shared_metal = bpy.data.materials['Chute | dark steel']
|
||||
shared_black = bpy.data.materials['Controls | soft black']
|
||||
for collection_name in ['01 | Grinder Body', '04 | Removable Portafilter Support']:
|
||||
for obj in bpy.data.collections[collection_name].objects:
|
||||
if obj.type != 'MESH':
|
||||
continue
|
||||
for slot in obj.material_slots:
|
||||
if slot.material and slot.material.name in ['Base | graphite', 'Support | brushed stainless steel']:
|
||||
slot.material = shared_metal
|
||||
elif slot.material and slot.material.name in ['Vents | shadow', 'Pads | silicone']:
|
||||
slot.material = shared_black
|
||||
activate(obj)
|
||||
bpy.ops.object.material_slot_remove_unused()
|
||||
|
||||
bpy.data.objects['Hopper | lid grip'].data.materials[0] = bpy.data.objects['Hopper | removable lid'].data.materials[0]
|
||||
|
||||
|
||||
def join_parts(objects, name, parent):
|
||||
objects = [obj for obj in objects if obj and obj.type == 'MESH']
|
||||
bpy.ops.object.select_all(action='DESELECT')
|
||||
for obj in objects:
|
||||
obj.select_set(True)
|
||||
bpy.context.view_layer.objects.active = objects[0]
|
||||
bpy.ops.object.join()
|
||||
joined = bpy.context.object
|
||||
joined.name = name
|
||||
joined.parent = parent
|
||||
return joined
|
||||
|
||||
|
||||
body_parts = [obj for obj in bpy.data.collections['01 | Grinder Body'].objects if obj.type == 'MESH' and obj not in [button, bpy.data.objects['Body | white 1-8 scale texture']]]
|
||||
join_parts(body_parts, 'Low | Grinder body', bpy.data.objects['01 | Grinder Body'])
|
||||
join_parts(list(bpy.data.collections['04 | Removable Portafilter Support'].objects), 'Low | Removable support', bpy.data.objects['04 | Removable Portafilter Support'])
|
||||
join_parts([bpy.data.objects['Hopper | removable lid'], bpy.data.objects['Hopper | lid grip']], 'Low | Hopper lid', bpy.data.objects['03 | Coffee Bean Hopper'])
|
||||
|
||||
scene['low_poly_target'] = 'Whole grinder including bean contents, excluding the detachable portafilter and studio. Target about 5000 triangles, hard budget 6000.'
|
||||
scene['bean_control'] = 'Scene bean_remaining_portions: 0-14. One fixed portion is consumed per completed portafilter. No vibration.'
|
||||
scene.render.engine = 'CYCLES'
|
||||
scene.cycles.samples = 64
|
||||
scene.cycles.use_denoising = True
|
||||
scene.render.resolution_x = 1100
|
||||
scene.render.resolution_y = 1100
|
||||
scene.render.resolution_percentage = 100
|
||||
scene.render.image_settings.file_format = 'PNG'
|
||||
scene.render.image_settings.color_mode = 'RGBA'
|
||||
scene.render.filepath = str(OUT / 'preview_low_poly.png')
|
||||
camera = bpy.data.objects['Preview Camera']
|
||||
scene.camera = camera
|
||||
camera.data.type = 'PERSP'
|
||||
camera.data.lens = 52
|
||||
camera.location = (0.43155157566070557, -0.8523870706558228, 0.5388725996017456)
|
||||
camera.rotation_euler = (Vector((0, -0.005, 0.16)) - camera.location).to_track_quat('-Z', 'Y').to_euler()
|
||||
scene.frame_set(1)
|
||||
scene.update_tag()
|
||||
bpy.context.view_layer.update()
|
||||
|
||||
component_triangles = {}
|
||||
for name in ['01 | Grinder Body', '02 | Grind Slider', '03 | Coffee Bean Hopper', '04 | Removable Portafilter Support']:
|
||||
component_triangles[name] = sum(triangles(obj) for obj in bpy.data.collections[name].objects if obj.type == 'MESH')
|
||||
bean_triangles = triangles(core) + 20 * hero_triangles
|
||||
component_triangles['05 | Coffee Beans'] = bean_triangles
|
||||
total_triangles = sum(component_triangles.values())
|
||||
assert total_triangles <= 6000, component_triangles
|
||||
assert bean_triangles <= 1000, bean_triangles
|
||||
|
||||
model_objects = set()
|
||||
for name in ['01 | Grinder Body', '02 | Grind Slider', '03 | Coffee Bean Hopper', '04 | Removable Portafilter Support', '05 | Coffee Beans']:
|
||||
root = bpy.data.objects[name]
|
||||
model_objects.add(root)
|
||||
model_objects.update(root.children_recursive)
|
||||
bpy.ops.object.select_all(action='DESELECT')
|
||||
for obj in model_objects:
|
||||
obj.select_set(True)
|
||||
bpy.context.view_layer.objects.active = bpy.data.objects['01 | Grinder Body']
|
||||
export_options = bpy.ops.export_scene.gltf.get_rna_type().properties.keys()
|
||||
kwargs = dict(filepath=str(GLB), export_format='GLB', use_selection=True, export_apply=True, export_cameras=False, export_lights=False, export_animations=False, export_extras=True)
|
||||
if 'export_gpu_instances' in export_options:
|
||||
kwargs['export_gpu_instances'] = True
|
||||
if 'export_gn_mesh' in export_options:
|
||||
kwargs['export_gn_mesh'] = True
|
||||
bpy.ops.export_scene.gltf(**kwargs)
|
||||
|
||||
raw = GLB.read_bytes()
|
||||
json_length = struct.unpack_from('<I', raw, 12)[0]
|
||||
gltf = json.loads(raw[20:20 + json_length])
|
||||
instance_count = 0
|
||||
for node in gltf.get('nodes', []):
|
||||
extension = node.get('extensions', {}).get('EXT_mesh_gpu_instancing')
|
||||
if extension:
|
||||
attributes = extension['attributes']
|
||||
accessor_index = attributes.get('_TRANSLATION', attributes.get('TRANSLATION'))
|
||||
instance_count += gltf['accessors'][accessor_index]['count']
|
||||
assert instance_count == 20, instance_count
|
||||
primitive_triangles = 0
|
||||
for mesh in gltf.get('meshes', []):
|
||||
for primitive in mesh['primitives']:
|
||||
if 'indices' in primitive:
|
||||
primitive_triangles += gltf['accessors'][primitive['indices']]['count'] // 3
|
||||
else:
|
||||
primitive_triangles += gltf['accessors'][primitive['attributes']['POSITION']]['count'] // 3
|
||||
primitive_draw_calls = sum(len(mesh['primitives']) for mesh in gltf.get('meshes', []))
|
||||
assert primitive_draw_calls <= 12, primitive_draw_calls
|
||||
exported_glass = next(material for material in gltf['materials'] if material.get('name') == 'Low | clear glass')
|
||||
assert exported_glass.get('doubleSided', False) is False
|
||||
|
||||
bsdf.inputs['Alpha'].default_value = 1.0
|
||||
bsdf.inputs['Transmission Weight'].default_value = 1.0
|
||||
bsdf.inputs['Roughness'].default_value = 0.025
|
||||
glass.surface_render_method = 'DITHERED'
|
||||
glass.use_raytrace_refraction = True
|
||||
glass.show_transparent_back = True
|
||||
glass.use_backface_culling = False
|
||||
glass.diffuse_color = (0.96, 0.985, 1.0, 1.0)
|
||||
glass['export_material_note'] = 'GLB was exported with lightweight alpha-blended glass before this physical Cycles glass was applied.'
|
||||
|
||||
report = {
|
||||
'source_baseline': '899c9ee',
|
||||
'source_sha256': source_hash,
|
||||
'blend': LOW.name,
|
||||
'glb': GLB.name,
|
||||
'blend_glass': 'Physical transmission, alpha 1, IOR 1.46, roughness 0.025',
|
||||
'glb_glass': 'Lightweight alpha blend 0.22, no refraction',
|
||||
'component_triangles': component_triangles,
|
||||
'total_render_triangles_including_instances': total_triangles,
|
||||
'bean_core_triangles': triangles(core),
|
||||
'bean_instance_count': 20,
|
||||
'bean_triangles_per_instance': hero_triangles,
|
||||
'triangle_budget': 6000,
|
||||
'bean_capacity_portions': CAPACITY,
|
||||
'beans_per_grind': 1,
|
||||
'bean_core_vertices': len(core.data.vertices),
|
||||
'bean_morph_levels': CAPACITY + 1,
|
||||
'material_count': len({slot.material for obj in model_objects if obj.type == 'MESH' for slot in obj.material_slots if slot.material}),
|
||||
'glb_primitive_triangles_excluding_gpu_instances': primitive_triangles,
|
||||
'glb_gpu_instances': instance_count,
|
||||
'glb_primitive_draw_calls': primitive_draw_calls,
|
||||
'texture_sizes': {'beans_low.png': list(bean_image.size), 'grind_scale_low.png': list(small_scale.size)},
|
||||
'portafilter_included': False,
|
||||
'vibration_or_particles': False,
|
||||
}
|
||||
REPORT.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
|
||||
|
||||
for screen in bpy.data.screens:
|
||||
for area in screen.areas:
|
||||
if area.type == 'VIEW_3D':
|
||||
area.spaces.active.shading.type = 'MATERIAL'
|
||||
area.spaces.active.region_3d.view_perspective = 'CAMERA'
|
||||
area.spaces.active.overlay.show_extras = False
|
||||
area.spaces.active.clip_start = 0.001
|
||||
if bpy.data.workspaces.get('Layout') and bpy.context.window:
|
||||
bpy.context.window.workspace = bpy.data.workspaces['Layout']
|
||||
bpy.ops.file.pack_all()
|
||||
bpy.ops.wm.save_as_mainfile(filepath=str(LOW))
|
||||
assert sha256(SOURCE.read_bytes()).hexdigest() == source_hash
|
||||
print('LOW_POLY_BUILD', json.dumps(report, ensure_ascii=False), flush=True)
|
||||
Reference in New Issue
Block a user