base_definitions.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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. class MantisTree(NodeTree):
  33. '''A custom node tree type that will show up in the editor type list'''
  34. bl_idname = 'MantisTree'
  35. bl_label = "Rigging Nodes"
  36. bl_icon = 'OUTLINER_OB_ARMATURE'
  37. tree_valid:BoolProperty(default=False)
  38. do_live_update:BoolProperty(default=True) # use this to disable updates for e.g. scripts
  39. num_links:IntProperty(default=-1)
  40. filepath:StringProperty(default="", subtype='FILE_PATH')
  41. is_executing:BoolProperty(default=False)
  42. is_exporting:BoolProperty(default=False)
  43. execution_id:StringProperty(default='')
  44. mantis_version:IntVectorProperty(default=[0,9,2])
  45. # this prevents the node group from executing on the next depsgraph update
  46. # because I don't always have control over when the dg update happens.
  47. prevent_next_exec:BoolProperty(default=False)
  48. parsed_tree={}
  49. if (bpy.app.version < (4, 4, 0)): # in 4.4 this leads to a crash
  50. @classmethod
  51. def valid_socket_type(cls : NodeTree, socket_idname: str):
  52. return valid_interface_types(cls, socket_idname)
  53. def update_tree(self, context = None):
  54. if self.is_exporting:
  55. return
  56. # return
  57. self.is_executing = True
  58. from . import readtree
  59. prGreen("Validating Tree: %s" % self.name)
  60. try:
  61. self.parsed_tree = readtree.parse_tree(self)
  62. if context:
  63. self.display_update(context)
  64. self.is_executing = False
  65. self.tree_valid = True
  66. except GraphError as e:
  67. prRed("Failed to update node tree due to error.")
  68. self.tree_valid = False
  69. self.is_executing = False
  70. raise e
  71. finally:
  72. self.is_executing = False
  73. def display_update(self, context):
  74. if self.is_exporting:
  75. return
  76. self.is_executing = True
  77. current_tree = bpy.context.space_data.path[-1].node_tree
  78. for node in current_tree.nodes:
  79. if hasattr(node, "display_update"):
  80. try:
  81. node.display_update(self.parsed_tree, context)
  82. except Exception as e:
  83. print("Node \"%s\" failed to update display with error: %s" %(wrapGreen(node.name), wrapRed(e)))
  84. self.is_executing = False
  85. # TODO: deal with invalid links properly.
  86. # - Non-hierarchy links should be ignored in the circle-check and so the links should be marked valid in such a circle
  87. # - hierarchy-links should be marked invalid and prevent the tree from executing.
  88. def execute_tree(self,context, error_popups = False):
  89. self.prevent_next_exec = False
  90. if self.is_exporting:
  91. return
  92. # return
  93. prGreen("Executing Tree: %s" % self.name)
  94. self.is_executing = True
  95. from . import readtree
  96. try:
  97. readtree.execute_tree(self.parsed_tree, self, context, error_popups)
  98. except RecursionError as e:
  99. prRed("Recursion error while parsing tree.")
  100. finally:
  101. self.is_executing = False
  102. class SchemaTree(NodeTree):
  103. '''A node tree representing a schema to generate a Mantis tree'''
  104. bl_idname = 'SchemaTree'
  105. bl_label = "Rigging Nodes Schema"
  106. bl_icon = 'RIGID_BODY_CONSTRAINT'
  107. # these are only needed for consistent interface, but should not be used
  108. do_live_update:BoolProperty(default=True) # default to true so that updates work
  109. is_executing:BoolProperty(default=False)
  110. is_exporting:BoolProperty(default=False)
  111. mantis_version:IntVectorProperty(default=[0,9,2])
  112. if (bpy.app.version < (4, 4, 0)): # in 4.4 this leads to a crash
  113. @classmethod
  114. def valid_socket_type(cls : NodeTree, socket_idname: str):
  115. return valid_interface_types(cls, socket_idname)
  116. from dataclasses import dataclass, field
  117. from typing import Any
  118. @dataclass
  119. class MantisSocketTemplate():
  120. name : str = field(default="")
  121. bl_idname : str = field(default="")
  122. traverse_target : str = field(default="")
  123. identifier : str = field(default="")
  124. display_shape : str = field(default="") # for arrays
  125. category : str = field(default="") # for use in display update
  126. blender_property : str | tuple[str] = field(default="") # for props_sockets -> evaluate sockets
  127. is_input : bool = field(default=False)
  128. hide : bool = field(default=False)
  129. use_multi_input : bool = field(default=False)
  130. default_value : Any = field(default=None)
  131. #TODO: do a better job explaining how MantisNode and MantisUINode relate.
  132. class MantisUINode:
  133. """
  134. This class contains the common user-interface features of Mantis nodes.
  135. MantisUINode objects will spawn one or more MantisNode objects when the graph is evaluated.
  136. The MantisNode objects will pull the data from the UI node and use it to generate the graph.
  137. """
  138. mantis_node_library=''
  139. mantis_node_class_name=''
  140. mantis_class=None
  141. @classmethod
  142. def poll(cls, ntree):
  143. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  144. @classmethod
  145. def set_mantis_class(self):
  146. from importlib import import_module
  147. # do not catch errors, they should cause a failure.
  148. try:
  149. module = import_module(self.mantis_node_library, package=mantis_root)
  150. self.mantis_class=getattr(module, self.mantis_node_class_name)
  151. except Exception as e:
  152. print(self)
  153. raise e
  154. def insert_link(self, link):
  155. if (bpy.app.version > (4, 4, 0)):
  156. return # this causes a crash due to a bug.
  157. context = bpy.context
  158. if context.space_data:
  159. node_tree = context.space_data.path[0].node_tree
  160. if node_tree.do_live_update:
  161. node_tree.update_tree(context)
  162. if (link.to_socket.is_linked == False):
  163. node_tree.num_links+=1
  164. elif (link.to_socket.is_multi_input):
  165. node_tree.num_links+=1
  166. def init_sockets(self, socket_templates : tuple[MantisSocketTemplate]):
  167. for template in socket_templates:
  168. collection = self.outputs
  169. if template.is_input:
  170. collection = self.inputs
  171. identifier = template.name
  172. if template.identifier:
  173. identifier = template.identifier
  174. socket = collection.new(
  175. template.bl_idname,
  176. template.name,
  177. identifier=identifier,
  178. use_multi_input=template.use_multi_input
  179. )
  180. socket.hide= template.hide
  181. if template.category:
  182. # a custom property for the UI functions to use.
  183. socket['category'] = template.category
  184. if template.default_value is not None:
  185. socket.default_value = template.default_value
  186. # this can throw a TypeError - it is the caller's
  187. # responsibility to send the right type.
  188. class SchemaUINode(MantisUINode):
  189. mantis_node_library='.schema_containers'
  190. @classmethod
  191. def poll(cls, ntree):
  192. return (ntree.bl_idname in ['SchemaTree'])
  193. class LinkNode(MantisUINode):
  194. mantis_node_library='.link_containers'
  195. @classmethod
  196. def poll(cls, ntree):
  197. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  198. class xFormNode(MantisUINode):
  199. mantis_node_library='.xForm_containers'
  200. @classmethod
  201. def poll(cls, ntree):
  202. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  203. class DeformerNode(MantisUINode):
  204. mantis_node_library='.deformer_containers'
  205. @classmethod
  206. def poll(cls, ntree):
  207. return (ntree.bl_idname in ['MantisTree', 'SchemaTree'])
  208. def poll_node_tree(self, object):
  209. if isinstance(object, MantisTree):
  210. return True
  211. return False
  212. # TODO: try to check identifiers instead of name.
  213. def node_group_update(node, force = False):
  214. if not node.is_updating:
  215. raise RuntimeError("Cannot update node while it is not marked as updating.")
  216. if not force:
  217. if (node.id_data.do_live_update == False) or \
  218. (node.id_data.is_executing == True) or \
  219. (node.id_data.is_exporting == True):
  220. return
  221. # note: if (node.id_data.is_exporting == True) I need to be able to update so I can make links.
  222. toggle_update = node.id_data.do_live_update
  223. node.id_data.do_live_update = False
  224. identifiers_in={socket.identifier:socket for socket in node.inputs}
  225. identifiers_out={socket.identifier:socket for socket in node.outputs}
  226. indices_in,indices_out={},{} # check by INDEX to see if the socket's name/type match.
  227. for collection, map in [(node.inputs, indices_in), (node.outputs, indices_out)]:
  228. for i, socket in enumerate(collection):
  229. map[socket.identifier]=i
  230. if node.node_tree is None:
  231. node.inputs.clear(); node.outputs.clear()
  232. node.id_data.do_live_update = toggle_update
  233. return
  234. found_in, found_out = [], []
  235. update_input, update_output = False, False
  236. for item in node.node_tree.interface.items_tree:
  237. if item.item_type != "SOCKET": continue
  238. if item.in_out == 'OUTPUT':
  239. if s:= identifiers_out.get(item.identifier): # if the requested output doesn't exist, update
  240. found_out.append(item.identifier)
  241. if (indices_out[s.identifier]!=item.index): update_output=True; continue
  242. if update_output: continue
  243. if s.bl_idname != item.socket_type: update_output = True; continue
  244. else: update_output = True; continue
  245. else:
  246. if s:= identifiers_in.get(item.identifier): # if the requested input doesn't exist, update
  247. found_in.append(item.identifier)
  248. if (indices_in[s.identifier]!=item.index): update_input=True; continue
  249. if update_input: continue # done here
  250. if s.bl_idname != item.socket_type: update_input = True; continue
  251. else: update_input = True; continue
  252. # Schema has an extra input for Length and for Extend.
  253. if node.bl_idname == 'MantisSchemaGroup':
  254. found_in.extend(['Schema Length', ''])
  255. # if we have too many elements, just get rid of the ones we don't need
  256. if len(node.inputs) > len(found_in):#
  257. for inp in node.inputs:
  258. if inp.identifier in found_in: continue
  259. node.inputs.remove(inp)
  260. if len(node.outputs) > len(found_out):
  261. for out in node.outputs:
  262. if out.identifier in found_out: continue
  263. node.outputs.remove(out)
  264. #
  265. if len(node.inputs) > 0 and (inp := node.inputs[-1]).bl_idname == 'WildcardSocket' and inp.is_linked:
  266. update_input = True
  267. if len(node.outputs) > 0 and (out := node.outputs[-1]).bl_idname == 'WildcardSocket' and out.is_linked:
  268. update_output = True
  269. #
  270. if not (update_input or update_output):
  271. node.id_data.do_live_update = toggle_update
  272. return
  273. if update_input or update_output:
  274. socket_map_in, socket_map_out = None, None
  275. socket_maps = get_socket_maps(node)
  276. if socket_maps is None and force == False:
  277. node.id_data.do_live_update = toggle_update
  278. return
  279. if socket_maps:
  280. socket_map_in, socket_map_out = socket_maps
  281. if update_input :
  282. if node.bl_idname == 'MantisSchemaGroup':
  283. schema_length=0
  284. if sl := node.inputs.get("Schema Length"):
  285. schema_length = sl.default_value
  286. # sometimes this isn't available yet # TODO not happy about this solution
  287. node.inputs.clear()
  288. if node.bl_idname == 'MantisSchemaGroup':
  289. node.inputs.new("IntSocket", "Schema Length", identifier='Schema Length')
  290. node.inputs['Schema Length'].default_value = schema_length
  291. if update_output: node.outputs.clear()
  292. from .utilities import relink_socket_map_add_socket
  293. for item in node.node_tree.interface.items_tree:
  294. if item.item_type != "SOCKET": continue
  295. if (item.in_out == 'INPUT' and update_input):
  296. socket = relink_socket_map_add_socket(node, node.inputs, item)
  297. if socket_map_in:
  298. do_relink(node, socket, socket_map_in)
  299. if (item.in_out == 'OUTPUT' and update_output):
  300. socket = relink_socket_map_add_socket(node, node.outputs, item)
  301. if socket_map_out:
  302. do_relink(node, socket, socket_map_out)
  303. # at this point there is no wildcard socket
  304. if socket_map_in and '__extend__' in socket_map_in.keys():
  305. do_relink(node, None, socket_map_in, in_out='INPUT', parent_name='Constant' )
  306. node.id_data.do_live_update = toggle_update
  307. def node_tree_prop_update(self, context):
  308. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  309. return # so we check if an update is currently running.
  310. self.is_updating = True
  311. try:
  312. node_group_update(self)
  313. finally: # ensure this line is run even if there is an error
  314. self.is_updating = False
  315. if self.bl_idname in ['MantisSchemaGroup'] and self.node_tree is not None:
  316. if len(self.inputs) == 0:
  317. self.inputs.new("IntSocket", "Schema Length", identifier='Schema Length')
  318. if self.inputs[-1].bl_idname != "WildcardSocket":
  319. self.inputs.new("WildcardSocket", "", identifier="__extend__")
  320. from bpy.types import NodeCustomGroup
  321. class MantisNodeGroup(Node, MantisUINode):
  322. bl_idname = "MantisNodeGroup"
  323. bl_label = "Node Group"
  324. node_tree:PointerProperty(type=NodeTree, poll=poll_node_tree, update=node_tree_prop_update,)
  325. is_updating:BoolProperty(default=False)
  326. def update(self):
  327. live_update = self.id_data.do_live_update
  328. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  329. return # so we check if an update is currently running.
  330. try:
  331. self.is_updating = True
  332. node_group_update(self)
  333. finally: # we need to reset this regardless of whether or not the operation succeeds!
  334. self.is_updating = False
  335. self.id_data.do_live_update = live_update # ensure this remains the same
  336. def draw_buttons(self, context, layout):
  337. row = layout.row(align=True)
  338. row.prop(self, "node_tree", text="")
  339. row.operator("mantis.edit_group", text="", icon='NODETREE', emboss=True)
  340. class GraphError(Exception):
  341. pass
  342. def get_signature_from_edited_tree(node, context):
  343. sig_path=[None,]
  344. for item in context.space_data.path[:-1]:
  345. sig_path.append(item.node_tree.nodes.active.name)
  346. return tuple(sig_path+[node.name])
  347. def poll_node_tree_schema(self, object):
  348. if isinstance(object, SchemaTree):
  349. return True
  350. return False
  351. # TODO tiny UI problem - inserting new links into the tree will not place them in the right place.
  352. class SchemaGroup(Node, MantisUINode):
  353. bl_idname = "MantisSchemaGroup"
  354. bl_label = "Node Schema"
  355. node_tree:PointerProperty(type=NodeTree, poll=poll_node_tree_schema, update=node_tree_prop_update,)
  356. is_updating:BoolProperty(default=False)
  357. def draw_buttons(self, context, layout):
  358. row = layout.row(align=True)
  359. row.prop(self, "node_tree", text="")
  360. row.operator("mantis.edit_group", text="", icon='NODETREE', emboss=True)
  361. def update(self):
  362. live_update = self.id_data.do_live_update
  363. if self.is_updating: # update() can be called from update() and that leads to an infinite loop.
  364. return # so we check if an update is currently running.
  365. self.is_updating = True
  366. try:
  367. node_group_update(self)
  368. # reset things if necessary:
  369. if self.node_tree:
  370. if len(self.inputs) == 0:
  371. self.inputs.new("IntSocket", "Schema Length", identifier='Schema Length')
  372. if self.inputs[-1].identifier != "__extend__":
  373. self.inputs.new("WildcardSocket", "", identifier="__extend__")
  374. finally: # we need to reset this regardless of whether or not the operation succeeds!
  375. self.is_updating = False
  376. self.id_data.do_live_update = live_update # ensure this remains the same
  377. NODES_REMOVED=["xFormRootNode"]
  378. # Node bl_idname, # Socket Name
  379. SOCKETS_REMOVED=[("UtilityDriverVariable", "Transform Channel"),
  380. ("xFormRootNode","World Out"),
  381. ("UtilitySwitch","xForm"),
  382. ("LinkDrivenParameter", "Enable")]
  383. # Node Class #Prior bl_idname # prior name # new bl_idname # new name, # Multi
  384. SOCKETS_RENAMED=[ ("LinkDrivenParameter", "DriverSocket", "Driver", "FloatSocket", "Value", False)]
  385. # NODE CLASS NAME IN_OUT SOCKET TYPE SOCKET NAME INDEX MULTI DEFAULT
  386. SOCKETS_ADDED=[("DeformerMorphTargetDeform", 'INPUT', 'BooleanSocket', "Use Shape Key", 1, False, False),
  387. ("DeformerMorphTargetDeform", 'INPUT', 'BooleanSocket', "Use Offset", 2, False, True),
  388. ("UtilityFCurve", 'INPUT', "eFCrvExtrapolationMode", "Extrapolation Mode", 0, False, 'CONSTANT'),
  389. ("LinkCopyScale", 'INPUT', "BooleanSocket", "Additive", 3, False, False)]
  390. # replace names with bl_idnames for reading the tree and solving schemas.
  391. replace_types = ["NodeGroupInput", "NodeGroupOutput", "SchemaIncomingConnection",
  392. "SchemaArrayInput", "SchemaConstInput", "SchemaConstOutput", "SchemaIndex",
  393. "SchemaOutgoingConnection", "SchemaConstantOutput", "SchemaArrayOutput",
  394. "SchemaArrayInputGet",]
  395. # anything that gets properties added in the graph... this is a clumsy approach but I need to watch for this
  396. # in schema generation and this is the easiest way to do it for now.
  397. custom_props_types = ["LinkArmature", "UtilityKeyframe", "UtilityFCurve", "UtilityDriver", "xFormBone"]
  398. # filters for determining if a link is a hierarchy link or a non-hierarchy (cyclic) link.
  399. from_name_filter = ["Driver",]
  400. to_name_filter = [
  401. "Custom Object xForm Override",
  402. "Custom Object",
  403. "Deform Bones",
  404. ]
  405. class MantisNode:
  406. """
  407. This class contains the basic interface for a Mantis Node.
  408. A MantisNode is used internally by Mantis to represent the final evaluated node graph.
  409. It gets generated with data from a MantisUINode when the graph is read.
  410. """
  411. def __init__(self, signature : tuple,
  412. base_tree : bpy.types.NodeTree,
  413. socket_templates : list[MantisSocketTemplate]=[]):
  414. self.base_tree=base_tree
  415. self.signature = signature
  416. self.inputs = MantisNodeSocketCollection(node=self, is_input=True)
  417. self.outputs = MantisNodeSocketCollection(node=self, is_input=False)
  418. self.parameters = {}
  419. self.drivers = {}
  420. self.node_type='UNINITIALIZED'
  421. self.hierarchy_connections, self.connections = [], []
  422. self.hierarchy_dependencies, self.dependencies = [], []
  423. self.prepared = False
  424. self.executed = False
  425. self.socket_templates = socket_templates
  426. if self.socket_templates:
  427. self.init_sockets()
  428. def init_sockets(self) -> None:
  429. self.inputs.init_sockets(self.socket_templates)
  430. self.outputs.init_sockets(self.socket_templates)
  431. def init_parameters(self, additional_parameters = {}) -> None:
  432. for socket in self.inputs:
  433. self.parameters[socket.name] = None
  434. for socket in self.outputs:
  435. self.parameters[socket.name] = None
  436. for key, value in additional_parameters.items():
  437. self.parameters[key]=value
  438. def gen_property_socket_map(self) -> dict:
  439. props_sockets = {}
  440. for s_template in self.socket_templates:
  441. if not s_template.blender_property:
  442. continue
  443. if isinstance(s_template.blender_property, str):
  444. props_sockets[s_template.blender_property]=(s_template.name, s_template.default_value)
  445. elif isinstance(s_template.blender_property, tuple):
  446. for index, sub_prop in enumerate(s_template.blender_property):
  447. props_sockets[sub_prop]=( (s_template.name, index),s_template.default_value[index] )
  448. return props_sockets
  449. def set_traverse(self, traversal_pairs = [(str, str)]) -> None:
  450. for (a, b) in traversal_pairs:
  451. self.inputs[a].set_traverse_target(self.outputs[b])
  452. self.outputs[b].set_traverse_target(self.inputs[a])
  453. def flush_links(self) -> None:
  454. for inp in self.inputs.values():
  455. inp.flush_links()
  456. for out in self.outputs.values():
  457. out.flush_links()
  458. def evaluate_input(self, input_name, index=0) -> Any:
  459. from .node_container_common import trace_single_line
  460. if not (self.inputs.get(input_name)): # get the named parameter if there is no input
  461. return self.parameters.get(input_name) # this will return None if the parameter does not exist.
  462. # this trace() should give a key error if there is a problem
  463. # it is NOT handled here because it should NOT happen - so I want the error message.
  464. trace = trace_single_line(self, input_name, index)
  465. prop = trace[0][-1].parameters[trace[1].name] #trace[0] = the list of traced nodes; read its parameters
  466. return prop
  467. def fill_parameters(self, ui_node=None) -> None:
  468. from .utilities import get_node_prototype
  469. from .node_container_common import get_socket_value
  470. if not ui_node:
  471. if ( (self.signature[0] in ["MANTIS_AUTOGENERATED", "SCHEMA_AUTOGENERATED" ]) or
  472. (self.signature[-1] in ["NodeGroupOutput", "NodeGroupInput"]) ): # I think this is harmless
  473. return None
  474. else:
  475. ui_node = get_node_prototype(self.signature, self.base_tree)
  476. if not ui_node:
  477. raise RuntimeError(wrapRed("No node prototype found for... %s" % ( [self.base_tree] + list(self.signature[1:]) ) ) )
  478. for key in self.parameters.keys():
  479. node_socket = ui_node.inputs.get(key)
  480. if self.parameters[key] is not None: # the parameters are usually initialized as None.
  481. continue # will be filled by the node itself
  482. if not node_socket: #maybe the node socket has no name
  483. if ( ( len(ui_node.inputs) == 0) and ( len(ui_node.outputs) == 1) ):
  484. # this is a simple input node.
  485. node_socket = ui_node.outputs[0]
  486. elif key == 'Name': # for Links we just use the Node Label, or if there is no label, the name.
  487. self.parameters[key] = ui_node.label if ui_node.label else ui_node.name
  488. continue
  489. else:
  490. pass
  491. if node_socket:
  492. if node_socket.bl_idname in ['RelationshipSocket', 'xFormSocket']:
  493. continue
  494. elif node_socket.is_linked and (not node_socket.is_output):
  495. pass # we will get the value from the link, because this is a linked input port.
  496. # very importantly, we do not pass linked outputs- fill these because they are probably Input nodes.
  497. elif hasattr(node_socket, "default_value"):
  498. if (value := get_socket_value(node_socket)) is not None:
  499. self.parameters[key] = value
  500. # TODO: try and remove the input if it is not needed (for performance speed)
  501. else:
  502. raise RuntimeError(wrapRed("No value found for " + self.__repr__() + " when filling out node parameters for " + ui_node.name + "::"+node_socket.name))
  503. else:
  504. pass
  505. # I don't think this works! but I like the idea
  506. def call_on_all_ancestors(self, *args, **kwargs):
  507. """Resolve the dependencies of this node with the named method and its arguments.
  508. First, dependencies are discovered by walking backwards through the tree. Once the root
  509. nodes are discovered, the method is called by each node in dependency order.
  510. The first argument MUST be the name of the method as a string.
  511. """
  512. prGreen(self)
  513. if args[0] == 'call_on_all_ancestors': raise RuntimeError("Very funny!")
  514. from .utilities import get_all_dependencies
  515. from collections import deque
  516. # get all dependencies by walking backward through the tree.
  517. all_dependencies = get_all_dependencies(self)
  518. # get just the roots
  519. can_solve = deque(filter(lambda a : len(a.hierarchy_connections) == 0, all_dependencies))
  520. solved = set()
  521. while can_solve:
  522. node = can_solve.pop()
  523. print(node)
  524. method = getattr(node, args[0])
  525. method(*args[0:], **kwargs)
  526. solved.add(node)
  527. can_solve.extendleft(filter(lambda a : a in all_dependencies, node.hierarchy_connections))
  528. # prPurple(can_solve)
  529. if self in solved:
  530. break
  531. # else:
  532. # for dep in all_dependencies:
  533. # if dep not in solved:
  534. # prOrange(dep)
  535. return
  536. # gets targets for constraints and deformers and should handle all cases
  537. def get_target_and_subtarget(self, constraint_or_deformer, input_name = "Target"):
  538. from bpy.types import PoseBone, Object, SplineIKConstraint
  539. subtarget = ''; target = self.evaluate_input(input_name)
  540. if target:
  541. if not hasattr(target, "bGetObject"):
  542. 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")
  543. return
  544. if (isinstance(target.bGetObject(), PoseBone)):
  545. subtarget = target.bGetObject().name
  546. target = target.bGetParentArmature()
  547. elif (isinstance(target.bGetObject(), Object) ):
  548. target = target.bGetObject()
  549. else:
  550. raise RuntimeError("Cannot interpret constraint or deformer target!")
  551. if (isinstance(constraint_or_deformer, SplineIKConstraint)):
  552. if target and target.type not in ["CURVE"]:
  553. raise GraphError(wrapRed("Error: %s requires a Curve input, not %s" %
  554. (self, type(target))))
  555. constraint_or_deformer.target = target# don't get a subtarget
  556. if (input_name == 'Pole Target'):
  557. constraint_or_deformer.pole_target, constraint_or_deformer.pole_subtarget = target, subtarget
  558. else:
  559. if hasattr(constraint_or_deformer, "target"):
  560. constraint_or_deformer.target = target
  561. if hasattr(constraint_or_deformer, "object"):
  562. constraint_or_deformer.object = target
  563. if hasattr(constraint_or_deformer, "subtarget"):
  564. constraint_or_deformer.subtarget = subtarget
  565. def bPrepare(self, bContext=None):
  566. return
  567. def bExecute(self, bContext=None):
  568. return
  569. def bFinalize(self, bContext=None):
  570. return
  571. def __repr__(self):
  572. return self.signature.__repr__()
  573. # do I need this and the link class above?
  574. class DummyLink:
  575. #gonna use this for faking links to keep the interface consistent
  576. def __init__(self, from_socket, to_socket, nc_from=None, nc_to=None, original_from=None, multi_input_sort_id=0):
  577. self.from_socket = from_socket
  578. self.to_socket = to_socket
  579. self.nc_from = nc_from
  580. self.nc_to = nc_to
  581. self.multi_input_sort_id = multi_input_sort_id
  582. # self.from_node = from_socket.node
  583. # self.to_node = to_socket.node
  584. if (original_from):
  585. self.original_from = original_from
  586. else:
  587. self.original_from = self.from_socket
  588. def __repr__(self):
  589. return(self.nc_from.__repr__()+":"+self.from_socket.name + " -> " + self.nc_to.__repr__()+":"+self.to_socket.name)
  590. def detect_hierarchy_link(from_node, from_socket, to_node, to_socket,):
  591. if to_node.node_type in ['DUMMY_SCHEMA', 'SCHEMA']:
  592. return False
  593. if (from_socket in from_name_filter) or (to_socket in to_name_filter):
  594. return False
  595. # if from_node.__class__.__name__ in ["UtilityCombineVector", "UtilityCombineThreeBool"]:
  596. # return False
  597. return True
  598. class NodeLink:
  599. from_node = None
  600. from_socket = None
  601. to_node = None
  602. to_socket = None
  603. def __init__(self, from_node, from_socket, to_node, to_socket, multi_input_sort_id=0):
  604. if from_node.signature == to_node.signature:
  605. raise RuntimeError("Cannot connect a node to itself.")
  606. self.from_node = from_node
  607. self.from_socket = from_socket
  608. self.to_node = to_node
  609. self.to_socket = to_socket
  610. self.from_node.outputs[self.from_socket].links.append(self)
  611. # it is the responsibility of the node that uses these links to sort them correctly based on the sort_id
  612. self.multi_input_sort_id = multi_input_sort_id
  613. self.to_node.inputs[self.to_socket].links.append(self)
  614. self.is_hierarchy = detect_hierarchy_link(from_node, from_socket, to_node, to_socket,)
  615. self.is_alive = True
  616. def __repr__(self):
  617. return self.from_node.outputs[self.from_socket].__repr__() + " --> " + self.to_node.inputs[self.to_socket].__repr__()
  618. # link_string = # if I need to colorize output for debugging.
  619. # if self.is_hierarchy:
  620. # return wrapOrange(link_string)
  621. # else:
  622. # return wrapWhite(link_string)
  623. def die(self):
  624. self.is_alive = False
  625. self.to_node.inputs[self.to_socket].flush_links()
  626. self.from_node.outputs[self.from_socket].flush_links()
  627. def insert_node(self, middle_node, middle_node_in, middle_node_out, re_init_hierarchy = True):
  628. to_node = self.to_node
  629. to_socket = self.to_socket
  630. self.to_node = middle_node
  631. self.to_socket = middle_node_in
  632. middle_node.outputs[middle_node_out].connect(to_node, to_socket)
  633. if re_init_hierarchy:
  634. from .utilities import init_connections, init_dependencies
  635. init_connections(self.from_node)
  636. init_connections(middle_node)
  637. init_dependencies(middle_node)
  638. init_dependencies(to_node)
  639. class NodeSocket:
  640. # @property # this is a read-only property.
  641. # def is_linked(self):
  642. # return bool(self.links)
  643. def __init__(self, is_input = False,
  644. node = None, name = None,
  645. traverse_target = None):
  646. self.can_traverse = False # to/from the other side of the parent node
  647. self.traverse_target = None
  648. self.node = node
  649. self.name = name
  650. self.is_input = is_input
  651. self.links = []
  652. self.is_linked = False
  653. if (traverse_target):
  654. self.can_traverse = True
  655. def connect(self, node, socket, sort_id=0):
  656. if (self.is_input):
  657. to_node = self.node; from_node = node
  658. to_socket = self.name; from_socket = socket
  659. else:
  660. from_node = self.node; to_node = node
  661. from_socket = self.name; to_socket = socket
  662. from_node.outputs[from_socket].is_linked = True
  663. to_node.inputs[to_socket].is_linked = True
  664. for l in from_node.outputs[from_socket].links:
  665. if l.to_node==to_node and l.to_socket==to_socket:
  666. return None
  667. new_link = NodeLink(
  668. from_node,
  669. from_socket,
  670. to_node,
  671. to_socket,
  672. sort_id)
  673. return new_link
  674. def set_traverse_target(self, traverse_target):
  675. self.traverse_target = traverse_target
  676. self.can_traverse = True
  677. def flush_links(self):
  678. """ Removes dead links from this socket."""
  679. self.links = [l for l in self.links if l.is_alive]
  680. self.is_linked = bool(self.links)
  681. @property
  682. def is_connected(self):
  683. return len(self.links)>0
  684. def __repr__(self):
  685. return self.node.__repr__() + "::" + self.name
  686. class MantisNodeSocketCollection(dict):
  687. def __init__(self, node, is_input=False):
  688. self.is_input = is_input
  689. self.node = node
  690. def init_sockets(self, sockets):
  691. for socket in sockets:
  692. if isinstance(socket, str):
  693. self[socket] = NodeSocket(is_input=self.is_input, name=socket, node=self.node)
  694. elif isinstance(socket, MantisSocketTemplate):
  695. if socket.is_input != self.is_input: continue
  696. self[socket.name] = NodeSocket(is_input=self.is_input, name=socket.name, node=self.node)
  697. else:
  698. raise RuntimeError(f"NodeSocketCollection keys must be str or MantisSocketTemplate, not {type(socket)}")
  699. def __delitem__(self, key):
  700. """Deletes a node socket by name, and all its links."""
  701. socket = self[key]
  702. for l in socket.links:
  703. l.die()
  704. super().__delitem__(key)
  705. def __iter__(self):
  706. """Makes the class iterable"""
  707. return iter(self.values())
  708. # The Mantis Solver class is used to store the execution-specific variables that are used
  709. # when executing the tree
  710. class MantisSolver():
  711. pass
  712. # GOAL: make the switch to "group overlay" paradigm