base_definitions.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. #Mantis Nodes Base
  2. import bpy
  3. from bpy.props import (BoolProperty, StringProperty, EnumProperty, CollectionProperty, \
  4. IntProperty, IntVectorProperty, PointerProperty, BoolVectorProperty)
  5. from . import ops_nodegroup
  6. from bpy.types import NodeTree, Node, PropertyGroup, Operator, UIList, Panel
  7. from .utilities import (prRed, prGreen, prPurple, prWhite,
  8. prOrange,
  9. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  10. wrapOrange,)
  11. from .utilities import get_socket_maps, relink_socket_map, do_relink
  12. def TellClasses():
  13. #Why use a function to do this? Because I don't need every class to register.
  14. return [ MantisTree,
  15. SchemaTree,
  16. MantisNodeGroup,
  17. SchemaGroup,
  18. ]
  19. def error_popup_draw(self, context):
  20. self.layout.label(text="Error executing tree. See Console.")
  21. mantis_root = ".".join(__name__.split('.')[:-1]) # absolute HACK
  22. class MantisTree(NodeTree):
  23. '''A custom node tree type that will show up in the editor type list'''
  24. bl_idname = 'MantisTree'
  25. bl_label = "Rigging Nodes"
  26. bl_icon = 'OUTLINER_OB_ARMATURE'
  27. tree_valid:BoolProperty(default=False)
  28. do_live_update:BoolProperty(default=True) # use this to disable updates for e.g. scripts
  29. num_links:IntProperty(default=-1)
  30. filepath:StringProperty(default="", subtype='FILE_PATH')
  31. is_executing:BoolProperty(default=False)
  32. is_exporting:BoolProperty(default=False)
  33. execution_id:StringProperty(default='')
  34. mantis_version:IntVectorProperty(default=[0,9,2])
  35. # this prevents the node group from executing on the next depsgraph update
  36. # because I don't always have control over when the dg update happens.
  37. prevent_next_exec:BoolProperty(default=False)
  38. parsed_tree={}
  39. if bpy.app.version >= (3, 2): # in 3.1 this can lead to a crash
  40. @classmethod
  41. def valid_socket_type(cls, socket_type: str):
  42. # https://docs.blender.org/api/master/bpy.types.NodeTree.html#bpy.types.NodeTree.valid_socket_type
  43. from .socket_definitions import Tell_bl_idnames
  44. return socket_type in Tell_bl_idnames()
  45. # thank you, Sverchok
  46. def update_tree(self, context = None):
  47. if self.is_exporting:
  48. return
  49. # return
  50. self.is_executing = True
  51. from . import readtree
  52. prGreen("Validating Tree: %s" % self.name)
  53. try:
  54. self.parsed_tree = readtree.parse_tree(self)
  55. if context:
  56. self.display_update(context)
  57. self.is_executing = False
  58. self.tree_valid = True
  59. except GraphError as e:
  60. prRed("Failed to update node tree due to error.")
  61. self.tree_valid = False
  62. self.is_executing = False
  63. raise e
  64. finally:
  65. self.is_executing = False
  66. def display_update(self, context):
  67. if self.is_exporting:
  68. return
  69. self.is_executing = True
  70. current_tree = bpy.context.space_data.path[-1].node_tree
  71. for node in current_tree.nodes:
  72. if hasattr(node, "display_update"):
  73. try:
  74. node.display_update(self.parsed_tree, context)
  75. except Exception as e:
  76. print("Node \"%s\" failed to update display with error: %s" %(wrapGreen(node.name), wrapRed(e)))
  77. self.is_executing = False
  78. # TODO: deal with invalid links properly.
  79. # - Non-hierarchy links should be ignored in the circle-check and so the links should be marked valid in such a circle
  80. # - hierarchy-links should be marked invalid and prevent the tree from executing.
  81. def execute_tree(self,context, error_popups = False):
  82. self.prevent_next_exec = False
  83. if self.is_exporting:
  84. return
  85. # return
  86. prGreen("Executing Tree: %s" % self.name)
  87. self.is_executing = True
  88. from . import readtree
  89. try:
  90. readtree.execute_tree(self.parsed_tree, self, context, error_popups)
  91. except RecursionError as e:
  92. prRed("Recursion error while parsing tree.")
  93. finally:
  94. self.is_executing = False
  95. class SchemaTree(NodeTree):
  96. '''A node tree representing a schema to generate a Mantis tree'''
  97. bl_idname = 'SchemaTree'
  98. bl_label = "Rigging Nodes Schema"
  99. bl_icon = 'RIGID_BODY_CONSTRAINT'
  100. # these are only needed for consistent interface, but should not be used
  101. do_live_update:BoolProperty(default=True) # default to true so that updates work
  102. is_executing:BoolProperty(default=False)
  103. is_exporting:BoolProperty(default=False)
  104. mantis_version:IntVectorProperty(default=[0,9,2])
  105. if bpy.app.version >= (3, 2): # in 3.1 this can lead to a crash
  106. @classmethod
  107. def valid_socket_type(cls, socket_type: str):
  108. # https://docs.blender.org/api/master/bpy.types.NodeTree.html#bpy.types.NodeTree.valid_socket_type
  109. from .socket_definitions import Tell_bl_idnames
  110. return socket_type in Tell_bl_idnames()
  111. # thank you, Sverchok
  112. #TODO: do a better job explaining how MantisNode and MantisUINode relate.
  113. class MantisUINode:
  114. """
  115. This class contains the common user-interface features of Mantis nodes.
  116. MantisUINode objects will spawn one or more MantisNode objects when the graph is evaluated.
  117. The MantisNode objects will pull the data from the UI node and use it to generate the graph.
  118. """
  119. mantis_node_library=''
  120. mantis_node_class_name=''
  121. mantis_class=None
  122. @classmethod
  123. def poll(cls, ntree):
  124. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  125. @classmethod
  126. def set_mantis_class(self):
  127. from importlib import import_module
  128. # do not catch errors, they should cause a failure.
  129. try:
  130. module = import_module(self.mantis_node_library, package=mantis_root)
  131. self.mantis_class=getattr(module, self.mantis_node_class_name)
  132. except Exception as e:
  133. print(self)
  134. raise e
  135. def insert_link(self, link):
  136. context = bpy.context
  137. if context.space_data:
  138. node_tree = context.space_data.path[0].node_tree
  139. from . import readtree
  140. if node_tree.do_live_update:
  141. node_tree.update_tree(context)
  142. if (link.to_socket.is_linked == False):
  143. node_tree.num_links+=1
  144. elif (link.to_socket.is_multi_input):
  145. node_tree.num_links+=1
  146. class SchemaUINode(MantisUINode):
  147. mantis_node_library='.schema_containers'
  148. @classmethod
  149. def poll(cls, ntree):
  150. return (ntree.bl_idname in ['SchemaTree'])
  151. class LinkNode(MantisUINode):
  152. mantis_node_library='.link_containers'
  153. @classmethod
  154. def poll(cls, ntree):
  155. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  156. class xFormNode(MantisUINode):
  157. mantis_node_library='.xForm_containers'
  158. @classmethod
  159. def poll(cls, ntree):
  160. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  161. class DeformerNode(MantisUINode):
  162. mantis_node_library='.deformer_containers'
  163. @classmethod
  164. def poll(cls, ntree):
  165. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  166. def poll_node_tree(self, object):
  167. if isinstance(object, MantisTree):
  168. return True
  169. return False
  170. # TODO: try to check identifiers instead of name.
  171. def node_group_update(node, force = False):
  172. if not force:
  173. if (node.id_data.do_live_update == False) or (node.id_data.is_executing == True):
  174. return
  175. # note: if (node.id_data.is_exporting == True) I need to be able to update so I can make links.
  176. toggle_update = node.id_data.do_live_update
  177. node.id_data.do_live_update = False
  178. identifiers_in={socket.identifier:socket for socket in node.inputs}
  179. identifiers_out={socket.identifier:socket for socket in node.outputs}
  180. if node.node_tree is None:
  181. node.inputs.clear(); node.outputs.clear()
  182. node.id_data.do_live_update = toggle_update
  183. return
  184. found_in, found_out = [], []
  185. update_input, update_output = False, False
  186. for item in node.node_tree.interface.items_tree:
  187. if item.item_type != "SOCKET": continue
  188. if item.in_out == 'OUTPUT':
  189. if s:= identifiers_out.get(item.identifier): # if the requested output doesn't exist, update
  190. found_out.append(item.identifier)
  191. if update_output: continue
  192. if s.bl_idname != item.socket_type: update_output = True; continue
  193. else: update_output = True; continue
  194. else:
  195. if s:= identifiers_in.get(item.identifier): # if the requested input doesn't exist, update
  196. found_in.append(item.identifier)
  197. if update_input: continue # done here
  198. if s.bl_idname != item.socket_type: update_input = True; continue
  199. else: update_input = True; continue
  200. # Schema has an extra input for Length and for Extend.
  201. if node.bl_idname == 'MantisSchemaGroup':
  202. found_in.extend(['Schema Length', ''])
  203. # if we have too many elements, just get rid of the ones we don't need
  204. if len(node.inputs) > len(found_in):#
  205. for inp in node.inputs:
  206. if inp.identifier in found_in: continue
  207. node.inputs.remove(inp)
  208. if len(node.outputs) > len(found_out):
  209. for out in node.outputs:
  210. if out.identifier in found_out: continue
  211. node.outputs.remove(out)
  212. #
  213. if len(node.inputs) > 0 and (inp := node.inputs[-1]).bl_idname == 'WildcardSocket' and inp.is_linked:
  214. update_input = True
  215. if len(node.outputs) > 0 and (out := node.outputs[-1]).bl_idname == 'WildcardSocket' and out.is_linked:
  216. update_output = True
  217. #
  218. if not (update_input or update_output):
  219. node.id_data.do_live_update = toggle_update
  220. return
  221. if update_input or update_output:
  222. socket_map_in, socket_map_out = get_socket_maps(node)
  223. if update_input :
  224. if node.bl_idname == 'MantisSchemaGroup':
  225. schema_length=0
  226. if sl := node.inputs.get("Schema Length"):
  227. schema_length = sl.default_value
  228. # sometimes this isn't available yet # TODO not happy about this solution
  229. node.inputs.clear()
  230. if node.bl_idname == 'MantisSchemaGroup':
  231. node.inputs.new("IntSocket", "Schema Length", identifier='Schema Length')
  232. node.inputs['Schema Length'].default_value = schema_length
  233. if update_output: node.outputs.clear()
  234. for item in node.node_tree.interface.items_tree:
  235. if item.item_type != "SOCKET": continue
  236. if (item.in_out == 'INPUT' and update_input):
  237. relink_socket_map(node, node.inputs, socket_map_in, item)
  238. if (item.in_out == 'OUTPUT' and update_output):
  239. relink_socket_map(node, node.outputs, socket_map_out, item)
  240. # at this point there is no wildcard socket
  241. if '__extend__' in socket_map_in.keys():
  242. do_relink(node, None, socket_map_in, in_out='INPUT', parent_name='Constant' )
  243. node.id_data.do_live_update = toggle_update
  244. def node_tree_prop_update(self, context):
  245. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  246. return # so we check if an update is currently running.
  247. self.is_updating = True
  248. node_group_update(self)
  249. self.is_updating = False
  250. if self.bl_idname in ['MantisSchemaGroup'] and self.node_tree is not None:
  251. if len(self.inputs) == 0:
  252. self.inputs.new("IntSocket", "Schema Length", identifier='Schema Length')
  253. if self.inputs[-1].bl_idname != "WildcardSocket":
  254. self.inputs.new("WildcardSocket", "", identifier="__extend__")
  255. from bpy.types import NodeCustomGroup
  256. class MantisNodeGroup(Node, MantisUINode):
  257. bl_idname = "MantisNodeGroup"
  258. bl_label = "Node Group"
  259. node_tree:PointerProperty(type=NodeTree, poll=poll_node_tree, update=node_tree_prop_update,)
  260. is_updating:BoolProperty(default=False)
  261. def update(self):
  262. live_update = self.id_data.do_live_update
  263. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  264. return # so we check if an update is currently running.
  265. try:
  266. self.is_updating = True
  267. node_group_update(self)
  268. self.is_updating = False
  269. finally: # we need to reset this regardless of whether or not the operation succeeds!
  270. self.is_updating = False
  271. self.id_data.do_live_update = live_update # ensure this remains the same
  272. def draw_buttons(self, context, layout):
  273. row = layout.row(align=True)
  274. row.prop(self, "node_tree", text="")
  275. row.operator("mantis.edit_group", text="", icon='NODETREE', emboss=True)
  276. class GraphError(Exception):
  277. pass
  278. def get_signature_from_edited_tree(node, context):
  279. sig_path=[None,]
  280. for item in context.space_data.path[:-1]:
  281. sig_path.append(item.node_tree.nodes.active.name)
  282. return tuple(sig_path+[node.name])
  283. def poll_node_tree_schema(self, object):
  284. if isinstance(object, SchemaTree):
  285. return True
  286. return False
  287. # TODO tiny UI problem - inserting new links into the tree will not place them in the right place.
  288. class SchemaGroup(Node, MantisUINode):
  289. bl_idname = "MantisSchemaGroup"
  290. bl_label = "Node Schema"
  291. node_tree:PointerProperty(type=NodeTree, poll=poll_node_tree_schema, update=node_tree_prop_update,)
  292. is_updating:BoolProperty(default=False)
  293. def draw_buttons(self, context, layout):
  294. row = layout.row(align=True)
  295. row.prop(self, "node_tree", text="")
  296. row.operator("mantis.edit_group", text="", icon='NODETREE', emboss=True)
  297. def update(self):
  298. live_update = self.id_data.do_live_update
  299. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  300. return # so we check if an update is currently running.
  301. self.is_updating = True
  302. try:
  303. node_group_update(self)
  304. # reset things if necessary:
  305. if self.node_tree:
  306. if len(self.inputs) == 0:
  307. self.inputs.new("IntSocket", "Schema Length", identifier='Schema Length')
  308. if self.inputs[-1].bl_idname != "WildcardSocket":
  309. self.inputs.new("WildcardSocket", "", identifier="__extend__")
  310. finally: # we need to reset this regardless of whether or not the operation succeeds!
  311. self.is_updating = False
  312. self.id_data.do_live_update = live_update # ensure this remains the same
  313. NODES_REMOVED=["xFormRootNode"]
  314. # Node bl_idname, # Socket Name
  315. SOCKETS_REMOVED=[("UtilityDriverVariable", "Transform Channel"),
  316. ("xFormRootNode","World Out"),
  317. ("UtilitySwitch","xForm"),
  318. ("LinkDrivenParameter", "Enable")]
  319. # Node Class #Prior bl_idname # prior name # new bl_idname # new name, # Multi
  320. SOCKETS_RENAMED=[ ("LinkDrivenParameter", "DriverSocket", "Driver", "FloatSocket", "Value", False)]
  321. # NODE CLASS NAME IN_OUT SOCKET TYPE SOCKET NAME INDEX MULTI DEFAULT
  322. SOCKETS_ADDED=[("DeformerMorphTargetDeform", 'INPUT', 'BooleanSocket', "Use Shape Key", 1, False, False),
  323. ("DeformerMorphTargetDeform", 'INPUT', 'BooleanSocket', "Use Offset", 2, False, True),
  324. ("UtilityFCurve", 'INPUT', "eFCrvExtrapolationMode", "Extrapolation Mode", 0, False, 'CONSTANT')]
  325. # replace names with bl_idnames for reading the tree and solving schemas.
  326. replace_types = ["NodeGroupInput", "NodeGroupOutput", "SchemaIncomingConnection",
  327. "SchemaArrayInput", "SchemaConstInput", "SchemaConstOutput", "SchemaIndex",
  328. "SchemaOutgoingConnection", "SchemaConstantOutput", "SchemaArrayOutput",
  329. "SchemaArrayInputGet",]
  330. # anything that gets properties added in the graph... this is a clumsy approach but I need to watch for this
  331. # in schema generation and this is the easiest way to do it for now.
  332. custom_props_types = ["LinkArmature", "UtilityKeyframe", "UtilityFCurve", "UtilityDriver", "xFormBone"]
  333. # filters for determining if a link is a hierarchy link or a non-hierarchy (cyclic) link.
  334. from_name_filter = ["Driver",]
  335. to_name_filter = [
  336. "Custom Object xForm Override",
  337. "Custom Object",
  338. "Deform Bones",
  339. ]
  340. class MantisNode:
  341. """
  342. This class contains the basic interface for a Mantis Node.
  343. A MantisNode is used internally by Mantis to represent the final evaluated node graph.
  344. It gets generated with data from a MantisUINode when the graph is read.
  345. """
  346. def __init__(self, signature, base_tree):
  347. self.base_tree=base_tree
  348. self.signature = signature
  349. self.inputs = MantisNodeSocketCollection(node=self, is_input=True)
  350. self.outputs = MantisNodeSocketCollection(node=self, is_input=False)
  351. self.parameters = {}
  352. self.drivers = {}
  353. self.node_type='UNINITIALIZED'
  354. self.hierarchy_connections, self.connections = [], []
  355. self.hierarchy_dependencies, self.dependencies = [], []
  356. self.prepared = False
  357. self.executed = False
  358. def init_parameters(self, additional_parameters = {}):
  359. for socket in self.inputs:
  360. self.parameters[socket.name] = None
  361. for socket in self.outputs:
  362. self.parameters[socket.name] = None
  363. for key, value in additional_parameters.items():
  364. self.parameters[key]=value
  365. def set_traverse(self, traversal_pairs = [(str, str)]):
  366. for (a, b) in traversal_pairs:
  367. self.inputs[a].set_traverse_target(self.outputs[b])
  368. self.outputs[b].set_traverse_target(self.inputs[a])
  369. def flush_links(self):
  370. for inp in self.inputs.values():
  371. inp.flush_links()
  372. for out in self.outputs.values():
  373. out.flush_links()
  374. def evaluate_input(self, input_name, index=0):
  375. from .node_container_common import trace_single_line
  376. if not (self.inputs.get(input_name)): # get the named parameter if there is no input
  377. return self.parameters.get(input_name) # this will return None if the parameter does not exist.
  378. # this trace() should give a key error if there is a problem
  379. # it is NOT handled here because it should NOT happen - so I want the error message.
  380. trace = trace_single_line(self, input_name, index)
  381. prop = trace[0][-1].parameters[trace[1].name] #trace[0] = the list of traced nodes; read its parameters
  382. return prop
  383. def fill_parameters(self, ui_node=None):
  384. from .utilities import get_node_prototype
  385. from .node_container_common import get_socket_value
  386. if not ui_node:
  387. if ( (self.signature[0] in ["MANTIS_AUTOGENERATED", "SCHEMA_AUTOGENERATED" ]) or
  388. (self.signature[-1] in ["NodeGroupOutput", "NodeGroupInput"]) ): # I think this is harmless
  389. return None
  390. else:
  391. ui_node = get_node_prototype(self.signature, self.base_tree)
  392. if not ui_node:
  393. raise RuntimeError(wrapRed("No node prototype found for... %s" % ( [self.base_tree] + list(self.signature[1:]) ) ) )
  394. for key in self.parameters.keys():
  395. node_socket = ui_node.inputs.get(key)
  396. if self.parameters[key] is not None: # the parameters are usually initialized as None.
  397. continue # will be filled by the node itself
  398. if not node_socket: #maybe the node socket has no name
  399. if ( ( len(ui_node.inputs) == 0) and ( len(ui_node.outputs) == 1) ):
  400. # this is a simple input node.
  401. node_socket = ui_node.outputs[0]
  402. elif key == 'Name': # for Links we just use the Node Label, or if there is no label, the name.
  403. self.parameters[key] = ui_node.label if ui_node.label else ui_node.name
  404. continue
  405. else:
  406. pass
  407. if node_socket:
  408. if node_socket.bl_idname in ['RelationshipSocket', 'xFormSocket']:
  409. continue
  410. elif node_socket.is_linked and (not node_socket.is_output):
  411. pass # we will get the value from the link, because this is a linked input port.
  412. # very importantly, we do not pass linked outputs- fill these because they are probably Input nodes.
  413. elif hasattr(node_socket, "default_value"):
  414. if (value := get_socket_value(node_socket)) is not None:
  415. self.parameters[key] = value
  416. # TODO: try and remove the input if it is not needed (for performance speed)
  417. else:
  418. raise RuntimeError(wrapRed("No value found for " + self.__repr__() + " when filling out node parameters for " + ui_node.name + "::"+node_socket.name))
  419. else:
  420. pass
  421. def call_on_all_ancestors(self, *args, **kwargs):
  422. """Resolve the dependencies of this node with the named method and its arguments.
  423. First, dependencies are discovered by walking backwards through the tree. Once the root
  424. nodes are discovered, the method is called by each node in dependency order.
  425. The first argument MUST be the name of the method as a string.
  426. """
  427. prGreen(self)
  428. if args[0] == 'call_on_all_ancestors': raise RuntimeError("Very funny!")
  429. from .utilities import get_all_dependencies
  430. from collections import deque
  431. # get all dependencies by walking backward through the tree.
  432. all_dependencies = get_all_dependencies(self)
  433. # get just the roots
  434. can_solve = deque(filter(lambda a : len(a.hierarchy_connections) == 0, all_dependencies))
  435. solved = set()
  436. while can_solve:
  437. node = can_solve.pop()
  438. print(node)
  439. method = getattr(node, args[0])
  440. method(*args[0:], **kwargs)
  441. solved.add(node)
  442. can_solve.extendleft(filter(lambda a : a in all_dependencies, node.hierarchy_connections))
  443. # prPurple(can_solve)
  444. if self in solved:
  445. break
  446. # else:
  447. # for dep in all_dependencies:
  448. # if dep not in solved:
  449. # prOrange(dep)
  450. return
  451. def bPrepare(self, bContext=None):
  452. return
  453. def bExecute(self, bContext=None):
  454. return
  455. def bFinalize(self, bContext=None):
  456. return
  457. def __repr__(self):
  458. return self.signature.__repr__()
  459. # do I need this and the link class above?
  460. class DummyLink:
  461. #gonna use this for faking links to keep the interface consistent
  462. def __init__(self, from_socket, to_socket, nc_from=None, nc_to=None, original_from=None, multi_input_sort_id=0):
  463. self.from_socket = from_socket
  464. self.to_socket = to_socket
  465. self.nc_from = nc_from
  466. self.nc_to = nc_to
  467. self.multi_input_sort_id = multi_input_sort_id
  468. # self.from_node = from_socket.node
  469. # self.to_node = to_socket.node
  470. if (original_from):
  471. self.original_from = original_from
  472. else:
  473. self.original_from = self.from_socket
  474. def __repr__(self):
  475. return(self.nc_from.__repr__()+":"+self.from_socket.name + " -> " + self.nc_to.__repr__()+":"+self.to_socket.name)
  476. class NodeLink:
  477. from_node = None
  478. from_socket = None
  479. to_node = None
  480. to_socket = None
  481. def __init__(self, from_node, from_socket, to_node, to_socket, multi_input_sort_id=0):
  482. if from_node.signature == to_node.signature:
  483. raise RuntimeError("Cannot connect a node to itself.")
  484. self.from_node = from_node
  485. self.from_socket = from_socket
  486. self.to_node = to_node
  487. self.to_socket = to_socket
  488. self.from_node.outputs[self.from_socket].links.append(self)
  489. # it is the responsibility of the node that uses these links to sort them correctly based on the sort_id
  490. self.multi_input_sort_id = multi_input_sort_id
  491. self.to_node.inputs[self.to_socket].links.append(self)
  492. from .node_container_common import detect_hierarchy_link
  493. self.is_hierarchy = detect_hierarchy_link(from_node, from_socket, to_node, to_socket,)
  494. self.is_alive = True
  495. def __repr__(self):
  496. return self.from_node.outputs[self.from_socket].__repr__() + " --> " + self.to_node.inputs[self.to_socket].__repr__()
  497. # link_string = # if I need to colorize output for debugging.
  498. # if self.is_hierarchy:
  499. # return wrapOrange(link_string)
  500. # else:
  501. # return wrapWhite(link_string)
  502. def die(self):
  503. self.is_alive = False
  504. self.to_node.inputs[self.to_socket].flush_links()
  505. self.from_node.outputs[self.from_socket].flush_links()
  506. def insert_node(self, middle_node, middle_node_in, middle_node_out, re_init_hierarchy = True):
  507. to_node = self.to_node
  508. to_socket = self.to_socket
  509. self.to_node = middle_node
  510. self.to_socket = middle_node_in
  511. middle_node.outputs[middle_node_out].connect(to_node, to_socket)
  512. if re_init_hierarchy:
  513. from .utilities import init_connections, init_dependencies
  514. init_connections(self.from_node)
  515. init_connections(middle_node)
  516. init_dependencies(middle_node)
  517. init_dependencies(to_node)
  518. class NodeSocket:
  519. # @property # this is a read-only property.
  520. # def is_linked(self):
  521. # return bool(self.links)
  522. def __init__(self, is_input = False,
  523. node = None, name = None,
  524. traverse_target = None):
  525. self.can_traverse = False # to/from the other side of the parent node
  526. self.traverse_target = None
  527. self.node = node
  528. self.name = name
  529. self.is_input = is_input
  530. self.links = []
  531. self.is_linked = False
  532. if (traverse_target):
  533. self.can_traverse = True
  534. def connect(self, node, socket, sort_id=0):
  535. if (self.is_input):
  536. to_node = self.node; from_node = node
  537. to_socket = self.name; from_socket = socket
  538. else:
  539. from_node = self.node; to_node = node
  540. from_socket = self.name; to_socket = socket
  541. from_node.outputs[from_socket].is_linked = True
  542. to_node.inputs[to_socket].is_linked = True
  543. for l in from_node.outputs[from_socket].links:
  544. if l.to_node==to_node and l.to_socket==to_socket:
  545. return None
  546. new_link = NodeLink(
  547. from_node,
  548. from_socket,
  549. to_node,
  550. to_socket,
  551. sort_id)
  552. return new_link
  553. def set_traverse_target(self, traverse_target):
  554. self.traverse_target = traverse_target
  555. self.can_traverse = True
  556. def flush_links(self):
  557. """ Removes dead links from this socket."""
  558. self.links = [l for l in self.links if l.is_alive]
  559. self.is_linked = bool(self.links)
  560. @property
  561. def is_connected(self):
  562. return len(self.links)>0
  563. def __repr__(self):
  564. return self.node.__repr__() + "::" + self.name
  565. class MantisNodeSocketCollection(dict):
  566. def __init__(self, node, is_input=False):
  567. self.is_input = is_input
  568. self.node = node
  569. def init_sockets(self, sockets):
  570. for socket in sockets:
  571. if not isinstance(socket, str): raise RuntimeError("NodeSocketCollection keys must be str.")
  572. self[socket] = NodeSocket(is_input=self.is_input, name=socket, node=self.node)
  573. def __delitem__(self, key):
  574. """Deletes a node socket by name, and all its links."""
  575. socket = self[key]
  576. for l in socket.links:
  577. l.die()
  578. super().__delitem__(key)
  579. def __iter__(self):
  580. """Makes the class iterable"""
  581. return iter(self.values())