readtree.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. from .utilities import prRed, prGreen, prPurple, prWhite, prOrange, \
  2. wrapRed, wrapGreen, wrapPurple, wrapWhite, wrapOrange
  3. # we need to reroute the incoming links to a new GroupInterface node
  4. # then we need to reroute the outgoing links from the GroupInterface
  5. # down into the tree - or visa versa (NodeGroupOutput input to Group output)
  6. def grp_node_reroute_common(in_node, out_node, interface):
  7. for in_node_input in in_node.inputs:
  8. while (in_node_input.links):
  9. in_link = in_node_input.links.pop()
  10. from_node = in_link.from_node; from_socket = in_link.from_socket
  11. # the inputs/outputs on the group and in/out nodes are IDs
  12. from_node.outputs[from_socket].connect(
  13. interface,in_node_input.name, sort_id = in_link.multi_input_sort_id)
  14. in_link.die()
  15. init_connections(from_node)
  16. for out_node_output in out_node.outputs:
  17. while (out_node_output.links):
  18. out_link = out_node_output.links.pop()
  19. to_node = out_link.to_node; to_socket = out_link.to_socket
  20. for l in interface.inputs[out_node_output.name].links:
  21. interface.outputs[out_node_output.name].connect(
  22. to_node, to_socket, sort_id = l.multi_input_sort_id)
  23. out_link.die()
  24. init_dependencies(to_node)
  25. init_dependencies(interface); init_connections(interface)
  26. def reroute_links_grp(group, all_nodes):
  27. from .internal_containers import GroupInterface
  28. interface = GroupInterface(
  29. ( *group.signature, "InputInterface"),
  30. group.base_tree, group.prototype, 'INPUT',)
  31. all_nodes[interface.signature] = interface
  32. if group.inputs:
  33. if group_input := all_nodes.get(( *group.signature, "NodeGroupInput")):
  34. grp_node_reroute_common(group, group_input, interface)
  35. else:
  36. raise RuntimeError("internal error: failed to enter a node group ")
  37. def reroute_links_grpout(group_output, all_nodes):
  38. if (group := all_nodes.get( ( *group_output.signature[:-1],) )):
  39. from .internal_containers import GroupInterface
  40. interface = GroupInterface(
  41. ( *group.signature, "OutputInterface"),
  42. group.base_tree, group.prototype, 'OUTPUT',)
  43. all_nodes[interface.signature] = interface
  44. grp_node_reroute_common(group_output, group, interface)
  45. else:
  46. prOrange(f"WARN: unconnected outputs from a node group "
  47. "(maybe you are running the tree from inside a node group?)")
  48. # FIXME I don't think these signatures are unique.
  49. def insert_lazy_parents(nc):
  50. from .link_nodes import LinkInherit
  51. from .base_definitions import NodeLink
  52. inherit_nc = None
  53. if nc.inputs["Relationship"].is_connected:
  54. link = nc.inputs["Relationship"].links[0]
  55. from_nc = link.from_node
  56. if from_nc.node_type in ["XFORM"] and link.from_socket in ["xForm Out"]:
  57. inherit_nc = LinkInherit(("MANTIS_AUTOGENERATED", *nc.signature[1:], "LAZY_INHERIT"), nc.base_tree)
  58. for from_link in from_nc.outputs["xForm Out"].links:
  59. if from_link.to_node == nc and from_link.to_socket == "Relationship":
  60. break # this is it
  61. from_link.to_node = inherit_nc; from_link.to_socket="Parent"
  62. from_link.to_node.inputs[from_link.to_socket].is_linked=True
  63. links=[]
  64. while (nc.inputs["Relationship"].links):
  65. to_link = nc.inputs["Relationship"].links.pop()
  66. if to_link.from_node == from_nc and to_link.from_socket == "xForm Out":
  67. continue # don't keep this one
  68. links.append(to_link)
  69. to_link.from_node.outputs[from_link.from_socket].is_linked=True
  70. nc.inputs["Relationship"].links=links
  71. link=NodeLink(from_node=inherit_nc, from_socket="Inheritance", to_node=nc, to_socket="Relationship")
  72. inherit_nc.inputs["Parent"].links.append(from_link)
  73. inherit_nc.parameters = {
  74. "Parent":None,
  75. "Inherit Rotation":True,
  76. "Inherit Scale":'FULL',
  77. "Connected":False,
  78. }
  79. # because the from node may have already been done.
  80. init_connections(from_nc)
  81. init_dependencies(from_nc)
  82. init_connections(inherit_nc)
  83. init_dependencies(inherit_nc)
  84. return inherit_nc
  85. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  86. # DATA FROM NODES #
  87. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  88. from .base_definitions import replace_types, NodeSocket
  89. def autogen_node(base_tree, ui_socket, signature, mContext):
  90. mantis_node=None
  91. from .internal_containers import AutoGenNode
  92. mantis_node = AutoGenNode(signature, base_tree)
  93. mantis_node.mContext = mContext
  94. mantis_node.outputs.init_sockets([ui_socket.name])
  95. mantis_node.ui_signature = None # does not exist in the UI
  96. return mantis_node
  97. # TODO: investigate whether I can set the properties in the downstream nodes directly.
  98. # I am doing this in Schema Solver and it seems to work quite efficiently.
  99. def make_connections_to_ng_dummy(base_tree, tree_path_names, local_nc, all_nc, nc_to):
  100. from .socket_definitions import no_default_value
  101. for inp in nc_to.prototype.inputs:
  102. if inp.bl_idname in no_default_value:
  103. continue
  104. nc_from = None
  105. to_s = inp.identifier
  106. if not inp.is_linked: # make an autogenerated NC for the inputs of the group node
  107. # This can be run inside schema. Make it unique with uuid() to be safe.
  108. from uuid import uuid4
  109. signature = ("MANTIS_AUTOGENERATED", *tree_path_names, nc_to.ui_signature[-1], inp.name, inp.identifier, str(uuid4()))
  110. nc_from = all_nc.get(signature) # creating this without checking and
  111. # using UUID signature leads to TERRIBLE CONFUSING BUGS.
  112. if nc_from is None:
  113. nc_from = autogen_node(base_tree, inp, signature, nc_to.mContext)
  114. from .node_container_common import get_socket_value
  115. if nc_from: # autogen can fail and we should catch it.
  116. nc_from.parameters = {inp.name:get_socket_value(inp)}
  117. local_nc[signature] = nc_from; all_nc[signature] = nc_from
  118. nc_from.outputs[inp.name].connect(node=nc_to, socket=to_s, sort_id=0)
  119. else:
  120. prRed("No available auto-generated class for input %s in %s" % (inp.name, np.name))
  121. def gen_node_containers(base_tree, current_tree, tree_path_names, all_nc, local_nc, dummy_nodes, group_nodes, schema_nodes ):
  122. from .internal_containers import DummyNode
  123. for ui_node in current_tree.nodes:
  124. # HACK I found that this isn't being set sometimes. I wonder why? It makes the most sense to do this here.
  125. if hasattr(ui_node, 'initialized'): ui_node.initialized=True
  126. # end HACK. TODO: find out why this is not set sometimes. This is only needed for UI socket change updates.
  127. if ui_node.bl_idname in ["NodeFrame", "NodeReroute"]:
  128. continue # not a Mantis Node
  129. if ui_node.bl_idname in ["NodeGroupInput", "NodeGroupOutput"]:
  130. # we only want ONE dummy in/out per tree_path, so use the bl_idname to make a Dummy node
  131. sig = (None, *tree_path_names, ui_node.bl_idname)
  132. ui_sig = (None, *tree_path_names, ui_node.name)
  133. if not local_nc.get(sig):
  134. nc = DummyNode( signature=sig , base_tree=base_tree, prototype=ui_node, ui_signature=ui_sig )
  135. local_nc[sig] = nc; all_nc[sig] = nc; dummy_nodes[sig] = nc
  136. if ui_node.bl_idname in ["NodeGroupOutput"]:
  137. nc.reroute_links = reroute_links_grpout
  138. elif ui_node.bl_idname in ["MantisNodeGroup", "MantisSchemaGroup"]:
  139. nc = DummyNode( signature= (sig := (None, *tree_path_names, ui_node.name) ), base_tree=base_tree, prototype=ui_node )
  140. local_nc[sig] = nc; all_nc[sig] = nc; dummy_nodes[sig] = nc
  141. make_connections_to_ng_dummy(base_tree, tree_path_names, local_nc, all_nc, nc)
  142. if ui_node.bl_idname == "MantisNodeGroup":
  143. group_nodes.append(nc)
  144. nc.reroute_links = reroute_links_grp
  145. else:
  146. group_nodes.append(nc)
  147. schema_nodes[sig] = nc
  148. # if it wasn't the types we ignore or the types we make a Dummy for, use this to catch all non-special cases.
  149. elif (nc_cls := ui_node.mantis_class):
  150. sig = (None, *tree_path_names, ui_node.name)
  151. if ui_node.bl_idname in replace_types:
  152. sig = (None, *tree_path_names, ui_node.bl_idname)
  153. if local_nc.get(sig):
  154. continue # already made
  155. nc = nc_cls( sig , base_tree)
  156. local_nc[sig] = nc; all_nc[sig] = nc
  157. nc.ui_signature = (*nc.ui_signature[:-1], ui_node.name) # just to ensure it points to a real node.
  158. else:
  159. nc = None
  160. prRed(f"Can't make nc for.. {ui_node.bl_idname}")
  161. # this should be done at init
  162. if nc.signature[0] not in ['MANTIS_AUTOGENERATED'] and nc.node_type not in ['SCHEMA', 'DUMMY', 'DUMMY_SCHEMA']:
  163. nc.fill_parameters()
  164. def data_from_tree(base_tree, tree_path, dummy_nodes, all_nc, all_schema):#
  165. # TODO: it should be relatively easy to make this use a while loop instead of recursion.
  166. local_nc, group_nodes = {}, []
  167. tree_path_names = [tree.name for tree in tree_path if hasattr(tree, "name")]
  168. if tree_path[-1]:
  169. current_tree = tree_path[-1].node_tree # this may be None.
  170. else:
  171. current_tree = base_tree
  172. #
  173. if current_tree: # the node-group may not have a tree set - if so, ignore it.
  174. from .utilities import clear_reroutes
  175. links = clear_reroutes(list(current_tree.links))
  176. gen_node_containers(base_tree, current_tree, tree_path_names, all_nc, local_nc, dummy_nodes, group_nodes, all_schema)
  177. from .utilities import link_node_containers
  178. for link in links:
  179. link_node_containers((None, *tree_path_names), link, local_nc)
  180. if current_tree == base_tree:
  181. # in the base tree, we need to auto-gen the default values in a slightly different way to node groups.
  182. insert_default_values_base_tree(base_tree, all_nc)
  183. # Now, descend into the Node Groups and recurse
  184. for nc in group_nodes:
  185. data_from_tree(base_tree, tree_path+[nc.prototype], dummy_nodes, all_nc, all_schema)
  186. return dummy_nodes, all_nc, all_schema
  187. from .utilities import check_and_add_root, init_connections, init_dependencies, init_schema_dependencies
  188. def is_signature_in_other_signature(parent_signature, child_signature):
  189. # If the other signature is shorter, it isn't a child node
  190. if len(parent_signature) > len(child_signature):
  191. return False
  192. return parent_signature[0:] == child_signature[:len(parent_signature)]
  193. def solve_schema_to_tree(nc, all_nc, roots=[], error_popups=False):
  194. from .utilities import get_node_prototype
  195. np = get_node_prototype(nc.signature, nc.base_tree)
  196. from .schema_solve import SchemaSolver
  197. solver = SchemaSolver(nc, all_nc.copy(), np, error_popups=error_popups)
  198. try:
  199. solved_nodes = solver.solve()
  200. except Exception as e:
  201. # # the schema will run the error cleanup code, we just need to raise or not
  202. solved_nodes = {}
  203. nc.base_tree.hash=''
  204. raise execution_error_cleanup(nc, e, show_error=error_popups)
  205. # maybe this should be done in schema solver. TODO invesitigate a more efficient way
  206. del_me = []
  207. for k, v in all_nc.items():
  208. # delete all the schema's prototype and interface nodes. The links have already been deleted by the solver.
  209. if v.signature[0] not in ['MANTIS_AUTOGENERATED'] and is_signature_in_other_signature(nc.signature, k):
  210. del_me.append(k)
  211. for k in del_me:
  212. del all_nc[k]
  213. for k,v in solved_nodes.items():
  214. all_nc[k]=v
  215. init_connections(v)
  216. check_and_add_root(v, roots, include_non_hierarchy=True)
  217. return solved_nodes
  218. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  219. # PARSE NODE TREE #
  220. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  221. schema_bl_idnames = [ "SchemaIndex",
  222. "SchemaArrayInput",
  223. "SchemaArrayInputGet",
  224. "SchemaArrayInputAll",
  225. "SchemaArrayOutput",
  226. "SchemaConstInput",
  227. "SchemaConstOutput",
  228. "SchemaOutgoingConnection",
  229. "SchemaIncomingConnection",
  230. ]
  231. from .utilities import get_all_dependencies
  232. def get_schema_length_dependencies(node, all_nodes={}):
  233. """ Get a list of all dependencies for the given node's length or array properties.
  234. This function will also recursively search for dependencies in its sub-trees.
  235. """
  236. deps = []
  237. prepare_links_to = ['Schema Length', 'Array', 'Index']
  238. def extend_dependencies_from_inputs(node):
  239. for inp in node.inputs.values():
  240. for l in inp.links:
  241. if not l.from_node in node.hierarchy_dependencies:
  242. continue
  243. if "MANTIS_AUTOGENERATED" in l.from_node.signature:
  244. deps.extend([l.from_node]) # why we need this lol
  245. if inp.name in prepare_links_to:
  246. deps.append(l.from_node)
  247. deps.extend(get_all_dependencies(l.from_node))
  248. def deps_filter(dep): # remove any nodes inside the schema
  249. if len(dep.signature) > len(node.signature):
  250. for i in range(len(node.signature)):
  251. dep_sig_elem, node_sig_elem = dep.signature[i], node.signature[i]
  252. if dep_sig_elem != node_sig_elem: break # they don't match, it isn't an inner-node
  253. else: # remove this, it didn't break, meaning it shares signature with outer node
  254. return False # this is an inner-node
  255. return True
  256. # this way we can handle Schema and Array Get nodes with one function
  257. extend_dependencies_from_inputs(node)
  258. if node.node_type == 'DUMMY_SCHEMA':
  259. trees = [(node.prototype.node_tree, node.signature)] # this is UI data
  260. while trees:
  261. tree, tree_signature = trees.pop()
  262. for sub_ui_node in tree.nodes:
  263. if sub_ui_node.bl_idname in ['NodeReroute', 'NodeFrame']:
  264. continue
  265. if sub_ui_node.bl_idname in schema_bl_idnames:
  266. sub_node = all_nodes[(*tree_signature, sub_ui_node.bl_idname)]
  267. else:
  268. sub_node = all_nodes[(*tree_signature, sub_ui_node.name)]
  269. if sub_node.node_type == 'DUMMY_SCHEMA':
  270. extend_dependencies_from_inputs(sub_node)
  271. trees.append((sub_node.prototype.node_tree, sub_node.signature))
  272. return list(filter(deps_filter, deps))
  273. def insert_default_values_base_tree(base_tree, all_mantis_nodes):
  274. # we can get this by name because group inputs are gathered to the bl_idname
  275. InputNode = all_mantis_nodes.get((None, 'NodeGroupInput'))
  276. if InputNode is None: return # nothing to do here.
  277. ui_node = InputNode.prototype
  278. for i, output in enumerate(InputNode.outputs):
  279. ui_output = ui_node.outputs[i] # I need this for the error messages to make sense
  280. assert ui_output.identifier == output.name, "Cannot find UI Socket for Default Value"
  281. for interface_item in base_tree.interface.items_tree:
  282. if interface_item.item_type == 'PANEL': continue
  283. if interface_item.identifier == output.name: break
  284. else:
  285. raise RuntimeError(f"Default value {ui_output.name} does not exist in {base_tree.name} ")
  286. if interface_item.item_type == "PANEL":
  287. raise RuntimeError(f"Cannot get default value for {ui_output.name} in {base_tree.name} ")
  288. default_value = None
  289. from bpy.types import bpy_prop_array
  290. from mathutils import Vector
  291. val_type = None
  292. if hasattr(ui_output, 'default_value'):
  293. val_type = type(ui_output.default_value) # why tf can't I match/case here?
  294. if val_type is bool: default_value = interface_item.default_bool
  295. elif val_type is int: default_value = interface_item.default_int
  296. elif val_type is float: default_value = interface_item.default_float
  297. elif val_type is Vector: default_value = interface_item.default_vector
  298. elif val_type is str: default_value = interface_item.default_string
  299. elif val_type is bpy_prop_array: default_value = interface_item.default_bool_vector
  300. elif interface_item.bl_socket_idname == "xFormSocket":
  301. if interface_item.default_xForm == 'ARMATURE':
  302. default_value = 'MANTIS_DEFAULT_ARMATURE'
  303. else:
  304. raise RuntimeError(f"No xForm connected for {ui_output.name} in {base_tree.name}.")
  305. else:
  306. raise RuntimeError(f"Cannot get default value for {ui_output.name} in {base_tree.name} ")
  307. output_name = output.name
  308. if interface_item.bl_socket_idname not in ['xFormSocket']:
  309. signature = ("MANTIS_AUTOGENERATED", f"Default Value {output.name}",)
  310. autogen_mantis_node = all_mantis_nodes.get(signature)
  311. if autogen_mantis_node is None:
  312. autogen_mantis_node = autogen_node(base_tree, output, signature, InputNode.mContext)
  313. autogen_mantis_node.parameters[output_name]=default_value
  314. elif interface_item.bl_socket_idname == 'xFormSocket' \
  315. and default_value == 'MANTIS_DEFAULT_ARMATURE':
  316. signature = ("MANTIS_AUTOGENERATED", "MANTIS_DEFAULT_ARMATURE",)
  317. autogen_mantis_node = all_mantis_nodes.get(signature)
  318. if autogen_mantis_node is None:
  319. from .xForm_nodes import xFormArmature
  320. autogen_mantis_node = xFormArmature(signature, base_tree)
  321. autogen_mantis_node.parameters['Name']=base_tree.name+'_MANTIS_AUTOGEN'
  322. autogen_mantis_node.mContext = InputNode.mContext
  323. from mathutils import Matrix
  324. autogen_mantis_node.parameters['Matrix'] = Matrix.Identity(4)
  325. output_name = 'xForm Out'
  326. while output.links:
  327. l = output.links.pop()
  328. to_node = l.to_node; to_socket = l.to_socket
  329. l.die()
  330. autogen_mantis_node.outputs[output_name].connect(to_node, to_socket)
  331. init_connections(l.from_node); init_dependencies(l.from_node)
  332. all_mantis_nodes[autogen_mantis_node.signature]=autogen_mantis_node
  333. def parse_tree(base_tree, error_popups=False):
  334. from uuid import uuid4
  335. base_tree.execution_id = uuid4().__str__() # set the unique id of this execution
  336. from .base_definitions import MantisExecutionContext
  337. mContext = MantisExecutionContext(base_tree=base_tree)
  338. import time
  339. data_start_time = time.time()
  340. # annoyingly I have to pass in values for all of the dicts because if I initialize them in the function call
  341. # then they stick around because the function definition inits them once and keeps a reference
  342. # so instead I have to supply them to avoid ugly code or bugs elsewhere
  343. # it's REALLY confusing when you run into this sort of problem. So it warrants four entire lines of comments!
  344. dummy_nodes, all_mantis_nodes, all_schema = data_from_tree(base_tree, tree_path = [None], dummy_nodes = {}, all_nc = {}, all_schema={})
  345. for dummy in dummy_nodes.values(): # reroute the links in the group nodes
  346. if (hasattr(dummy, "reroute_links")):
  347. dummy.reroute_links(dummy, all_mantis_nodes)
  348. prGreen(f"Pulling data from tree took {time.time() - data_start_time} seconds")
  349. # base_tree.parsed_tree = all_mantis_nodes # for debugging
  350. start_time = time.time()
  351. solve_only_these = []; solve_only_these.extend(list(all_schema.values()))
  352. roots, array_nodes = [], []
  353. from collections import deque
  354. unsolved_schema = deque()
  355. from .base_definitions import array_output_types, GraphError
  356. for mantis_node in all_mantis_nodes.values():
  357. # add the Mantis Context here, so that it available during parsing.
  358. mantis_node.mContext = mContext
  359. if mantis_node.node_type in ["DUMMY"]: # clean up the groups
  360. if mantis_node.prototype.bl_idname in ("MantisNodeGroup", "NodeGroupOutput"):
  361. continue
  362. # Initialize the dependencies and connections (from/to links) for each node.
  363. # we record & store it because using a getter is much slower (according to profiling)
  364. init_dependencies(mantis_node); init_connections(mantis_node)
  365. check_and_add_root(mantis_node, roots, include_non_hierarchy=True)
  366. # Array nodes need a little special treatment, they're quasi-schemas
  367. if mantis_node.__class__.__name__ in array_output_types:
  368. solve_only_these.append(mantis_node)
  369. array_nodes.append(mantis_node)
  370. from itertools import chain
  371. for schema in chain(all_schema.values(), array_nodes):
  372. # We must remove the schema/array nodes that are inside a schema tree.
  373. for i in range(len(schema.signature)-1): # -1, we don't want to check this node, obviously
  374. if parent := all_schema.get(schema.signature[:i+1]):
  375. # This will be solved along with its parent schema.
  376. solve_only_these.remove(schema)
  377. break
  378. for schema in all_schema.values():
  379. if schema not in solve_only_these: continue
  380. init_schema_dependencies(schema, all_mantis_nodes)
  381. solve_only_these.extend(get_schema_length_dependencies(schema, all_mantis_nodes))
  382. unsolved_schema.append(schema)
  383. for array in array_nodes:
  384. if array not in solve_only_these: continue
  385. solve_only_these.extend(get_schema_length_dependencies(array))
  386. solve_only_these.extend(array_nodes)
  387. schema_solve_done = set()
  388. solve_only_these = set(solve_only_these)
  389. solve_layer = unsolved_schema.copy(); solve_layer.extend(roots)
  390. while(solve_layer):
  391. n = solve_layer.pop()
  392. if n not in solve_only_these:
  393. continue
  394. if n.signature in all_schema.keys():
  395. for dep in n.hierarchy_dependencies:
  396. if dep not in schema_solve_done and (dep in solve_only_these):
  397. if dep.prepared:
  398. continue
  399. solve_layer.appendleft(n)
  400. break
  401. else:
  402. try:
  403. solved_nodes = solve_schema_to_tree(n, all_mantis_nodes, roots, error_popups=error_popups)
  404. except Exception as e:
  405. e = execution_error_cleanup(n, e, show_error=error_popups)
  406. solved_nodes = {}
  407. if error_popups == False:
  408. raise e
  409. return # break out of this function regardless.
  410. unsolved_schema.remove(n)
  411. schema_solve_done.add(n)
  412. for node in solved_nodes.values():
  413. init_dependencies(node); init_connections(node)
  414. solve_layer.appendleft(node)
  415. schema_solve_done.add(node) # CRITICAL to prevent freezes.
  416. for conn in n.hierarchy_connections:
  417. if conn not in schema_solve_done and conn not in solve_layer:
  418. solve_layer.appendleft(conn)
  419. continue
  420. else:
  421. for dep in n.hierarchy_dependencies:
  422. if dep not in schema_solve_done:
  423. break
  424. else:
  425. try:
  426. n.bPrepare()
  427. except Exception as e:
  428. e = execution_error_cleanup(n, e, show_error=error_popups)
  429. if error_popups == False:
  430. raise e
  431. schema_solve_done.add(n)
  432. for conn in n.hierarchy_connections:
  433. if conn not in schema_solve_done and conn not in solve_layer:
  434. solve_layer.appendleft(conn)
  435. continue
  436. if unsolved_schema:
  437. raise RuntimeError("Failed to resolve all schema declarations")
  438. # I had a problem with this looping forever. I think it is resolved... but I don't know lol
  439. all_mantis_nodes = list(all_mantis_nodes.values())
  440. kept_nc = {}
  441. while (all_mantis_nodes):
  442. nc = all_mantis_nodes.pop()
  443. if nc in array_nodes:
  444. continue
  445. if nc.node_type in ["DUMMY", 'SCHEMA', 'DUMMY_SCHEMA']:
  446. continue # screen out the prototype schema nodes, group in/out, and group placeholders
  447. # cleanup autogen nodes
  448. if nc.signature[0] == "MANTIS_AUTOGENERATED" and len(nc.inputs) == 0 and len(nc.outputs) == 1:
  449. from .base_definitions import can_remove_socket_for_autogen
  450. output=list(nc.outputs.values())[0]
  451. value=list(nc.parameters.values())[0]
  452. # We can remove this node if it is safe to push it into the other node's socket.
  453. keep_me = False
  454. for l in output.links:
  455. to_node = l.to_node; to_socket = l.to_socket
  456. # do not remove the socket if it is a custom property.
  457. if not can_remove_socket_for_autogen(to_node, to_socket):
  458. keep_me = True; continue
  459. l.die()
  460. to_node.parameters[to_socket] = value
  461. del to_node.inputs[to_socket]
  462. init_dependencies(to_node) # to remove the autogen node we no longer need.
  463. if not keep_me:
  464. continue
  465. init_connections(nc) # because we have removed many connections.
  466. if (nc.node_type in ['XFORM']) and ("Relationship" in nc.inputs.keys()):
  467. if (new_nc := insert_lazy_parents(nc)):
  468. kept_nc[new_nc.signature]=new_nc
  469. # be sure to add the Mantis context.
  470. new_nc.mContext =mContext
  471. kept_nc[nc.signature]=nc
  472. prWhite(f"Parsing tree took {time.time()-start_time} seconds.")
  473. prWhite("Number of Nodes: %s" % (len(kept_nc)))
  474. return kept_nc
  475. from .utilities import switch_mode
  476. def execution_error_cleanup(node, exception, switch_objects = [], show_error=False ):
  477. from bpy import context
  478. ui_sig = None
  479. if show_error: # show a popup and select the relevant nodes
  480. if node:
  481. if node.mContext:
  482. if node.mContext.execution_failed==True:
  483. # already have an error, pass it to avoid printing
  484. return # a second error (it's confusing to users.)
  485. node.mContext.execution_failed=True
  486. ui_sig = node.ui_signature
  487. # TODO: see about zooming-to-node.
  488. base_tree = node.base_tree
  489. tree = base_tree
  490. try:
  491. pass
  492. space = context.space_data
  493. for name in ui_sig[1:]:
  494. for n in tree.nodes: n.select = False
  495. n = tree.nodes[name]
  496. n.select = True
  497. tree.nodes.active = n
  498. if hasattr(n, "node_tree"):
  499. tree = n.node_tree
  500. except AttributeError: # not being run in node graph
  501. pass
  502. finally:
  503. def error_popup_draw(self, context):
  504. self.layout.label(text=f"Error: {exception}")
  505. self.layout.label(text=f"see node: {ui_sig[1:]}.")
  506. context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  507. switch_mode(mode='OBJECT', objects=switch_objects)
  508. for ob in switch_objects:
  509. ob.data.pose_position = 'POSE'
  510. prRed(f"Error: {exception} in node {ui_sig}")
  511. return exception
  512. def sort_execution(nodes, xForm_pass):
  513. execution_failed=False
  514. sorted_nodes = []
  515. from .node_container_common import GraphError
  516. # check for cycles here by keeping track of the number of times a node has been visited.
  517. visited={}
  518. check_max_len=len(nodes)**2 # seems too high but safe. In a well-ordered graph, I guess this number should be less than the number of nodes.
  519. max_iterations = len(nodes)**2
  520. i = 0
  521. while(xForm_pass):
  522. if execution_failed: break
  523. if i >= max_iterations:
  524. execution_failed = True
  525. raise GraphError("There is probably a cycle somewhere in the graph. "
  526. "Or a connection missing in a Group/Schema Input")
  527. i+=1
  528. n = xForm_pass.pop()
  529. if visited.get(n.signature) is not None:
  530. visited[n.signature]+=1
  531. else:
  532. visited[n.signature]=0
  533. if visited[n.signature] > check_max_len:
  534. execution_failed = True
  535. raise GraphError("There is a probably a cycle in the graph somewhere. "
  536. "Or a connection missing in a Group/Schema Input")
  537. # we're trying to solve the halting problem at this point.. don't do that.
  538. # TODO find a better way! there are algo's for this but they will require using a different solving algo, too
  539. if n.execution_prepared:
  540. continue
  541. if n.node_type not in ['XFORM', 'UTILITY']:
  542. for dep in n.hierarchy_dependencies:
  543. if not dep.execution_prepared:
  544. xForm_pass.appendleft(n) # hold it
  545. break
  546. else:
  547. n.execution_prepared=True
  548. sorted_nodes.append(n)
  549. for conn in n.hierarchy_connections:
  550. if not conn.execution_prepared:
  551. xForm_pass.appendleft(conn)
  552. else:
  553. for dep in n.hierarchy_dependencies:
  554. if not dep.execution_prepared:
  555. break
  556. else:
  557. n.execution_prepared=True
  558. sorted_nodes.append(n)
  559. for conn in n.hierarchy_connections:
  560. if not conn.execution_prepared:
  561. xForm_pass.appendleft(conn)
  562. return sorted_nodes, execution_failed
  563. def execute_tree(nodes, base_tree, context, error_popups = False):
  564. assert nodes is not None, "Failed to parse tree."
  565. assert len(nodes) > 0, "No parsed nodes for execution."\
  566. " Mantis probably failed to parse the tree."
  567. import bpy
  568. from time import time
  569. from .node_container_common import GraphError
  570. original_active = context.view_layer.objects.active
  571. start_execution_time = time()
  572. mContext = None
  573. from collections import deque
  574. xForm_pass = deque()
  575. for nc in nodes.values():
  576. if not mContext: # just grab one of these. this is a silly way to do this.
  577. mContext = nc.mContext
  578. mContext.b_objects = {} # clear the objects and recreate them
  579. nc.reset_execution()
  580. check_and_add_root(nc, xForm_pass)
  581. mContext.execution_failed = False
  582. select_me, switch_me = [], [] # switch the mode on these objects
  583. active = None # only need it for switching modes
  584. try:
  585. sorted_nodes, execution_failed = sort_execution(nodes, xForm_pass)
  586. for n in sorted_nodes:
  587. try:
  588. if not n.prepared:
  589. n.bPrepare(context)
  590. if not n.executed:
  591. n.bTransformPass(context)
  592. if (n.__class__.__name__ == "xFormArmature" ):
  593. ob = n.bGetObject()
  594. switch_me.append(ob)
  595. active = ob
  596. if not (n.__class__.__name__ == "xFormBone" ) and hasattr(n, "bGetObject"):
  597. ob = n.bGetObject()
  598. if isinstance(ob, bpy.types.Object):
  599. select_me.append(ob)
  600. except Exception as e:
  601. e = execution_error_cleanup(n, e, show_error=error_popups)
  602. if error_popups == False:
  603. raise e
  604. execution_failed = True; break
  605. switch_mode(mode='POSE', objects=switch_me)
  606. for n in sorted_nodes:
  607. try:
  608. if not n.prepared:
  609. n.bPrepare(context)
  610. if not n.executed:
  611. n.bRelationshipPass(context)
  612. except Exception as e:
  613. e = execution_error_cleanup(n, e, show_error=error_popups)
  614. if error_popups == False:
  615. raise e
  616. execution_failed = True; break
  617. switch_mode(mode='OBJECT', objects=switch_me)
  618. # switch to pose mode here so that the nodes can use the final pose data
  619. # this will require them to update the depsgraph.
  620. for ob in switch_me:
  621. ob.data.pose_position = 'POSE'
  622. for n in sorted_nodes:
  623. try:
  624. n.bFinalize(context)
  625. except Exception as e:
  626. e = execution_error_cleanup(n, e, show_error=error_popups)
  627. if error_popups == False:
  628. raise e
  629. execution_failed = True; break
  630. # REST pose for deformer bind, so everything is in the rest position
  631. for ob in switch_me:
  632. ob.data.pose_position = 'REST'
  633. # finally, apply modifiers and bind stuff
  634. for n in sorted_nodes:
  635. try:
  636. n.bModifierApply(context)
  637. except Exception as e:
  638. e = execution_error_cleanup(n, e, show_error=error_popups)
  639. if error_popups == False:
  640. raise e
  641. execution_failed = True; break
  642. for ob in switch_me:
  643. ob.data.pose_position = 'POSE'
  644. tot_time = (time() - start_execution_time)
  645. if not execution_failed:
  646. prGreen(f"Executed tree of {len(sorted_nodes)} nodes in {tot_time} seconds")
  647. if (original_active):
  648. context.view_layer.objects.active = original_active
  649. original_active.select_set(True)
  650. except Exception as e:
  651. e = execution_error_cleanup(None, e, switch_me, show_error=error_popups)
  652. if error_popups == False:
  653. raise e
  654. prRed(f"Failed to execute tree.")
  655. finally:
  656. context.view_layer.objects.active = active
  657. # clear the selection first.
  658. from itertools import chain
  659. for ob in context.selected_objects:
  660. try:
  661. ob.select_set(False)
  662. except RuntimeError: # it isn't in the view layer
  663. pass
  664. for ob in chain(select_me, mContext.b_objects.values()):
  665. try:
  666. ob.select_set(True)
  667. except RuntimeError: # it isn't in the view layer
  668. pass