readtree.py 43 KB

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