Compare commits

..
Author SHA1 Message Date
Arrel
24d9930ce0 Enhance repeat_grid function: add spacing parameters for customizable grid spacing 2025-07-07 10:32:49 -04:00
Arrel
08c3cd5d67 Fix Repeat Grid example: improve parameter naming, add proper spacing calculation
- Rename parameters from width/height to columns/rows for clarity
- Implement proper bounding box calculation for geometry spacing
- Fix grid vertex calculation (use N+1 vertices for N cells)
- Add explanatory comments for grid sizing logic
- Fix method chaining for mesh_to_points
2025-07-07 10:32:49 -04:00
Preetham Pemmasani
96a1b293cc fix a spelling mistake
pase -> paste
2024-10-27 07:20:11 -04:00
Alfredo
6952ec507a replace dictionary used to count node input links with collections.Counter 2023-11-17 13:49:19 -05:00
Alfredo
e380e6f9db precalculate number of links to node input sockets to avoid using the 'links' property 2023-11-17 13:49:19 -05:00
Alfredo
f0d43fb92d disambiguate duplicate variable name 'node' within inner loop for readability 2023-11-17 13:49:19 -05:00
Alfredo
5cf07a1af5 rewrite topological sort, avoiding calls to the expensive 'links' property of the NodeSocket class 2023-11-17 13:49:19 -05:00
Carson Katri
8a1b4c4321 Add check for nested trees 2023-11-17 13:45:46 -05:00
Carson Katri
6c25f12729 Support Blender 3.x alongside 4.x 2023-11-17 13:45:46 -05:00
Carson Katri
56d61980ad Allow passing domain to store 2023-11-17 13:45:46 -05:00
Carson Katri
da99654edb Add repeat zone support 2023-11-15 12:55:31 -05:00
Alfredo
e3befbefc9 Migrate to NodeTree.interface API for Blender 4.0 release 2023-11-11 14:09:37 -05:00
Carson Katri
63a7516905 Refactor simulation API to use simulation_zone decorator 2023-11-11 14:04:40 -05:00
Carson Katri
467ae71ec6 Add curve support 2023-11-11 14:04:20 -05:00
Alfredo
1ffed55184 support more math dunder methods 2023-10-08 10:58:29 -04:00
Adam P
f42e0ba456 Fix some cases of node name collisions
Some compositor and texture nodes share names with the geometry nodes versions. This change sorts them so that the geometry ones are registered last, overriding the incorrect ones. The Math node is handled separately, because here the ShaderNodeMath is the correct one to use, for some reason.
2023-04-21 16:56:05 -04:00
Carson Katri
258a7c51c6 Update for Blender 3.5 release 2023-04-01 16:33:48 -04:00
Carson Katri
5fbc7d1ba0
Merge pull request #4 from carson-katri/named-outputs
Support Named Outputs
2023-02-12 11:45:21 -05:00
Carson Katri
bfe5aae3cd Fix capture 2023-02-12 11:11:03 -05:00
Carson Katri
87793fe8d1 Use isinstance for Named Attribute 2023-02-12 11:08:20 -05:00
Carson Katri
34c1eb50c8 Fix actions 2022-12-09 16:03:40 -05:00
Carson Katri
775f8fa466 Add deploy preview step 2022-12-09 16:02:30 -05:00
Carson Katri
840701d916 Document named outputs syntax 2022-12-09 15:55:32 -05:00
Carson Katri
16a11e91af Handle dict output 2022-12-09 15:51:38 -05:00
20 changed files with 512 additions and 149 deletions

View file

@ -6,6 +6,8 @@ on:
- main
pull_request:
concurrency: preview-${{ github.ref }}
jobs:
deploy:
runs-on: ubuntu-20.04
@ -28,3 +30,9 @@ jobs:
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
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(
size_x=width, size_y=height,
vertices_x=width, vertices_y=height
).mesh_to_points()
).mesh.mesh_to_points()
return g.instance_on_points(instance=geometry)
```

View file

@ -1,34 +1,42 @@
import bpy
import typing
from collections import deque, Counter
def _arrange(node_tree, padding: typing.Tuple[float, float] = (50, 25)):
# Organize the nodes into columns based on their links.
columns: typing.List[typing.List[typing.Any]] = []
def contains_link(node, column):
return any(
any(
any(link.from_node == node for link in input.links)
for input in n.inputs
)
for n in column
)
for node in reversed(node_tree.nodes):
if (x := next(
filter(
lambda x: contains_link(node, x[1]),
enumerate(columns)
),
None
)) is not None:
if x[0] > 0:
columns[x[0] - 1].append(node)
else:
columns.insert(x[0], [node])
def topo_sort(graph):
in_degree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
in_degree[v] += 1
queue = deque([u for u in in_degree if in_degree[u] == 0])
topo_order = []
while queue:
u = queue.popleft()
topo_order.append(u)
for v in graph[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
queue.append(v)
return topo_order
graph = { node:set() for node in node_tree.nodes }
node_input_link_count = Counter()
for link in node_tree.links:
graph[link.from_node].add(link.to_node)
node_input_link_count[link.to_socket] += 1
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])
else:
if len(columns) == 0:
columns.append([node])
else:
columns[len(columns) - 1].append(node)
columns[column_index[node]].append(node)
columns = reversed(columns)
# 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
@ -46,7 +54,7 @@ def _arrange(node_tree, padding: typing.Tuple[float, float] = (50, 25)):
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]
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 len(i.links) == 0, node.inputs)))
unset_vector_count = len(list(filter(lambda i: i.enabled and i.type == 'VECTOR' and node_input_link_count[i] == 0, node.inputs)))
node_height = (
NODE_HEADER_HEIGHT \
+ (output_count * NODE_LINK_HEIGHT) \

View file

@ -1,11 +1,12 @@
import bpy
import bl_ui
import itertools
import enum
import re
import os
from .state import State
from .types import *
from .static.input_group import InputGroup
from .static.curve import Curve
from ..absolute_path import absolute_path
class OutputsList(dict):
@ -13,6 +14,21 @@ class OutputsList(dict):
__setattr__ = dict.__setitem__
__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(_primary_arg=None, **kwargs):
for k, v in kwargs.copy().items():
@ -28,6 +44,13 @@ def build_node(node_type):
argname = prop.identifier.lower().replace(' ', '_')
if argname in kwargs:
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):
value = value.value
setattr(node, prop.identifier, value)
@ -40,20 +63,6 @@ def build_node(node_type):
if node_input2.name.lower().replace(' ', '_') == argname and node_input2.type == node_input.type:
all_with_name.append(node_input2)
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]
if isinstance(value, enum.Enum):
value = value.value
@ -105,35 +114,18 @@ 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 })
setattr(globals()[node_namespace_name], enum_type_name, enum_type)
registered_nodes.add(node_type)
for category_name in list(filter(lambda x: x.startswith('NODE_MT_category_GEO_'), dir(bpy.types))):
category = getattr(bpy.types, category_name)
if not hasattr(category, 'category'):
category_path = category.bl_label.lower().replace(' ', '_')
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))):
denylist = {'filter'} # some nodes should be excluded.
class_denylist = {'CompositorNodeMath', 'TextureNodeMath'}
node_types_to_register = []
for node_type_name in dir(bpy.types):
node_type = getattr(bpy.types, node_type_name)
if issubclass(node_type, bpy.types.GeometryNode):
register_node(node_type)
if isinstance(node_type, type) and issubclass(node_type, bpy.types.Node):
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)
def create_documentation():
temp_node_group = bpy.data.node_groups.new('temp_node_group', 'GeometryNodeTree')
@ -155,6 +147,7 @@ def create_documentation():
docstrings = []
symbols = []
enums = {}
skipped_nodes = []
for func in sorted(documentation.keys()):
try:
method = documentation[func]
@ -261,12 +254,8 @@ def create_documentation():
{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"
symbols.append(f"""def {func}({', '.join(symbol_args)}) -> {return_type_hint}: \"\"\"![]({image}.webp)\"\"\"""")
except Exception as e:
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)
except:
skipped_nodes.append(documentation[func].bl_node_type.__name__)
continue
bpy.data.node_groups.remove(temp_node_group)
html = f"""
@ -362,6 +351,9 @@ class Type:
fpyi.write(contents)
fpy.write(contents)
if len(skipped_nodes) > 0:
pass # This could be reported later.
def create_docs():
create_documentation()
bpy.app.timers.register(create_docs)
bpy.app.timers.register(create_docs)

View file

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

54
api/static/curve.py Normal file
View file

@ -0,0 +1,54 @@
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

51
api/static/repeat.py Normal file
View file

@ -0,0 +1,51 @@
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,25 +1,48 @@
import bpy
import inspect
import typing
class SimulationInput:
class DeltaTime: pass
class ElapsedTime: pass
def simulation(block: typing.Callable[typing.Any, 'Geometry']):
def simulation_zone(block: typing.Callable):
"""
Create a simulation input/output block.
> Only available in the `geometry-node-simulation` branch of Blender 3.5.
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 Blender 3.6+.
"""
def wrapped(geometry: 'Geometry', *args, **kwargs):
from geometry_script import simulation_input, simulation_output
simulation_in = simulation_input(geometry=geometry)
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)
for key, value in signature.parameters.items():
match value.annotation:
case SimulationInput.DeltaTime:
kwargs[key] = simulation_in.delta_time
case SimulationInput.ElapsedTime:
kwargs[key] = simulation_in.elapsed_time
return simulation_output(geometry=block(simulation_in.geometry, *args, **kwargs)).geometry
# setup zone
simulation_in = State.current_node_tree.nodes.new(bpy.types.GeometryNodeSimulationInput.__name__)
simulation_out = State.current_node_tree.nodes.new(bpy.types.GeometryNodeSimulationOutput.__name__)
simulation_in.pair_with_output(simulation_out)
# clear state items
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

View file

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

View file

@ -20,6 +20,15 @@ def socket_type_to_data_type(socket_type):
case _:
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.
class _TypeMeta(type):
def __getitem__(self, args):
@ -57,10 +66,15 @@ class Type(metaclass=_TypeMeta):
self.socket_type = type(socket).__name__
def _math(self, other, operation, reverse=False):
if self._socket.type == 'VECTOR':
return geometry_script.vector_math(operation=operation, vector=(other, self) if reverse else (self, other))
if other is None:
vector_or_value = self
else:
return geometry_script.math(operation=operation, value=(other, self) if reverse else (self, other))
vector_or_value = (other, self) if reverse else (self, other)
if self._socket.type == 'VECTOR':
return geometry_script.vector_math(operation=operation, vector=vector_or_value)
else:
return geometry_script.math(operation=operation, value=vector_or_value)
def __add__(self, other):
return self._math(other, 'ADD')
@ -92,6 +106,36 @@ class Type(metaclass=_TypeMeta):
def __rmod__(self, other):
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):
return geometry_script.compare(operation=operation, a=self, b=other)
@ -175,13 +219,15 @@ class Type(metaclass=_TypeMeta):
def capture(self, value, **kwargs):
data_type = socket_type_to_data_type(value._socket.type)
geometry, attribute = self.capture_attribute(data_type=data_type, value=value, **kwargs)
return geometry, attribute
res = self.capture_attribute(data_type=data_type, value=value, **kwargs)
return res.geometry, res.attribute
def transfer(self, attribute, **kwargs):
data_type = socket_type_to_data_type(attribute._socket.type)
return self.transfer_attribute(data_type=data_type, attribute=attribute, **kwargs)
def __getitem__(self, subscript):
if self._socket.type == 'VECTOR' and isinstance(subscript, int):
return self._get_xyz_component(subscript)
if isinstance(subscript, tuple):
accessor = subscript[0]
args = subscript[1:]

View file

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

View file

@ -0,0 +1,32 @@
# 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.

After

Width:  |  Height:  |  Size: 36 KiB

View file

@ -0,0 +1,42 @@
# 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

@ -0,0 +1,38 @@
# 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

@ -1,26 +0,0 @@
# 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.

After

Width:  |  Height:  |  Size: 108 KiB

View file

@ -41,6 +41,19 @@ def cube_tree():
![](./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
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,9 +1,26 @@
from geometry_script import *
@tree("Repeat Grid")
def repeat_grid(geometry: Geometry, width: Int, height: Int):
def repeat_grid(
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(
size_x=width, size_y=height,
vertices_x=width, vertices_y=height
).mesh_to_points()
size_x=total_x, size_y=total_y,
vertices_x=columns + 1, vertices_y=rows + 1
).mesh.mesh_to_points()
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"3. Search for 'Python > Analysis: Extra Paths")
vscode.label(text=f"4. Click 'Add Item'")
vscode.label(text=f"5. Pase the typeshed path from above")
vscode.label(text=f"5. Paste the typeshed path from above")