forked from nortikin/sverchok
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_tree.py
573 lines (479 loc) · 22.9 KB
/
node_tree.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# This file is part of project Sverchok. It's copyrighted by the contributors
# recorded in the version control history of the file, available from
# its original location https://github.com/nortikin/sverchok/commit/master
#
# SPDX-License-Identifier: GPL3
# License-Filename: LICENSE
import inspect
import time
from contextlib import contextmanager
from itertools import chain, cycle
import bpy
from bpy.props import StringProperty, BoolProperty, EnumProperty
from bpy.types import NodeTree
from sverchok.core.socket_data import SvNoDataError
from sverchok.core.events import TreeEvent
from sverchok.core.main_tree_handler import TreeHandler
from sverchok.core.group_handlers import NodeIdManager
from sverchok.data_structure import classproperty, post_load_call
from sverchok.utils import get_node_class_reference
from sverchok.utils.sv_node_utils import recursive_framed_location_finder
from sverchok.utils.docstring import SvDocstring
import sverchok.utils.logging
from sverchok.utils.logging import debug, catch_log_error
from sverchok.ui import color_def
from sverchok.ui.nodes_replacement import set_inputs_mapping, set_outputs_mapping
from sverchok.ui import bgl_callback_nodeview as sv_bgl
from sverchok.utils.handle_blender_data import BlTree
class SvNodeTreeCommon:
"""Common class for all Sverchok trees (regular trees and group ones)"""
tree_id_memory: StringProperty(default="") # identifier of the tree, should be used via `tree_id` property
@property
def tree_id(self):
"""Identifier of the tree"""
if not self.tree_id_memory:
self.tree_id_memory = str(hash(self) ^ hash(time.monotonic()))
return self.tree_id_memory
def update_gl_scale_info(self, origin=None):
"""
the nodeview scale and dpi differs between users and must be queried to get correct nodeview
x,y and dpi scale info.
this is instead of calling `get_dpi_factor` on every redraw.
"""
debug(f"update_gl_scale_info called from {origin or self.name}")
try:
from sverchok.utils.context_managers import sv_preferences
with sv_preferences() as prefs:
prefs.set_nodeview_render_params(None)
except Exception as err:
debug('failed to get gl scale info', err)
@contextmanager
def init_tree(self):
"""It suppresses calling the update method of nodes,
main usage of it is during generating tree with python (JSON import)"""
is_already_initializing = 'init_tree' in self
if is_already_initializing:
yield self
else:
self['init_tree'] = ''
try:
yield self
finally:
del self['init_tree']
class SverchCustomTree(NodeTree, SvNodeTreeCommon):
''' Sverchok - architectural node programming of geometry in low level '''
bl_idname = 'SverchCustomTreeType'
bl_label = 'Sverchok Nodes'
bl_icon = 'RNA'
def turn_off_ng(self, context):
"""
Turn on/off displaying objects in viewport generated by viewer nodes
Viewer nodes should have `show_viewport` method which takes 'to_show' bool argument
"""
for node in self.nodes:
try:
node.show_viewport(self.sv_show)
except AttributeError:
pass
def on_draft_mode_changed(self, context):
"""
This is triggered when Draft mode of the tree is toggled.
"""
draft_nodes = []
for node in self.nodes:
if hasattr(node, 'does_support_draft_mode') and node.does_support_draft_mode():
draft_nodes.append(node)
node.on_draft_mode_changed(self.sv_draft)
# From the user perspective, some of node parameters
# got new parameter values, so the setup should be recalculated;
# but techically, node properties were not changed
# (only other properties were shown in UI), so enabling/disabling
# of draft mode does not automatically trigger tree update.
# Here we trigger it manually.
if draft_nodes:
self.update_nodes(draft_nodes)
sv_process: BoolProperty(
name="Process",
default=True,
description='Update upon tree and node property changes',
update=lambda s, c: TreeHandler.send(TreeEvent(TreeEvent.TREE_UPDATE, s)),
options=set(),
)
sv_animate: BoolProperty(name="Animate", default=True, description='Animate this layout', options=set())
sv_show: BoolProperty(name="Show", default=True, description='Show this layout', update=turn_off_ng, options=set())
sv_show_time_graph: BoolProperty(name="Time Graph", default=False, options=set()) # todo is not used now
sv_show_time_nodes: BoolProperty(name="Node times", default=False, options=set(), update=lambda s, c: s.update_ui())
show_time_mode: EnumProperty(
items=[(n, n, '') for n in ["Per node", "Cumulative"]],
options=set(),
update=lambda s, c: s.update_ui(),
description="Mode of showing node update timings",
)
sv_show_socket_menus: BoolProperty(
name = "Show socket menus",
description = "Display socket dropdown menu buttons. NOTE: options that are enabled in those menus will be effective regardless of this checkbox!",
default = False,
options=set())
# draft mode replaces selected properties of certain nodes with smaller values to lighten cpu load.
sv_draft: BoolProperty(
name="Draft",
description="Draft (simplified processing) mode",
default=False,
update=on_draft_mode_changed,
options=set(),
)
def update(self):
"""This method is called if collection of nodes or links of the tree was changed"""
TreeHandler.send(TreeEvent(TreeEvent.TREE_UPDATE, self))
def force_update(self):
"""Update whole tree from scratch"""
# ideally we would never like to use this method but we live in the real world
TreeHandler.send(TreeEvent(TreeEvent.FORCE_UPDATE, self))
def update_nodes(self, nodes, cancel=True):
"""This method expects to get list of its nodes which should be updated"""
return TreeHandler.send(TreeEvent(TreeEvent.NODES_UPDATE, self, nodes, cancel))
def process_ani(self):
"""
Process the Sverchok node tree if animation layers show true.
For animation callback/handler
"""
if self.sv_animate:
animated_nodes = (n for n in self.nodes if hasattr(n, 'is_animatable') and n.is_animatable)
TreeHandler.send(TreeEvent(TreeEvent.FRAME_CHANGE, self, animated_nodes))
def update_ui(self):
""" The method get information about node statistic of last update from the handler to show in view space
The method is usually called by main handler to reevaluate view of the nodes in the tree
even if the tree is not in the Live update mode"""
nodes_errors = TreeHandler.get_error_nodes(self)
if self.sv_show_time_nodes:
update_time = (TreeHandler.get_cum_time(self) if self.show_time_mode == "Cumulative"
else TreeHandler.get_update_time(self))
else:
update_time = cycle([None])
for node, error, update in zip(self.nodes, nodes_errors, update_time):
if hasattr(node, 'update_ui'):
node.update_ui(error, update)
class UpdateNodes:
"""Everything related with update system of nodes"""
# identifier of the node, should be used via `node_id` property
# overriding the property without `skip_save` option can lead to wrong importing bgl viewer nodes
n_id: StringProperty(options={'SKIP_SAVE'})
@property
def node_id(self):
"""Identifier of the node"""
if not self.n_id:
self.n_id = str(hash(self) ^ hash(time.monotonic()))
return self.n_id
def sv_init(self, context):
"""
This method will be called during node creation
Typically it is used for socket creating and assigning properties to sockets
"""
pass
def sv_update(self):
"""
This method can be overridden in inherited classes.
It will be triggered upon any `node tree` editor changes (new/copy/delete links/nodes).
Calling of this method is unordered among other calls of the method of other nodes in a tree.
"""
pass
def sv_copy(self, original):
"""
Override this method to do anything node-specific
at the moment of node being copied.
"""
pass
def sv_free(self):
"""
Override this method to do anything node-specific upon node removal
"""
pass
def init(self, context):
"""
this function is triggered upon node creation,
- delegates further initialization information to sv_init
"""
if self.sv_default_color:
self.use_custom_color = True
self.color = self.sv_default_color
with catch_log_error():
self.sv_init(context)
def sv_new_input(self, socket_type, name, **attrib_dict):
socket = self.inputs.new(socket_type, name)
for att in attrib_dict:
setattr(socket, att, attrib_dict[att])
return socket
def free(self):
"""Called upon the node removal"""
self.sv_free()
for s in self.outputs:
s.sv_forget()
# This is inevitable evil cause of flexible nature of node_ids inside group trees
node_id = NodeIdManager.extract_node_id(self) if BlTree(self.id_data).is_group_tree else self.node_id
self.update_ui(node_id=node_id)
def copy(self, original):
"""Called upon the node being copied"""
self.n_id = ""
self.sv_copy(original)
def update(self):
"""
The method will be triggered upon editor changes, typically before node tree update method.
It is better to avoid using this trigger.
"""
if 'init_tree' in self.id_data: # tree is building by a script - let it do this
return
self.sv_update()
def update_ui(self, error=None, update_time=None, node_id=None):
"""updating tree contextual information -> node colors, text
node_id only for usage of a group tree"""
sv_settings = bpy.context.preferences.addons[sverchok.__name__].preferences
exception_color = sv_settings.exception_color
no_data_color = sv_settings.no_data_color
error_pref = "error"
update_pref = "update_time"
node_id = node_id or self.node_id # inevitable evil
# update error colors
if error is not None:
color = no_data_color if isinstance(error, SvNoDataError) else exception_color
self.set_temp_color(color)
sv_bgl.draw_text(self, repr(error), error_pref + node_id, color, 1.3, "UP")
else:
sv_bgl.callback_disable(error_pref + node_id)
self.set_temp_color()
# show update timing
if update_time is not None:
update_time = int(update_time * 1000)
sv_bgl.draw_text(self, f'{update_time}ms', update_pref + node_id, align="UP", dynamic_location=False)
else:
sv_bgl.callback_disable(update_pref + node_id)
# update object numbers
for s in chain(self.inputs, self.outputs):
if hasattr(s, 'update_objects_number'):
s.update_objects_number()
def insert_link(self, link):
"""It will be triggered only if one socket is connected with another by user"""
def process_node(self, context):
"""Call this method to revaluate the node tree whenever node properties was changed"""
self.id_data.update_nodes([self])
class NodeUtils:
"""
Helper methods.
Most of them have nothing related with nodes and using as aliases of some functionality.
The class can be surely ignored during creating of new nodes.
"""
def get_logger(self):
if hasattr(self, "draw_label"):
name = self.draw_label()
else:
name = self.label
if not name:
name = self.bl_label
if not name:
name = self.__class__.__name__
# add information about the module location
frame, _, line, *_ = inspect.stack()[2]
module = inspect.getmodule(frame)
module_name = module.__name__ if module is not None else ''
name = f'{module_name} {line} ({name})'
return sverchok.utils.logging.getLogger(name)
def debug(self, msg, *args, **kwargs):
self.get_logger().debug(msg, *args, **kwargs)
def info(self, msg, *args, **kwargs):
self.get_logger().info(msg, *args, **kwargs)
def warning(self, msg, *args, **kwargs):
self.get_logger().warning(msg, *args, **kwargs)
def error(self, msg, *args, **kwargs):
self.get_logger().error(msg, *args, **kwargs)
def exception(self, msg, *args, **kwargs):
self.get_logger().exception(msg, *args, **kwargs)
def wrapper_tracked_ui_draw_op(self, layout_element, operator_idname, **keywords):
"""
this wrapper allows you to track the origin of a clicked operator, by automatically passing
the node_name and tree_name to the operator.
example usage:
row.separator()
self.wrapper_tracked_ui_draw_op(row, "node.view3d_align_from", icon='CURSOR', text='')
"""
op = layout_element.operator(operator_idname, **keywords)
op.node_name = self.name
op.tree_name = self.id_data.name
return op
def get_bpy_data_from_name(self, identifier, bpy_data_kind): # todo, method which have nothing related with nodes
"""
fail gracefully?
This function acknowledges that the identifier being passed can be a string or an object proper.
for a long time Sverchok stored the result of a prop_search as a StringProperty, and many nodes will
be stored with that data in .blends, here we try to permit older blends having data stored as a string,
but newly used prop_search results will be stored as a pointerproperty of type bpy.types.Object
regarding the need to trim the first 3 chars of a stored StringProperty, best let Blender devs enlighten you
https://developer.blender.org/T58641
example usage inside a node:
text = self.get_bpy_data_from_name(self.filename, bpy.data.texts)
if the text does not exist you get None
"""
if not identifier:
# this can happen if a json import goes through attributes arbitrarily.
# self.info("no identifier passed to the get_bpy_data_from_name function.")
return None
try:
if isinstance(identifier, bpy.types.Object) and identifier.name in bpy_data_kind:
return bpy_data_kind.get(identifier.name) # todo it looks ridiculous to search known object
elif isinstance(identifier, str):
if identifier in bpy_data_kind:
return bpy_data_kind.get(identifier)
elif identifier[3:] in bpy_data_kind:
return bpy_data_kind.get(identifier[3:])
# something went wrong. the blend does not contain the objectname
self.info(f"{identifier} not found in {bpy_data_kind}, returning None instead")
if bpy_data_kind.bl_rna.identifier == 'BlendDataTexts':
# if we are in texts and this key is not found:
# - it's possible the named datablock incurred name collision
# - or it has not yet been created (usually json import, attribute order issue)
file_names = {t.name for t in bpy_data_kind}
self.info(f"The currently loaded blend file does contain the following text files {file_names}")
except Exception as err:
self.error(f"identifier '{identifier}' not found in {bpy_data_kind} - with error {err}")
return None
def safe_socket_remove(self, kind, key, failure_message=None):
sockets = getattr(self, kind)
if key in sockets:
sockets.remove(sockets[key])
else:
canned_msg = f"{self.name}.{kind} has no socket named {key} - did not remove"
self.debug(failure_message or canned_msg)
class SverchCustomTreeNode(UpdateNodes, NodeUtils):
"""Base class for all nodes"""
_docstring = None # A cache for docstring property
@classproperty
def docstring(cls):
"""
Get SvDocstring instance parsed from node's docstring.
"""
if cls._docstring is None:
cls._docstring = SvDocstring(cls.__doc__)
return cls._docstring
@classmethod
def poll(cls, ntree):
return ntree.bl_idname in ['SverchCustomTreeType', 'SvGroupTree']
@property
def absolute_location(self):
"""
When a node is inside a frame (and parented to it) then node.location is relative to its parent's location.
This function returns the location in absolute screen terms whether the node is framed or not.
The return type is a tuple (x, y) (not a Vector)
"""
return recursive_framed_location_finder(self, self.location[:])
@property
def sv_default_color(self):
return color_def.get_color(self.bl_idname)
def set_temp_color(self, color=None):
"""This method memorize its initial color and override it with given one
if given color is None it tries to return its initial color or do nothing"""
if color is None:
# looks like the node should return its initial color (user choice)
if 'user_color' in self:
self.use_custom_color = self['use_user_color']
del self['use_user_color']
self.color = self['user_color']
del self['user_color']
# set temporary color
else:
# save overridden color (only once)
if 'user_color' not in self:
self['use_user_color'] = self.use_custom_color
self['user_color'] = self.color
self.use_custom_color = True
self.color = color
def rclick_menu(self, context, layout):
"""
Override this method to add specific items into the node's right-click menu.
Default implementation calls `node_replacement_menu'.
"""
self.node_replacement_menu(context, layout)
# Replacing old nodes by new - functionality
def node_replacement_menu(self, context, layout):
"""
Draw menu items with node replacement operators.
This is called from `rclick_menu()' method by default.
Items are defined by `replacement_nodes' class property.
Expected format is
replacement_nodes = [
(new_node_bl_idname, inputs_mapping_dict, outputs_mapping_dict)
]
where new_node_bl_idname is bl_idname of replacement node class,
inputs_mapping_dict is a dictionary mapping names of inputs of this node
to names of inputs to new node, and outputs_mapping_dict is a dictionary
mapping names of outputs of this node to names of outputs of new node.
inputs_mapping_dict and outputs_mapping_dict can be None.
"""
if hasattr(self, "replacement_nodes"):
for bl_idname, inputs_mapping, outputs_mapping in self.replacement_nodes:
node_class = get_node_class_reference(bl_idname)
if node_class:
text = "Replace with {}".format(node_class.bl_label)
op = layout.operator("node.sv_replace_node", text=text)
op.old_node_name = self.name
op.new_bl_idname = bl_idname
set_inputs_mapping(op, inputs_mapping)
set_outputs_mapping(op, outputs_mapping)
else:
self.error("Can't build replacement menu: no such node class: %s",bl_idname)
def migrate_links_from(self, old_node, operator):
"""
This method is called by node replacement operator.
By default, it removes existing links from old_node
and creates corresponding links for this (new) node.
Override it to implement custom re-linking at node
replacement.
Most nodes do not have to override this method.
"""
tree = self.id_data
# Copy incoming / outgoing links
old_in_links = [link for link in tree.links if link.to_node == old_node]
old_out_links = [link for link in tree.links if link.from_node == old_node]
for old_link in old_in_links:
new_target_socket_name = operator.get_new_input_name(old_link.to_socket.name)
if new_target_socket_name in self.inputs:
new_target_socket = self.inputs[new_target_socket_name]
new_link = tree.links.new(old_link.from_socket, new_target_socket)
else:
self.debug("New node %s has no input named %s, skipping", self.name, new_target_socket_name)
tree.links.remove(old_link)
for old_link in old_out_links:
new_source_socket_name = operator.get_new_output_name(old_link.from_socket.name)
# We have to remove old link before creating new one
# Blender would not allow two links pointing to the same target socket
old_target_socket = old_link.to_socket
tree.links.remove(old_link)
if new_source_socket_name in self.outputs:
new_source_socket = self.outputs[new_source_socket_name]
new_link = tree.links.new(new_source_socket, old_target_socket)
else:
self.debug("New node %s has no output named %s, skipping", self.name, new_source_socket_name)
def migrate_from(self, old_node):
"""
This method is called by node replacement operator.
Override it to correctly copy settings from old_node
to this (new) node.
This is called after migrate_links_from().
Default implementation does nothing.
"""
pass
@property
def prefs_over_sized_buttons(self):
try:
addon = bpy.context.preferences.addons.get(sverchok.__name__)
prefs = addon.preferences
except Exception as err:
print('failed to access addon preferences for button size', err)
return False
return prefs.over_sized_buttons
@post_load_call
def add_use_fake_user_to_trees():
"""When ever space node editor switches to another tree or creates new one,
this function will set True to `use_fake_user` of all Sverchok trees"""
def set_fake_user():
[setattr(t, 'use_fake_user', True) for t in bpy.data.node_groups if t.bl_idname == 'SverchCustomTreeType']
bpy.msgbus.subscribe_rna(key=(bpy.types.SpaceNodeEditor, 'node_tree'), owner=object(), args=(),
notify=set_fake_user)
register, unregister = bpy.utils.register_classes_factory([SverchCustomTree])