Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion __init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""NodeForge Blender addon package."""

NODEFORGE_VERSION = (0, 97, 5)
NODEFORGE_VERSION = (0, 98, 0)

bl_info = {
"name": "NodeForge",
"author": "nachitima",
Expand Down
24 changes: 12 additions & 12 deletions blender/bundle.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
)
from ..errors import CompileError
from .nodes import _new_node
from .input_delivery import deliver_input, require_output
from .values import make_value

_BUNDLE_SOCKET_TYPES = {
Expand All @@ -24,7 +25,7 @@
}

def build_bundle(group, items, *, x=0, y=0):
"""Build a Combine Bundle node from already-materialized runtime item Values."""
"""Build a Combine Bundle, delivering items after dynamic sockets are defined."""
node = _new_node(group, "NodeCombineBundle", x, y)
try:
for item_name, value in items:
Expand All @@ -41,15 +42,12 @@ def build_bundle(group, items, *, x=0, y=0):
raise CompileError(
f"bundle(): generated input order mismatch for {item_name!r}; got {getattr(socket, 'name', None)!r}"
)
try:
group.links.new(value.socket, socket)
except Exception as exc:
raise CompileError(f"bundle(): failed to link item {item_name!r}: {exc}") from exc
deliver_input(group, socket, value, context=f"bundle() item {item_name!r}")
return make_value(node.outputs["Bundle"], TYPE_BUNDLE)


def build_bundle_get(group, bundle_value, path_value, output_type, *, x=0, y=0):
"""Build Get Bundle Item from already-materialized runtime operands."""
"""Build Get Bundle Item with a physical Bundle and consumer-aware Path."""
if bundle_value.typ != TYPE_BUNDLE:
raise CompileError(f"bundle_get() first argument expects Bundle, got {bundle_value.typ}")
if path_value.typ != TYPE_STRING:
Expand All @@ -58,15 +56,16 @@ def build_bundle_get(group, bundle_value, path_value, output_type, *, x=0, y=0):
node = _new_node(group, "NodeGetBundleItem", x, y)
try:
node.socket_type = socket_type
group.links.new(bundle_value.socket, node.inputs["Bundle"])
group.links.new(path_value.socket, node.inputs["Path"])
except Exception as exc:
raise CompileError(f"bundle_get(): failed to configure Get Bundle Item: {exc}") from exc
physical_bundle = require_output(group, bundle_value, context="bundle_get() Bundle")
deliver_input(group, node.inputs["Bundle"], physical_bundle, context="bundle_get() Bundle")
deliver_input(group, node.inputs["Path"], path_value, context="bundle_get() Path")
return make_value(node.outputs["Item"], output_type)


def build_bundle_set(group, bundle_value, path_value, item_value, *, x=0, y=0):
"""Build Store Bundle Item from already-materialized runtime operands."""
"""Build Store Bundle Item with typed Path/Item socket delivery."""
if bundle_value.typ != TYPE_BUNDLE:
raise CompileError(f"bundle_set() first argument expects Bundle, got {bundle_value.typ}")
if path_value.typ != TYPE_STRING:
Expand All @@ -75,11 +74,12 @@ def build_bundle_set(group, bundle_value, path_value, item_value, *, x=0, y=0):
node = _new_node(group, "NodeStoreBundleItem", x, y)
try:
node.socket_type = socket_type
group.links.new(bundle_value.socket, node.inputs["Bundle"])
group.links.new(path_value.socket, node.inputs["Path"])
group.links.new(item_value.socket, node.inputs["Item"])
except Exception as exc:
raise CompileError(f"bundle_set(): failed to configure Store Bundle Item: {exc}") from exc
physical_bundle = require_output(group, bundle_value, context="bundle_set() Bundle")
deliver_input(group, node.inputs["Bundle"], physical_bundle, context="bundle_set() Bundle")
deliver_input(group, node.inputs["Path"], path_value, context="bundle_set() Path")
deliver_input(group, node.inputs["Item"], item_value, context="bundle_set() Item")
return make_value(node.outputs["Bundle"], TYPE_BUNDLE)


Expand Down
218 changes: 113 additions & 105 deletions blender/geometry.py

Large diffs are not rendered by default.

36 changes: 36 additions & 0 deletions blender/group_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,42 @@ def _sync_bundle_dynamic_items(src_group, node_map):
f"Failed to recreate Bundle item {src_item.name!r} on node {src_node.name!r}: {exc}"
) from exc

# Items rebuild their input/output sockets after generic RNA copying.
# Restore their defaults now, otherwise successful updates silently
# replace unlinked constant values with Blender's initial zero values.
for direction in ("inputs", "outputs"):
source = getattr(src_node, direction)
target = getattr(dst_node, direction)
if len(source) != len(target):
raise CompileError(f"Bundle cutover changed {direction} count on {src_node.name!r}")
for src_socket, dst_socket in zip(source, target):
if (src_socket.name != dst_socket.name
or src_socket.bl_idname != dst_socket.bl_idname):
raise CompileError(f"Bundle cutover changed {direction} socket type/name on {src_node.name!r}")
if not hasattr(src_socket, "default_value"):
continue
_copy_socket_default(src_socket, dst_socket)
before = src_socket.default_value
after = dst_socket.default_value
if hasattr(before, 'as_pointer'):
equal = hasattr(after, 'as_pointer') and before.as_pointer() == after.as_pointer()
elif isinstance(before, (str, int, float, bool)):
equal = before == after
else:
try:
old, new = tuple(before), tuple(after)
except (TypeError, ValueError):
equal = before == after
else:
equal = len(old) == len(new) and all(
abs(float(a) - float(b)) <= 1e-6 for a, b in zip(old, new)
)
if not equal:
raise CompileError(
f"Bundle cutover lost {direction} default {src_socket.name!r} "
f"on {src_node.name!r}"
)

for attr in ("active_index", "define_signature"):
if not hasattr(src_node, attr) or not hasattr(dst_node, attr):
continue
Expand Down
236 changes: 236 additions & 0 deletions blender/input_delivery.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
"""Consumer-aware delivery of typed values to resolved Blender input sockets.

A socket default is a physical representation only for a conventional visible
input. Hidden, contextual, unsupported and multi-input destinations require
explicit producers and links rather than assuming Blender's unconnected state.
"""

from __future__ import annotations

from dataclasses import dataclass

from ..errors import CompileError
from ..nf_types import NFType
from ..semantic.callable_contracts import canonicalize_group_input_default
from .socket_types import runtime_socket_nf_type, runtime_socket_owner_tree, validate_runtime_value_socket
from .values import ConstantPayload, DeferredConstant, Value


@dataclass(frozen=True)
class MenuLiteral:
"""An enum-backed Blender input without a general runtime producer."""

value: str


@dataclass(frozen=True)
class InputRealization:
"""Report the actual physical realization for raw metadata and tests."""

mode: str
default: object | None = None
links: int = 0


def _same_value(expected, actual) -> bool:
"""Compare a canonical numeric/tuple default with Blender's RNA readback."""
if isinstance(expected, tuple):
try:
actual_parts = tuple(actual)
except TypeError:
return False
return len(expected) == len(actual_parts) and all(
_same_value(a, b) for a, b in zip(expected, actual_parts)
)
if type(expected) is bool:
return type(actual) is bool and expected == actual
if type(expected) is int:
return type(actual) is int and expected == actual
if type(expected) is float:
return type(actual) in {int, float} and abs(float(actual) - expected) <= 1e-6
return expected == actual


def _input_type(socket):
"""Return the physical input type without guessing from display labels."""
return runtime_socket_nf_type(socket)


def _interface_has_contextual_fallback(socket) -> bool:
"""Detect non-VALUE defaults of a physical GeometryNodeGroup call input."""
node = getattr(socket, "node", None)
if getattr(node, "bl_idname", None) != "GeometryNodeGroup":
return False
tree = getattr(node, "node_tree", None)
interface = getattr(tree, "interface", None)
if interface is None:
return True
identifier = getattr(socket, "identifier", None)
for item in interface.items_tree:
if (
getattr(item, "item_type", None) == "SOCKET"
and getattr(item, "in_out", None) == "INPUT"
and getattr(item, "identifier", None) == identifier
):
return getattr(item, "default_input", "VALUE") != "VALUE"
# The physical input is not reliably backed by a visible interface item.
return True


def _is_safe_default(socket) -> bool:
"""Conservatively recognize ordinary visible writable scalar input defaults."""
if bool(getattr(socket, "is_multi_input", False)):
return False
if bool(getattr(socket, "is_unavailable", False)) or not bool(getattr(socket, "enabled", True)):
return False
if bool(getattr(socket, "hide_value", False)) or _interface_has_contextual_fallback(socket):
return False
return hasattr(socket, "default_value")


def _constant_from(operand, socket, context: str) -> DeferredConstant:
"""Normalize a deferred carrier or raw literal against one resolved input."""
if isinstance(operand, DeferredConstant):
return operand
if isinstance(operand, ConstantPayload):
return DeferredConstant(operand.typ, operand.value)
typ = _input_type(socket)
if typ is None:
raise CompileError(f"{context}: unsupported input socket type {getattr(socket, 'bl_idname', None)!r}")
return DeferredConstant(typ, operand)


def _validate_type(socket, typ: NFType, context: str):
"""Require exact typing except for the preexisting Int→Float widening."""
physical = _input_type(socket)
if physical is None:
raise CompileError(f"{context}: unsupported input socket type {getattr(socket, 'bl_idname', None)!r}")
if typ != physical and not (typ is NFType.INT and physical is NFType.FLOAT):
raise CompileError(f"{context}: input expects {physical.value}, got {typ.value}")


def validate_input(group, socket, operand, *, context: str = "node input"):
"""Preflight a resolved socket/operand without adding links or default values."""
if getattr(socket, "is_output", False):
raise CompileError(f"{context}: destination must be an input socket")
node = getattr(socket, "node", None)
if getattr(node, "id_data", None) is not group:
raise CompileError(f"{context}: input belongs to a different node tree")
if bool(getattr(socket, "is_unavailable", False)) or not bool(getattr(socket, "enabled", True)):
raise CompileError(f"{context}: input socket is unavailable")
if getattr(socket, "bl_idname", "") == "NodeSocketMenu":
if isinstance(operand, DeferredConstant):
# An inline String default is still a known enum literal, not a
# String output socket. Menu inputs have no runtime String link.
if operand.typ is not NFType.STRING:
raise CompileError(f"{context}: Menu input requires a String enum literal")
operand.bind_group(group)
literal = operand.value
elif type(operand) is str:
literal = operand
else:
raise CompileError(f"{context}: Menu input requires a compile-time String enum literal")
if not literal:
raise CompileError(f"{context}: Menu input requires a non-empty enum literal")
if not hasattr(socket, "default_value"):
raise CompileError(f"{context}: Menu input has no supported literal default")
return MenuLiteral(literal)
if isinstance(operand, Value):
_validate_type(socket, operand.typ, context)
validate_runtime_value_socket(operand.socket, operand.typ, group, context=context)
return operand
constant = _constant_from(operand, socket, context)
_validate_type(socket, constant.typ, context)
if constant.typ is NFType.INT and _input_type(socket) is NFType.FLOAT:
# Widen only for the physical input, preserving the source carrier type.
canonicalize_group_input_default(NFType.FLOAT, constant.value)
return constant


def require_output(group, operand, *, context: str = "constant", allow_native_conversion: bool = False) -> Value:
"""Return a physical output, allocating one typed producer per deferred owner."""
if isinstance(operand, Value):
if allow_native_conversion:
# Group outputs have historically accepted Blender's native links
# (notably Object Info Rotation -> NodeForge Vector). Preserve the
# physical source's output/owner invariants without changing types.
source = operand.socket
physical = runtime_socket_nf_type(source)
if (runtime_socket_owner_tree(source) is not group
or not getattr(source, "is_output", False)
or physical is None
or physical is not operand.typ and not (
operand.typ is NFType.VECTOR and physical is NFType.ROTATION
)):
# Object Info's Rotation output has an existing Blender-native
# Rotation->Vector conversion. Reject every other typed mismatch.
raise CompileError(f"{context}: invalid physical output socket for native group conversion")
else:
validate_runtime_value_socket(operand.socket, operand.typ, group, context=context)
return operand
if not isinstance(operand, DeferredConstant):
raise CompileError(f"{context}: expected a typed backend operand")
operand.bind_group(group)
if operand._materialized is not None:
return operand._materialized
from .nodes import (
_bool_value, _color_value, _int_value, _rotation_value,
_string_value, _value, _vector_value,
)

producers = {
NFType.FLOAT: _value,
NFType.INT: _int_value,
NFType.BOOL: _bool_value,
NFType.VECTOR: _vector_value,
NFType.COLOR: _color_value,
NFType.ROTATION: _rotation_value,
NFType.STRING: _string_value,
}
producer = producers.get(operand.typ)
if producer is None:
raise CompileError(f"{context}: cannot materialize {operand.typ.value} constant")
value = producer(group, operand.value)
operand._materialized = value
return value


def deliver_input(group, socket, operand, *, context: str = "node input") -> InputRealization:
"""Write an eligible default or connect a validated physical producer to an input."""
checked = validate_input(group, socket, operand, context=context)
if isinstance(checked, MenuLiteral):
try:
socket.default_value = checked.value
except Exception as exc:
raise CompileError(f"{context}: failed to assign Menu input: {exc}") from exc
if socket.default_value != checked.value:
raise CompileError(f"{context}: Menu input did not store the requested literal")
return InputRealization("literal_default", default=checked.value)
if isinstance(checked, Value):
try:
group.links.new(checked.socket, socket)
except Exception as exc:
raise CompileError(f"{context}: failed to link runtime input: {exc}") from exc
return InputRealization("single_link", links=1)
checked.bind_group(group)
if _is_safe_default(socket) and not checked._shared_runtime:
default = checked.value
if checked.typ is NFType.INT and _input_type(socket) is NFType.FLOAT:
default = canonicalize_group_input_default(NFType.FLOAT, default)
try:
socket.default_value = default
except Exception as exc:
raise CompileError(f"{context}: failed to assign socket default: {exc}") from exc
actual = socket.default_value
if not _same_value(default, actual):
raise CompileError(f"{context}: Blender did not store an equivalent socket default")
return InputRealization("literal_default", default=default)
value = require_output(group, checked, context=context)
try:
group.links.new(value.socket, socket)
except Exception as exc:
raise CompileError(f"{context}: failed to link constant input: {exc}") from exc
return InputRealization("single_link", links=1)


__all__ = ["InputRealization", "validate_input", "deliver_input", "require_output"]
Loading
Loading