base_definitions.py 55 KB

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