-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
323 lines (255 loc) · 9.24 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
from __future__ import annotations
import ast
import traceback
import bpy
from bpy.types import Context, Event
from .constants import SHADER_MATH_CALLS, Function, PrintRepresent
from .node_composers import (
ComposeCompositorMathNodes,
ComposeGeometryMathNodes,
ComposeNodes,
ComposeShaderMathNodes,
ComposeTextureMathNodes,
)
from .operations import (
CompositorSimpleMathOperation,
Operation,
ShaderMathOperation,
TextureSimpleMathOperation,
Tree,
)
from .rustlike_result import Err, Ok, Result
InputSocketType = [
("VALUE", "Value", "Use values to connect variables."),
("REROUTE", "Reroute", "Use reroute nodes to connect variables."),
("GROUP", "Group", "Create a group for the generated nodes."),
]
VariableSortMode = [
("NONE", "None", "Variables are sorted pseudorandomly"),
("ALPHABET", "Alphabet", "Variables are sorted alphabetically"),
(
"INSERTION",
"Insertion",
"Variables are sorted based on when they were added in the chain",
),
]
NodeType = [
("MATH", "Math", "Use basic math nodes."),
("VECTOR", "Vector", "Use vector nodes."),
]
class ComposeNodeTree(bpy.types.Operator):
bl_idname = "node.compose_qm_nodes"
bl_label = "Node Quick Maths: Compose nodes"
show_available_functions: bpy.props.BoolProperty(
name="Show available functions",
default=False,
)
hide_nodes: bpy.props.BoolProperty(
name="Hide nodes",
description="Hides nodes to preserve grid space",
)
center_nodes: bpy.props.BoolProperty(
name="Center nodes",
description="Centers the generated nodes. This is a personal preference",
)
editor_type: bpy.props.StringProperty(name="Editor Type")
expression: bpy.props.StringProperty(description="The source expression for the nodes")
input_socket_type: bpy.props.EnumProperty(items=InputSocketType, default="REROUTE")
generate_previews: bool
var_sort_mode: str
def invoke(self, context: Context, event: Event) -> set[str]:
wm = context.window_manager
ui_mode = context.area.ui_type
self.editor_type = ui_mode
if context.preferences.addons[__package__].preferences.debug_prints:
print(f"NQM: Editor type: {self.editor_type}")
self.generate_previews = context.preferences.addons[__package__].preferences.generate_previews
self.var_sort_mode = context.preferences.addons[__package__].preferences.sort_vars
return wm.invoke_props_dialog(self, confirm_text="Create", width=600)
def current_operation_type(
self,
) -> (
tuple[
type[Operation],
type[ComposeNodes],
dict[str, dict[str, Function | PrintRepresent]],
]
| None
):
if self.editor_type == "ShaderNodeTree":
return (
ShaderMathOperation,
ComposeShaderMathNodes,
SHADER_MATH_CALLS,
)
if self.editor_type == "GeometryNodeTree":
return (
ShaderMathOperation,
ComposeGeometryMathNodes,
SHADER_MATH_CALLS,
)
if self.editor_type == "CompositorNodeTree":
return (
CompositorSimpleMathOperation,
ComposeCompositorMathNodes,
SHADER_MATH_CALLS,
)
if self.editor_type == "TextureNodeTree":
return (
TextureSimpleMathOperation,
ComposeTextureMathNodes,
SHADER_MATH_CALLS,
)
return None
def generate_tree(self, expression: str) -> Result[tuple[ast.Expr, Tree], str]:
op_type = self.current_operation_type()
if op_type is None:
return Err("No known operation type available")
op, _, _ = op_type
try:
mod = ast.parse(expression.strip(), mode="exec")
r = op.validate(mod)
if r.is_err():
return Err(r.unwrap_err())
expr: ast.Expr = mod.body[0]
except SyntaxError as e:
traceback.print_exc()
print(e)
return Err("Could not parse expression")
try:
parsed = op.parse(expr)
except Exception as e:
traceback.print_exc()
return Err(str(e))
if not isinstance(parsed, Operation):
return Err("Parsed expression is not an Operation")
return Ok((expr, parsed.to_tree(sort_mode=self.var_sort_mode)))
def execute(self, context: Context):
# Create nodes from tree
bpy.ops.node.select_all(action="DESELECT")
tree = self.generate_tree(self.expression)
o = self.current_operation_type()
if tree.is_err() or o is None:
return {"CANCELLED"}
expr, tree = tree.unwrap()
_, composer_class, _ = o
composer = composer_class(
socket_type=self.input_socket_type,
center_nodes=self.center_nodes,
hide_nodes=self.hide_nodes,
)
return composer.run(expr, tree, context)
def draw(self, context: Context):
layout = self.layout
o = self.current_operation_type()
if o is None:
layout.label(text="This node editor is currently not supported!")
return
_, comp, calls = o
layout.prop(self, "expression")
options_box = layout.box()
options = options_box.column(align=True)
options.row().prop(self, "input_socket_type", expand=True)
options = options.row()
col1 = options.column(align=True)
col1.prop(self, "hide_nodes")
col1.prop(
self,
"center_nodes",
)
col2 = options.column(align=True)
col2.prop(self, "show_available_functions")
if self.show_available_functions:
functions_box = layout.column()
functions_box.label(text="Available functions:")
functions_box.separator()
b = functions_box.box()
row = b.row()
for category, funcs in calls.items():
func_row = row.column(heading=category)
func_row.label(text=category)
for name, func in funcs.items():
text = name + str(func) if isinstance(func, Function) else func
func_row.label(text=text, translate=False)
txt = self.expression
if txt:
r = self.generate_tree(txt)
if r.is_err(): # print the error
msg = r.unwrap_err()
if context.preferences.addons[__package__].preferences.debug_prints:
print(msg)
b = layout.box()
err_col = b.column()
err_col.label(text="Error:")
for line in msg.splitlines():
err_col.label(text=line, translate=False)
elif self.generate_previews: # create a representation of the node tree under the settings
preview_box = layout.box()
composer = comp(
socket_type=self.input_socket_type,
center_nodes=self.center_nodes,
hide_nodes=self.hide_nodes,
)
composer.preview_generate(r.unwrap()[1].root, preview_box.row())
class Preferences(bpy.types.AddonPreferences):
bl_idname = __package__
debug_prints: bpy.props.BoolProperty(
name="Debug Print",
description="Enables debug prints in the terminal",
default=False,
)
generate_previews: bpy.props.BoolProperty(
name="Generate Previews",
description="Generates previews of node trees before creating them",
default=True,
)
sort_vars: bpy.props.EnumProperty(
items=VariableSortMode,
name="Sort variables",
description="The order which to sort variables",
default="INSERTION",
)
def draw(self, context):
layout = self.layout
row = layout.column(align=True)
row.label(text="Check the Keymaps settings to edit activation. Default is Ctrl + M")
row.prop(self, "debug_prints")
row.prop(self, "generate_previews")
r = row.row()
r.label(text="Sort variables by...")
r.prop(self, "sort_vars", expand=True)
addon_keymaps = []
def registerKeymaps():
wm = bpy.context.window_manager
if wm.keyconfigs.addon:
km = wm.keyconfigs.addon.keymaps.get("Node Editor")
if not km:
km = wm.keyconfigs.addon.keymaps.new(name="Node Editor", space_type="NODE_EDITOR")
kmi = km.keymap_items.new(
"node.compose_qm_nodes",
"M",
"PRESS",
ctrl=True,
)
addon_keymaps.append((km, kmi))
def unregisterKeymaps():
for km, kmi in addon_keymaps:
km.keymap_items.remove(kmi)
addon_keymaps.clear()
classes = (
ComposeNodeTree,
Preferences,
)
def register():
from bpy.utils import register_class
for cls in classes:
register_class(cls)
registerKeymaps()
def unregister():
unregisterKeymaps()
from bpy.utils import unregister_class
for cls in reversed(classes):
unregister_class(cls)
registerKeymaps()
if __name__ == "__main__":
register()