base_definitions.py 52 KB

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