base_definitions.py 44 KB

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