base_definitions.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  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. from .mantis_dataclasses import MantisSocketTemplate
  13. FLOAT_EPSILON=0.0001 # used to check against floating point inaccuracy
  14. links_sort_key= lambda a : (-a.multi_input_sort_id, -a.sub_sort_id)
  15. def TellClasses():
  16. #Why use a function to do this? Because I don't need every class to register.
  17. return [ MantisTree,
  18. SchemaTree,
  19. MantisNodeGroup,
  20. SchemaGroup,
  21. ]
  22. def error_popup_draw(self, context):
  23. self.layout.label(text="Error executing tree. See Console.")
  24. mantis_root = ".".join(__name__.split('.')[:-1]) # absolute HACK
  25. from os import environ
  26. # https://docs.blender.org/api/master/bpy.types.NodeTree.html#bpy.types.NodeTree.valid_socket_type
  27. # thank you, Sverchok
  28. def valid_interface_types(cls : NodeTree, socket_idname : str):
  29. from .socket_definitions import tell_valid_bl_idnames, TellClasses
  30. #TODO: do the versioning code to handle this so it can be in all versions
  31. if bpy.app.version <= (4,4,0): # should work in 4.4.1
  32. return socket_idname in [cls.bl_idname for cls in TellClasses()]
  33. elif bpy.app.version == (4,5,0): # workaround for a BUG
  34. return ['NodeSocketGeometry']
  35. else: # once versioning is finished this will be unnecesary.
  36. return socket_idname in tell_valid_bl_idnames()
  37. def fix_reroute_colors(tree):
  38. context = bpy.context
  39. if any((tree.is_executing, tree.is_exporting, tree.do_live_update==False, context.space_data is None) ):
  40. return
  41. from collections import deque
  42. from .utilities import socket_seek
  43. from .socket_definitions import MantisSocket
  44. reroutes_without_color = deque()
  45. for n in tree.nodes:
  46. if n.bl_idname=='NodeReroute' and n.inputs[0].bl_idname == "NodeSocketColor":
  47. reroutes_without_color.append(n)
  48. try:
  49. while reroutes_without_color:
  50. rr = reroutes_without_color.pop()
  51. if rr.inputs[0].is_linked:
  52. link = rr.inputs[0].links[0]
  53. socket = socket_seek(link, tree.links)
  54. if isinstance(socket, MantisSocket):
  55. rr.socket_idname = socket.bl_idname
  56. except Exception as e:
  57. print(wrapOrange("WARN: Updating reroute color failed with exception: ")+wrapWhite(f"{e.__class__.__name__}"))
  58. #functions to identify the state of the system using hashes
  59. # this function runs a lot so it should be optimized as well as possible.
  60. def hash_tree(tree):
  61. trees=set(); links=[]; hash_data=""
  62. for node in tree.nodes:
  63. hash_data+=str(node.name)
  64. if hasattr(node, 'node_tree') and node.node_tree:
  65. trees.add(node.node_tree)
  66. for other_tree in trees:
  67. hash_data+=str(hash_tree(other_tree))
  68. for link in tree.links:
  69. links.append( link.from_node.name+link.from_socket.name+
  70. link.to_node.name+link.to_socket.name+
  71. str(link.multi_input_sort_id) )
  72. links.sort(); hash_data+=''.join(links)
  73. return hash(hash_data)
  74. MANTIS_VERSION_MAJOR=0
  75. MANTIS_VERSION_MINOR=13
  76. MANTIS_VERSION_SUB=2
  77. class MantisTree(NodeTree):
  78. '''A custom node tree type that will show up in the editor type list'''
  79. bl_idname = 'MantisTree'
  80. bl_label = "Rigging Nodes"
  81. bl_icon = 'OUTLINER_OB_ARMATURE'
  82. tree_valid:BoolProperty(default=False)
  83. hash:StringProperty(default='')
  84. do_live_update:BoolProperty(default=True) # use this to disable updates for e.g. scripts
  85. num_links:IntProperty(default=-1)
  86. # operator settings for re-exporting the tree.
  87. filepath:StringProperty(default="", subtype='FILE_PATH')
  88. export_all_subtrees_together:BoolProperty(default=True)
  89. #
  90. is_executing:BoolProperty(default=False)
  91. is_exporting:BoolProperty(default=False)
  92. execution_id:StringProperty(default='')
  93. # prev_execution_id:StringProperty(default='')
  94. mantis_version:IntVectorProperty(default=[
  95. MANTIS_VERSION_MAJOR, MANTIS_VERSION_MINOR, MANTIS_VERSION_SUB])
  96. # this prevents the node group from executing on the next depsgraph update
  97. # because I don't always have control over when the dg upadte happens.
  98. prevent_next_exec:BoolProperty(default=False)
  99. #added to work around a bug in 4.5.0 LTS
  100. interface_helper : StringProperty(default='')
  101. parsed_tree={}
  102. if (bpy.app.version < (4, 4, 0) or bpy.app.version >= (4,5,0)): # in 4.4 this leads to a crash
  103. @classmethod
  104. def valid_socket_type(cls : NodeTree, socket_idname: str):
  105. return valid_interface_types(cls, socket_idname)
  106. def update(self): # set the reroute colors
  107. if (bpy.app.version >= (4,4,0)):
  108. fix_reroute_colors(self)
  109. def update_tree(self, context = None, force=False, error_popups=False):
  110. if self.is_exporting:
  111. return
  112. my_hash = str( hash_tree(self) )
  113. if (my_hash != self.hash) or force:
  114. self.hash = my_hash
  115. self.is_executing = True
  116. from . import readtree
  117. prGreen("Validating Tree: %s" % self.name)
  118. try:
  119. import bpy # I am importing here so that the context passed in
  120. # is used for display update... but I always want to do this
  121. scene = bpy.context.scene
  122. scene.render.use_lock_interface = True
  123. self.parsed_tree = readtree.parse_tree(self, error_popups)
  124. if context:
  125. self.display_update(context)
  126. self.tree_valid = True
  127. except Exception as e:
  128. prRed("Failed to update node tree due to error.")
  129. self.tree_valid = False
  130. self.hash='' # unset the hash to mark the tree as un-parsed.
  131. raise e
  132. finally:
  133. scene.render.use_lock_interface = False
  134. self.is_executing = False
  135. def display_update(self, context):
  136. if self.is_exporting:
  137. return
  138. self.is_executing = True
  139. current_tree = bpy.context.space_data.path[-1].node_tree
  140. for node in current_tree.nodes:
  141. if hasattr(node, "display_update"):
  142. try:
  143. node.display_update(self.parsed_tree, context)
  144. except Exception as e:
  145. print("Node \"%s\" failed to update display with error: %s" %(wrapGreen(node.name), wrapRed(e)))
  146. self.is_executing = False
  147. # TODO: deal with invalid links properly.
  148. # - Non-hierarchy links should be ignored in the circle-check and so the links should be marked valid in such a circle
  149. # - hierarchy-links should be marked invalid and prevent the tree from executing.
  150. def execute_tree(self,context, error_popups = False, profile=False):
  151. self.prevent_next_exec = False
  152. if not self.hash:
  153. return
  154. if self.is_exporting or self.is_executing:
  155. return
  156. prGreen("Executing Tree: %s" % self.name)
  157. self.is_executing = True
  158. from . import readtree
  159. try:
  160. context.scene.render.use_lock_interface = True
  161. readtree.execute_tree(self.parsed_tree, self, context, error_popups, profile=profile)
  162. except RecursionError as e:
  163. prRed("Recursion error while parsing tree.")
  164. finally:
  165. context.scene.render.use_lock_interface = False
  166. self.is_executing = False
  167. class SchemaTree(NodeTree):
  168. '''A node tree representing a schema to generate a Mantis tree'''
  169. bl_idname = 'SchemaTree'
  170. bl_label = "Rigging Nodes Schema"
  171. bl_icon = 'RIGID_BODY_CONSTRAINT'
  172. # these are only needed for consistent interface, but should not be used
  173. do_live_update:BoolProperty(default=True) # default to true so that updates work
  174. is_executing:BoolProperty(default=False)
  175. is_exporting:BoolProperty(default=False)
  176. mantis_version:IntVectorProperty(default=[
  177. MANTIS_VERSION_MAJOR, MANTIS_VERSION_MINOR, MANTIS_VERSION_SUB])
  178. # see the note in MantisTree
  179. interface_helper : StringProperty(default='')
  180. if (bpy.app.version < (4, 4, 0) or bpy.app.version >= (4,5,0)): # in 4.4 this leads to a crash
  181. @classmethod
  182. def valid_socket_type(cls : NodeTree, socket_idname: str):
  183. return valid_interface_types(cls, socket_idname)
  184. def update(self): # set the reroute colors
  185. if (bpy.app.version >= (4,4,0)):
  186. fix_reroute_colors(self)
  187. #TODO: do a better job explaining how MantisNode and MantisUINode relate.
  188. class MantisUINode:
  189. """
  190. This class contains the common user-interface features of Mantis nodes.
  191. MantisUINode objects will spawn one or more MantisNode objects when the graph is evaluated.
  192. The MantisNode objects will pull the data from the UI node and use it to generate the graph.
  193. """
  194. mantis_node_library=''
  195. mantis_node_class_name=''
  196. mantis_class=None
  197. @classmethod
  198. def poll(cls, ntree):
  199. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  200. @classmethod
  201. def set_mantis_class(self):
  202. from importlib import import_module
  203. # do not catch errors, they should cause a failure.
  204. try:
  205. module = import_module(self.mantis_node_library, package=mantis_root)
  206. self.mantis_class=getattr(module, self.mantis_node_class_name)
  207. except Exception as e:
  208. print(self)
  209. raise e
  210. def insert_link(self, link):
  211. if (bpy.app.version >= (4, 4, 0)):
  212. return # this causes a crash due to a bug.
  213. context = bpy.context
  214. if context.space_data:
  215. node_tree = context.space_data.path[0].node_tree
  216. if node_tree.do_live_update:
  217. node_tree.update_tree(context)
  218. if (link.to_socket.is_linked == False):
  219. node_tree.num_links+=1
  220. elif (link.to_socket.is_multi_input):
  221. node_tree.num_links+=1
  222. def init_sockets(self, socket_templates : tuple[MantisSocketTemplate]):
  223. for template in socket_templates:
  224. collection = self.outputs
  225. if template.is_input:
  226. collection = self.inputs
  227. identifier = template.name
  228. if template.identifier:
  229. identifier = template.identifier
  230. use_multi_input = template.use_multi_input if template.is_input else False
  231. socket = collection.new(
  232. template.bl_idname,
  233. template.name,
  234. identifier=identifier,
  235. use_multi_input=use_multi_input
  236. )
  237. socket.hide= template.hide
  238. if template.category:
  239. # a custom property for the UI functions to use.
  240. socket.category = template.category
  241. if template.default_value is not None:
  242. socket.default_value = template.default_value
  243. # this can throw a TypeError - it is the caller's
  244. # responsibility to send the right type.
  245. if template.use_multi_input: # this is an array
  246. socket.display_shape = 'SQUARE_DOT'
  247. class SchemaUINode(MantisUINode):
  248. mantis_node_library='.schema_nodes'
  249. is_updating:BoolProperty(default=False)
  250. @classmethod
  251. def poll(cls, ntree):
  252. return (ntree.bl_idname in ['SchemaTree'])
  253. class LinkNode(MantisUINode):
  254. mantis_node_library='.link_nodes'
  255. @classmethod
  256. def poll(cls, ntree):
  257. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  258. class xFormNode(MantisUINode):
  259. mantis_node_library='.xForm_nodes'
  260. @classmethod
  261. def poll(cls, ntree):
  262. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  263. class DeformerNode(MantisUINode):
  264. mantis_node_library='.deformer_nodes'
  265. @classmethod
  266. def poll(cls, ntree):
  267. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  268. def poll_node_tree(self, object):
  269. forbid = []
  270. context = bpy.context
  271. if context.space_data:
  272. if context.space_data.path:
  273. for path_item in context.space_data.path:
  274. forbid.append(path_item.node_tree.name)
  275. if isinstance(object, MantisTree) and object.name not in forbid:
  276. return True
  277. return False
  278. # TODO: try and remove the extra loop used here... but it is OK for now
  279. def should_remove_socket(node, socket):
  280. # a function to check if the socket is in the interface
  281. id_found = False
  282. for item in node.node_tree.interface.items_tree:
  283. if item.item_type != "SOCKET": continue
  284. if item.identifier == socket.identifier:
  285. id_found = True; break
  286. return not id_found
  287. # TODO: try to check identifiers instead of name.
  288. def node_group_update(node, force = False):
  289. if not node.is_updating:
  290. raise RuntimeError("Cannot update node while it is not marked as updating.")
  291. if not force:
  292. if (node.id_data.do_live_update == False) or \
  293. (node.id_data.is_executing == True) or \
  294. (node.id_data.is_exporting == True):
  295. return
  296. # note: if (node.id_data.is_exporting == True) I need to be able to update so I can make links.
  297. if node.node_tree is None:
  298. node.inputs.clear(); node.outputs.clear()
  299. return
  300. toggle_update = node.id_data.do_live_update
  301. node.id_data.do_live_update = False
  302. identifiers_in={socket.identifier:socket for socket in node.inputs}
  303. identifiers_out={socket.identifier:socket for socket in node.outputs}
  304. interface_names_in, interface_names_out = {}, {}
  305. for interface_item in node.node_tree.interface.items_tree:
  306. if interface_item.item_type != 'SOCKET': continue
  307. if interface_item.in_out == 'INPUT':
  308. interface_names_in[interface_item.identifier] = interface_item.name
  309. else:
  310. interface_names_out[interface_item.identifier] = interface_item.name
  311. indices_in,indices_out={},{} # check by INDEX to see if the socket's name/type match.
  312. for collection, map in [(node.inputs, indices_in), (node.outputs, indices_out)]:
  313. for i, socket in enumerate(collection):
  314. map[socket.identifier]=i
  315. if node.node_tree is None:
  316. node.inputs.clear(); node.outputs.clear()
  317. node.id_data.do_live_update = toggle_update
  318. return
  319. found_in, found_out = [], []
  320. update_input, update_output = False, False
  321. for item in node.node_tree.interface.items_tree:
  322. if item.item_type != "SOCKET": continue
  323. if item.in_out == 'OUTPUT':
  324. if s:= identifiers_out.get(item.identifier): # if the requested output doesn't exist, update
  325. if interface_names_out.get(item.identifier) != s.name: update_output = True; continue
  326. found_out.append(item.identifier)
  327. if (indices_out[s.identifier]!=item.index): update_output=True; continue
  328. if update_output: continue
  329. if s.bl_idname != item.bl_socket_idname: update_output = True; continue
  330. else: update_output = True; continue
  331. else:
  332. if s:= identifiers_in.get(item.identifier): # if the requested input doesn't exist, update
  333. if interface_names_in.get(item.identifier) != s.name: update_input = True; continue
  334. found_in.append(item.identifier)
  335. if (indices_in[s.identifier]!=item.index): update_input=True; continue
  336. if update_input: continue # done here
  337. if s.bl_idname != item.bl_socket_idname: update_input = True; continue
  338. else: update_input = True; continue
  339. # Schema has an extra input for Length and for Extend.
  340. if node.bl_idname == 'MantisSchemaGroup':
  341. found_in.extend(['Schema Length', ''])
  342. # get the socket maps before modifying stuff
  343. if update_input or update_output:
  344. socket_maps = get_socket_maps(node,)
  345. if socket_maps:
  346. socket_map_in, socket_map_out = socket_maps
  347. if node.bl_idname == "MantisSchemaGroup" and \
  348. len(node.inputs)+len(node.outputs)<=2 and\
  349. len(node.node_tree.interface.items_tree) > 0:
  350. socket_map_in, socket_map_out = None, None
  351. # We have to initialize the node because it only has its base inputs.
  352. elif socket_maps is None:
  353. node.id_data.do_live_update = toggle_update
  354. # if we have too many elements, just get rid of the ones we don't need
  355. if len(node.inputs) > len(found_in):#
  356. for inp in node.inputs:
  357. if inp.identifier in found_in: continue
  358. node.inputs.remove(inp)
  359. if len(node.outputs) > len(found_out):
  360. for out in node.outputs:
  361. if out.identifier in found_out: continue
  362. node.outputs.remove(out)
  363. #
  364. if len(node.inputs) > 0 and (inp := node.inputs[-1]).bl_idname == 'WildcardSocket' and inp.is_linked:
  365. update_input = True
  366. #
  367. if not (update_input or update_output):
  368. node.id_data.do_live_update = toggle_update
  369. return
  370. if update_input or update_output and (socket_maps is not None):
  371. if update_input :
  372. if node.bl_idname == 'MantisSchemaGroup':
  373. schema_length=0
  374. if sl := node.inputs.get("Schema Length"):
  375. schema_length = sl.default_value
  376. # sometimes this isn't available yet # TODO not happy about this solution
  377. remove_me=[]
  378. # remove all found map items but the Schema Length input (reuse it)
  379. for i, socket in enumerate(node.inputs):
  380. if socket.identifier == "Schema Length" and i == 0:
  381. continue
  382. elif (socket_map_in is None) or socket.identifier in socket_map_in.keys():
  383. remove_me.append(socket)
  384. elif should_remove_socket(node, socket):
  385. remove_me.append(socket)
  386. while remove_me:
  387. node.inputs.remove(remove_me.pop())
  388. if update_output:
  389. remove_me=[]
  390. for socket in node.outputs:
  391. if (socket_map_out is None) or socket.identifier in socket_map_out.keys():
  392. remove_me.append(socket)
  393. elif should_remove_socket(node, socket):
  394. remove_me.append(socket)
  395. while remove_me:
  396. node.inputs.remove(remove_me.pop())
  397. from .utilities import relink_socket_map_add_socket
  398. reorder_me_input = []; input_index = 0
  399. reorder_me_output = []; output_index = 0
  400. def update_group_sockets(interface_item, is_input):
  401. socket_map = socket_map_in if is_input else socket_map_out
  402. socket_collection = node.inputs if is_input else node.outputs
  403. counter = input_index if is_input else output_index
  404. reorder_collection = reorder_me_input if is_input else reorder_me_output
  405. if socket_map:
  406. if item.identifier in socket_map.keys():
  407. socket = relink_socket_map_add_socket(node, socket_collection, item, item.in_out)
  408. do_relink(node, socket, socket_map, item.in_out)
  409. else:
  410. for has_socket in socket_collection:
  411. if has_socket.bl_idname == item.bl_socket_idname and \
  412. has_socket.name == item.name:
  413. reorder_collection.append((has_socket, counter))
  414. break
  415. else:
  416. socket = relink_socket_map_add_socket(node, socket_collection, item, item.in_out)
  417. else:
  418. socket = relink_socket_map_add_socket(node, socket_collection, item, item.in_out)
  419. counter += 1
  420. # TODO: de-duplicate this hideous stuff
  421. for item in node.node_tree.interface.items_tree:
  422. if item.item_type != "SOCKET": continue
  423. if (item.in_out == 'INPUT' and update_input):
  424. # check and see if it exists... should only happen in curves on startup
  425. if item.bl_socket_idname in ['EnumCurveSocket']:
  426. for exists in node.inputs: # NOTE: check if the socket was not deleted
  427. if exists.identifier == item.identifier:
  428. # this happens for curve inputs because of some shennanigans with how
  429. # blender loads IDs - I can't set the ID until the file has loaded
  430. # so I have to avoid touching the socket until then...
  431. break
  432. else:
  433. update_group_sockets(item, True)
  434. else:
  435. update_group_sockets(item, True)
  436. input_index += 1
  437. if (item.in_out == 'OUTPUT' and update_output):
  438. if item.bl_socket_idname in ['EnumCurveSocket']: # LOOK up there at the comment!
  439. for exists in node.outputs:
  440. if exists.identifier == item.identifier:
  441. break
  442. else:
  443. update_group_sockets(item, False)
  444. else:
  445. update_group_sockets(item, False)
  446. output_index += 1
  447. both_reorders = zip([reorder_me_input, reorder_me_output], [node.inputs, node.outputs])
  448. for reorder_task, collection in both_reorders:
  449. for socket, position in reorder_task:
  450. for i, s in enumerate(collection): # get the index
  451. if s.identifier == socket.identifier: break
  452. else:
  453. prRed(f"WARN: could not reorder socket {socket.name}")
  454. to_index = position
  455. if (not socket.is_output) and node.bl_idname == "MantisSchemaGroup":
  456. to_index+=1
  457. collection.move(i, to_index)
  458. # at this point there is no wildcard socket
  459. if socket_map_in and '__extend__' in socket_map_in.keys():
  460. do_relink(node, None, socket_map_in, in_out='INPUT', parent_name='Constant' )
  461. node.id_data.do_live_update = toggle_update
  462. def node_tree_prop_update(self, context):
  463. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  464. return # so we check if an update is currently running.
  465. self.is_updating = True
  466. def init_schema(self, context):
  467. if len(self.inputs) == 0:
  468. self.inputs.new("UnsignedIntSocket", "Schema Length", identifier='Schema Length')
  469. if self.inputs[-1].bl_idname != "WildcardSocket":
  470. self.inputs.new("WildcardSocket", "", identifier="__extend__")
  471. init_schema(self, context)
  472. try:
  473. node_group_update(self, force=True)
  474. finally: # ensure this line is run even if there is an error
  475. self.is_updating = False
  476. if self.bl_idname in ['MantisSchemaGroup'] and self.node_tree is not None:
  477. init_schema(self, context)
  478. from bpy.types import NodeCustomGroup
  479. def group_draw_buttons(self, context, layout):
  480. row = layout.row(align=True)
  481. row.prop(self, "node_tree", text="")
  482. if self.node_tree is None:
  483. row.operator("mantis.new_node_tree", text="", icon='PLUS', emboss=True)
  484. else:
  485. row.operator("mantis.edit_group", text="", icon='NODETREE', emboss=True)
  486. class MantisNodeGroup(Node, MantisUINode):
  487. bl_idname = "MantisNodeGroup"
  488. bl_label = "Node Group"
  489. node_tree:PointerProperty(type=NodeTree, poll=poll_node_tree, update=node_tree_prop_update,)
  490. is_updating:BoolProperty(default=False)
  491. def draw_label(self):
  492. if self.node_tree is None:
  493. return "Node Group"
  494. else:
  495. return self.node_tree.name
  496. def draw_buttons(self, context, layout):
  497. group_draw_buttons(self, context, layout)
  498. def update(self):
  499. if self.node_tree is None:
  500. return
  501. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  502. return # so we check if an update is currently running.
  503. live_update = self.id_data.do_live_update
  504. self.is_updating = True
  505. try:
  506. node_group_update(self)
  507. finally: # we need to reset this regardless of whether or not the operation succeeds!
  508. self.is_updating = False
  509. self.id_data.do_live_update = live_update # ensure this remains the same
  510. class GraphError(Exception):
  511. pass
  512. class BlenderVersionError(Exception):
  513. pass
  514. def get_signature_from_edited_tree(node, context):
  515. sig_path=[None,]
  516. for item in context.space_data.path[:-1]:
  517. sig_path.append(item.node_tree.nodes.active.name)
  518. return tuple(sig_path+[node.name])
  519. def poll_node_tree_schema(self, object):
  520. if isinstance(object, SchemaTree):
  521. return True
  522. return False
  523. # TODO tiny UI problem - inserting new links into the tree will not place them in the right place.
  524. class SchemaGroup(Node, MantisUINode):
  525. bl_idname = "MantisSchemaGroup"
  526. bl_label = "Node Schema"
  527. node_tree:PointerProperty(type=NodeTree, poll=poll_node_tree_schema, update=node_tree_prop_update,)
  528. is_updating:BoolProperty(default=False)
  529. def draw_buttons(self, context, layout):
  530. group_draw_buttons(self, context, layout)
  531. def draw_label(self):
  532. if self.node_tree is None:
  533. return "Schema Group"
  534. else:
  535. return self.node_tree.name
  536. def update(self):
  537. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  538. return # so we check if an update is currently running.
  539. if self.node_tree is None:
  540. return
  541. live_update = self.id_data.do_live_update
  542. self.is_updating = True
  543. try:
  544. node_group_update(self)
  545. # reset things if necessary:
  546. if self.node_tree:
  547. if len(self.inputs) == 0:
  548. self.inputs.new("UnsignedIntSocket", "Schema Length", identifier='Schema Length')
  549. if self.inputs[-1].identifier != "__extend__":
  550. self.inputs.new("WildcardSocket", "", identifier="__extend__")
  551. finally: # we need to reset this regardless of whether or not the operation succeeds!
  552. self.is_updating = False
  553. self.id_data.do_live_update = live_update # ensure this remains the same
  554. # replace names with bl_idnames for reading the tree and solving schemas.
  555. replace_types = ["NodeGroupInput", "NodeGroupOutput", "SchemaIncomingConnection",
  556. "SchemaArrayInput", "SchemaArrayInputAll", "SchemaConstInput", "SchemaConstOutput",
  557. "SchemaIndex", "SchemaOutgoingConnection", "SchemaArrayOutput","SchemaArrayInputGet",
  558. ]
  559. # anything that gets properties added in the graph... this is a clumsy approach but I need to watch for this
  560. # in schema generation and this is the easiest way to do it for now.
  561. custom_props_types = ["LinkArmature", "UtilityKeyframe", "UtilityFCurve", "UtilityDriver", "xFormBone",
  562. "xFormArmature", "xFormGeometryObject", "xFormObjectInstance", "xFormCurvePin",]
  563. # filters for determining if a link is a hierarchy link or a non-hierarchy (cyclic) link.
  564. from_name_filter = ["Driver",]
  565. to_name_filter = [
  566. "Custom Object xForm Override",
  567. "Custom Object",
  568. "Deform Bones",
  569. ]
  570. # nodes that must be solved as if they were Schema because they send arrays out.
  571. array_output_types = [
  572. 'UtilityArrayGet', 'UtilityKDChoosePoint', 'UtilityKDChooseXForm',
  573. ]
  574. def can_remove_socket_for_autogen(node, socket) -> bool:
  575. """ Whether to enable socket removal optimization for the socket
  576. This should be disallowed if e.g. it is a custom property.
  577. """
  578. return False # for now! This doesn't seem to be working...
  579. # the problem is that Schema does this, and so does Readtree
  580. # and they can try and both do it. That's bad.
  581. if node.socket_templates:
  582. for s_template in node.socket_templates:
  583. if s_template.name == socket:
  584. # raise NotImplementedError
  585. return True
  586. elif node.node_type == 'UTILITY':
  587. return True # HACK because most utilities don't have socket templates yet
  588. return False
  589. # TODO:
  590. # - get the execution context in the execution code
  591. # - from there, begin to use it for stuff I can't do without it
  592. # - and slowly start transferring stuff to it
  593. # The Mantis Overlay class is used to store node-tree specific information
  594. # such as inputs and outputs
  595. # used for e.g. allowing strings to pass as $variables in node names
  596. class MantisOverlay():
  597. def __init__( self, parent, inputs, outputs, ):
  598. pass
  599. # The MantisExecutionContext class is used to store the execution-specific variables
  600. # that are used when executing the tree
  601. # Importantly, it is NOT used to store variables between solutions, these belong to the
  602. # tree itself.
  603. class MantisExecutionContext():
  604. def __init__(
  605. self,
  606. base_tree,
  607. ):
  608. self.base_tree = base_tree
  609. self.execution_id = base_tree.execution_id
  610. self.execution_failed=False
  611. self.b_objects={} # objects created by Mantis during execution
  612. from typing import Any
  613. class MantisNode:
  614. """
  615. This class contains the basic interface for a Mantis Node.
  616. A MantisNode is used internally by Mantis to represent the final evaluated node graph.
  617. It gets generated with data from a MantisUINode when the graph is read.
  618. """
  619. def __init__(self, signature : tuple,
  620. base_tree : bpy.types.NodeTree,
  621. socket_templates : list[MantisSocketTemplate]=[],):
  622. self.base_tree=base_tree
  623. self.signature = signature
  624. self.ui_signature = signature
  625. self.inputs = MantisNodeSocketCollection(node=self, is_input=True)
  626. self.outputs = MantisNodeSocketCollection(node=self, is_input=False)
  627. self.parameters, self.drivers = {}, {}; self.bObject=None
  628. self.node_type='UNINITIALIZED'
  629. self.hierarchy_connections, self.connections = [], []
  630. self.hierarchy_dependencies, self.dependencies = [], []
  631. self.prepared, self.executed = False, False
  632. self.execution_prepared = False
  633. # the above is for tracking prep state in execution, so that I can avoid preparing nodes
  634. # again without changing the readtree code much.
  635. self.socket_templates = socket_templates
  636. self.mContext = None # for now I am gonna set this at runtime
  637. # I know it isn't "beautiful OOP" or whatever, but it is just easier
  638. # code should be simple and do things in the simplest way.
  639. # in the future I can refactor it, but it will require changes to 100+
  640. # classes, instead of adding about 5 lines of code elsewhere.
  641. if self.socket_templates:
  642. self.init_sockets()
  643. @property
  644. def name(self):
  645. return self.ui_signature[-1]
  646. @property
  647. def bl_idname(self): # this and the above exist solely to maintain interface w/bpy.types.Node
  648. from .utilities import get_ui_node
  649. return get_ui_node(self.ui_signature, self.base_tree).bl_idname
  650. def reset_execution(self) -> None:
  651. """ Reset the node for additional execution without re-building the tree."""
  652. self.drivers={}; self.bObject=None
  653. self.executed = False
  654. self.execution_prepared = False
  655. def init_sockets(self) -> None:
  656. self.inputs.init_sockets(self.socket_templates)
  657. self.outputs.init_sockets(self.socket_templates)
  658. def init_parameters(self, additional_parameters = {}) -> None:
  659. for socket in self.inputs:
  660. self.parameters[socket.name] = None
  661. for socket in self.outputs:
  662. self.parameters[socket.name] = None
  663. for key, value in additional_parameters.items():
  664. self.parameters[key]=value
  665. def gen_property_socket_map(self) -> dict:
  666. props_sockets = {}
  667. for s_template in self.socket_templates:
  668. if not s_template.blender_property:
  669. continue
  670. if isinstance(s_template.blender_property, str):
  671. props_sockets[s_template.blender_property]=(s_template.name, s_template.default_value)
  672. elif isinstance(s_template.blender_property, (tuple, list)):
  673. for index, sub_prop in enumerate(s_template.blender_property):
  674. props_sockets[sub_prop]=( (s_template.name, index),s_template.default_value[index] )
  675. return props_sockets
  676. def set_traverse(self, traversal_pairs = [(str, str)]) -> None:
  677. for (a, b) in traversal_pairs:
  678. self.inputs[a].set_traverse_target(self.outputs[b])
  679. self.outputs[b].set_traverse_target(self.inputs[a])
  680. def clear_traverse(self, inputs = [str], outputs = [str]) -> None:
  681. for inp in inputs:
  682. self.inputs[inp].set_traverse(None)
  683. for out in outputs:
  684. self.inputs[out].set_traverse(None)
  685. def flush_links(self) -> None:
  686. for inp in self.inputs.values():
  687. inp.flush_links()
  688. for out in self.outputs.values():
  689. out.flush_links()
  690. def update_socket_value(self, blender_property, value) -> bool:
  691. change_handled=False
  692. if self.node_type == 'LINK':
  693. if len(self.bObject) == 0: # - there are no downstream xForms
  694. return True # so there is nothing to do here
  695. for b_ob in self.bObject:
  696. try:
  697. setattr(b_ob, blender_property, value)
  698. change_handled=True
  699. except Exception as e:
  700. print("Failed to update mantis socket because of %s" % e,
  701. "Updating tree instead.")
  702. else:
  703. try:
  704. b_ob = self.bObject
  705. if self.node_type == 'XFORM': # HACK
  706. b_ob = self.bGetObject()
  707. setattr(b_ob, blender_property, value)
  708. change_handled=True
  709. except Exception as e:
  710. print("Failed to update mantis socket because of %s" % e,
  711. "Updating tree instead.")
  712. return change_handled
  713. def ui_modify_socket(self, ui_socket, socket_name=None) -> bool:
  714. """ Handle changes in the node's UI. Updates the rig if possible."""
  715. # Always update the node's data
  716. change_handled=False
  717. if socket_name is None: socket_name = ui_socket.name
  718. value = ui_socket.default_value
  719. if socket_name == 'Enable': value = not value
  720. try:
  721. self.parameters[ui_socket.name]=value
  722. except KeyError:
  723. prRed(f"Unhandled change occured in socket {ui_socket.name} in node"
  724. f" {ui_socket.node.name} in tree {ui_socket.node.id_data.name}.")
  725. for s_template in self.socket_templates:
  726. if s_template.name==ui_socket.name:
  727. change_handled = True
  728. if not s_template.blender_property: return False
  729. elif isinstance(s_template.blender_property, str):
  730. change_handled &= self.update_socket_value(
  731. s_template.blender_property, value)
  732. else: # it is a tuple
  733. for i, prop in enumerate(s_template.blender_property):
  734. try:
  735. change_handled &= self.update_socket_value(
  736. prop, value[i])
  737. except IndexError:
  738. prRed(f"{ui_socket.name} does not have enough values to unpack"
  739. " to update the Mantis tree. Please report this as a bug.")
  740. change_handled=False
  741. break # we don't have to look through any more socket templates
  742. return change_handled
  743. # the goal here is to tag the node as unprepared
  744. # but some nodes are always prepared, so we have to kick it forward.
  745. def reset_execution_recursive(self):
  746. self.reset_execution()
  747. if self.prepared==False: return # all good from here
  748. for conn in self.hierarchy_connections:
  749. conn.reset_execution_recursive()
  750. def evaluate_input(self, input_name, index=0) -> Any:
  751. from .node_common import trace_single_line
  752. if not (self.inputs.get(input_name)): # get the named parameter if there is no input
  753. return self.parameters.get(input_name) # this will return None if the parameter does not exist.
  754. # this trace() should give a key error if there is a problem
  755. # it is NOT handled here because it should NOT happen - so I want the error message.
  756. trace = trace_single_line(self, input_name, index)
  757. prop = trace[0][-1].parameters[trace[1].name] #trace[0] = the list of traced nodes; read its parameters
  758. return prop
  759. def fill_parameters(self, ui_node=None) -> None:
  760. from .utilities import get_ui_node
  761. from .node_common import get_socket_value
  762. if not ui_node:
  763. if ( (self.signature[0] in ["MANTIS_AUTOGENERATED", "SCHEMA_AUTOGENERATED" ]) or
  764. (self.signature[-1] in ["NodeGroupOutput", "NodeGroupInput"]) ): # I think this is harmless
  765. return None
  766. else: # BUG shouldn't this use ui_signature??
  767. ui_node = get_ui_node(self.signature, self.base_tree)
  768. if not ui_node:
  769. raise RuntimeError(wrapRed("No UI Node found for... %s" % ( [self.base_tree] + list(self.signature[1:]) ) ) )
  770. for key in self.parameters.keys():
  771. node_socket = ui_node.inputs.get(key)
  772. if self.parameters[key] is not None: # the parameters are usually initialized as None.
  773. continue # will be filled by the node itself
  774. if not node_socket: #maybe the node socket has no name
  775. if ( ( len(ui_node.inputs) == 0) and ( len(ui_node.outputs) == 1) ):
  776. node_socket = ui_node.outputs[0] # this is a simple input node.
  777. elif key == 'Name': # for Links we just use the Node Label, or if there is no label, the name.
  778. self.parameters[key] = ui_node.label if ui_node.label else ui_node.name
  779. continue
  780. if node_socket:
  781. if node_socket.bl_idname in ['RelationshipSocket', 'xFormSocket']: continue
  782. elif node_socket.is_linked and (not node_socket.is_output): continue
  783. # we will get the value from the link, because this is a linked input port.
  784. # very importantly, we do not pass linked outputs
  785. # fill these because they are probably Input nodes.
  786. elif hasattr(node_socket, "default_value"):
  787. if (value := get_socket_value(node_socket)) is not None:
  788. self.parameters[key] = value
  789. else:
  790. raise RuntimeError(wrapRed("No value found for " + self.__repr__() + " when filling out node parameters for " + ui_node.name + "::"+node_socket.name))
  791. # I don't think this works! but I like the idea
  792. def call_on_all_ancestors(self, *args, **kwargs):
  793. """Resolve the dependencies of this node with the named method and its arguments.
  794. First, dependencies are discovered by walking backwards through the tree. Once the root
  795. nodes are discovered, the method is called by each node in dependency order.
  796. The first argument MUST be the name of the method as a string.
  797. """
  798. if args[0] == 'call_on_all_ancestors': raise RuntimeError("Very funny!")
  799. from .utilities import get_all_dependencies
  800. from collections import deque
  801. # get all dependencies by walking backward through the tree.
  802. all_dependencies = get_all_dependencies(self)
  803. # get just the roots
  804. can_solve = deque(filter(lambda a : len(a.hierarchy_connections) == 0, all_dependencies))
  805. solved = set()
  806. while can_solve:
  807. node = can_solve.pop()
  808. method = getattr(node, args[0])
  809. method(*args[0:], **kwargs)
  810. solved.add(node)
  811. can_solve.extendleft(filter(lambda a : a in all_dependencies, node.hierarchy_connections))
  812. if self in solved:
  813. break
  814. return
  815. # gets targets for constraints and deformers and should handle all cases
  816. def get_target_and_subtarget(self, constraint_or_deformer, input_name = "Target"):
  817. from bpy.types import PoseBone, Object, SplineIKConstraint
  818. subtarget = ''; target = self.evaluate_input(input_name)
  819. if target:
  820. if not hasattr(target, "bGetObject"):
  821. if hasattr(constraint_or_deformer, 'name'):
  822. name = constraint_or_deformer.name
  823. else:
  824. name = 'NAME NOT FOUND'
  825. prRed(f"No {input_name} target found for {name} in {self} because there is no connected node, or node is wrong type")
  826. return
  827. if (isinstance(target.bGetObject(), PoseBone)):
  828. subtarget = target.bGetObject().name
  829. target = target.bGetParentArmature()
  830. elif (isinstance(target.bGetObject(), Object) ):
  831. target = target.bGetObject()
  832. else:
  833. raise RuntimeError("Cannot interpret constraint or deformer target!")
  834. if (isinstance(constraint_or_deformer, SplineIKConstraint)):
  835. if target and target.type not in ["CURVE"]:
  836. raise GraphError(wrapRed("Error: %s requires a Curve input, not %s" %
  837. (self, type(target))))
  838. constraint_or_deformer.target = target# don't get a subtarget
  839. if (input_name == 'Pole Target'):
  840. constraint_or_deformer.pole_target, constraint_or_deformer.pole_subtarget = target, subtarget
  841. else:
  842. if hasattr(constraint_or_deformer, "target"):
  843. constraint_or_deformer.target = target
  844. if hasattr(constraint_or_deformer, "object"):
  845. constraint_or_deformer.object = target
  846. if hasattr(constraint_or_deformer, "subtarget"):
  847. constraint_or_deformer.subtarget = subtarget
  848. # PASSES DEFINED HERE!
  849. def bPrepare(self, bContext=None):
  850. return # This one runs BEFORE anything else
  851. def bTransformPass(self, bContext=None):
  852. return # This one runs in EDIT MODE
  853. def bRelationshipPass(self, bContext=None):
  854. return # This one runs in POSE MODE
  855. def bFinalize(self, bContext=None):
  856. return
  857. def bModifierApply(self, bContext=None):
  858. return
  859. if environ.get("DOERROR"):
  860. def __repr__(self):
  861. return self.signature.__repr__()
  862. else:
  863. def __repr__(self):
  864. return self.ui_signature.__repr__()
  865. # do I need this and the link class above?
  866. class DummyLink:
  867. #gonna use this for faking links to keep the interface consistent
  868. def __init__(self, from_socket, to_socket, from_mantis_node=None, to_mantis_node=None, original_from=None, multi_input_sort_id=0):
  869. self.from_socket = from_socket
  870. self.to_socket = to_socket
  871. self.from_mantis_node = from_mantis_node
  872. self.to_mantis_node = to_mantis_node
  873. self.multi_input_sort_id = multi_input_sort_id
  874. # self.from_node = from_socket.node
  875. # self.to_node = to_socket.node
  876. if (original_from):
  877. self.original_from = original_from
  878. else:
  879. self.original_from = self.from_socket
  880. def __repr__(self):
  881. return(self.from_mantis_node.__repr__()+":"+self.from_socket.name + " -> " + self.to_mantis_node.__repr__()+":"+self.to_socket.name)
  882. def detect_hierarchy_link(from_node, from_socket, to_node, to_socket,):
  883. if to_node.node_type in ['DUMMY_SCHEMA', 'SCHEMA']:
  884. return False #TODO: find out if filtering SCHEMA types is wise
  885. if (from_socket in from_name_filter) or (to_socket in to_name_filter):
  886. return False
  887. # if from_node.__class__.__name__ in ["UtilityCombineVector", "UtilityCombineThreeBool"]:
  888. # return False
  889. return True
  890. class NodeLink:
  891. from_node = None
  892. from_socket = None
  893. to_node = None
  894. to_socket = None
  895. def __init__(self, from_node, from_socket, to_node, to_socket, multi_input_sort_id=0, sub_sort_id=0):
  896. if from_node.signature == to_node.signature:
  897. raise RuntimeError("Cannot connect a node to itself.")
  898. self.from_node = from_node
  899. self.from_socket = from_socket
  900. self.to_node = to_node
  901. self.to_socket = to_socket
  902. self.from_node.outputs[self.from_socket].links.append(self)
  903. # it is the responsibility of the node that uses these links to sort them correctly based on the sort_id
  904. self.multi_input_sort_id = multi_input_sort_id # this is the sort_id of the link in the UI
  905. self.sub_sort_id = sub_sort_id # this is for sorting within a bundled link (one link in the UI)
  906. self.to_node.inputs[self.to_socket].links.append(self)
  907. self.is_hierarchy = detect_hierarchy_link(from_node, from_socket, to_node, to_socket,)
  908. self.is_alive = True
  909. def __repr__(self):
  910. return self.from_node.outputs[self.from_socket].__repr__() + " --> " + self.to_node.inputs[self.to_socket].__repr__()
  911. # link_string = # if I need to colorize output for debugging.
  912. # if self.is_hierarchy:
  913. # return wrapOrange(link_string)
  914. # else:
  915. # return wrapWhite(link_string)
  916. def die(self):
  917. self.is_alive = False
  918. self.to_node.inputs[self.to_socket].flush_links()
  919. self.from_node.outputs[self.from_socket].flush_links()
  920. def insert_node(self, middle_node, middle_node_in, middle_node_out, re_init_hierarchy = True):
  921. to_node = self.to_node
  922. to_socket = self.to_socket
  923. self.to_node = middle_node
  924. self.to_socket = middle_node_in
  925. middle_node.outputs[middle_node_out].connect(to_node, to_socket)
  926. if re_init_hierarchy:
  927. from .utilities import init_connections, init_dependencies
  928. init_connections(self.from_node)
  929. init_connections(middle_node)
  930. init_dependencies(middle_node)
  931. init_dependencies(to_node)
  932. class NodeSocket:
  933. # @property # this is a read-only property.
  934. # def is_linked(self):
  935. # return bool(self.links)
  936. def __init__(self, is_input = False,
  937. node = None, name = None,
  938. traverse_target = None):
  939. self.can_traverse = False # to/from the other side of the parent node
  940. self.traverse_target = None
  941. self.node = node
  942. self.name = name
  943. self.is_input = is_input
  944. self.links = []
  945. self.is_linked = False
  946. if (traverse_target):
  947. self.can_traverse = True
  948. def connect(self, node, socket, sort_id=0, sub_sort_id=0):
  949. if (self.is_input):
  950. to_node = self.node; from_node = node
  951. to_socket = self.name; from_socket = socket
  952. else:
  953. from_node = self.node; to_node = node
  954. from_socket = self.name; to_socket = socket
  955. from_node.outputs[from_socket].is_linked = True
  956. to_node.inputs[to_socket].is_linked = True
  957. # NOTE: I have removed a check for duplicate links here.
  958. # Schemas sometimes have valid duplicate links.
  959. # It is conceivable that this will lead to bugs, but I judge it unlikely.
  960. new_link = NodeLink(
  961. from_node,
  962. from_socket,
  963. to_node,
  964. to_socket,
  965. sort_id,
  966. sub_sort_id)
  967. return new_link
  968. def set_traverse_target(self, traverse_target):
  969. self.traverse_target = traverse_target
  970. if traverse_target: self.can_traverse = True
  971. else: self.can_traverse = False
  972. def flush_links(self):
  973. """ Removes dead links from this socket."""
  974. self.links = [l for l in self.links if l.is_alive]
  975. self.links.sort(key=links_sort_key)
  976. self.is_linked = bool(self.links)
  977. @property
  978. def is_connected(self):
  979. return len(self.links)>0
  980. def __repr__(self):
  981. return self.node.__repr__() + "::" + self.name
  982. class MantisNodeSocketCollection(dict):
  983. def __init__(self, node, is_input=False):
  984. self.is_input = is_input
  985. self.node = node
  986. def init_sockets(self, sockets):
  987. for socket in sockets:
  988. if isinstance(socket, str):
  989. self[socket] = NodeSocket(is_input=self.is_input, name=socket, node=self.node)
  990. elif isinstance(socket, MantisSocketTemplate):
  991. if socket.is_input != self.is_input: continue
  992. self[socket.name] = NodeSocket(is_input=self.is_input, name=socket.name, node=self.node)
  993. else:
  994. raise RuntimeError(f"NodeSocketCollection keys must be str or MantisSocketTemplate, not {type(socket)}")
  995. def __delitem__(self, key):
  996. """Deletes a node socket by name, and all its links."""
  997. socket = self[key]
  998. for l in socket.links:
  999. l.die()
  1000. super().__delitem__(key)
  1001. def __iter__(self):
  1002. """Makes the class iterable"""
  1003. return iter(self.values())