base_definitions.py 68 KB

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