Files
AnyImage/tools/nodes/groups/image_depth_cutout.py

393 lines
20 KiB
Python

"""Build O Image Depth Cutout."""
import bpy
from anyimage.operators.cutout_tool.shape import NORMAL_REDUCTION_ATTRIBUTE_NAME
from ..common.nodes import (
interface_socket, group_input, float_input, read_float_attribute,
store_float_attribute, prepare_node_group, sample_field, evaluate_field,
compare_node,
)
from ..common.boundary_smoothing import smooth_cut_boundary
from ..common.cutout import _position_field, _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
from ..common.cutout_boundary import original_boundary_field, remove_boundary_triangles, taper_split_profile
NODE_GROUP_NAME = "O Image Depth Cutout"
def build_normal_weight(group, is_shell):
"""Use full shell smoothing and thickness-weighted balloon smoothing."""
control = group_input(group.nodes, {"Thickness"})
amount = group.nodes.new("GeometryNodeSwitch")
amount.input_type = "FLOAT"
group.links.new(is_shell, amount.inputs["Switch"])
group.links.new(control.outputs["Thickness"], amount.inputs["False"])
amount.inputs["True"].default_value = 1
ramp = group.nodes.new("ShaderNodeMapRange")
ramp.interpolation_type = "SMOOTHSTEP"
ramp.clamp = True
group.links.new(amount.outputs[0], ramp.inputs["Value"])
return ramp.outputs["Result"]
def blend_normal(group, original, smoothed, weight):
"""Normalize the thickness-weighted blend on the consumer geometry."""
mix = group.nodes.new("ShaderNodeMix")
mix.data_type = "VECTOR"
if isinstance(weight, (int, float)):
mix.inputs[0].default_value = weight
else:
group.links.new(weight, mix.inputs[0])
group.links.new(original, mix.inputs[4])
group.links.new(smoothed, mix.inputs[5])
normalize = group.nodes.new("ShaderNodeVectorMath")
normalize.operation = "NORMALIZE"
group.links.new(mix.outputs["Result"], normalize.inputs[0])
return normalize.outputs[0]
def build_volume_fields(group, rim=None):
"""Evaluate the center and thickness on the original front surface."""
links = group.links
if rim is None:
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])
interior = _math(group, "SUBTRACT", 1, rim)
depth = axes.outputs["Y"]
depth_slow = group.nodes.new("GeometryNodeBlurAttribute")
depth_slow.data_type = "FLOAT"
depth_slow.inputs["Iterations"].default_value = 256
links.new(depth, depth_slow.inputs["Value"])
links.new(interior, depth_slow.inputs["Weight"])
profile_slow = group.nodes.new("GeometryNodeBlurAttribute")
profile_slow.data_type = "FLOAT"
profile_slow.inputs["Iterations"].default_value = 256
links.new(profile, profile_slow.inputs["Value"])
links.new(interior, profile_slow.inputs["Weight"])
center = _math(group, "SUBTRACT", depth_slow.outputs[0], profile_slow.outputs[0])
residual = _math(group, "SUBTRACT", axes.outputs["Y"], 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 {
"profile": profile, "depth": depth, "interior": interior,
"depth_slow": depth_slow.outputs[0], "profile_slow": profile_slow.outputs[0],
"center": center, "thickness": thickness,
}
def build_shell_fields(group, geometry, fields, is_shell, normal_weight=1):
"""Evaluate rear directions on the center surface and select shell thickness."""
nodes, links = group.nodes, group.links
position = nodes.new("GeometryNodeInputPosition")
axes = nodes.new("ShaderNodeSeparateXYZ")
links.new(position.outputs[0], axes.inputs[0])
center_position = nodes.new("ShaderNodeCombineXYZ")
for axis in ("X", "Z"):
links.new(axes.outputs[axis], center_position.inputs[axis])
links.new(fields["center"], center_position.inputs["Y"])
surface = nodes.new("GeometryNodeSetPosition")
links.new(geometry, surface.inputs["Geometry"])
links.new(center_position.outputs[0], surface.inputs["Position"])
normal = nodes.new("GeometryNodeInputNormal")
blur = nodes.new("GeometryNodeBlurAttribute")
blur.data_type = "FLOAT_VECTOR"
links.new(group_input(nodes, {"Normal Smooth"}).outputs["Normal Smooth"], blur.inputs["Iterations"])
links.new(normal.outputs[0], blur.inputs["Value"])
normalized = blend_normal(group, normal.outputs[0], blur.outputs[0], normal_weight)
rear_normal = sample_field(group, surface.outputs[0], normalized, "FLOAT_VECTOR")
control = group_input(nodes, {"Shell Thickness"})
thickness = nodes.new("GeometryNodeSwitch")
thickness.input_type = "FLOAT"
links.new(is_shell, thickness.inputs["Switch"])
links.new(fields["thickness"], thickness.inputs["False"])
links.new(control.outputs["Shell Thickness"], thickness.inputs["True"])
return {"thickness": thickness.outputs[0], "normal": rear_normal}
def build_front_fields(group, volume, front_normal, normal_weight=1):
"""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, depth = volume["profile"], volume["depth"]
depth_slow, profile_slow = volume["depth_slow"], volume["profile_slow"]
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
smooth = group.nodes.new("GeometryNodeBlurAttribute")
smooth.data_type = "FLOAT_VECTOR"
links.new(normal, smooth.inputs["Value"])
iterations = group_input(group.nodes, {"Normal Smooth"}).outputs["Normal Smooth"]
# Preserve the existing extra smoothing of the inflation direction at 100.
links.new(_math(group, "MULTIPLY", iterations, 5.12), smooth.inputs["Iterations"])
normalized = blend_normal(group, normal, smooth.outputs[0], normal_weight)
return {"structure": structure, "inflation_normal": normalized}
def build_inflation_position(group, position, distance, fields):
"""Inflate the Balloon front 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"
displacement = _math(group, "MULTIPLY", profile.outputs["Attribute"], response)
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])
enabled = group.nodes.new("GeometryNodeSwitch")
enabled.input_type = "VECTOR"
links.new(control.outputs["Front Inflation"], enabled.inputs["Switch"])
links.new(position, enabled.inputs["False"])
links.new(result.outputs[0], enabled.inputs["True"])
return enabled.outputs[0]
def build_front_normal(group, normal_weight):
links = group.links
normal = group.nodes.new("GeometryNodeInputNormal")
blur = group.nodes.new("GeometryNodeBlurAttribute")
blur.data_type = "FLOAT_VECTOR"
links.new(normal.outputs[0], blur.inputs["Value"])
links.new(group_input(group.nodes, {"Normal Smooth"}).outputs["Normal Smooth"], blur.inputs["Iterations"])
normalized = blend_normal(group, normal.outputs[0], blur.outputs[0], normal_weight)
return evaluate_field(group, normalized, "FLOAT_VECTOR", "POINT")
def build_shell_position(group, position, front, is_shell, 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 y(value):
result = group.nodes.new("ShaderNodeSeparateXYZ")
links.new(value, result.inputs[0])
return result.outputs["Y"]
# Shell and the thin end of Balloon share the actual front normal.
front_y = y(front)
raw_y = y(position)
distance = _math(group, "SUBTRACT", raw_y, front_y)
normal = fields["front_normal"]
thin_offset = vector("SCALE", normal, distance)
shell_position = vector("ADD", front, thin_offset)
control = group_input(group.nodes, {"Thickness"})
clamp = group.nodes.new("ShaderNodeClamp")
links.new(control.outputs["Thickness"], clamp.inputs["Value"])
t = clamp.outputs[0]
radius = _math(group, "MULTIPLY", _math(group, "SUBTRACT", front_y, fields["center"]), t)
rear = read_float_attribute(group, NORMAL_REDUCTION_ATTRIBUTE_NAME)
rear_radius = _math(group, "MULTIPLY", rear, _math(group, "ADD", radius, distance))
direction = vector("SUBTRACT", fields["normal"], (0, 1, 0))
rear_shift = vector("SCALE", direction, rear_radius)
axis_offset = group.nodes.new("ShaderNodeCombineXYZ")
links.new(distance, axis_offset.inputs["Y"])
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, mix.outputs["Result"])
choose = group.nodes.new("GeometryNodeSwitch")
choose.input_type = "VECTOR"
links.new(is_shell, choose.inputs["Switch"])
inflated = build_inflation_position(group, balloon_position, distance, fields)
links.new(inflated, choose.inputs["False"])
links.new(shell_position, choose.inputs["True"])
return choose.outputs[0]
def _build_depth_surface(group, geometry, controls):
"""Project the mesh and sample front-surface fields while shaping the shell."""
links = group.links
split = controls.outputs["Depth Split"]
image = controls.outputs["Depth Image"]
scale = controls.outputs["Uniform Scale"]
original = geometry
geometry, corner_camera, cut_vertex = split_depth_surface(
group, geometry, sample_face_camera(group, image), split, controls.outputs["Reference Depth"],
controls.outputs["Depth Scale"], triangles=True,
)
geometry = remove_boundary_triangles(group, geometry)
boundary = edge_boundary_field(group.nodes, group.links)
rim = evaluate_field(group, boundary, "FLOAT", "POINT")
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"],
)
projection = smooth_cut_boundary(group, projection, cut_vertex, boundary=rim)
# Clamped depth pixels can collapse adjacent outline samples after projection.
edge = group.nodes.new("GeometryNodeInputMeshEdgeVertices")
length = group.nodes.new("ShaderNodeVectorMath")
length.operation = "DISTANCE"
links.new(edge.outputs["Position 1"], length.inputs[0])
links.new(edge.outputs["Position 2"], length.inputs[1])
typical = group.nodes.new("GeometryNodeAttributeStatistic")
typical.data_type, typical.domain = "FLOAT", "EDGE"
links.new(projection, typical.inputs["Geometry"])
links.new(length.outputs["Value"], typical.inputs["Attribute"])
merge = group.nodes.new("GeometryNodeMergeByDistance")
merge.mode = "CONNECTED"
links.new(projection, merge.inputs["Geometry"])
links.new(_math(group, "MULTIPLY", typical.outputs["Mean"], 1e-6), merge.inputs["Distance"])
projection = merge.outputs["Geometry"]
projection = taper_split_profile(group, projection, original_boundary_field(group, original, rim))
# The mode field is shared by the geometry and thickness choices.
mode = group.nodes.new("GeometryNodeMenuSwitch")
mode.data_type = "BOOLEAN"
for item, name in zip(mode.enum_items, ("Balloon", "Shell")):
item.name = name
links.new(controls.outputs["Mode"], mode.inputs["Menu"])
mode.inputs["Balloon"].default_value = False
mode.inputs["Shell"].default_value = True
is_shell = mode.outputs[0]
selected_thickness = group.nodes.new("GeometryNodeSwitch")
selected_thickness.input_type = "FLOAT"
links.new(is_shell, selected_thickness.inputs["Switch"])
links.new(controls.outputs["Thickness"], selected_thickness.inputs["False"])
links.new(controls.outputs["Shell Thickness"], selected_thickness.inputs["True"])
has_thickness = compare_node(group, "GREATER_THAN", selected_thickness.outputs[0], 1e-6)
zero_shell = group.nodes.new("GeometryNodeSwitch")
zero_shell.input_type = "GEOMETRY"
links.new(has_thickness, zero_shell.inputs["Switch"])
links.new(projection, zero_shell.inputs["False"])
volume = build_volume_fields(group, rim)
normal_weight = build_normal_weight(group, is_shell)
normal = build_front_normal(group, normal_weight)
front = build_front_fields(group, volume, normal, normal_weight)
shell_fields = build_shell_fields(group, projection, volume, is_shell, normal_weight)
shell = thicken_depth_surface(
group, projection, shell_fields["thickness"], back_mask=NORMAL_REDUCTION_ATTRIBUTE_NAME, weld_zero_thickness=True,
)
fields = {
name: sample_field(group, projection, value, data_type, index=shell["source_index"])
for name, value, data_type in (
("center", volume["center"], "FLOAT"), ("front_normal", normal, "FLOAT_VECTOR"),
("structure", front["structure"], "FLOAT"), ("inflation_normal", front["inflation_normal"], "FLOAT_VECTOR"),
)
}
fields.update({
name: sample_field(group, projection, value, "FLOAT_VECTOR" if name == "normal" else "FLOAT",
index=shell["source_index"])
for name, value in shell_fields.items()
})
oriented = build_shell_position(group, shell["position"], shell["front"], is_shell, fields)
links.new(oriented, shell["position_input"])
links.new(shell["geometry"], zero_shell.inputs["True"])
return zero_shell.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'
interface_socket(group, 'Geometry', 'INPUT', 'NodeSocketGeometry')
interface_socket(group, 'Mode', 'INPUT', 'NodeSocketMenu')
float_input(group, 'Thickness', 0.0, maximum=2.0).description = 'Control how much the surface bulges in Balloon mode. Zero removes the bulge.'
float_input(group, 'Shell Thickness', 0.0, maximum=1.0, subtype='DISTANCE').description = 'Add thickness behind the original surface while keeping the front surface in place.'
float_input(group, 'Depth Scale', 1.0, maximum=2.0)
float_input(group, 'Depth Split', 0.1, maximum=1, subtype='FACTOR').description = 'Split the mesh where depth changes abruptly. Scaled by Depth Scale: a flat projection stays whole, higher values detect smaller depth jumps.'
options = group.interface.new_panel(name='Options', default_closed=True)
boundary_smooth = interface_socket(group, 'Boundary Smooth', 'INPUT', 'NodeSocketInt', options)
boundary_smooth.default_value, boundary_smooth.min_value, boundary_smooth.max_value = 4, 0, 16
boundary_smooth.description = 'Smooth geometry near the original outline and Depth Split edges. Zero disables boundary smoothing.'
normal_smooth = interface_socket(group, 'Normal Smooth', 'INPUT', 'NodeSocketInt', options)
normal_smooth.default_value, normal_smooth.min_value, normal_smooth.max_value = 64, 16, 512
normal_smooth.description = 'Control smoothing of front and rear displacement normals. Higher values produce smoother directions.'
float_input(group, 'Front Inflation', 0.2, maximum=1, subtype='FACTOR', parent=options).description = 'Control how much the front surface bulges in Balloon mode. Zero keeps the original front surface.'
float_input(group, 'Reference Depth', 1.0, subtype='DISTANCE', parent=options)
data = group.interface.new_panel(name='Data', default_closed=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')
controls = group_input(group.nodes, set())
geometry = store_float_attribute(group, controls.outputs['Geometry'], NORMAL_REDUCTION_ATTRIBUTE_NAME, 0.0)
geometry = _build_depth_surface(group, geometry, controls)
_shade_output(group, geometry)
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 == 'Shell Thickness':
item.name = 'Thickness'
return group