Compare commits

..
20 changed files with 149 additions and 512 deletions

View file

@ -6,8 +6,6 @@ on:
- main - main
pull_request: pull_request:
concurrency: preview-${{ github.ref }}
jobs: jobs:
deploy: deploy:
runs-on: ubuntu-20.04 runs-on: ubuntu-20.04
@ -30,9 +28,3 @@ jobs:
with: with:
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./book/book publish_dir: ./book/book
- name: Deploy preview
uses: rossjrw/pr-preview-action@v1
if: ${{ github.ref != 'refs/heads/main' }}
with:
source-dir: ./book/book

View file

@ -16,7 +16,7 @@ def repeat_grid(geometry: Geometry, width: Int, height: Int):
g = grid( g = grid(
size_x=width, size_y=height, size_x=width, size_y=height,
vertices_x=width, vertices_y=height vertices_x=width, vertices_y=height
).mesh.mesh_to_points() ).mesh_to_points()
return g.instance_on_points(instance=geometry) return g.instance_on_points(instance=geometry)
``` ```

View file

@ -1,42 +1,34 @@
import bpy import bpy
import typing import typing
from collections import deque, Counter
def _arrange(node_tree, padding: typing.Tuple[float, float] = (50, 25)): def _arrange(node_tree, padding: typing.Tuple[float, float] = (50, 25)):
# Organize the nodes into columns based on their links. # Organize the nodes into columns based on their links.
columns: typing.List[typing.List[typing.Any]] = [] columns: typing.List[typing.List[typing.Any]] = []
def contains_link(node, column):
def topo_sort(graph): return any(
in_degree = {u: 0 for u in graph} any(
for u in graph: any(link.from_node == node for link in input.links)
for v in graph[u]: for input in n.inputs
in_degree[v] += 1 )
queue = deque([u for u in in_degree if in_degree[u] == 0]) for n in column
topo_order = [] )
while queue: for node in reversed(node_tree.nodes):
u = queue.popleft() if (x := next(
topo_order.append(u) filter(
for v in graph[u]: lambda x: contains_link(node, x[1]),
in_degree[v] -= 1 enumerate(columns)
if in_degree[v] == 0: ),
queue.append(v) None
return topo_order )) is not None:
if x[0] > 0:
graph = { node:set() for node in node_tree.nodes } columns[x[0] - 1].append(node)
node_input_link_count = Counter() else:
for link in node_tree.links: columns.insert(x[0], [node])
graph[link.from_node].add(link.to_node) else:
node_input_link_count[link.to_socket] += 1 if len(columns) == 0:
sorted_nodes = topo_sort(graph)
column_index = {}
for node in reversed(sorted_nodes):
column_index[node] = max([ column_index[adj_node] for adj_node in graph[node] ], default=-1) + 1
if column_index[node] == len(columns):
columns.append([node]) columns.append([node])
else: else:
columns[column_index[node]].append(node) columns[len(columns) - 1].append(node)
columns = reversed(columns)
# Arrange the columns, computing the size of the node manually so arrangement can be done without UI being visible. # Arrange the columns, computing the size of the node manually so arrangement can be done without UI being visible.
UI_SCALE = bpy.context.preferences.view.ui_scale UI_SCALE = bpy.context.preferences.view.ui_scale
@ -54,7 +46,7 @@ def _arrange(node_tree, padding: typing.Tuple[float, float] = (50, 25)):
output_count = len(list(filter(lambda i: i.enabled, node.outputs))) output_count = len(list(filter(lambda i: i.enabled, node.outputs)))
parent_props = [prop.identifier for base in type(node).__bases__ for prop in base.bl_rna.properties] parent_props = [prop.identifier for base in type(node).__bases__ for prop in base.bl_rna.properties]
properties_count = len([prop for prop in node.bl_rna.properties if prop.identifier not in parent_props]) properties_count = len([prop for prop in node.bl_rna.properties if prop.identifier not in parent_props])
unset_vector_count = len(list(filter(lambda i: i.enabled and i.type == 'VECTOR' and node_input_link_count[i] == 0, node.inputs))) unset_vector_count = len(list(filter(lambda i: i.enabled and i.type == 'VECTOR' and len(i.links) == 0, node.inputs)))
node_height = ( node_height = (
NODE_HEADER_HEIGHT \ NODE_HEADER_HEIGHT \
+ (output_count * NODE_LINK_HEIGHT) \ + (output_count * NODE_LINK_HEIGHT) \

View file

@ -1,12 +1,11 @@
import bpy import bpy
import bl_ui
import itertools import itertools
import enum import enum
import re import re
import os
from .state import State from .state import State
from .types import * from .types import *
from .static.input_group import InputGroup from .static.input_group import InputGroup
from .static.curve import Curve
from ..absolute_path import absolute_path from ..absolute_path import absolute_path
class OutputsList(dict): class OutputsList(dict):
@ -14,21 +13,6 @@ class OutputsList(dict):
__setattr__ = dict.__setitem__ __setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__ __delattr__ = dict.__delitem__
def set_or_create_link(x, node_input):
if issubclass(type(x), Type):
State.current_node_tree.links.new(x._socket, node_input)
else:
def link_constant():
constant = Type(value=x)
State.current_node_tree.links.new(constant._socket, node_input)
if node_input.hide_value:
link_constant()
else:
try:
node_input.default_value = x
except:
link_constant()
def build_node(node_type): def build_node(node_type):
def build(_primary_arg=None, **kwargs): def build(_primary_arg=None, **kwargs):
for k, v in kwargs.copy().items(): for k, v in kwargs.copy().items():
@ -44,13 +28,6 @@ def build_node(node_type):
argname = prop.identifier.lower().replace(' ', '_') argname = prop.identifier.lower().replace(' ', '_')
if argname in kwargs: if argname in kwargs:
value = kwargs[argname] value = kwargs[argname]
if isinstance(value, list) and len(value) > 0 and isinstance(value[0], Curve):
for i, curve in enumerate(value):
curve.apply(getattr(node, prop.identifier).curves[i])
continue
if isinstance(value, Curve):
value.apply(getattr(node, prop.identifier).curves[0])
continue
if isinstance(value, enum.Enum): if isinstance(value, enum.Enum):
value = value.value value = value.value
setattr(node, prop.identifier, value) setattr(node, prop.identifier, value)
@ -63,6 +40,20 @@ def build_node(node_type):
if node_input2.name.lower().replace(' ', '_') == argname and node_input2.type == node_input.type: if node_input2.name.lower().replace(' ', '_') == argname and node_input2.type == node_input.type:
all_with_name.append(node_input2) all_with_name.append(node_input2)
if argname in kwargs: if argname in kwargs:
def set_or_create_link(x, node_input):
if issubclass(type(x), Type):
State.current_node_tree.links.new(x._socket, node_input)
else:
def link_constant():
constant = Type(value=x)
State.current_node_tree.links.new(constant._socket, node_input)
if node_input.hide_value:
link_constant()
else:
try:
node_input.default_value = x
except:
link_constant()
value = kwargs[argname] value = kwargs[argname]
if isinstance(value, enum.Enum): if isinstance(value, enum.Enum):
value = value.value value = value.value
@ -114,17 +105,34 @@ def register_node(node_type, category_path=None):
enum_type = enum.Enum(enum_type_name, { map_case_name(i): i.identifier for i in prop.enum_items }) enum_type = enum.Enum(enum_type_name, { map_case_name(i): i.identifier for i in prop.enum_items })
setattr(globals()[node_namespace_name], enum_type_name, enum_type) setattr(globals()[node_namespace_name], enum_type_name, enum_type)
registered_nodes.add(node_type) registered_nodes.add(node_type)
for category_name in list(filter(lambda x: x.startswith('NODE_MT_category_GEO_'), dir(bpy.types))):
denylist = {'filter'} # some nodes should be excluded. category = getattr(bpy.types, category_name)
class_denylist = {'CompositorNodeMath', 'TextureNodeMath'} if not hasattr(category, 'category'):
node_types_to_register = [] category_path = category.bl_label.lower().replace(' ', '_')
for node_type_name in dir(bpy.types): add_node_type = bl_ui.node_add_menu.add_node_type
draw_node_group_add_menu = bl_ui.node_add_menu.draw_node_group_add_menu
draw_assets_for_catalog = bl_ui.node_add_menu.draw_assets_for_catalog
bl_ui.node_add_menu.add_node_type = lambda _layout, node_type_name: register_node(getattr(bpy.types, node_type_name), category_path)
bl_ui.node_add_menu.draw_node_group_add_menu = lambda _context, _layout: None
bl_ui.node_add_menu.draw_assets_for_catalog = lambda _context, _layout: None
class CategoryStub:
bl_label = ""
def __init__(self):
self.layout = Layout()
class Layout:
def separator(self): pass
category.draw(CategoryStub(), None)
bl_ui.node_add_menu.add_node_type = add_node_type
bl_ui.node_add_menu.draw_node_group_add_menu = draw_node_group_add_menu
bl_ui.node_add_menu.draw_assets_for_catalog = draw_assets_for_catalog
else:
category_path = category.category.name.lower().replace(' ', '_')
for node in category.category.items(None):
node_type = getattr(bpy.types, node.nodetype)
register_node(node_type, category_path)
for node_type_name in list(filter(lambda x: 'GeometryNode' in x, dir(bpy.types))):
node_type = getattr(bpy.types, node_type_name) node_type = getattr(bpy.types, node_type_name)
if isinstance(node_type, type) and issubclass(node_type, bpy.types.Node): if issubclass(node_type, bpy.types.GeometryNode):
if node_type.is_registered_node_type() and node_type.bl_rna.name.lower() not in denylist and node_type.__name__ not in class_denylist:
node_types_to_register.append(node_type)
node_types_to_register.sort(key=lambda node_type: node_type.__name__.startswith("GeometryNode"))
for node_type in node_types_to_register:
register_node(node_type) register_node(node_type)
def create_documentation(): def create_documentation():
@ -147,7 +155,6 @@ def create_documentation():
docstrings = [] docstrings = []
symbols = [] symbols = []
enums = {} enums = {}
skipped_nodes = []
for func in sorted(documentation.keys()): for func in sorted(documentation.keys()):
try: try:
method = documentation[func] method = documentation[func]
@ -254,8 +261,12 @@ def create_documentation():
{output_symbol_separator.join(output_symbols)}""") {output_symbol_separator.join(output_symbols)}""")
return_type_hint = list(symbol_outputs.values())[0] if len(output_symbols) == 1 else f"{node_namespace_name}.Result" return_type_hint = list(symbol_outputs.values())[0] if len(output_symbols) == 1 else f"{node_namespace_name}.Result"
symbols.append(f"""def {func}({', '.join(symbol_args)}) -> {return_type_hint}: \"\"\"![]({image}.webp)\"\"\"""") symbols.append(f"""def {func}({', '.join(symbol_args)}) -> {return_type_hint}: \"\"\"![]({image}.webp)\"\"\"""")
except: except Exception as e:
skipped_nodes.append(documentation[func].bl_node_type.__name__) import os, sys
print(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
continue continue
bpy.data.node_groups.remove(temp_node_group) bpy.data.node_groups.remove(temp_node_group)
html = f""" html = f"""
@ -351,9 +362,6 @@ class Type:
fpyi.write(contents) fpyi.write(contents)
fpy.write(contents) fpy.write(contents)
if len(skipped_nodes) > 0:
pass # This could be reported later.
def create_docs(): def create_docs():
create_documentation() create_documentation()
bpy.app.timers.register(create_docs) bpy.app.timers.register(create_docs)

View file

@ -44,19 +44,12 @@ class Attribute:
""" """
Creates a "Named Attribute" node with the correct arguments passed, and returns the "Attribute" socket. Creates a "Named Attribute" node with the correct arguments passed, and returns the "Attribute" socket.
""" """
from geometry_script import named_attribute, Type from geometry_script import named_attribute
result = named_attribute(data_type=self.data_type, name=self.name, *args, **kwargs) return named_attribute(data_type=self.data_type, name=self.name, *args, **kwargs).attribute
# Handle Blender 3.5+, which includes an `exists` result.
if isinstance(result, Type):
return result
else:
return result.attribute
def exists(self, *args, **kwargs): def exists(self, *args, **kwargs):
""" """
Creates a "Named Attribute" node with the correct arguments passed, and returns the "Exists" socket. Creates a "Named Attribute" node with the correct arguments passed, and returns the "Exists" socket.
> Only available in Blender 3.5+
""" """
from geometry_script import named_attribute from geometry_script import named_attribute
return named_attribute(data_type=self.data_type, name=self.name, *args, **kwargs).exists return named_attribute(data_type=self.data_type, name=self.name, *args, **kwargs).exists
@ -66,10 +59,9 @@ class Attribute:
Creates a "Store Named Attribute" node with the correct arguments passed, and returns the modified `Geometry`. Creates a "Store Named Attribute" node with the correct arguments passed, and returns the modified `Geometry`.
""" """
from geometry_script import store_named_attribute from geometry_script import store_named_attribute
if 'domain' not in kwargs:
kwargs['domain'] = self.domain
return store_named_attribute( return store_named_attribute(
data_type=self.data_type, data_type=self.data_type,
domain=self.domain,
geometry=geometry, geometry=geometry,
name=self.name, name=self.name,
value=value, value=value,

View file

@ -1,54 +0,0 @@
from typing import List
import enum
class HandleType(enum.Enum):
AUTO = 'AUTO'
VECTOR = 'VECTOR'
AUTO_CLAMPED = 'AUTO_CLAMPED'
class Point:
"""
A single point on a curve
"""
x: float
y: float
handle_type: HandleType
def __init__(self, x: float, y: float, handle_type: HandleType = HandleType.AUTO):
self.x = x
self.y = y
self.handle_type = handle_type
class Curve:
"""
A class that represents a curve.
Create a curve from a set of `Point`s.
```python
my_curve = Curve(
Point(0, 0, Handle.AUTO_CLAMPED),
Point(0.2, 0.3, Handle.AUTO),
Point(1, 1, Handle.VECTOR)
)
```
"""
points: List[Point]
def __init__(self, *points: Point):
if len(points) == 1 and isinstance(points[0], list):
self.points = points[0]
else:
self.points = list(points)
def apply(self, curve):
"""
Apply the points to a curve object.
"""
for i, point in enumerate(self.points):
if len(curve.points) > i:
curve.points[i].location = (point.x, point.y)
curve.points[i].handle_type = point.handle_type.value
else:
curve.points.new(point.x, point.y).handle_type = point.handle_type.value

View file

@ -1,51 +0,0 @@
import bpy
import inspect
import typing
def repeat_zone(block: typing.Callable):
"""
Create a repeat input/output block.
> Only available in Blender 4.0+.
"""
def wrapped(*args, **kwargs):
from geometry_script.api.node_mapper import OutputsList, set_or_create_link
from geometry_script.api.state import State
from geometry_script.api.types import Type, socket_class_to_data_type
signature = inspect.signature(block)
# setup zone
repeat_in = State.current_node_tree.nodes.new(bpy.types.GeometryNodeRepeatInput.__name__)
repeat_out = State.current_node_tree.nodes.new(bpy.types.GeometryNodeRepeatOutput.__name__)
repeat_in.pair_with_output(repeat_out)
# clear state items
for item in repeat_out.repeat_items:
repeat_out.repeat_items.remove(item)
# link the iteration count
set_or_create_link(args[0], repeat_in.inputs[0])
# create state items from block signature
repeat_items = {}
for param in signature.parameters.values():
repeat_items[param.name] = (param.annotation, param.default, None, None)
for i, arg in enumerate(repeat_items.items()):
repeat_out.repeat_items.new(socket_class_to_data_type(arg[1][0].socket_type), arg[0].replace('_', ' ').title())
# skip the first index, which is reserved for the iteration count
i = i + 1
set_or_create_link(kwargs[arg[0]] if arg[0] in kwargs else args[i], repeat_in.inputs[i])
step = block(*[Type(o) for o in repeat_in.outputs[:-1]])
if isinstance(step, Type):
step = (step,)
for i, result in enumerate(step):
set_or_create_link(result, repeat_out.inputs[i])
if len(repeat_out.outputs[:-1]) == 1:
return Type(repeat_out.outputs[0])
else:
return OutputsList({o.name.lower().replace(' ', '_'): Type(o) for o in repeat_out.outputs[:-1]})
return wrapped

View file

@ -1,48 +1,25 @@
import bpy
import inspect import inspect
import typing import typing
def simulation_zone(block: typing.Callable): class SimulationInput:
class DeltaTime: pass
class ElapsedTime: pass
def simulation(block: typing.Callable[typing.Any, 'Geometry']):
""" """
Create a simulation input/output block. Create a simulation input/output block.
In Blender 4.0+, you must return a boolean value for the "Skip" argument as the first element in the return tuple. > Only available in the `geometry-node-simulation` branch of Blender 3.5.
> Only available in Blender 3.6+.
""" """
def wrapped(*args, **kwargs): def wrapped(geometry: 'Geometry', *args, **kwargs):
from geometry_script.api.node_mapper import OutputsList, set_or_create_link from geometry_script import simulation_input, simulation_output
from geometry_script.api.state import State simulation_in = simulation_input(geometry=geometry)
from geometry_script.api.types import Type, socket_class_to_data_type
signature = inspect.signature(block) signature = inspect.signature(block)
for key, value in signature.parameters.items():
# setup zone match value.annotation:
simulation_in = State.current_node_tree.nodes.new(bpy.types.GeometryNodeSimulationInput.__name__) case SimulationInput.DeltaTime:
simulation_out = State.current_node_tree.nodes.new(bpy.types.GeometryNodeSimulationOutput.__name__) kwargs[key] = simulation_in.delta_time
simulation_in.pair_with_output(simulation_out) case SimulationInput.ElapsedTime:
kwargs[key] = simulation_in.elapsed_time
# clear state items return simulation_output(geometry=block(simulation_in.geometry, *args, **kwargs)).geometry
for item in simulation_out.state_items:
simulation_out.state_items.remove(item)
# create state items from block signature
state_items = {}
for param in [*signature.parameters.values()][1:]:
state_items[param.name] = (param.annotation, param.default, None, None)
for i, arg in enumerate(state_items.items()):
simulation_out.state_items.new(socket_class_to_data_type(arg[1][0].socket_type), arg[0].replace('_', ' ').title())
set_or_create_link(kwargs[arg[0]] if arg[0] in kwargs else args[i], simulation_in.inputs[i])
step = block(*[Type(o) for o in simulation_in.outputs[:-1]])
if isinstance(step, Type):
step = (step,)
for i, result in enumerate(step):
set_or_create_link(result, simulation_out.inputs[i])
if len(simulation_out.outputs[:-1]) == 1:
return Type(simulation_out.outputs[0])
else:
return OutputsList({o.name.lower().replace(' ', '_'): Type(o) for o in simulation_out.outputs[:-1]})
return wrapped return wrapped

View file

@ -8,16 +8,12 @@ from .state import State
from .types import * from .types import *
from .node_mapper import * from .node_mapper import *
from .static.attribute import * from .static.attribute import *
from .static.curve import *
from .static.expression import * from .static.expression import *
from .static.input_group import * from .static.input_group import *
from .static.repeat import *
from .static.sample_mode import * from .static.sample_mode import *
from .static.simulation import * from .static.simulation import *
from .arrange import _arrange from .arrange import _arrange
IS_BLENDER_4 = bpy.app.version[0] >= 4
def _as_iterable(x): def _as_iterable(x):
if isinstance(x, Type): if isinstance(x, Type):
return [x,] return [x,]
@ -26,17 +22,6 @@ def _as_iterable(x):
except TypeError: except TypeError:
return [x,] return [x,]
def get_node_inputs(x):
if IS_BLENDER_4:
return [i for i in x.interface.items_tree if i.item_type == 'SOCKET' and i.in_out == 'INPUT']
else:
return x.inputs
def get_node_outputs(x):
if IS_BLENDER_4:
return [i for i in x.interface.items_tree if i.item_type == 'SOCKET' and i.in_out == 'OUTPUT']
else:
return x.outputs
def tree(name): def tree(name):
tree_name = name tree_name = name
def build_tree(builder): def build_tree(builder):
@ -48,26 +33,12 @@ def tree(name):
node_group = bpy.data.node_groups[tree_name] node_group = bpy.data.node_groups[tree_name]
else: else:
node_group = bpy.data.node_groups.new(tree_name, 'GeometryNodeTree') node_group = bpy.data.node_groups.new(tree_name, 'GeometryNodeTree')
if IS_BLENDER_4:
node_group.is_modifier = True
# Clear the node group before building # Clear the node group before building
for node in node_group.nodes: for node in node_group.nodes:
node_group.nodes.remove(node) node_group.nodes.remove(node)
while len(node_group.inputs) > sum(map(lambda p: len(p.annotation.__annotations__) if issubclass(p.annotation, InputGroup) else 1, list(signature.parameters.values()))):
node_inputs = get_node_inputs(node_group) node_group.inputs.remove(node_group.inputs[-1])
input_count = sum(map(lambda p: len(p.annotation.__annotations__) if issubclass(p.annotation, InputGroup) else 1, list(signature.parameters.values()))) for group_output in node_group.outputs:
for node_input in node_inputs[input_count:]:
if IS_BLENDER_4:
node_group.interface.remove(node_input)
else:
node_group.inputs.remove(node_input)
for group_output in get_node_outputs(node_group):
if IS_BLENDER_4:
node_group.interface.remove(group_output)
else:
node_group.outputs.remove(group_output) node_group.outputs.remove(group_output)
# Setup the group inputs # Setup the group inputs
@ -93,26 +64,17 @@ def tree(name):
inputs[param.name] = (param.annotation, param.default, None, None) inputs[param.name] = (param.annotation, param.default, None, None)
# Create the input sockets and collect input values. # Create the input sockets and collect input values.
node_inputs = get_node_inputs(node_group) for i, node_input in enumerate(node_group.inputs):
for i, node_input in enumerate(node_inputs):
if node_input.bl_socket_idname != list(inputs.values())[i][0].socket_type: if node_input.bl_socket_idname != list(inputs.values())[i][0].socket_type:
for ni in node_inputs: for ni in node_group.inputs:
if IS_BLENDER_4:
node_group.interface.remove(ni)
else:
node_group.inputs.remove(ni) node_group.inputs.remove(ni)
break break
builder_inputs = {} builder_inputs = {}
node_inputs = get_node_inputs(node_group)
for i, arg in enumerate(inputs.items()): for i, arg in enumerate(inputs.items()):
input_name = arg[0].replace('_', ' ').title() input_name = arg[0].replace('_', ' ').title()
if len(node_inputs) > i: if len(node_group.inputs) > i:
node_inputs[i].name = input_name node_group.inputs[i].name = input_name
node_input = node_inputs[i] node_input = node_group.inputs[i]
else:
if IS_BLENDER_4:
node_input = node_group.interface.new_socket(socket_type=arg[1][0].socket_type, name=input_name, in_out='INPUT')
else: else:
node_input = node_group.inputs.new(arg[1][0].socket_type, input_name) node_input = node_group.inputs.new(arg[1][0].socket_type, input_name)
if arg[1][1] != inspect.Parameter.empty: if arg[1][1] != inspect.Parameter.empty:
@ -136,35 +98,18 @@ def tree(name):
outputs = builder(**builder_inputs) outputs = builder(**builder_inputs)
# Create the output sockets # Create the output sockets
if isinstance(outputs, dict):
# Use a dict to name each return value
for i, (k, v) in enumerate(outputs.items()):
if not issubclass(type(v), Type):
v = Type(value=v)
if IS_BLENDER_4:
node_group.interface.new_socket(socket_type=v.socket_type, name=k, in_out='OUTPUT')
else:
node_group.outputs.new(v.socket_type, k)
node_group.links.new(v._socket, group_output_node.inputs[i])
else:
for i, result in enumerate(_as_iterable(outputs)): for i, result in enumerate(_as_iterable(outputs)):
if not issubclass(type(result), Type): if not issubclass(type(result), Type):
result = Type(value=result) result = Type(value=result)
# raise Exception(f"Return value '{result}' is not a valid 'Type' subclass.") # raise Exception(f"Return value '{result}' is not a valid 'Type' subclass.")
if IS_BLENDER_4:
node_group.interface.new_socket(socket_type=result.socket_type, name='Result', in_out='OUTPUT')
else:
node_group.outputs.new(result.socket_type, 'Result') node_group.outputs.new(result.socket_type, 'Result')
node_group.links.new(result._socket, group_output_node.inputs[i]) link = node_group.links.new(result._socket, group_output_node.inputs[i])
_arrange(node_group) _arrange(node_group)
# Return a function that creates a NodeGroup node in the tree. # Return a function that creates a NodeGroup node in the tree.
# This lets @trees be used in other @trees via simple function calls. # This lets @trees be used in other @trees via simple function calls.
def group_reference(*args, **kwargs): def group_reference(*args, **kwargs):
if IS_BLENDER_4:
result = geometrynodegroup(node_tree=node_group, *args, **kwargs)
else:
result = group(node_tree=node_group, *args, **kwargs) result = group(node_tree=node_group, *args, **kwargs)
group_outputs = [] group_outputs = []
for group_output in result._socket.node.outputs: for group_output in result._socket.node.outputs:

View file

@ -20,15 +20,6 @@ def socket_type_to_data_type(socket_type):
case _: case _:
return socket_type return socket_type
def socket_class_to_data_type(socket_class_name):
match socket_class_name:
case 'NodeSocketGeometry':
return 'GEOMETRY'
case 'NodeSocketFloat':
return 'FLOAT'
case _:
return socket_class_name
# The base class all exposed socket types conform to. # The base class all exposed socket types conform to.
class _TypeMeta(type): class _TypeMeta(type):
def __getitem__(self, args): def __getitem__(self, args):
@ -66,15 +57,10 @@ class Type(metaclass=_TypeMeta):
self.socket_type = type(socket).__name__ self.socket_type = type(socket).__name__
def _math(self, other, operation, reverse=False): def _math(self, other, operation, reverse=False):
if other is None:
vector_or_value = self
else:
vector_or_value = (other, self) if reverse else (self, other)
if self._socket.type == 'VECTOR': if self._socket.type == 'VECTOR':
return geometry_script.vector_math(operation=operation, vector=vector_or_value) return geometry_script.vector_math(operation=operation, vector=(other, self) if reverse else (self, other))
else: else:
return geometry_script.math(operation=operation, value=vector_or_value) return geometry_script.math(operation=operation, value=(other, self) if reverse else (self, other))
def __add__(self, other): def __add__(self, other):
return self._math(other, 'ADD') return self._math(other, 'ADD')
@ -106,36 +92,6 @@ class Type(metaclass=_TypeMeta):
def __rmod__(self, other): def __rmod__(self, other):
return self._math(other, 'MODULO', True) return self._math(other, 'MODULO', True)
def __floordiv__(self, other):
return self._math(other, 'DIVIDE')._math(None,'FLOOR')
def __rfloordiv__(self, other):
return self._math(other, 'DIVIDE',True)._math(None,'FLOOR')
def __pow__(self, other):
return self._math(other, 'POWER')
def __rpow__(self, other):
return self._math(other, 'POWER', True)
def __matmul__(self, other):
return self._math(other, 'DOT_PRODUCT')
def __rmatmul__(self, other):
return self._math(other, 'DOT_PRODUCT', True)
def __abs__(self):
return self._math(None,'ABSOLUTE')
def __neg__(self):
return self._math(-1, 'MULTIPLY')
def __pos__(self):
return self
def __round__(self):
return self._math(None,'ROUND')
def _compare(self, other, operation): def _compare(self, other, operation):
return geometry_script.compare(operation=operation, a=self, b=other) return geometry_script.compare(operation=operation, a=self, b=other)
@ -219,15 +175,13 @@ class Type(metaclass=_TypeMeta):
def capture(self, value, **kwargs): def capture(self, value, **kwargs):
data_type = socket_type_to_data_type(value._socket.type) data_type = socket_type_to_data_type(value._socket.type)
res = self.capture_attribute(data_type=data_type, value=value, **kwargs) geometry, attribute = self.capture_attribute(data_type=data_type, value=value, **kwargs)
return res.geometry, res.attribute return geometry, attribute
def transfer(self, attribute, **kwargs): def transfer(self, attribute, **kwargs):
data_type = socket_type_to_data_type(attribute._socket.type) data_type = socket_type_to_data_type(attribute._socket.type)
return self.transfer_attribute(data_type=data_type, attribute=attribute, **kwargs) return self.transfer_attribute(data_type=data_type, attribute=attribute, **kwargs)
def __getitem__(self, subscript): def __getitem__(self, subscript):
if self._socket.type == 'VECTOR' and isinstance(subscript, int):
return self._get_xyz_component(subscript)
if isinstance(subscript, tuple): if isinstance(subscript, tuple):
accessor = subscript[0] accessor = subscript[0]
args = subscript[1:] args = subscript[1:]

View file

@ -21,10 +21,8 @@
- [Input Groups](./api/advanced-scripting/input-groups.md) - [Input Groups](./api/advanced-scripting/input-groups.md)
- [Attributes](./api/advanced-scripting/attributes.md) - [Attributes](./api/advanced-scripting/attributes.md)
- [Boolean Math](./api/advanced-scripting/boolean-math.md) - [Boolean Math](./api/advanced-scripting/boolean-math.md)
- [Curves](./api/advanced-scripting/curves.md)
- [Drivers](./api/advanced-scripting/drivers.md) - [Drivers](./api/advanced-scripting/drivers.md)
- [Simulation Zones](./api/advanced-scripting/simulation-zones.md) - [Simulation](./api/advanced-scripting/simulation.md)
- [Repeat Zones](./api/advanced-scripting/repeat-zones.md)
# Tutorials # Tutorials

View file

@ -1,32 +0,0 @@
# Curves
Some nodes, such as *Float Curve* take a curve as a property. You can create a curve with the `Curve` class.
```python
float_curve(
mapping=Curve(
Point(0, 0),
Point(0.5, 0.25),
Point(1, 1, HandleType.VECTOR), # Optionally specify a handle type, such as `AUTO`, `VECTOR`, or `AUTO_CLAMPED`.
)
)
```
![](./float_curve.png)
You can also pass the points as a list to `Curve`.
```python
points = [Point(0, 0), Point(1, 1)]
float_curve(
mapping=Curve(points)
)
```
If a node has multiple curve properties, such as the *Vector Curves* node, pass a list of curves to the node.
```python
vector_curves(
mapping=[x_curve, y_curve, z_curve]
)
```

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

View file

@ -1,42 +0,0 @@
# Repeat Zones
Blender 4.0 introduced repeat zones.
Using a *Repeat Input* and *Repeat Output* node, you can loop a block of nodes for a specific number of iterations.
You must use the `@repeat_zone` decorator to create these special linked nodes.
```python
from geometry_script import *
@tree
def test_loop(geometry: Geometry):
@repeat_zone
def doubler(value: Float):
return value * 2
return points(count=doubler(5, 1)) # double the input value 5 times.
```
The function should modify the input values and return them in the same order.
When calling the repeat zone, pass the *Iterations* argument first, then any other arguments the function accepts.
For example:
```python
def doubler(value: Float) -> Float
```
would be called as:
```python
doubler(iteration_count, value)
```
When a repeat zone has multiple arguments, return a tuple from the zone.
```python
@repeat_zone
def multi_doubler(value1: Float, value2: Float):
return (value1 * 2, value2 * 2)
```

View file

@ -1,38 +0,0 @@
# Simulation Zones
Blender 3.6 includes simulation nodes.
Using a *Simulation Input* and *Simulation Output* node, you can create effects that change over time.
As a convenience, the `@simulation_zone` decorator is provided to make simulation node blocks easier to create.
```python
from geometry_script import *
@tree
def test_sim(geometry: Geometry):
@simulation_zone
def my_sim(delta_time, geometry: Geometry, value: Float):
return (geometry, value)
return my_sim(geometry, 0.26).value
```
The first argument should always be `delta_time`. Any other arguments must also be returned as a tuple with their modified values.
Each frame, the result from the previous frame is passed into the zone's inputs.
The initial call to `my_sim` in `test_sim` provides the initial values for the simulation.
## Blender 4.0+
A "Skip" argument was added to the *Simulation Output* node in Blender 4.0.
Return a boolean value first from any simulation zone to determine whether the step should be skipped.
The simplest way to migrate existing node trees is by adding `False` to the return tuple.
```python
@simulation_zone
def my_sim(delta_time, geometry: Geometry, value: Float):
return (False, geometry, value)
```
You can pass any boolean value as the skip output.

View file

@ -0,0 +1,26 @@
# Simulation
> This API is subject to change as future builds of Blender with simulation nodes are released.
The `geometry-nodes-simulation` branch of Blender 3.5 includes support for "simulation nodes".
Using a *Simulation Input* and *Simulation Output* node, you can create effects that change over time.
As a convenience, the `@simulation` decorator is provided to make simulation node blocks easier to create.
```python
@simulation
def move_over_time(
geometry: Geometry, # the first input must be `Geometry`
speed: Float,
dt: SimulationInput.DeltaTime, # Automatically passes the delta time on any argument annotated with `SimulationInput.DeltaTime`.
elapsed: SimulationInput.ElapsedTime, # Automatically passes the elapsed time
) -> Geometry:
return geometry.set_position(
offset=combine_xyz(x=speed)
)
```
Every frame the argument `geometry` will be set to the geometry from the previous frame. This allows the offset to accumulate over time.
The `SimulationInput.DeltaTime`/`SimulationInput.ElapsedTime` types mark arguments that should be given the outputs from the *Simulation Input* node.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

View file

@ -41,19 +41,6 @@ def cube_tree():
![](./cube_tree_int.png) ![](./cube_tree_int.png)
By default, each output is named 'Result'. To customize the name, return a dictionary.
```python
@tree("Cube Tree")
def cube_tree():
return {
"My Cube": cube(),
"Scale Constant": 5
}
```
![](./cube_tree_named_outputs.png)
## Group Input ## Group Input
All arguments in a tree function must be annotated with a valid socket type. These types are provided by Geometry Script, and are not equivalent to Python's built-in types. Let's add a size argument to our Cube Tree. All arguments in a tree function must be annotated with a valid socket type. These types are provided by Geometry Script, and are not equivalent to Python's built-in types. Let's add a size argument to our Cube Tree.

View file

@ -1,26 +1,9 @@
from geometry_script import * from geometry_script import *
@tree("Repeat Grid") @tree("Repeat Grid")
def repeat_grid( def repeat_grid(geometry: Geometry, width: Int, height: Int):
geometry: Geometry,
columns: Int,
rows: Int,
spacing_x: Float = 0.0,
spacing_y: Float = 0.0
):
# measure your geometry’s bounds
bbox = geometry.bounding_box()
span_x = bbox.max.x - bbox.min.x
span_y = bbox.max.y - bbox.min.y
# total grid size = N * object size
total_x = columns * span_x + (columns - 1) * spacing_x
total_y = rows * span_y + (rows - 1) * spacing_y
# one extra vertex gives N cells
g = grid( g = grid(
size_x=total_x, size_y=total_y, size_x=width, size_y=height,
vertices_x=columns + 1, vertices_y=rows + 1 vertices_x=width, vertices_y=height
).mesh.mesh_to_points() ).mesh_to_points()
return g.instance_on_points(instance=geometry) return g.instance_on_points(instance=geometry)

View file

@ -25,4 +25,4 @@ class GeometryScriptPreferences(bpy.types.AddonPreferences):
vscode.label(text=f"2. Search for 'Preferences: Open Settings (UI)'") vscode.label(text=f"2. Search for 'Preferences: Open Settings (UI)'")
vscode.label(text=f"3. Search for 'Python > Analysis: Extra Paths") vscode.label(text=f"3. Search for 'Python > Analysis: Extra Paths")
vscode.label(text=f"4. Click 'Add Item'") vscode.label(text=f"4. Click 'Add Item'")
vscode.label(text=f"5. Paste the typeshed path from above") vscode.label(text=f"5. Pase the typeshed path from above")