"""Build O Image Depth Cutout.""" import bpy from mathutils import Matrix from anyimage.operators.cutout_tool.shape import CUTOUT_Z_TO_X, NORMAL_SCALE_ATTRIBUTE_NAME from ..common.nodes import interface_socket, group_input, math_node, float_input, menu_switch, read_float_attribute, store_float_attribute, prepare_node_group, capture_fields, evaluate_field from ..common.smoothing import expand_smooth from ..common.cutout import _island_cleanup, _position_field, _remove_zero_thickness, _shade_output from ..common.depth_surface import _math, project_depth_surface, build_surface_camera, split_depth_surface, sample_face_camera, thicken_depth_surface from ..common.smoothing import edge_boundary_field NODE_GROUP_NAME = "O Image Depth Cutout" def build_volume_fields(group): """Evaluate the center and thickness on the original front surface.""" links = group.links rim = evaluate_field(group, edge_boundary_field(group.nodes, links), "FLOAT", "POINT") profile = read_float_attribute(group, "o_balloon") position = group.nodes.new("GeometryNodeInputPosition") axes = group.nodes.new("ShaderNodeSeparateXYZ") links.new(position.outputs[0], axes.inputs[0]) seed = _math(group, "SUBTRACT", axes.outputs["Z"], profile) interior = _math(group, "SUBTRACT", 1, rim) blur = group.nodes.new("GeometryNodeBlurAttribute") blur.data_type = "FLOAT" blur.inputs["Iterations"].default_value = 256 links.new(seed, blur.inputs["Value"]) links.new(interior, blur.inputs["Weight"]) center = blur.outputs[0] residual = _math(group, "SUBTRACT", axes.outputs["Z"], center) full = _math(group, "ADD", residual, profile) minimum = _math(group, "MULTIPLY", profile, 0.05) positive = _math(group, "MAXIMUM", full, minimum) control = group_input(group.nodes, {"Thickness"}) thickness = _math(group, "MULTIPLY", positive, control.outputs["Thickness"]) return {"rim": rim, "center": center, "thickness": thickness} def build_volume_rounding(group, geometry, fields, uniform): links = group.links control = group.nodes.new("NodeGroupInput") profile = group.nodes.new("GeometryNodeInputNamedAttribute") profile.data_type = "FLOAT" profile.inputs["Name"].default_value = "o_balloon" balloon = profile.outputs["Attribute"] maximum = group.nodes.new("GeometryNodeAttributeStatistic") maximum.data_type, maximum.domain = "FLOAT", "POINT" links.new(geometry, maximum.inputs["Geometry"]) links.new(balloon, maximum.inputs["Attribute"]) limit = _math(group, "MAXIMUM", maximum.outputs["Max"], 1e-8) falloff = group.nodes.new("ShaderNodeMapRange") falloff.interpolation_type = "SMOOTHERSTEP" falloff.inputs["To Min"].default_value = 1 falloff.inputs["To Max"].default_value = 0 links.new(balloon, falloff.inputs["Value"]) links.new(limit, falloff.inputs["From Max"]) weight = _math(group, "MULTIPLY", falloff.outputs[0], control.outputs["Edge Round"]) center = fields["center"] position = group.nodes.new("GeometryNodeInputPosition") axes = group.nodes.new("ShaderNodeSeparateXYZ") links.new(position.outputs[0], axes.inputs[0]) target = _math(group, "ADD", center, balloon) delta = _math(group, "SUBTRACT", target, axes.outputs["Z"]) delta = _math(group, "MULTIPLY", delta, weight) enabled = _math(group, "MINIMUM", control.outputs["Thickness"], 1) enabled = _math(group, "MAXIMUM", enabled, 0) delta = _math(group, "MULTIPLY", delta, enabled) rear = _math(group, "MULTIPLY", balloon, weight) rear = _math(group, "MULTIPLY", rear, control.outputs["Thickness"]) thickness = fields["thickness"] total = _math(group, "ADD", thickness, delta) total = _math(group, "ADD", total, rear) # Evaluate normals on a separate center surface with identical point indices. center_position = group.nodes.new("ShaderNodeCombineXYZ") for axis in ("X", "Y"): links.new(axes.outputs[axis], center_position.inputs[axis]) links.new(center, center_position.inputs["Z"]) surface = group.nodes.new("GeometryNodeSetPosition") links.new(geometry, surface.inputs["Geometry"]) links.new(center_position.outputs[0], surface.inputs["Position"]) normal = group.nodes.new("GeometryNodeInputNormal") blur = group.nodes.new("GeometryNodeBlurAttribute") blur.data_type = "FLOAT_VECTOR" links.new(normal.outputs[0], blur.inputs["Value"]) local = group.nodes.new("NodeGroupInput") links.new(local.outputs["Normal Smooth"], blur.inputs["Iterations"]) normalize = group.nodes.new("ShaderNodeVectorMath") normalize.operation = "NORMALIZE" links.new(blur.outputs[0], normalize.inputs[0]) index = group.nodes.new("GeometryNodeInputIndex") sample = group.nodes.new("GeometryNodeSampleIndex") sample.data_type, sample.domain = "FLOAT_VECTOR", "POINT" links.new(surface.outputs[0], sample.inputs["Geometry"]) links.new(normalize.outputs[0], sample.inputs["Value"]) links.new(index.outputs[0], sample.inputs["Index"]) thickness = group.nodes.new("GeometryNodeSwitch") thickness.input_type = "FLOAT" links.new(uniform, thickness.inputs["Switch"]) links.new(total, thickness.inputs["False"]) links.new(control.outputs["Uniform Thickness"], thickness.inputs["True"]) carrier, captured = capture_fields( group, geometry, "POINT", edge_weight=("FLOAT", weight), front_delta=("FLOAT", delta), thickness=("FLOAT", thickness.outputs[0]), normal=("VECTOR", sample.outputs[0]), ) displacement = group.nodes.new("ShaderNodeCombineXYZ") links.new(captured["front_delta"], displacement.inputs["Z"]) front = group.nodes.new("GeometryNodeSetPosition") links.new(carrier, front.inputs["Geometry"]) links.new(displacement.outputs[0], front.inputs["Offset"]) choose = group.nodes.new("GeometryNodeSwitch") choose.input_type = "GEOMETRY" links.new(uniform, choose.inputs["Switch"]) links.new(front.outputs[0], choose.inputs["False"]) links.new(carrier, choose.inputs["True"]) return choose.outputs[0], captured def build_front_fields(group, rim, front_normal): """Fit structural amplitude over neighbouring points before creating the shell.""" links = group.links def blur(value, weight=None): result = group.nodes.new("GeometryNodeBlurAttribute") result.data_type = "FLOAT" result.inputs["Iterations"].default_value = 256 links.new(value, result.inputs["Value"]) if weight is not None: links.new(weight, result.inputs["Weight"]) return result.outputs[0] profile_node = group.nodes.new("GeometryNodeInputNamedAttribute") profile_node.data_type = "FLOAT" profile_node.inputs["Name"].default_value = "o_balloon" profile = profile_node.outputs["Attribute"] interior = _math(group, "SUBTRACT", 1, rim) position = group.nodes.new("GeometryNodeInputPosition") axes = group.nodes.new("ShaderNodeSeparateXYZ") links.new(position.outputs[0], axes.inputs[0]) depth = axes.outputs["Z"] depth_slow = blur(depth, interior) profile_slow = blur(profile, interior) depth_bump = _math(group, "SUBTRACT", depth, depth_slow) profile_bump = _math(group, "SUBTRACT", profile, profile_slow) numerator = _math(group, "MULTIPLY", depth_bump, profile_bump) denominator = _math(group, "MULTIPLY", profile_bump, profile_bump) numerator = blur(numerator) denominator = blur(denominator) denominator = _math(group, "MAXIMUM", denominator, 1e-10) structure = _math(group, "DIVIDE", numerator, denominator) structure = _math(group, "MAXIMUM", structure, 0) normal = front_normal controls = group.nodes.new("NodeGroupInput") # Keep the accepted broad front-direction filter at the default of 50; # zero disables both this filter and the initial front/back normal filters. spread = _math(group, "MULTIPLY", controls.outputs["Normal Smooth"], 256 / 50) smooth = group.nodes.new("GeometryNodeBlurAttribute") smooth.data_type = "FLOAT_VECTOR" links.new(normal, smooth.inputs["Value"]) links.new(spread, smooth.inputs["Iterations"]) normalize = group.nodes.new("ShaderNodeVectorMath") normalize.operation = "NORMALIZE" links.new(smooth.outputs[0], normalize.inputs[0]) return {"structure": structure, "inflation_normal": normalize.outputs[0]} def build_inflation_position(group, position, distance, uniform, fields): """Grow both modes continuously while leaving the rear cap in place.""" links = group.links structure = fields["structure"] control = group.nodes.new("NodeGroupInput") a = _math(group, "MULTIPLY", control.outputs["Thickness"], control.outputs["Front Inflation"]) # A shifted cubic blend preserves continuous growth and height order. shifted = _math(group, "ADD", a, 0.75) quadratic = _math(group, "MULTIPLY", a, shifted) quadratic = _math(group, "ADD", quadratic, 0.1875) q = _math(group, "MULTIPLY", a, quadratic) k = _math(group, "ADD", structure, 0.25) square = _math(group, "MULTIPLY", k, k) cube = _math(group, "MULTIPLY", square, k) total = _math(group, "ADD", cube, q) root = _math(group, "POWER", total, 1 / 3) root_square = _math(group, "MULTIPLY", root, root) product = _math(group, "MULTIPLY", root, k) denominator = _math(group, "ADD", root_square, product) denominator = _math(group, "ADD", denominator, square) response = _math(group, "DIVIDE", q, denominator) profile = group.nodes.new("GeometryNodeInputNamedAttribute") profile.data_type = "FLOAT" profile.inputs["Name"].default_value = "o_balloon" balloon = _math(group, "MULTIPLY", profile.outputs["Attribute"], response) uniform_control = group.nodes.new("NodeGroupInput") uniform_amount = _math(group, "MULTIPLY", uniform_control.outputs["Uniform Thickness"], uniform_control.outputs["Front Inflation"]) selected = group.nodes.new("GeometryNodeSwitch") selected.input_type = "FLOAT" links.new(uniform, selected.inputs["Switch"]) links.new(balloon, selected.inputs["False"]) links.new(uniform_amount, selected.inputs["True"]) displacement = selected.outputs[0] height = fields["thickness"] layer = _math(group, "DIVIDE", distance, height) layer = _math(group, "ADD", 1, layer) layer = _math(group, "MAXIMUM", layer, 0) layer = _math(group, "MINIMUM", layer, 1) displacement = _math(group, "MULTIPLY", displacement, layer) normal = fields["inflation_normal"] offset = group.nodes.new("ShaderNodeVectorMath") offset.operation = "SCALE" links.new(normal, offset.inputs[0]) links.new(displacement, offset.inputs[3]) result = group.nodes.new("ShaderNodeVectorMath") result.operation = "ADD" links.new(position, result.inputs[0]) links.new(offset.outputs[0], result.inputs[1]) return result.outputs[0] def build_front_normal(group): links = group.links normal = group.nodes.new("GeometryNodeInputNormal") control = group.nodes.new("NodeGroupInput") blur = group.nodes.new("GeometryNodeBlurAttribute") blur.data_type = "FLOAT_VECTOR" links.new(normal.outputs[0], blur.inputs["Value"]) links.new(control.outputs["Normal Smooth"], blur.inputs["Iterations"]) normalize = group.nodes.new("ShaderNodeVectorMath") normalize.operation = "NORMALIZE" links.new(blur.outputs[0], normalize.inputs[0]) return evaluate_field(group, normalize.outputs[0], "FLOAT_VECTOR", "POINT") def build_shell_position(group, position, front, uniform, fields): links = group.links def connect(value, target): if hasattr(value, "node"): links.new(value, target) else: target.default_value = value def vector(operation, a, b): result = group.nodes.new("ShaderNodeVectorMath") result.operation = operation connect(a, result.inputs[0]) connect(b, result.inputs[3 if operation == "SCALE" else 1]) return result.outputs[0] def z(value): result = group.nodes.new("ShaderNodeSeparateXYZ") links.new(value, result.inputs[0]) return result.outputs["Z"] # Uniform and the thin end of Balloon share the actual front normal. front_z = z(front) raw_z = z(position) distance = _math(group, "SUBTRACT", raw_z, front_z) normal = fields["front_normal"] thin_offset = vector("SCALE", normal, distance) uniform_position = vector("ADD", front, thin_offset) # R = t * (front_z - center) + (1 - t) * front_delta, with t clamped. # This avoids division by Thickness and removes the old zero-thickness drift. control = group.nodes.new("NodeGroupInput") clamp = group.nodes.new("ShaderNodeClamp") links.new(control.outputs["Thickness"], clamp.inputs["Value"]) t = clamp.outputs[0] center = fields["center"] delta = fields["front_delta"] radius = _math(group, "SUBTRACT", front_z, center) radius = _math(group, "MULTIPLY", radius, t) remaining = _math(group, "SUBTRACT", 1, t) remainder = _math(group, "MULTIPLY", remaining, delta) radius = _math(group, "ADD", radius, remainder) # Front and rear use the same edge field, evaluated on their own caps. edge = fields["edge_weight"] mask = read_float_attribute(group, "o_normal_scale") remaining = _math(group, "SUBTRACT", 1, edge) remaining = _math(group, "MULTIPLY", remaining, mask) weight = _math(group, "SUBTRACT", 1, remaining) difference = _math(group, "SUBTRACT", weight, edge) base = _math(group, "MULTIPLY", difference, radius) layer = _math(group, "MULTIPLY", weight, distance) rear_radius = _math(group, "ADD", base, layer) front_radius = _math(group, "MULTIPLY", edge, radius) normal = fields["normal"] direction = vector("SUBTRACT", normal, (0, 0, 1)) front_shift = vector("SCALE", direction, front_radius) front_position = vector("ADD", front, front_shift) rear_shift = vector("SCALE", direction, rear_radius) axis_offset = group.nodes.new("ShaderNodeCombineXYZ") links.new(distance, axis_offset.inputs["Z"]) full_offset = vector("ADD", axis_offset.outputs[0], rear_shift) # Smoothly reach the existing full-volume shape at Thickness >= 1. transition = group.nodes.new("ShaderNodeMapRange") transition.interpolation_type = "SMOOTHERSTEP" links.new(t, transition.inputs["Value"]) mix = group.nodes.new("ShaderNodeMix") mix.data_type = "VECTOR" links.new(transition.outputs[0], mix.inputs[0]) links.new(thin_offset, mix.inputs[4]) links.new(full_offset, mix.inputs[5]) balloon_position = vector("ADD", front_position, mix.outputs["Result"]) choose = group.nodes.new("GeometryNodeSwitch") choose.input_type = "VECTOR" links.new(uniform, choose.inputs["Switch"]) links.new(balloon_position, choose.inputs["False"]) links.new(uniform_position, choose.inputs["True"]) return build_inflation_position(group, choose.outputs[0], distance, uniform, fields) def _build_depth_surface(group, geometry, controls): """Project the cleaned mesh, capture surface fields, and connect the shell.""" links = group.links split = controls.outputs["Split Threshold"] image = controls.outputs["Depth Image"] scale = controls.outputs["Uniform Scale"] geometry, corner_camera, cut_vertex = split_depth_surface( group, geometry, sample_face_camera(group, image), split, scale, triangles=True, ) camera = build_surface_camera(group, _position_field(group, image), corner_camera, cut_vertex, split) projection = project_depth_surface( group, geometry, camera, scale, controls.outputs["Reference Depth"], controls.outputs["Depth Scale"], ) # The mode field is shared by the geometry and thickness choices. mode = menu_switch(group, "Mode", ("Balloon", "Uniform"), "BOOLEAN") mode.inputs["Balloon"].default_value = False mode.inputs["Uniform"].default_value = True uniform = mode.outputs[0] volume = build_volume_fields(group) normal = build_front_normal(group) front = build_front_fields(group, volume["rim"], normal) shared, fields = capture_fields( group, projection, "POINT", center=("FLOAT", volume["center"]), front_normal=("VECTOR", normal), structure=("FLOAT", front["structure"]), inflation_normal=("VECTOR", front["inflation_normal"]), ) rounded, rounding = build_volume_rounding(group, shared, {**volume, **fields}, uniform) fields.update(rounding) shell = thicken_depth_surface( group, rounded, fields["thickness"], back_mask=NORMAL_SCALE_ATTRIBUTE_NAME, weld_zero_thickness=True, ) oriented = build_shell_position(group, shell["position"], shell["front"], uniform, fields) links.new(oriented, shell["position_input"]) amount = group.nodes.new("GeometryNodeSwitch") amount.input_type = "FLOAT" links.new(uniform, amount.inputs["Switch"]) links.new(controls.outputs["Thickness"], amount.inputs["False"]) links.new(controls.outputs["Uniform Thickness"], amount.inputs["True"]) return _remove_zero_thickness(group, projection, shell["geometry"], amount.outputs[0]) def build_image_depth_cutout_group(): name = NODE_GROUP_NAME existing = bpy.data.node_groups.get(name) if existing is not None: return existing group = bpy.data.node_groups.new(name, 'GeometryNodeTree') group.is_modifier, group.use_fake_user = (True, True) group.color_tag = 'GEOMETRY' group['anyimage_asset_revision'] = 11 interface_socket(group, 'Geometry', 'INPUT', 'NodeSocketGeometry') interface_socket(group, 'Mode', 'INPUT', 'NodeSocketMenu') float_input(group, 'Thickness', 1.0).description = 'Balloon profile multiplier; zero returns the sheet' float_input(group, 'Uniform Thickness', 0.0, subtype='DISTANCE').description = 'Distance used only by Uniform thickness mode' float_input(group, 'Depth Scale', 1.0) float_input(group, 'Split Threshold', 0.0, maximum=1, subtype='FACTOR') iterations = interface_socket(group, 'Smooth', 'INPUT', 'NodeSocketInt') iterations.default_value = 0 iterations.min_value, iterations.max_value = (0, 20) options = group.interface.new_panel(name='Options', default_closed=True) float_input(group, 'Cleanup Threshold', 0.0, parent=options) float_input(group, 'Reference Depth', 1.0, subtype='DISTANCE', parent=options) float_input(group, 'Edge Round', 0.2, maximum=1, subtype='FACTOR', parent=options) float_input(group, 'Front Inflation', 1.0, maximum=32, parent=options) normal_iterations = interface_socket(group, 'Normal Smooth', 'INPUT', 'NodeSocketInt', options) normal_iterations.default_value = 50 normal_iterations.min_value, normal_iterations.max_value = (0, 50) float_input(group, 'Smooth Weight', 1.0, maximum=1, subtype='FACTOR', parent=options) data = group.interface.new_panel(name='Data', default_closed=True) interface_socket(group, 'Inward Axis', 'INPUT', 'NodeSocketMenu', data).hide_in_modifier = True float_input(group, 'Uniform Scale', 1.0, parent=data).hide_in_modifier = True interface_socket(group, 'Depth Image', 'INPUT', 'NodeSocketImage', data).hide_in_modifier = True interface_socket(group, 'Geometry', 'OUTPUT', 'NodeSocketGeometry') base = group_input(group.nodes, {'Geometry', 'Cleanup Threshold'}) area = math_node(group.nodes, 'MULTIPLY') area.inputs[1].default_value = 0.01 group.links.new(base.outputs['Cleanup Threshold'], area.inputs[0]) cleaned = _island_cleanup(group, base.outputs['Geometry'], area.outputs[0]) cleaned = store_float_attribute(group, cleaned, NORMAL_SCALE_ATTRIBUTE_NAME, 1.0, domain='FACE') controls = group_input(group.nodes, set()) geometry = _build_depth_surface(group, cleaned, controls) geometry = expand_smooth(group, geometry, iterations_name='Smooth', weight_name='Smooth Weight') orient = group.nodes.new('GeometryNodeTransform') orient.inputs['Rotation'].default_value = Matrix(CUTOUT_Z_TO_X).to_euler() group.links.new(geometry, orient.inputs['Geometry']) axis = menu_switch(group, 'Inward Axis', ('-Z', '+X'), 'GEOMETRY') group.links.new(geometry, axis.inputs['-Z']) group.links.new(orient.outputs[0], axis.inputs['+X']) _shade_output(group, axis.outputs[0]) prepare_node_group(group) for item in group.interface.items_tree: if item.item_type != 'SOCKET' or item.in_out != 'INPUT': continue if item.name == 'Mode': item.default_value = 'Balloon' elif item.name == 'Inward Axis': item.default_value = '-Z' elif item.name == 'Uniform Thickness': item.name = 'Thickness' return group