base_definitions.py 50 KB

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