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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def make_cube(size: Float["Size"] = 2.0) -> Geometry:
```

5. Return to the NodeForge sidebar and select the new text in **Text Script**.
6. Click **Compile Script**. NodeForge places a `make_cube` Group Node in the existing base Geometry Nodes tree; its implementation lives in a nested node group.
6. Click **Compile Script**. NodeForge creates a `make_cube` node-group datablock.
7. Connect the Group Node's **Value** output to the existing **Group Output** geometry input.

See the [Get Started guide](https://denikryt.github.io/NodeForge/docs/latest/GET_STARTED/) for the complete beginner workflow.
Expand Down
4 changes: 2 additions & 2 deletions __init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"""NodeForge Blender addon package."""

NODEFORGE_VERSION = (0, 93, 3)
NODEFORGE_VERSION = (0, 94, 2)

bl_info = {
"name": "NodeForge",
"author": "nachitima",
"version": NODEFORGE_VERSION,
"blender": (5, 2, 0),
"location": "Geometry Nodes Editor > Sidebar > NodeForge > Compile/Update Script; Add Menu > Script > Compile Group",
"location": "Geometry Nodes Editor > Sidebar > NodeForge > Compile Script; Add Menu > Script > Compile Group",
"description": "Compile a Python-like DSL into Geometry Nodes node groups. Catalog library: reusable functions, bundled examples, and user-owned local DSL scripts.",
"category": "Node",
}
Expand Down
90 changes: 28 additions & 62 deletions blender/direct_composition.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
"""Initial NodeForge composition into a caller-owned base GeometryNodeTree.

This is an internal target-specific lowering primitive. It does not replace or
manage nodes inserted during an earlier successful composition operation.
"""
"""Lower prepared physical root IR using an externally managed build attempt."""

from __future__ import annotations

from ..errors import CompileError
from ..function_instances import FunctionCompilationTrace
from .function_materializer import FunctionMaterializationContext, FunctionMaterializer
from .group_backend import BlenderGroupBuildTransaction
from .ir_lowering import BlenderIRLoweringContext, lower_body


Expand All @@ -27,83 +22,57 @@ def validate_prepared_direct(prepared, target):
'direct base-tree installation is unavailable')


def compose_prepared_initial(prepared, target, backend, session, *, source_module,
transaction=None):
"""Lower prepared source in place; a supplied nested transaction remains caller-owned.
def compose_prepared_initial(prepared, target, backend, session, *,
transaction, root_input_endpoint):
"""Lower root IR; the calling root updater owns commit, cleanup and rollback.

Every attempt cleans up only its own newly inserted root nodes. An
internally created transaction is committed or rolled back here; an
externally supplied one is neither committed nor rolled back here.
The transaction and canonical input endpoint belong to the same outer root
attempt, including all nested inline expansions targeting this tree.
"""
validate_prepared_direct(prepared, target)
preexisting_nodes = {node.as_pointer() for node in target.nodes}
own_transaction = transaction is None
if transaction is None:
transaction = BlenderGroupBuildTransaction()
cache = {}
trace = FunctionCompilationTrace()
if not prepared.body.statements:
raise CompileError(
'Root lowering requires a physical top-level body; '
'definition-only sources use GROUPS_ONLY publication'
)
context = BlenderIRLoweringContext(
group=target,
runtime_bindings={},
source_callable_session=session,
function_materializer=FunctionMaterializer(group_backend=backend),
function_materialization_context=FunctionMaterializationContext(
function_group_cache=cache,
function_group_cache={},
function_group_transaction=transaction,
function_compilation_trace=trace,
function_compilation_trace=FunctionCompilationTrace(),
source_callable_session=session,
),
helper_namespace=target.name,
extension_registry=session.resolved_environment.extension_registry,
root_input_endpoint=root_input_endpoint,
)
try:
if prepared.body.statements:
lower_body(context, prepared.body, {}, base_depth=1)
else:
_place_definition_entries(prepared, context, source_module)
if own_transaction:
transaction.commit()
except Exception as error:
cleanup_failure = None
for node in tuple(target.nodes):
if node.as_pointer() not in preexisting_nodes:
try:
target.nodes.remove(node)
except Exception as exc:
if cleanup_failure is None:
cleanup_failure = exc
if own_transaction:
try:
transaction.rollback()
except Exception as exc:
if cleanup_failure is None:
cleanup_failure = exc
if cleanup_failure is not None:
error.add_note(f"Direct-composition node cleanup or rollback also failed: {cleanup_failure}")
raise error from cleanup_failure
raise
# NODEFORGE-TEMP-ISSUE61-ROOT-STAGING: Root-producing Compile still lowers in the authoritative tree while physical Extension API v2 is rejected in root. Issue #61 PR 2 must replace this call with native-copy private staging and strict subgraph transfer; delete this marker when no backend can receive the authoritative root.
lower_body(context, prepared.body, {}, base_depth=1)
return target


def _place_definition_entries(prepared, context, snapshot):
"""Place zero-incoming source functions without treating them as DSL calls.
def materialize_definition_entries(prepared, materializer, materialization_context, snapshot):
"""Publish only zero-incoming source definitions, without root node placement.

Required inputs deliberately remain unconnected. Input types come only
from validated annotations; defaults do not supply missing types.
The caller owns the shared group transaction and its commit/rollback. The
same source-function IDs and materializer are used by direct compilation.
"""
from ..compiler_identities import GroupCompilationIdentity, module_definition_function_id
from ..function_instances import function_materialization_owner_scope
from ..semantic.function_signatures import compile_function_signature
from ..semantic.source_callables import serialize_local_signature
from ..semantic.ir import IRFunctionMaterialization, IRFunctionMaterializationMode
from .library_groups import apply_function_node_display_name

graph = prepared.source_call_graph
if graph is None:
raise CompileError('Definition-only initial placement lacks a resolved call graph')
session = context.source_callable_session
raise CompileError('Definition-only compilation lacks a resolved call graph')
session = materialization_context.source_callable_session
env, compile_time_values = session.callable_environment_for_module(snapshot)
for index, reference in enumerate(graph.entries):
groups = []
for reference in graph.entries:
fn = snapshot.definitions[reference.name]
signature = compile_function_signature(
fn, owner_scope=reference.stable_key(),
Expand All @@ -123,10 +92,7 @@ def _place_definition_entries(prepared, context, snapshot):
compile_time_values=compile_time_values, source_module=snapshot,
helper_namespace=fn.name,
)
nested = context.function_materializer.materialize_module(
prepared_callable, materialization, context.function_materialization_context,
)
node = context.group.nodes.new('GeometryNodeGroup')
node.node_tree = nested.group
node.location = (index * 260, 0)
apply_function_node_display_name(node, nested.group)
groups.append(materializer.materialize_module(
prepared_callable, materialization, materialization_context,
).group)
return tuple(groups)
33 changes: 32 additions & 1 deletion blender/ir_lowering.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from .nodes import _id as _field_id, _index as _field_index, _normal as _field_normal, _position as _field_position
from .bundle import build_bundle, build_bundle_get, build_bundle_set
from .object_info import resolve_object_property_explicit
from .raw_nodes import build_materialized_raw_node
from .raw_nodes import build_materialized_raw_node, read_existing_raw_group_input
from .extension_backend import lower_extension_call
from ..semantic.ir import (
IRBinary,
Expand Down Expand Up @@ -127,6 +127,14 @@ def _create_repeat_zone(group, state_specs, index_name, x=0, y=0):
return ri, ro


@dataclass
class RootInputEndpoint:
"""One mutable root-only Group Input selection for a compilation attempt."""

node: object | None = None
created_by_attempt: bool = False


@dataclass(frozen=True)
class BlenderIRLoweringContext:
"""Explicit Blender backend inputs for one Semantic IR lowering operation.
Expand All @@ -147,6 +155,7 @@ class BlenderIRLoweringContext:
extension_registry: object | None = None
generated_resource_transaction: object | None = None
layout_origin: tuple[float, float] = (0.0, 0.0)
root_input_endpoint: RootInputEndpoint | None = None

def __post_init__(self):
"""Freeze value bindings while retaining explicit mutable backend-owned maps."""
Expand Down Expand Up @@ -527,6 +536,27 @@ def _lower_builtin_call(context, operation, operands, x, y):
raise CompileError(f"Internal error: unknown raw-node input mode {mode!r}")
raw_inputs.append((selector, value_spec))
outputs = options["outputs"]
endpoint = getattr(context, 'root_input_endpoint', None)
if options["bl_idname"] == 'NodeGroupInput' and endpoint is not None:
if endpoint.node is None:
node = next((item for item in group.nodes if item.bl_idname == 'NodeGroupInput'), None)
if node is None:
result = build_materialized_raw_node(
group, bl_idname='NodeGroupInput', props=dict(options['props']),
inputs=raw_inputs, output=options['output'], typ=options['typ'],
outputs=list(outputs) if outputs is not None else None,
x=x, y=y, context='node()',
)
endpoint.node = result[0].socket.node if isinstance(result, tuple) else result.socket.node
endpoint.created_by_attempt = True
return result
endpoint.node = node
return read_existing_raw_group_input(
endpoint.node, props=dict(options['props']), inputs=raw_inputs,
output=options['output'], typ=options['typ'],
outputs=list(outputs) if outputs is not None else None,
context='node()',
)
return build_materialized_raw_node(
group,
bl_idname=options["bl_idname"],
Expand Down Expand Up @@ -662,6 +692,7 @@ def _lower_inline_source_call(context, operation, operands, prepared, x, y):
extension_registry=context.extension_registry,
generated_resource_transaction=context.generated_resource_transaction,
layout_origin=child_origin,
root_input_endpoint=context.root_input_endpoint,
)
result = lower_body(bound_context, prepared.group.body, inputs, base_depth=0)
outputs = result.explicit_outputs if result.explicit_outputs else (
Expand Down
54 changes: 54 additions & 0 deletions blender/raw_nodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,60 @@ def build_materialized_raw_node(
return make_value(socket, out_typ)


def read_existing_raw_group_input(node, *, props, inputs, output, typ, outputs,
context="node()"):
"""Read one retained Group Input without changing its RNA, links or metadata.

The root compositor has selected the canonical physical node. This uses
the same selector/physical-type checks as new raw-node construction, but
treats any requested properties as assertions about current RNA state.
"""
if getattr(node, 'bl_idname', None) != 'NodeGroupInput':
raise CompileError(f"{context}: expected a canonical NodeGroupInput")
if not isinstance(props, dict) or not isinstance(inputs, (list, tuple)):
raise CompileError(f"{context}: invalid raw-node props or inputs")
if inputs:
raise CompileError(f"{context}: NodeGroupInput has no assignable input sockets")
for name, requested in props.items():
if not isinstance(name, str) or not name or name.startswith('['):
raise CompileError(f"{context}: invalid raw node property {name!r}")
prop = node.bl_rna.properties.get(name)
if prop is None or getattr(prop, 'is_readonly', False):
raise CompileError(f"{context}: invalid or read-only property {name!r} on NodeGroupInput")
actual = _normalize_json_value(getattr(node, name), f"{context}: property {name!r}")
expected = _normalize_json_value(requested, f"{context}: property {name!r}")
if not _normalized_equal(actual, expected):
raise CompileError(f"{context}: existing NodeGroupInput property {name!r} differs from requested value")

if outputs is None:
if output is None or typ is None:
raise CompileError(f"{context}: raw node requires an output and type")
_validate_public_type(typ, f"{context}: typ")
declarations = [(None, output, typ)]
else:
if not isinstance(outputs, (list, tuple)) or not outputs:
raise CompileError(f"{context}: outputs cannot be empty")
declarations = outputs
selected = []
for item in declarations:
if not isinstance(item, (list, tuple)) or len(item) != 3:
raise CompileError(f"{context}: outputs must contain (alias, selector, type) triples")
alias, selector, out_typ = item
if outputs is not None and (not isinstance(alias, str) or not alias):
raise CompileError(f"{context}: output aliases must be non-empty strings")
_validate_public_type(out_typ, f"{context}: output type")
label = _selector_label(selector)
socket = resolve_socket(node.outputs, selector, direction='output', context=context)
_validate_runtime_socket_type(socket, out_typ, direction='output', context=context, socket_name=label)
_capture_physical_socket_ref(socket, direction='output', context=f"{context}: output {label}")
_reject_duplicate_physical_socket(
selected, socket, context=f"{context}: two output selectors resolve to the same physical socket",
)
selected.append(socket)
values = tuple(make_value(socket, item[2]) for socket, item in zip(selected, declarations))
return values if outputs is not None else values[0]


def _selector_label(selector) -> str:
"""Return a user-facing diagnostic label for one normalized source selector."""
if isinstance(selector, str):
Expand Down
18 changes: 13 additions & 5 deletions blender/root_update.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,9 +328,10 @@ def _fail(error, failures, *, possible_change):
raise RootUpdateError(summary, may_have_mutated=possible_change or bool(failures)) from error


def replace_prepared_root(prepared, target, backend, session, *, source_module):
def replace_prepared_root(prepared, target, backend, session):
"""Stage exactly once into `target`, cut over and commit nested groups last."""
from .direct_composition import compose_prepared_initial, validate_prepared_direct
from .ir_lowering import RootInputEndpoint

validate_base_target(target)
reject_node_local_animation(target)
Expand All @@ -349,18 +350,25 @@ def replace_prepared_root(prepared, target, backend, session, *, source_module):
if node.parent is not None and node.parent.as_pointer() in old_ptrs}
boundary = _boundary(target)
transaction = BlenderGroupBuildTransaction()
endpoint = RootInputEndpoint()
backup = None
cutover_started = False
io_detach_started = False
try:
backup = target.copy()
mark_transaction_private(backup)
compose_prepared_initial(prepared, target, backend, session,
source_module=source_module, transaction=transaction)
transaction=transaction, root_input_endpoint=endpoint)
created = tuple(node for node in target.nodes if node.as_pointer() not in preexisting_ptrs)
if any(node.bl_idname in _IO_TYPES for node in created):
raise CompileError('Direct Update cannot insert new structural Group Input/Output nodes')
new = created
allowed_input = (endpoint.node.as_pointer() if endpoint.created_by_attempt
and endpoint.node is not None else None)
if any(node.bl_idname == 'NodeGroupOutput'
or (node.bl_idname == 'NodeGroupInput' and node.as_pointer() != allowed_input)
for node in created):
raise CompileError('Compile cannot insert unapproved structural Group Input/Output nodes')
if _interface_signature(target) != interface_before:
raise CompileError('Compile changed the root interface during staging')
new = tuple(node for node in created if node.bl_idname not in _IO_TYPES)
matched = _matches(old, new)
for node in io_nodes:
if node.parent is not None and node.parent.as_pointer() in old_ptrs:
Expand Down
2 changes: 1 addition & 1 deletion blender_manifest.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
schema_version = "1.0.0"
id = "nodeforge"
version = "0.93.3"
version = "0.94.2"
name = "NodeForge"
tagline = "Compile a procedural DSL into Blender Geometry Nodes"
maintainer = "nachitima"
Expand Down
Loading
Loading