From 07d76e18b55a00f1c9078c5e28a6fc9683d69efa Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 4 May 2026 15:10:32 +0100 Subject: [PATCH] Port nodes-to-script converter workflow --- docs/research/geometry-script-fork-notes.md | 54 ++- notes/fresh-workspace-handoff.md | 21 +- ...2-Port-node-tree-conversion-operator.patch | 389 ++++++++++++++++++ state/evidence.jsonl | 1 + state/map.yaml | 5 +- tools/setup_geometry_script_clone.ps1 | 40 +- tools/smoke_nodes_to_script_converter.py | 74 ++++ 7 files changed, 563 insertions(+), 21 deletions(-) create mode 100644 patches/geometry-script/0002-Port-node-tree-conversion-operator.patch create mode 100644 tools/smoke_nodes_to_script_converter.py diff --git a/docs/research/geometry-script-fork-notes.md b/docs/research/geometry-script-fork-notes.md index de0eaf6..6f3f9d9 100644 --- a/docs/research/geometry-script-fork-notes.md +++ b/docs/research/geometry-script-fork-notes.md @@ -23,6 +23,7 @@ The fork is intentionally kept small. As of 2026-05-04, its live branches are: ```text main vibegeometry/blender-5-nested-tree-groups +vibegeometry/blender-5-nodes-to-script ``` Upstream may still have historical branches such as `gh-pages` or @@ -68,17 +69,60 @@ Run from the VibeGeometry repo root: ``` This clones upstream into `external/geometry-script`, creates or switches to the -patch branch, and applies the patch stored in: +current VibeGeometry toolchain branch, and applies the patches stored in: ```text patches/geometry-script/0001-fix-nested-tree-group-references-on-blender-4.patch +patches/geometry-script/0002-Port-node-tree-conversion-operator.patch ``` `external/` is intentionally ignored by the VibeGeometry repository. The clone is source-controlled as its own repo, not smuggled into this repo as a pile of vendor files. -## Active Patch Branch +## Toolchain Branch + +Branch: + +```text +vibegeometry/blender-5-nodes-to-script +``` + +This is the branch VibeGeometry should use locally. It contains: + +- the nested `@tree` group fix from + `vibegeometry/blender-5-nested-tree-groups` +- a Blender 5.1 port of the historical `nodes_to_script` converter prototype + +The converter adds: + +- `operators/convert_tree.py` +- a callable `convert_node_tree(tree)` function for headless tests +- a `geometry_script.convert_tree` node editor operator that writes a generated + script into a Blender text datablock + +Smoke test: + +```powershell +& 'C:\Program Files (x86)\Steam\steamapps\common\Blender\blender.exe' --background '.\experiments\source-blends\shriinivas-fieldvalue.blend' --python '.\tools\smoke_nodes_to_script_converter.py' -- --groups 'Create Decimal' 'Digit At' 'Next Digit' 'Seven Segments' 'Delete Segments' 'Field Value' --json '.\experiments\inspection\nodes-to-script-smoke.json' --out-dir '.\experiments\inspection\nodes-to-script-output' +``` + +Current acceptance: + +- Converter runs in Blender 5.1.1. +- Generated drafts compile as Python for the tested groups. +- The full 176-node `Field Value` source group emits a 179-line draft script. +- Generated text is a bootstrap draft, not doctrine-quality final code. + +Known limits: + +- Nested source group calls are emitted by source group name, so dependency + groups must be converted or replaced by hand-authored equivalents. +- The generated script preserves node-level wiring and therefore can be noisy. +- Behavioral equivalence still needs the same evaluated-geometry or scalar + harness verification used by the hand translations. + +## Upstream PR Branch Branch: @@ -116,6 +160,6 @@ Verification: ## Fork/PR Todo - Upstream PR: https://github.com/carson-katri/geometry-script/pull/69 -- Keep `external/geometry-script` on - `vibegeometry/blender-5-nested-tree-groups` until that PR is merged or a - better maintained fork replaces it. +- Keep PR #69 limited to the nested `@tree` fix. Converter work belongs on + `vibegeometry/blender-5-nodes-to-script` unless it is intentionally prepared + as a separate upstream PR. diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index abe150a..0c27549 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -51,19 +51,22 @@ turns the form into graph structure, a small code sketch, and the verification cue. The repo-local Geometry Script clone has a Blender 5.1 patch for nested `@tree` -group reuse. See `docs/research/geometry-script-fork-notes.md`. +group reuse plus a ported `nodes_to_script` converter. See +`docs/research/geometry-script-fork-notes.md`. Run `.\tools\setup_geometry_script_clone.ps1` if `external/geometry-script` is missing in a fresh workspace. -The patch branch is pushed to `GameCult/geometry-script`, and the upstream PR is +The local toolchain branch is `vibegeometry/blender-5-nodes-to-script`. +The upstream PR branch is `vibegeometry/blender-5-nested-tree-groups`, and PR +#69 is intentionally limited to the nested-group fix: https://github.com/carson-katri/geometry-script/pull/69. -The GameCult fork is intentionally pruned to `main` plus the active -`vibegeometry/blender-5-nested-tree-groups` branch. Upstream branch clutter -should not be copied forward unless a future patch actually needs it. +The GameCult fork is intentionally pruned to `main` plus VibeGeometry-owned +tooling branches. Upstream branch clutter should not be copied forward unless a +future patch actually needs it. -The current next action is to test or port upstream Geometry Script's -`nodes_to_script` prototype before attempting the full 176-node `Field Value` -translation. `Geometry Nodes Group.002` is a wrapper around the full `Field -Value` group rather than an independent helper. +The current next action is to use the generated +`experiments/inspection/nodes-to-script-output/field_value.py` draft as a map +for a cleaned `VG Field Value` translation. `Geometry Nodes Group.002` is a +wrapper around the full `Field Value` group rather than an independent helper. ## Important Invariants diff --git a/patches/geometry-script/0002-Port-node-tree-conversion-operator.patch b/patches/geometry-script/0002-Port-node-tree-conversion-operator.patch new file mode 100644 index 0000000..ba64a8b --- /dev/null +++ b/patches/geometry-script/0002-Port-node-tree-conversion-operator.patch @@ -0,0 +1,389 @@ +From 277d8b01284fba5fe07c759483963859bf35c781 Mon Sep 17 00:00:00 2001 +From: Meta Vens +Date: Mon, 4 May 2026 15:06:48 +0100 +Subject: [PATCH] Port node tree conversion operator + +--- + __init__.py | 9 ++ + operators/__init__.py | 1 + + operators/convert_tree.py | 316 ++++++++++++++++++++++++++++++++++++++ + 3 files changed, 326 insertions(+) + create mode 100644 operators/__init__.py + create mode 100644 operators/convert_tree.py + +diff --git a/__init__.py b/__init__.py +index 9e428e7..df8432a 100644 +--- a/__init__.py ++++ b/__init__.py +@@ -22,6 +22,7 @@ import webbrowser + from .api.tree import * + from .preferences import GeometryScriptPreferences + from .absolute_path import absolute_path ++from .operators.convert_tree import ConvertTree + + bl_info = { + "name" : "Geometry Script", +@@ -74,6 +75,10 @@ def templates_menu_draw(self, context): + def editor_header_draw(self, context): + self.layout.menu(GeometryScriptMenu.bl_idname) + ++def node_header_draw(self, context): ++ if context.space_data.tree_type == 'GeometryNodeTree': ++ self.layout.operator(ConvertTree.bl_idname) ++ + def auto_resolve(): + if bpy.context.scene.geometry_script_settings.auto_resolve: + try: +@@ -97,8 +102,10 @@ def register(): + bpy.utils.register_class(GeometryScriptPreferences) + bpy.utils.register_class(OpenDocumentation) + bpy.utils.register_class(GeometryScriptMenu) ++ bpy.utils.register_class(ConvertTree) + + bpy.types.TEXT_HT_header.append(editor_header_draw) ++ bpy.types.NODE_HT_header.append(node_header_draw) + + bpy.types.Scene.geometry_script_settings = bpy.props.PointerProperty(type=GeometryScriptSettings) + +@@ -111,7 +118,9 @@ def unregister(): + bpy.utils.unregister_class(GeometryScriptPreferences) + bpy.utils.unregister_class(OpenDocumentation) + bpy.utils.unregister_class(GeometryScriptMenu) ++ bpy.utils.unregister_class(ConvertTree) + bpy.types.TEXT_HT_header.remove(editor_header_draw) ++ bpy.types.NODE_HT_header.remove(node_header_draw) + try: + bpy.app.timers.unregister(auto_resolve) + except: +diff --git a/operators/__init__.py b/operators/__init__.py +new file mode 100644 +index 0000000..ea7f7d1 +--- /dev/null ++++ b/operators/__init__.py +@@ -0,0 +1 @@ ++"""Geometry Script Blender operators.""" +diff --git a/operators/convert_tree.py b/operators/convert_tree.py +new file mode 100644 +index 0000000..8485ea2 +--- /dev/null ++++ b/operators/convert_tree.py +@@ -0,0 +1,316 @@ ++import collections.abc ++import keyword ++import re ++ ++import bpy ++import mathutils ++ ++ ++_SOCKET_TYPE_NAMES = { ++ "BOOLEAN": "Bool", ++ "COLLECTION": "Collection", ++ "GEOMETRY": "Geometry", ++ "IMAGE": "Image", ++ "INT": "Int", ++ "MATERIAL": "Material", ++ "MENU": "Menu", ++ "OBJECT": "Object", ++ "RGBA": "Color", ++ "ROTATION": "Rotation", ++ "STRING": "String", ++ "TEXTURE": "Texture", ++ "VALUE": "Float", ++ "VECTOR": "Vector", ++} ++ ++_PROP_DENYLIST = { ++ "bl_idname", ++ "bl_label", ++ "bl_static_type", ++ "color", ++ "dimensions", ++ "height", ++ "hide", ++ "inputs", ++ "internal_links", ++ "label", ++ "location", ++ "mute", ++ "name", ++ "outputs", ++ "parent", ++ "rna_type", ++ "select", ++ "show_options", ++ "show_preview", ++ "show_texture", ++ "type", ++ "use_custom_color", ++ "warning_propagation", ++ "width", ++} ++ ++ ++def _snake_case(value): ++ value = re.sub(r"[^0-9A-Za-z_]+", "_", value.strip()) ++ value = re.sub(r"_+", "_", value).strip("_").lower() ++ if not value: ++ value = "value" ++ if value[0].isdigit(): ++ value = "_" + value ++ if keyword.iskeyword(value): ++ value += "_" ++ return value ++ ++ ++def _node_function_name(node): ++ if node.bl_idname == "GeometryNodeGroup" and getattr(node, "node_tree", None): ++ return _snake_case(node.node_tree.name) ++ return _snake_case(node.bl_rna.name) ++ ++ ++def _socket_name(socket): ++ return _snake_case(socket.name or socket.identifier) ++ ++ ++def _enabled_sockets(sockets): ++ return [socket for socket in sockets if socket.enabled and socket.type != "CUSTOM"] ++ ++ ++def _convert_value(value): ++ if isinstance(value, mathutils.Vector): ++ return tuple(value) ++ if isinstance(value, mathutils.Euler): ++ return tuple(value) ++ if isinstance(value, mathutils.Color): ++ return tuple(value) ++ if isinstance(value, bpy.types.bpy_prop_array): ++ return tuple(value) ++ if isinstance(value, collections.abc.Iterable) and not isinstance(value, (str, bytes)): ++ try: ++ return tuple(value) ++ except TypeError: ++ return value ++ return value ++ ++ ++def _literal(value): ++ value = _convert_value(value) ++ if isinstance(value, bpy.types.ID): ++ return "None" ++ return repr(value) ++ ++ ++def _socket_type_annotation(socket): ++ return _SOCKET_TYPE_NAMES.get(socket.type, "Type") ++ ++ ++class _Assignment: ++ def __init__(self, name, node): ++ self.name = name ++ self.node = node ++ self.props = {} ++ self.arguments = {} ++ self.argument_outputs = {} ++ self.argument_is_multi_input = {} ++ ++ def flattened_arguments(self): ++ result = [] ++ for value in self.arguments.values(): ++ if isinstance(value, _Assignment): ++ result.append(value) ++ elif isinstance(value, list): ++ result.extend(item for item in value if isinstance(item, _Assignment)) ++ return result ++ ++ def _value_expr(self, key, value, index=None): ++ if isinstance(value, list): ++ values = [self._value_expr(key, item, index=i) for i, item in enumerate(value)] ++ if self.argument_is_multi_input.get(key, False): ++ return "[" + ", ".join(values) + "]" ++ if len(values) == 1: ++ return values[0] ++ return "(" + ", ".join(values) + ")" ++ if not isinstance(value, _Assignment): ++ return _literal(value) ++ if value.node.type == "GROUP_INPUT": ++ output_name = self.argument_outputs[key] if index is None else self.argument_outputs[key][index] ++ return output_name ++ output_name = self.argument_outputs[key] if index is None else self.argument_outputs[key][index] ++ enabled_outputs = _enabled_sockets(value.node.outputs) ++ if len(enabled_outputs) > 1: ++ return f"{value.name}.{output_name}" ++ return value.name ++ ++ def _argument_expr(self, key, value): ++ return f"{key}={self._value_expr(key, value)}" ++ ++ def result_targets(self): ++ return self.name ++ ++ def to_script(self): ++ args = [] ++ for key, value in self.props.items(): ++ args.append(f"{key}={_literal(value)}") ++ for key, value in self.arguments.items(): ++ args.append(self._argument_expr(key, value)) ++ return f"{self.result_targets()} = {_node_function_name(self.node)}({', '.join(args)})" ++ ++ ++def _collect_node_props(node): ++ props = {} ++ parent_props = set() ++ if getattr(node.bl_rna, "base", None) is not None: ++ parent_props.update(prop.identifier for prop in node.bl_rna.base.bl_rna.properties) ++ for prop in node.bl_rna.properties: ++ if prop.identifier in parent_props or prop.identifier in _PROP_DENYLIST: ++ continue ++ if prop.is_readonly and prop.type not in {"ENUM", "BOOLEAN", "INT", "FLOAT", "STRING"}: ++ continue ++ try: ++ value = getattr(node, prop.identifier) ++ except Exception: ++ continue ++ if prop.type == "POINTER": ++ continue ++ if prop.type == "COLLECTION": ++ continue ++ props[_snake_case(prop.identifier)] = _convert_value(value) ++ return props ++ ++ ++def _collect_input_defaults(node): ++ props = {} ++ for socket in _enabled_sockets(node.inputs): ++ if not hasattr(socket, "default_value") or socket.hide_value: ++ continue ++ props[_socket_name(socket)] = _convert_value(socket.default_value) ++ return props ++ ++ ++def _topological_sort(root): ++ seen = set() ++ order = [] ++ ++ def visit(assignment): ++ if assignment in seen: ++ return ++ seen.add(assignment) ++ for dependency in assignment.flattened_arguments(): ++ visit(dependency) ++ order.append(assignment) ++ ++ visit(root) ++ return order ++ ++ ++def _function_arguments(group_input): ++ if group_input is None: ++ return [] ++ arguments = [] ++ for output in _enabled_sockets(group_input.outputs): ++ arguments.append(f"{_socket_name(output)}: {_socket_type_annotation(output)}") ++ return arguments ++ ++ ++def _return_entries(group_output, output_assignment): ++ entries = [] ++ for socket in _enabled_sockets(group_output.node.inputs): ++ key = _socket_name(socket) ++ if key not in group_output.arguments: ++ continue ++ value = group_output.arguments[key] ++ expr = group_output._argument_expr(key, value).split("=", 1)[1] ++ entries.append(f'"{socket.name}": {expr}') ++ if entries: ++ return "{ " + ", ".join(entries) + " }" ++ return output_assignment.name ++ ++ ++def convert_node_tree(tree): ++ """Return a best-effort Geometry Script draft for a Blender node tree.""" ++ assignments = [] ++ node_to_assignment = {} ++ node_type_counts = {} ++ incoming_links = {} ++ ++ for node in tree.nodes: ++ prefix = _snake_case(node.type[:1] or "node") ++ count = node_type_counts.get(prefix, 0) + 1 ++ node_type_counts[prefix] = count ++ assignment = _Assignment(f"{prefix}{count}", node) ++ assignment.props.update(_collect_node_props(node)) ++ assignments.append(assignment) ++ node_to_assignment[node] = assignment ++ ++ for link in tree.links: ++ incoming_links.setdefault(link.to_socket, []).append((node_to_assignment[link.from_node], _socket_name(link.from_socket))) ++ ++ for assignment in assignments: ++ grouped_inputs = {} ++ for socket in _enabled_sockets(assignment.node.inputs): ++ key = _socket_name(socket) ++ grouped_inputs.setdefault(key, []).append(socket) ++ for key, sockets in grouped_inputs.items(): ++ values = [] ++ output_names = {} ++ is_multi_input = any(socket.is_multi_input for socket in sockets) ++ for socket in sockets: ++ links = incoming_links.get(socket, []) ++ if links: ++ for from_assignment, output_name in links: ++ output_names[len(values)] = output_name ++ values.append(from_assignment) ++ elif hasattr(socket, "default_value") and not socket.hide_value: ++ values.append(_convert_value(socket.default_value)) ++ if not values: ++ continue ++ if len(values) == 1: ++ assignment.arguments[key] = values[0] ++ if output_names: ++ assignment.argument_outputs[key] = output_names[0] ++ else: ++ assignment.arguments[key] = values ++ assignment.argument_outputs[key] = output_names ++ assignment.argument_is_multi_input[key] = is_multi_input ++ ++ group_output = next((assignment for assignment in assignments if assignment.node.type == "GROUP_OUTPUT"), None) ++ if group_output is None: ++ raise ValueError(f"Node tree {tree.name!r} has no Group Output node") ++ group_input = next((node for node in tree.nodes if node.type == "GROUP_INPUT"), None) ++ ++ sorted_assignments = [ ++ assignment ++ for assignment in _topological_sort(group_output) ++ if assignment.node.type not in {"GROUP_INPUT", "GROUP_OUTPUT"} ++ ] ++ body = "\n ".join(assignment.to_script() for assignment in sorted_assignments) ++ if not body: ++ body = "pass" ++ ++ arguments = ", ".join(_function_arguments(group_input)) ++ function_name = _snake_case(tree.name) ++ return_expr = _return_entries(group_output, sorted_assignments[-1] if sorted_assignments else group_output) ++ ++ return ( ++ "from geometry_script import *\n\n" ++ f'@tree("{tree.name}")\n' ++ f"def {function_name}({arguments}):\n" ++ f" {body}\n" ++ f" return {return_expr}\n" ++ ) ++ ++ ++class ConvertTree(bpy.types.Operator): ++ bl_idname = "geometry_script.convert_tree" ++ bl_label = "Convert to Geometry Script" ++ ++ @classmethod ++ def poll(cls, context): ++ return bool(getattr(getattr(context, "space_data", None), "node_tree", None)) ++ ++ def execute(self, context): ++ script = convert_node_tree(context.space_data.node_tree) ++ script_datablock = bpy.data.texts.new(context.space_data.node_tree.name + ".py") ++ script_datablock.write(script) ++ return {"FINISHED"} +-- +2.53.0.windows.3 + diff --git a/state/evidence.jsonl b/state/evidence.jsonl index 72d4ebb..fa4ebf1 100644 --- a/state/evidence.jsonl +++ b/state/evidence.jsonl @@ -19,3 +19,4 @@ {"ts": "2026-05-04T13:37:51+00:00", "type": "research", "status": "accepted", "note": "Full fieldvalue Field Value graph is a 176-node composition with menu switches, capture attributes across domains, sample-index reads, instancing, transforms, delete geometry, and material assignment. Manual one-pass translation would be high-risk; next action should test or port upstream Geometry Script nodes_to_script as a generated first-draft tool before attempting the full graph."} {"ts": "2026-05-04T13:47:26+00:00", "type": "documentation", "status": "accepted", "note": "Reframed procedural doctrine as a spatial reasoning playbook rather than abstraction glossary. Each doctrine pattern should describe the visual cue, mental move, Geometry Script code shape, and verification cue so metaphors help an agent choose tools while reasoning about form."} {"ts": "2026-05-04T13:51:58+00:00", "type": "documentation", "status": "accepted", "note": "Audited procedural doctrine snippets against the verified Geometry Script translations and removed conceptual shorthand. Doctrine snippets should use the same explicit Geometry Script node-call style as the scripts that passed Blender verification, with excerpts clearly behaving as excerpts rather than pseudocode."} +{"ts": "2026-05-04T14:10:09+00:00", "type": "tooling", "status": "accepted", "note": "Ported upstream Geometry Script nodes_to_script prototype onto GameCult fork branch vibegeometry/blender-5-nodes-to-script. Added callable convert_node_tree(tree), UI operator registration, patch persistence, and a Blender smoke harness. In Blender 5.1.1 the converter emits compiling draft scripts for Create Decimal, Digit At, Next Digit, Seven Segments, Delete Segments, and the 176-node Field Value group; generated output is a bootstrap draft requiring cleanup and behavioral verification."} diff --git a/state/map.yaml b/state/map.yaml index cf79224..1edf11a 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -70,6 +70,7 @@ current_artifacts: - tools/verify_piechart_translations.py - tools/verify_fieldvalue_translations.py - tools/geometry_script_loader.py + - tools/smoke_nodes_to_script_converter.py pending_contracts: - schemas/scene-brief.schema.json - schemas/node-graph-manifest.schema.json @@ -84,8 +85,8 @@ data_flow: - If state grows faster than understanding, cut it back. current_status: - summary: VibeGeometry has an initial persistence scaffold plus verified Geometry Script translations for inspected Shriinivas cartesian, pie chart, and field-value helper/chassis/mask/branch graph families. - next_action: Test or port upstream Geometry Script's `nodes_to_script` prototype before attempting the full 176-node `Field Value` translation. + summary: VibeGeometry has an initial persistence scaffold plus verified Geometry Script translations for inspected Shriinivas cartesian, pie chart, and field-value helper/chassis/mask/branch graph families. The repo-local Geometry Script fork now includes a Blender 5.1 nodes_to_script converter port that emits compiling drafts for tested source groups. + next_action: Use the generated `experiments/inspection/nodes-to-script-output/field_value.py` draft as a map for a cleaned `VG Field Value` translation. remotes: vibegeometry: https://github.com/GameCult/VibeGeometry geometry_script_fork: https://github.com/GameCult/geometry-script diff --git a/tools/setup_geometry_script_clone.ps1 b/tools/setup_geometry_script_clone.ps1 index 6dad7f4..4304f9b 100644 --- a/tools/setup_geometry_script_clone.ps1 +++ b/tools/setup_geometry_script_clone.ps1 @@ -1,13 +1,36 @@ param( [string]$RepoUrl = "https://github.com/carson-katri/geometry-script.git", - [string]$Branch = "vibegeometry/blender-5-nested-tree-groups" + [string]$Branch = "vibegeometry/blender-5-nodes-to-script" ) $ErrorActionPreference = "Stop" +if (Get-Variable -Name PSNativeCommandUseErrorActionPreference -ErrorAction SilentlyContinue) { + $PSNativeCommandUseErrorActionPreference = $false +} $root = Resolve-Path (Join-Path $PSScriptRoot "..") $target = Join-Path $root "external\geometry-script" -$patch = Join-Path $root "patches\geometry-script\0001-fix-nested-tree-group-references-on-blender-4.patch" +$patchDir = Join-Path $root "patches\geometry-script" + +function Test-GitPatch { + param( + [string]$Mode, + [string]$PatchPath + ) + + $previous = $ErrorActionPreference + $ErrorActionPreference = "Continue" + try { + if ($Mode -eq "Reverse") { + & git -C $target apply --reverse --check $PatchPath 2>$null + } else { + & git -C $target apply --check $PatchPath 2>$null + } + return $LASTEXITCODE -eq 0 + } finally { + $ErrorActionPreference = $previous + } +} if (!(Test-Path $target)) { New-Item -ItemType Directory -Force (Split-Path $target) | Out-Null @@ -23,9 +46,16 @@ if ($branches) { git -C $target switch -c $Branch origin/main } -$alreadyApplied = git -C $target log --oneline --grep "Fix nested tree group references on Blender 4+" -1 -if (!$alreadyApplied) { - git -C $target am $patch +$patches = Get-ChildItem -Path $patchDir -Filter "*.patch" | Sort-Object Name +foreach ($patch in $patches) { + if (Test-GitPatch -Mode "Forward" -PatchPath $patch.FullName) { + git -C $target am $patch.FullName + continue + } + + if (!(Test-GitPatch -Mode "Reverse" -PatchPath $patch.FullName)) { + throw "Patch is neither applicable nor already applied: $($patch.FullName)" + } } git -C $target status --short --branch diff --git a/tools/smoke_nodes_to_script_converter.py b/tools/smoke_nodes_to_script_converter.py new file mode 100644 index 0000000..e14fdc3 --- /dev/null +++ b/tools/smoke_nodes_to_script_converter.py @@ -0,0 +1,74 @@ +"""Smoke-test Geometry Script's node-tree-to-script converter in Blender.""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +GEOMETRY_SCRIPT = ROOT / "external" / "geometry-script" + + +def _load_converter(): + sys.path.insert(0, str(ROOT)) + from tools.geometry_script_loader import load_repo_geometry_script + + load_repo_geometry_script() + from geometry_script.operators.convert_tree import convert_node_tree + + return convert_node_tree + + +def main() -> int: + import bpy + + parser = argparse.ArgumentParser() + parser.add_argument("--groups", nargs="+", required=True) + parser.add_argument("--json", type=Path) + parser.add_argument("--out-dir", type=Path) + args = parser.parse_args(sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []) + + convert_node_tree = _load_converter() + results = [] + ok = True + for name in args.groups: + tree = bpy.data.node_groups[name] + try: + script = convert_node_tree(tree) + compile(script, f"", "exec") + output_path = None + if args.out_dir: + args.out_dir.mkdir(parents=True, exist_ok=True) + output_path = args.out_dir / f"{name.replace(' ', '_').lower()}.py" + output_path.write_text(script, encoding="utf-8") + result = { + "group": name, + "ok": True, + "script_length": len(script), + "line_count": len(script.splitlines()), + "header": script.splitlines()[:8], + "output_path": str(output_path) if output_path else None, + } + except Exception as exc: + ok = False + result = { + "group": name, + "ok": False, + "error_type": type(exc).__name__, + "error": str(exc), + } + results.append(result) + + payload = {"ok": ok, "results": results} + if args.json: + args.json.parent.mkdir(parents=True, exist_ok=True) + args.json.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8") + print("VG_NODES_TO_SCRIPT_SMOKE " + json.dumps(payload, sort_keys=True)) + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main())