readtree.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. from ..utilities.utilities import prRed, prGreen, prPurple, prWhite, prOrange, \
  2. wrapRed, wrapGreen, wrapPurple, wrapWhite, wrapOrange
  3. # FIXME I don't think these signatures are unique.
  4. # TODO this is a really silly and bad and also really dumb way to do this
  5. def insert_lazy_parents(mantis_node):
  6. from ..link_nodes import LinkInherit
  7. inherit_node = None
  8. if mantis_node.inputs["Relationship"].is_connected:
  9. from ..utilities.node_common import trace_single_line_safe
  10. # BUG this line can create infinite loops
  11. node_line, last_socket = trace_single_line_safe(mantis_node, 'Relationship')
  12. # if last_socket is from a valid XFORM, it is the relationship in
  13. # because it was traversed from the xForm Out... so get the traverse target.
  14. if last_socket.traverse_target is None:
  15. return # this is not a valid lazy parent.
  16. for other_node in node_line[1:]: # skip the first one, it is the same node
  17. if other_node.node_type == 'LINK':
  18. return # this one has a realtionship connection.
  19. elif other_node.node_type == 'XFORM':
  20. break
  21. if other_node.node_type in ["XFORM"] and last_socket.traverse_target.name in ["xForm Out"]:
  22. for link in other_node.outputs['xForm Out'].links:
  23. if link.to_node == mantis_node: link.die()
  24. inherit_node = LinkInherit(("MANTIS_AUTOGENERATED", *mantis_node.signature[1:], "LAZY_INHERIT"), mantis_node.base_tree)
  25. l = other_node.outputs['xForm Out'].connect(inherit_node, 'Parent')
  26. l1 = inherit_node.outputs['Inheritance'].connect(mantis_node, 'Relationship')
  27. inherit_node.parameters = { "Parent":None,
  28. "Inherit Rotation":True,
  29. "Inherit Scale":'FULL',
  30. "Connected":False, }
  31. # because the from node may have already been done.
  32. init_connections(other_node); init_dependencies(other_node)
  33. init_connections(inherit_node); init_dependencies(inherit_node)
  34. return inherit_node
  35. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  36. # DATA FROM NODES #
  37. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  38. from ..base_definitions import replace_types, NodeSocket
  39. def autogen_node(base_tree, ui_socket, signature, mContext):
  40. mantis_node=None
  41. from ..internal_nodes import AutoGenNode
  42. mantis_node = AutoGenNode(signature, base_tree)
  43. mantis_node.mContext = mContext
  44. mantis_node.outputs[ui_socket.name] = NodeSocket(is_input=False, name=ui_socket.name, node=mantis_node)
  45. mantis_node.ui_signature = None # does not exist in the UI
  46. return mantis_node
  47. # TODO: investigate whether I can set the properties in the downstream nodes directly.
  48. # I am doing this in Schema Solver and it seems to work quite efficiently.
  49. def make_connections_to_ng_dummy(base_tree, tree_path_names, local_mantis_nodes, all_mantis_nodes, to_mantis_node):
  50. from ..socket_definitions import no_default_value
  51. for inp in to_mantis_node.ui_node.inputs:
  52. if inp.bl_idname in no_default_value:
  53. continue
  54. from_mantis_node = None
  55. to_s = inp.identifier
  56. if not inp.is_linked: # make an autogenerated NC for the inputs of the group node
  57. # This can be run inside schema. Make it unique with uuid() to be safe.
  58. from uuid import uuid4
  59. signature = ("MANTIS_AUTOGENERATED", *tree_path_names, to_mantis_node.ui_signature[-1], inp.name, inp.identifier, str(uuid4()))
  60. from_mantis_node = all_mantis_nodes.get(signature) # creating this without checking and
  61. # using UUID signature leads to TERRIBLE CONFUSING BUGS.
  62. if from_mantis_node is None:
  63. from_mantis_node = autogen_node(base_tree, inp, signature, to_mantis_node.mContext)
  64. from ..utilities.node_common import get_socket_value
  65. if from_mantis_node: # autogen can fail and we should catch it.
  66. from_mantis_node.parameters = {inp.name:get_socket_value(inp)}
  67. local_mantis_nodes[signature] = from_mantis_node; all_mantis_nodes[signature] = from_mantis_node
  68. from_mantis_node.outputs[inp.name].connect(node=to_mantis_node, socket=to_s, sort_id=0)
  69. else:
  70. prRed("No available auto-generated class for input %s in %s" % (inp.name, np.name))
  71. def gen_mantis_nodes(base_tree, current_tree, tree_path_names, mContext, all_mantis_nodes, local_mantis_nodes, dummy_nodes, group_nodes, schema_nodes, in_schema ):
  72. from ..internal_nodes import DummyNode
  73. for ui_node in current_tree.nodes:
  74. if ui_node.bl_idname in ["NodeFrame", "NodeReroute"]:
  75. continue # not a Mantis Node
  76. if ui_node.bl_idname in ["NodeGroupInput", "NodeGroupOutput"]:
  77. # we only want ONE dummy in/out per tree_path, so use the bl_idname to make a Dummy node
  78. sig = (None, *tree_path_names, ui_node.bl_idname)
  79. ui_sig = (None, *tree_path_names, ui_node.name)
  80. if not local_mantis_nodes.get(sig):
  81. mantis_node = DummyNode( signature=sig , base_tree=base_tree, ui_node=ui_node, ui_signature=ui_sig )
  82. local_mantis_nodes[sig] = mantis_node; all_mantis_nodes[sig] = mantis_node; dummy_nodes[sig] = mantis_node
  83. if ui_node.bl_idname in ["NodeGroupOutput"]:
  84. mantis_node.reroute_links_type = 'out'
  85. elif ui_node.bl_idname in ["MantisNodeGroup", "MantisSchemaGroup"]:
  86. mantis_node = DummyNode( signature= (sig := (None, *tree_path_names, ui_node.name) ), base_tree=base_tree, ui_node=ui_node )
  87. local_mantis_nodes[sig] = mantis_node; all_mantis_nodes[sig] = mantis_node; dummy_nodes[sig] = mantis_node
  88. make_connections_to_ng_dummy(base_tree, tree_path_names, local_mantis_nodes, all_mantis_nodes, mantis_node)
  89. group_nodes.append(mantis_node)
  90. if ui_node.bl_idname == "MantisNodeGroup":
  91. mantis_node.reroute_links_type = 'group'
  92. else:
  93. mantis_node.reroute_links_type = 'schema'
  94. schema_nodes[sig] = mantis_node
  95. # if it wasn't the types we ignore or the types we make a Dummy for, use this to catch all non-special cases.
  96. elif (mantis_class := ui_node.mantis_class):
  97. sig = (None, *tree_path_names, ui_node.name)
  98. if ui_node.bl_idname in replace_types:
  99. sig = (None, *tree_path_names, ui_node.bl_idname)
  100. if local_mantis_nodes.get(sig):
  101. continue # already made
  102. print (mantis_class)
  103. mantis_node = mantis_class( sig , base_tree)
  104. local_mantis_nodes[sig] = mantis_node; all_mantis_nodes[sig] = mantis_node
  105. mantis_node.ui_signature = (*mantis_node.ui_signature[:-1], ui_node.name) # just to ensure it points to a real node.
  106. else:
  107. mantis_node = None
  108. prRed(f"Can't make mantis_node for.. {ui_node.bl_idname}")
  109. # this should be done at init
  110. mantis_node.mContext = mContext
  111. if mantis_node.signature[0] not in ['MANTIS_AUTOGENERATED'] and mantis_node.node_type not in ['SCHEMA', 'DUMMY', 'DUMMY_SCHEMA']:
  112. mantis_node.fill_parameters()
  113. mantis_node.is_schema_prototype = in_schema
  114. def data_from_tree(base_tree, tree_path, mContext, dummy_nodes, all_mantis_nodes, all_schema, in_schema):#
  115. # TODO: it should be relatively easy to make this use a while loop instead of recursion.
  116. local_mantis_nodes, group_nodes = {}, []
  117. tree_path_names = [tree.name for tree in tree_path if hasattr(tree, "name")]
  118. if tree_path[-1]:
  119. current_tree = tree_path[-1].node_tree # this may be None.
  120. else:
  121. current_tree = base_tree
  122. #
  123. if current_tree: # the node-group may not have a tree set - if so, ignore it.
  124. if not in_schema:
  125. in_schema = current_tree.bl_idname in ['SchemaTree']
  126. from ..utilities.utilities import clear_reroutes
  127. links = clear_reroutes(list(current_tree.links))
  128. gen_mantis_nodes(base_tree, current_tree, tree_path_names, mContext, all_mantis_nodes, local_mantis_nodes, dummy_nodes, group_nodes, all_schema, in_schema)
  129. from ..utilities.utilities import link_mantis_nodes
  130. for link in links:
  131. link_mantis_nodes((None, *tree_path_names), link, local_mantis_nodes)
  132. if current_tree == base_tree:
  133. # in the base tree, we need to auto-gen the default values in a slightly different way to node groups.
  134. insert_default_values_base_tree(base_tree, all_mantis_nodes)
  135. # Now, descend into the Node Groups and recurse
  136. for mantis_node in group_nodes:
  137. data_from_tree(base_tree, tree_path+[mantis_node.ui_node], mContext, dummy_nodes, all_mantis_nodes, all_schema, in_schema)
  138. return dummy_nodes, all_mantis_nodes, all_schema
  139. STRING_PADDING = 4
  140. overlay_valid_socket_types = [
  141. "FloatSocket", "FloatPositiveSocket", "FloatFactorSocket",
  142. "FloatAngleSocket", "UnsignedIntSocket", "IntSocket", "StringSocket",
  143. ]
  144. # Do not use these input names as overlay keys:
  145. forbidden_key_names = ["",]
  146. forbidden_in_key_name = ['$',]
  147. def node_scan_overlays(node, socket_id,):
  148. from ..utilities.node_common import GraphError
  149. interface_nodes = node.mContext.interface_nodes
  150. from ..utilities.utilities import get_ui_node
  151. ui_node = get_ui_node(node.ui_signature, node.base_tree)
  152. # we'll assume that the overlay tag system checked if this is linked.
  153. # First let's check if it is a simple input node, by checking outputs that are marked "input"
  154. for socket in ui_node.outputs:
  155. # weird edge case for simple input nodes with unnamed sockets
  156. # the socket.identifier is not used by Mantis but it defaults to 'socket'\
  157. if socket.identifier == socket_id and socket.input == True: break
  158. else:
  159. for socket in ui_node.inputs:
  160. if socket.identifier == socket_id: break
  161. else:
  162. raise KeyError(f"Socket not found by ID {socket_id} in node {node.ui_signature}\n"
  163. f"Candidates: {[socket.identifier for socket in ui_node.inputs]}")
  164. value = socket.default_value # get the ACTUAL UI value
  165. if not isinstance(value, str): return
  166. # First step: get the interface nodes and the overlay keys
  167. # this should only check interfaces that are ancestors of this node
  168. my_interfaces = []
  169. for index in range(len(node.signature)-1):
  170. if index == 0: continue # root
  171. interface_signature = (*node.signature[:index+1], "InputInterface")
  172. my_interfaces.append( interface_nodes[interface_signature] )
  173. # the my_interfaces list is sorted in REVERSE order of importance
  174. # Next, get all the overlay providers.
  175. name_to_id_map = {}
  176. name_to_type_map = {} # Just for printing reasonable error messages
  177. overlay_keys = set()
  178. root_overlay_values = {}
  179. # First, we'll get the base tree's default inputs
  180. for interface_item in node.mContext.base_tree.interface.items_tree:
  181. if interface_item.item_type != "SOCKET": continue
  182. if interface_item.in_out != "INPUT": continue
  183. # NOTE this will need to change if overlays extend to other data types
  184. if hasattr(interface_item, "default_string"):
  185. # NOTE that there may be duplicate names. Too bad!
  186. root_overlay_values[interface_item.name] = interface_item.default_string
  187. elif hasattr(interface_item, "default_int"):
  188. root_overlay_values[interface_item.name] = str(interface_item.default_int).zfill(STRING_PADDING)
  189. elif hasattr(interface_item, "default_float"):
  190. root_overlay_values[interface_item.name] = str(interface_item.default_float).zfill(STRING_PADDING)
  191. overlay_keys.add(interface_item.name)
  192. name_to_id_map[interface_item.name] = None # don't worry about it
  193. name_to_type_map[interface_item.name] = interface_item.bl_socket_idname
  194. for interface_node in interface_nodes.values():
  195. # problem: the interface node stores socket identifiers as keys
  196. # so in reality we need to get the group UI node and ask for its input names
  197. # if there is a duplicate name, too bad!
  198. group_ui_node = get_ui_node(interface_node.ui_signature[:-1], node.base_tree)
  199. for interface_item in group_ui_node.node_tree.interface.items_tree:
  200. if interface_item.item_type != 'SOCKET': continue
  201. if interface_item.in_out != 'INPUT': continue
  202. if interface_item.name in forbidden_key_names: continue
  203. for substr in forbidden_in_key_name:
  204. if substr in interface_item.name:
  205. break
  206. else: # if we do not find a bad substr
  207. name_to_id_map[interface_item.name]=interface_item.identifier
  208. name_to_type_map[interface_item.name] = interface_item.bl_socket_idname
  209. overlay_keys.add(interface_item.name)
  210. # sort by reverse length so we find "CatsAndFrogs" before "Cats"
  211. overlay_keys = sorted(overlay_keys, key= lambda a :-1*len(a))
  212. # First I need to break it into substrings based on quotation marks
  213. from ..utilities.utilities import split_quoted_substrings_to_strings
  214. quoted_substrings = split_quoted_substrings_to_strings(value)
  215. overlay_tries = []
  216. for quoted_substring in quoted_substrings:
  217. overlay_tries.extend(quoted_substring.split("$"))
  218. result = overlay_tries[0] # the 0th element is always before the split character
  219. # the reason for the difference between overlay_try and key is because
  220. # we don't actually know if the $text part has a key in it
  221. for overlay_try in overlay_tries[1:]:
  222. if not overlay_try: continue # some of these are empty
  223. overlay_resolved_value = "$" + overlay_try
  224. for key in overlay_keys:
  225. if key in overlay_try:
  226. overlay_resolved_value = "$" + key
  227. for interface in reversed(my_interfaces): # since this is reversed when we build it
  228. if interface.inputs.get(actual_key := name_to_id_map.get(key)):
  229. overlay_value = None
  230. try:
  231. overlay_value = interface.evaluate_input(actual_key)
  232. except KeyError:
  233. if (socket_type := name_to_type_map.get(key) or 'NOT FOUND') in overlay_valid_socket_types:
  234. raise GraphError(f"Error: Variable {key} is not supported because it has "
  235. f"an invalid input in the node group: {interface.signature[:-1]}.")
  236. raise GraphError( f"Error: Variable {key} is not supported because it is "
  237. f"type {socket_type}" )
  238. continue
  239. # NOTE that the above can also be caused by any BUG occuring in node group update
  240. # because it causes the interface to be invalid for the UI node that spawns the interface node.
  241. if isinstance(overlay_value, (float, int)):
  242. overlay_value = str(overlay_value).zfill(STRING_PADDING)
  243. assert (isinstance(overlay_value, str)), f"Error: Variable {key} is not supported because it is type {type(overlay_value)}"
  244. overlay_resolved_value = overlay_try.replace(key, overlay_value)
  245. break
  246. else: # we'll try the base tree
  247. if base_tree_result := root_overlay_values.get(overlay_try):
  248. overlay_resolved_value = base_tree_result
  249. else:
  250. prOrange(f"WARN: no overlay value applied for {node.ui_signature} for key {key}")
  251. break # we found the key and are done here. One found Key per overlay-try
  252. result += overlay_resolved_value
  253. # Simple Input sockets with unnamed sockets assign this ID automatically
  254. # But Mantis uses the name instead. Usually the name and ID are the same.
  255. if socket_id == 'socket' and ui_node.outputs[0].name == "":
  256. socket_id = ''
  257. node.parameters[socket_id] = result
  258. return result # because sometimes I need to get the result, too
  259. from ..utilities.utilities import check_and_add_root, init_connections, init_dependencies, init_schema_dependencies
  260. def solve_schema_to_tree(mantis_node, all_mantis_nodes, roots=[], error_popups=False):
  261. from ..utilities.utilities import get_ui_node
  262. np = get_ui_node(mantis_node.signature, mantis_node.base_tree)
  263. from .schema_solve import SchemaSolver
  264. solver = SchemaSolver(mantis_node, all_mantis_nodes.copy(), np, error_popups=error_popups)
  265. try:
  266. solved_nodes = solver.solve()
  267. except Exception as e:
  268. # # the schema will run the error cleanup code, we just need to raise or not
  269. solved_nodes = {}
  270. mantis_node.base_tree.hash_recursive=''
  271. raise execution_error_cleanup(mantis_node, e, show_error=error_popups)
  272. for k,v in solved_nodes.items():
  273. all_mantis_nodes[k]=v
  274. init_connections(v)
  275. check_and_add_root(v, roots, include_non_hierarchy=True)
  276. return solved_nodes
  277. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  278. # PARSE NODE TREE #
  279. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  280. schema_bl_idnames = [ "SchemaIndex",
  281. "SchemaArrayInput",
  282. "SchemaArrayInputGet",
  283. "SchemaArrayInputAll",
  284. "SchemaArrayOutput",
  285. "SchemaConstInput",
  286. "SchemaConstOutput",
  287. "SchemaOutgoingConnection",
  288. "SchemaIncomingConnection",
  289. ]
  290. from ..utilities.utilities import get_all_dependencies
  291. def get_schema_length_dependencies(node, all_nodes={}):
  292. """ Get a list of all dependencies for the given node's length or array properties.
  293. This function will also recursively search for dependencies in its sub-trees.
  294. """
  295. deps = []
  296. prepare_links_to = ['Schema Length', 'Array', 'Index']
  297. def extend_dependencies_from_inputs(node):
  298. for inp in node.inputs.values():
  299. for l in inp.links:
  300. if not l.from_node in node.hierarchy_dependencies:
  301. continue
  302. if "MANTIS_AUTOGENERATED" in l.from_node.signature:
  303. deps.extend([l.from_node]) # why we need this lol
  304. if inp.name in prepare_links_to:
  305. deps.append(l.from_node)
  306. deps.extend(get_all_dependencies(l.from_node))
  307. def deps_filter(dep): # remove any nodes inside the schema
  308. if len(dep.signature) > len(node.signature):
  309. for i in range(len(node.signature)):
  310. dep_sig_elem, node_sig_elem = dep.signature[i], node.signature[i]
  311. if dep_sig_elem != node_sig_elem: break # they don't match, it isn't an inner-node
  312. else: # remove this, it didn't break, meaning it shares signature with outer node
  313. return False # this is an inner-node
  314. return True
  315. # this way we can handle Schema and Array Get nodes with one function
  316. extend_dependencies_from_inputs(node)
  317. if node.node_type == 'DUMMY_SCHEMA':
  318. trees = [(node.ui_node.node_tree, node.signature)] # this is UI data
  319. while trees:
  320. tree, tree_signature = trees.pop()
  321. for sub_ui_node in tree.nodes:
  322. if sub_ui_node.bl_idname in ['NodeReroute', 'NodeFrame']:
  323. continue
  324. if sub_ui_node.bl_idname in schema_bl_idnames:
  325. sub_node = all_nodes[(*tree_signature, sub_ui_node.bl_idname)]
  326. else:
  327. sub_node = all_nodes[(*tree_signature, sub_ui_node.name)]
  328. if sub_node.node_type == 'DUMMY_SCHEMA':
  329. extend_dependencies_from_inputs(sub_node)
  330. trees.append((sub_node.ui_node.node_tree, sub_node.signature))
  331. return list(filter(deps_filter, deps))
  332. def insert_default_values_base_tree(base_tree, all_mantis_nodes):
  333. # we can get this by name because group inputs are gathered to the bl_idname
  334. InputNode = all_mantis_nodes.get((None, 'NodeGroupInput'))
  335. if InputNode is None: return # nothing to do here.
  336. ui_node = InputNode.ui_node
  337. for i, output in enumerate(InputNode.outputs):
  338. ui_output = ui_node.outputs[i] # I need this for the error messages to make sense
  339. assert ui_output.identifier == output.name, "Cannot find UI Socket for Default Value"
  340. for interface_item in base_tree.interface.items_tree:
  341. if interface_item.item_type == 'PANEL': continue
  342. if interface_item.identifier == output.name: break
  343. else:
  344. raise RuntimeError(f"Default value {ui_output.name} does not exist in {base_tree.name} ")
  345. if interface_item.item_type == "PANEL":
  346. raise RuntimeError(f"Cannot get default value for {ui_output.name} in {base_tree.name} ")
  347. default_value = None
  348. from bpy.types import bpy_prop_array
  349. from mathutils import Vector
  350. val_type = None
  351. if hasattr(ui_output, 'default_value'):
  352. val_type = type(ui_output.default_value) # why tf can't I match/case here?
  353. if val_type is bool: default_value = interface_item.default_bool
  354. elif val_type is int: default_value = interface_item.default_int
  355. elif val_type is float: default_value = interface_item.default_float
  356. elif val_type is Vector: default_value = interface_item.default_vector
  357. elif val_type is str: default_value = interface_item.default_string
  358. elif val_type is bpy_prop_array: default_value = interface_item.default_bool_vector
  359. elif interface_item.bl_socket_idname == "xFormSocket":
  360. if interface_item.default_xForm == 'ARMATURE':
  361. default_value = 'MANTIS_DEFAULT_ARMATURE'
  362. else:
  363. raise RuntimeError(f"No xForm connected for {ui_output.name} in {base_tree.name}.")
  364. else:
  365. raise RuntimeError(f"Cannot get default value for {ui_output.name} in {base_tree.name} ")
  366. output_name = output.name
  367. if interface_item.bl_socket_idname not in ['xFormSocket']:
  368. signature = ("MANTIS_AUTOGENERATED", f"Default Value {output.name}",)
  369. autogen_mantis_node = all_mantis_nodes.get(signature)
  370. if autogen_mantis_node is None:
  371. autogen_mantis_node = autogen_node(base_tree, output, signature, InputNode.mContext)
  372. autogen_mantis_node.parameters[output_name]=default_value
  373. elif interface_item.bl_socket_idname == 'xFormSocket' \
  374. and default_value == 'MANTIS_DEFAULT_ARMATURE':
  375. signature = ("MANTIS_AUTOGENERATED", "MANTIS_DEFAULT_ARMATURE",)
  376. autogen_mantis_node = all_mantis_nodes.get(signature)
  377. if autogen_mantis_node is None:
  378. from ..xForm_nodes import xFormArmature
  379. autogen_mantis_node = xFormArmature(signature, base_tree)
  380. autogen_mantis_node.parameters['Name']=base_tree.name+'_MANTIS_AUTOGEN'
  381. autogen_mantis_node.mContext = InputNode.mContext
  382. from mathutils import Matrix
  383. autogen_mantis_node.parameters['Matrix'] = Matrix.Identity(4)
  384. output_name = 'xForm Out'
  385. while output.links:
  386. l = output.links.pop()
  387. to_node = l.to_node; to_socket = l.to_socket
  388. l.die()
  389. autogen_mantis_node.outputs[output_name].connect(to_node, to_socket)
  390. init_connections(l.from_node); init_dependencies(l.from_node)
  391. all_mantis_nodes[autogen_mantis_node.signature]=autogen_mantis_node
  392. def parse_tree(base_tree, error_popups=False):
  393. from uuid import uuid4
  394. base_tree.execution_id = uuid4().__str__() # set the unique id of this execution
  395. from ..base_definitions import MantisExecutionContext
  396. from ..utilities.node_common import GraphError
  397. mContext = MantisExecutionContext(base_tree=base_tree)
  398. import time
  399. data_start_time = time.time()
  400. # annoyingly I have to pass in values for all of the dicts because if I initialize them in the function call
  401. # then they stick around because the function definition inits them once and keeps a reference
  402. # so instead I have to supply them to avoid ugly code or bugs elsewhere
  403. # it's REALLY confusing when you run into this sort of problem. So it warrants four entire lines of comments!
  404. try:
  405. dummy_nodes, all_mantis_nodes, all_schema = data_from_tree(
  406. base_tree,
  407. tree_path = [None],
  408. mContext=mContext,
  409. dummy_nodes = {},
  410. all_mantis_nodes = {},
  411. all_schema={},
  412. in_schema=False
  413. )
  414. except GraphError as e:
  415. base_tree.tree_valid = False; base_tree.hash_recursive=""
  416. if error_popups:
  417. from bpy import context
  418. def error_popup_draw(self, context):
  419. error_popup_draw_inner(self.layout, e, ())
  420. context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  421. else: raise e
  422. return # it is not possible to parse the tree until GraphErrors are resolved.
  423. for dummy in dummy_nodes.values(): # reroute the links in the group nodes
  424. dummy.reroute_links(all_mantis_nodes)
  425. prGreen(f"Pulling data from tree took {time.time() - data_start_time} seconds")
  426. start_time = time.time()
  427. solve_only_these = []; solve_only_these.extend(list(all_schema.values()))
  428. roots, array_nodes = [], []
  429. from collections import deque
  430. unsolved_schema = deque()
  431. from ..base_definitions import array_output_types, GraphError
  432. for mantis_node in all_mantis_nodes.values():
  433. # TODO I still need to assign mContext here because of autogen_node
  434. # so I have to do a deeper refactor to ensure autogen nodes get this at creation time.
  435. mantis_node.mContext = mContext
  436. if mantis_node.node_type in ["DUMMY"]: # clean up the groups
  437. if mantis_node.ui_node.bl_idname in ("MantisNodeGroup", "NodeGroupOutput"):
  438. continue
  439. # Initialize the dependencies and connections (from/to links) for each node.
  440. # we record & store it because using a getter is much slower (according to profiling)
  441. init_dependencies(mantis_node); init_connections(mantis_node)
  442. check_and_add_root(mantis_node, roots, include_non_hierarchy=True)
  443. # Array nodes need a little special treatment, they're quasi-schemas
  444. if mantis_node.__class__.__name__ in array_output_types:
  445. solve_only_these.append(mantis_node)
  446. array_nodes.append(mantis_node)
  447. if mantis_node.node_type == 'INTERFACE':
  448. mContext.interface_nodes[mantis_node.signature] = mantis_node
  449. from itertools import chain
  450. for schema in chain(all_schema.values(), array_nodes):
  451. # We must remove the schema/array nodes that are inside a schema tree.
  452. for i in range(len(schema.signature)-1): # -1, we don't want to check this node, obviously
  453. if parent := all_schema.get(schema.signature[:i+1]):
  454. # This will be solved along with its parent schema.
  455. solve_only_these.remove(schema)
  456. break
  457. for schema in all_schema.values():
  458. if schema not in solve_only_these: continue
  459. init_schema_dependencies(schema, all_mantis_nodes)
  460. solve_only_these.extend(get_schema_length_dependencies(schema, all_mantis_nodes))
  461. unsolved_schema.append(schema)
  462. for array in array_nodes:
  463. if array not in solve_only_these: continue
  464. solve_only_these.extend(get_schema_length_dependencies(array))
  465. solve_only_these.extend(array_nodes)
  466. schema_solve_done = set()
  467. solve_only_these = set(solve_only_these)
  468. solve_layer = unsolved_schema.copy(); solve_layer.extend(roots)
  469. while(solve_layer):
  470. n = solve_layer.pop()
  471. if n not in solve_only_these:
  472. continue
  473. if n.signature in all_schema.keys():
  474. for dep in n.hierarchy_dependencies:
  475. if dep not in schema_solve_done and (dep in solve_only_these):
  476. if dep.prepared:
  477. continue
  478. solve_layer.appendleft(n)
  479. break
  480. else:
  481. try:
  482. solved_nodes = solve_schema_to_tree(n, all_mantis_nodes, roots, error_popups=error_popups)
  483. except Exception as e:
  484. e = execution_error_cleanup(n, e, show_error=error_popups)
  485. solved_nodes = {}
  486. if error_popups == False:
  487. raise e
  488. return # it is not possible to parse the tree.
  489. unsolved_schema.remove(n)
  490. schema_solve_done.add(n)
  491. for node in solved_nodes.values():
  492. init_dependencies(node); init_connections(node)
  493. solve_layer.appendleft(node)
  494. schema_solve_done.add(node) # CRITICAL to prevent freezes.
  495. for conn in n.hierarchy_connections:
  496. if conn not in schema_solve_done and conn not in solve_layer:
  497. solve_layer.appendleft(conn)
  498. continue
  499. else:
  500. for dep in n.hierarchy_dependencies:
  501. if dep not in schema_solve_done:
  502. break
  503. else:
  504. try:
  505. n.bPrepare()
  506. except Exception as e:
  507. e = execution_error_cleanup(n, e, show_error=error_popups)
  508. if error_popups == False:
  509. raise e
  510. schema_solve_done.add(n)
  511. for conn in n.hierarchy_connections:
  512. if conn not in schema_solve_done and conn not in solve_layer:
  513. solve_layer.appendleft(conn)
  514. continue
  515. if unsolved_schema:
  516. raise RuntimeError("Failed to resolve all schema declarations")
  517. # I had a problem with this looping forever. I think it is resolved... but I don't know lol
  518. all_mantis_nodes = list(all_mantis_nodes.values())
  519. kept_mantis_node = {}
  520. while (all_mantis_nodes):
  521. mantis_node = all_mantis_nodes.pop()
  522. if mantis_node.node_type in ["DUMMY", 'SCHEMA', 'DUMMY_SCHEMA']:
  523. continue # screen out the ui_node schema nodes, group in/out, and group placeholders
  524. # cleanup autogen nodes
  525. if mantis_node.signature[0] == "MANTIS_AUTOGENERATED" and len(mantis_node.inputs) == 0 and len(mantis_node.outputs) == 1:
  526. from ..base_definitions import can_remove_socket_for_autogen
  527. output=list(mantis_node.outputs.values())[0]
  528. value=list(mantis_node.parameters.values())[0]
  529. # We can remove this node if it is safe to push it into the other node's socket.
  530. keep_me = False
  531. for l in output.links:
  532. to_node = l.to_node; to_socket = l.to_socket
  533. # do not remove the socket if it is a custom property.
  534. if not can_remove_socket_for_autogen(to_node, to_socket):
  535. keep_me = True; continue
  536. l.die()
  537. to_node.parameters[to_socket] = value
  538. del to_node.inputs[to_socket]
  539. init_dependencies(to_node) # to remove the autogen node we no longer need.
  540. if not keep_me:
  541. continue
  542. init_connections(mantis_node) # because we have removed many connections.
  543. if (mantis_node.node_type in ['XFORM']) and ("Relationship" in mantis_node.inputs.keys()):
  544. from ..utilities.node_common import GraphError
  545. try:
  546. if (new_mantis_node := insert_lazy_parents(mantis_node)):
  547. kept_mantis_node[new_mantis_node.signature]=new_mantis_node
  548. # be sure to add the Mantis context.
  549. new_mantis_node.mContext =mContext
  550. except GraphError as e:
  551. e = execution_error_cleanup(mantis_node, e, show_error=error_popups)
  552. if error_popups == False:
  553. raise e
  554. return # it is not possible to parse the tree.
  555. kept_mantis_node[mantis_node.signature]=mantis_node
  556. prWhite(f"Parsing tree took {time.time()-start_time} seconds.")
  557. prWhite("Number of Nodes: %s" % (len(kept_mantis_node)))
  558. return kept_mantis_node
  559. from ..utilities.utilities import switch_mode
  560. def error_popup_draw_inner(layout, exception, ui_sig = ()):
  561. node_string = f"See node: {ui_sig[1:]}." if ui_sig else ""
  562. message = f"Error: {exception}\n" + node_string
  563. lines = message.splitlines()
  564. for line in lines:
  565. layout.label(text=line)
  566. def execution_error_cleanup(node, exception, switch_objects = [], show_error=False ):
  567. from bpy import context
  568. ui_sig = None
  569. if show_error: # show a popup and select the relevant nodes
  570. if node:
  571. if node.mContext:
  572. if node.mContext.execution_failed==True:
  573. # already have an error, pass it to avoid printing
  574. return # a second error (it's confusing to users.)
  575. node.mContext.execution_failed=True
  576. ui_sig = node.ui_signature
  577. # TODO: see about zooming-to-node.
  578. base_tree = node.base_tree
  579. tree = base_tree
  580. try:
  581. for name in ui_sig[1:]:
  582. for n in tree.nodes: n.select = False
  583. n = tree.nodes[name]
  584. n.select = True
  585. tree.nodes.active = n
  586. if hasattr(n, "node_tree"):
  587. tree = n.node_tree
  588. except AttributeError: # not being run in node graph
  589. pass
  590. finally:
  591. def error_popup_draw(self, context):
  592. error_popup_draw_inner(self.layout, exception, ui_sig)
  593. context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  594. switch_mode(mode='OBJECT', objects=switch_objects)
  595. for ob in switch_objects:
  596. ob.data.pose_position = 'POSE'
  597. prRed(f"Error: {exception} in node {ui_sig}")
  598. return exception
  599. def print_cycle(nodes):
  600. ret_str = ""
  601. for node in nodes:
  602. ret_str+= node.__repr__() + '\n'
  603. return ret_str
  604. def sort_execution(nodes, error_popups):
  605. from ..utilities.node_common import GraphError
  606. from collections import deque
  607. xForm_pass = deque()
  608. execution_failed = False
  609. sorted_nodes = []
  610. # initialize the hierarchy dependency count. We'll use this to ensure there
  611. # are no cycles (using Kahn's algorithm).
  612. expected_sort_quantity = len(nodes)
  613. for mantis_node in nodes.values():
  614. if mantis_node.node_type in ['DUMMY', 'DUMMY_SCHEMA', 'INTERFACE']:
  615. expected_sort_quantity -=1 ; continue
  616. if mantis_node.is_schema_prototype:
  617. expected_sort_quantity -= 1; continue
  618. mantis_node.unmet_hierarchy_dependency_count = len(mantis_node.hierarchy_dependencies)
  619. if mantis_node.unmet_hierarchy_dependency_count == 0 :
  620. xForm_pass.append(mantis_node)
  621. processed_count = 0
  622. while(xForm_pass):
  623. n = xForm_pass.pop()
  624. # if n.execution_prepared: continue
  625. n.execution_prepared = True
  626. sorted_nodes.append(n)
  627. processed_count+=1
  628. for child in n.hierarchy_connections:
  629. child.unmet_hierarchy_dependency_count-= 1
  630. if child.unmet_hierarchy_dependency_count == 0:
  631. xForm_pass.append(child)
  632. if processed_count < expected_sort_quantity:
  633. cycle = []
  634. for n in nodes.values():
  635. if n.execution_prepared == False:
  636. cycle.append(n)
  637. execution_failed = True
  638. e = GraphError("Detected a cycle in the tree, containing at "
  639. "least one of the following nodes: " + print_cycle(cycle))
  640. e = execution_error_cleanup(cycle[-1], e, show_error=error_popups)
  641. prRed(processed_count, expected_sort_quantity)
  642. raise e
  643. return sorted_nodes, execution_failed
  644. def execute_tree(nodes, base_tree, context, error_popups = False, profile=False):
  645. assert nodes is not None, "Failed to parse tree."
  646. assert len(nodes) > 0, "No parsed nodes for execution."\
  647. " Mantis probably failed to parse the tree."
  648. import bpy
  649. from time import time
  650. original_active = context.view_layer.objects.active
  651. start_execution_time = time()
  652. mContext = None
  653. for mantis_node in nodes.values():
  654. if not mContext: # just grab one of these. this is a silly way to do this.
  655. mContext = mantis_node.mContext
  656. mContext.b_objects = {} # clear the objects and recreate them
  657. mantis_node.reset_execution()
  658. mContext.execution_failed = False
  659. interface_nodes = {}
  660. from ..internal_nodes import GroupInterface
  661. for node in nodes.values():
  662. if isinstance(node, GroupInterface):
  663. interface_nodes[node.signature] = node
  664. overlay_tagged_nodes = {}
  665. for node_signature, socket_id in mContext.tagged_for_overlay:
  666. if overlay_tagged_nodes.get(node_signature):
  667. overlay_tagged_nodes[node_signature].append(socket_id)
  668. else:
  669. overlay_tagged_nodes[node_signature] = [socket_id]
  670. def check_and_apply_overlay(n):
  671. if overlays_for_this_node := overlay_tagged_nodes.get(n.signature):
  672. for socket_id in overlays_for_this_node:
  673. node_scan_overlays(n, socket_id,)
  674. select_me, switch_me = [], [] # switch the mode on these objects
  675. active = None # only need it for switching modes
  676. select_me = []
  677. profiler = None
  678. if profile:
  679. from ..dev_helpers.profile_nodes import NodeProfiler
  680. profiler = NodeProfiler()
  681. profiler.new_session(mContext.execution_id)
  682. sort_key = 'total'
  683. try:
  684. sorted_nodes, execution_failed = sort_execution(nodes, error_popups=error_popups)
  685. except Exception as e:
  686. # We'll fire the popup in sort_execution because it has the node in scope
  687. if error_popups == False:
  688. raise e
  689. execution_failed = True
  690. try:
  691. for n in sorted_nodes:
  692. if execution_failed: break
  693. try:
  694. check_and_apply_overlay(n)
  695. if not n.prepared:
  696. if profiler: profiler.record(n, "bPrepare", context)
  697. else: n.bPrepare(context)
  698. if not n.executed:
  699. if profiler: profiler.record(n, "bTransformPass", context)
  700. else: n.bTransformPass(context)
  701. if (n.__class__.__name__ == "xFormArmature" ):
  702. ob = n.bGetObject()
  703. switch_me.append(ob)
  704. active = ob
  705. if not (n.__class__.__name__ == "xFormBone" ) and hasattr(n, "bGetObject"):
  706. ob = n.bGetObject()
  707. if isinstance(ob, bpy.types.Object):
  708. select_me.append(ob)
  709. except Exception as e:
  710. e = execution_error_cleanup(n, e, show_error=error_popups)
  711. if error_popups == False:
  712. raise e
  713. execution_failed = True; break
  714. switch_mode(mode='POSE', objects=switch_me)
  715. for n in sorted_nodes:
  716. try:
  717. check_and_apply_overlay(n)
  718. if not n.prepared:
  719. if profiler: profiler.record(n, "bPrepare", context)
  720. else: n.bPrepare(context)
  721. if not n.executed:
  722. if profiler: profiler.record(n, "bRelationshipPass", context)
  723. else: n.bRelationshipPass(context)
  724. except Exception as e:
  725. e = execution_error_cleanup(n, e, show_error=error_popups)
  726. if error_popups == False:
  727. raise e
  728. execution_failed = True; break
  729. switch_mode(mode='OBJECT', objects=switch_me)
  730. # switch to pose mode here so that the nodes can use the final pose data
  731. # this will require them to update the depsgraph.
  732. for ob in switch_me:
  733. ob.data.pose_position = 'POSE'
  734. for n in sorted_nodes:
  735. try:
  736. if profiler: profiler.record(n, "bFinalize", context)
  737. else: n.bFinalize(context)
  738. except Exception as e:
  739. e = execution_error_cleanup(n, e, show_error=error_popups)
  740. if error_popups == False:
  741. raise e
  742. execution_failed = True; break
  743. # REST pose for deformer bind, so everything is in the rest position
  744. for ob in switch_me:
  745. ob.data.pose_position = 'REST'
  746. # finally, apply modifiers and bind stuff
  747. for n in sorted_nodes:
  748. try:
  749. if profiler: profiler.record(n, "bModifierApply", context)
  750. else: n.bModifierApply(context)
  751. except Exception as e:
  752. e = execution_error_cleanup(n, e, show_error=error_popups)
  753. if error_popups == False:
  754. raise e
  755. execution_failed = True; break
  756. for ob in switch_me:
  757. ob.data.pose_position = 'POSE'
  758. tot_time = (time() - start_execution_time)
  759. if not execution_failed:
  760. prGreen(f"Executed tree of {len(sorted_nodes)} nodes in {tot_time} seconds")
  761. if profiler:
  762. from ..dev_helpers.profile_nodes import summarize_profile
  763. summarize_profile(profiler._current, pass_name='bPrepare', sort_key = sort_key)
  764. summarize_profile(profiler._current, pass_name='bTransformPass', sort_key = sort_key)
  765. summarize_profile(profiler._current, pass_name='bRelationshipPass', sort_key = sort_key)
  766. summarize_profile(profiler._current, pass_name='bFinalize', sort_key = sort_key)
  767. summarize_profile(profiler._current, pass_name='bModifierApply', sort_key = sort_key)
  768. if (original_active):
  769. context.view_layer.objects.active = original_active
  770. original_active.select_set(True)
  771. except Exception as e:
  772. e = execution_error_cleanup(None, e, switch_me, show_error=error_popups)
  773. if error_popups == False:
  774. raise e
  775. prRed(f"Failed to execute tree.")
  776. finally:
  777. context.view_layer.objects.active = active
  778. # clear the selection first.
  779. from itertools import chain
  780. for ob in context.selected_objects:
  781. try:
  782. ob.select_set(False)
  783. except RuntimeError: # it isn't in the view layer
  784. pass
  785. for ob in chain(select_me, mContext.b_objects.values()):
  786. try:
  787. ob.select_set(True)
  788. except RuntimeError: # it isn't in the view layer
  789. pass