readtree.py 31 KB

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