base_definitions.py 49 KB

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