base_definitions.py 49 KB

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