readtree.py 43 KB

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