base_definitions.py 48 KB

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