readtree.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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_node_containers(base_tree, current_tree, tree_path_names, 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. local_nc[sig] = nc; all_nc[sig] = nc; dummy_nodes[sig] = nc
  135. if ui_node.bl_idname in ["NodeGroupOutput"]:
  136. nc.reroute_links = reroute_links_grpout
  137. elif ui_node.bl_idname in ["MantisNodeGroup", "MantisSchemaGroup"]:
  138. nc = DummyNode( signature= (sig := (None, *tree_path_names, ui_node.name) ), base_tree=base_tree, prototype=ui_node )
  139. local_nc[sig] = nc; all_nc[sig] = nc; dummy_nodes[sig] = nc
  140. make_connections_to_ng_dummy(base_tree, tree_path_names, local_nc, all_nc, nc)
  141. if ui_node.bl_idname == "MantisNodeGroup":
  142. group_nodes.append(nc)
  143. nc.reroute_links = reroute_links_grp
  144. else:
  145. group_nodes.append(nc)
  146. schema_nodes[sig] = nc
  147. # if it wasn't the types we ignore or the types we make a Dummy for, use this to catch all non-special cases.
  148. elif (nc_cls := ui_node.mantis_class):
  149. sig = (None, *tree_path_names, ui_node.name)
  150. if ui_node.bl_idname in replace_types:
  151. sig = (None, *tree_path_names, ui_node.bl_idname)
  152. if local_nc.get(sig):
  153. continue # already made
  154. nc = nc_cls( sig , base_tree)
  155. local_nc[sig] = nc; all_nc[sig] = nc
  156. nc.ui_signature = (*nc.ui_signature[:-1], ui_node.name) # just to ensure it points to a real node.
  157. else:
  158. nc = None
  159. prRed(f"Can't make nc for.. {ui_node.bl_idname}")
  160. # this should be done at init
  161. if nc.signature[0] not in ['MANTIS_AUTOGENERATED'] and nc.node_type not in ['SCHEMA', 'DUMMY', 'DUMMY_SCHEMA']:
  162. nc.fill_parameters()
  163. def data_from_tree(base_tree, tree_path, dummy_nodes, all_nc, all_schema):#
  164. # TODO: it should be relatively easy to make this use a while loop instead of recursion.
  165. local_nc, group_nodes = {}, []
  166. tree_path_names = [tree.name for tree in tree_path if hasattr(tree, "name")]
  167. if tree_path[-1]:
  168. current_tree = tree_path[-1].node_tree # this may be None.
  169. else:
  170. current_tree = base_tree
  171. #
  172. if current_tree: # the node-group may not have a tree set - if so, ignore it.
  173. from .utilities import clear_reroutes
  174. links = clear_reroutes(list(current_tree.links))
  175. gen_node_containers(base_tree, current_tree, tree_path_names, all_nc, local_nc, dummy_nodes, group_nodes, all_schema)
  176. from .utilities import link_node_containers
  177. for link in links:
  178. link_node_containers((None, *tree_path_names), link, local_nc)
  179. # Now, descend into the Node Groups and recurse
  180. for nc in group_nodes:
  181. data_from_tree(base_tree, tree_path+[nc.prototype], dummy_nodes, all_nc, all_schema)
  182. return dummy_nodes, all_nc, all_schema
  183. from .utilities import check_and_add_root, init_connections, init_dependencies, init_schema_dependencies
  184. def is_signature_in_other_signature(parent_signature, child_signature):
  185. # If the other signature is shorter, it isn't a child node
  186. if len(parent_signature) > len(child_signature):
  187. return False
  188. return parent_signature[0:] == child_signature[:len(parent_signature)]
  189. def solve_schema_to_tree(nc, all_nc, roots=[], error_popups=False):
  190. from .utilities import get_node_prototype
  191. np = get_node_prototype(nc.signature, nc.base_tree)
  192. from .schema_solve import SchemaSolver
  193. solver = SchemaSolver(nc, all_nc.copy(), np, error_popups=error_popups)
  194. try:
  195. solved_nodes = solver.solve()
  196. except Exception as e:
  197. # # the schema will run the error cleanup code, we just need to raise or not
  198. solved_nodes = {}
  199. nc.base_tree.hash=''
  200. raise execution_error_cleanup(nc, e, show_error=error_popups)
  201. # maybe this should be done in schema solver. TODO invesitigate a more efficient way
  202. del_me = []
  203. for k, v in all_nc.items():
  204. # delete all the schema's prototype and interface nodes. The links have already been deleted by the solver.
  205. if v.signature[0] not in ['MANTIS_AUTOGENERATED'] and is_signature_in_other_signature(nc.signature, k):
  206. del_me.append(k)
  207. for k in del_me:
  208. del all_nc[k]
  209. for k,v in solved_nodes.items():
  210. all_nc[k]=v
  211. init_connections(v)
  212. check_and_add_root(v, roots, include_non_hierarchy=True)
  213. return solved_nodes
  214. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  215. # PARSE NODE TREE #
  216. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  217. schema_bl_idnames = [ "SchemaIndex",
  218. "SchemaArrayInput",
  219. "SchemaArrayInputGet",
  220. "SchemaArrayInputAll",
  221. "SchemaArrayOutput",
  222. "SchemaConstInput",
  223. "SchemaConstOutput",
  224. "SchemaOutgoingConnection",
  225. "SchemaIncomingConnection",
  226. ]
  227. from .utilities import get_all_dependencies
  228. def get_schema_length_dependencies(node, all_nodes={}):
  229. """ Get a list of all dependencies for the given node's length or array properties.
  230. This function will also recursively search for dependencies in its sub-trees.
  231. """
  232. deps = []
  233. prepare_links_to = ['Schema Length', 'Array', 'Index']
  234. def extend_dependencies_from_inputs(node):
  235. for inp in node.inputs.values():
  236. for l in inp.links:
  237. if not l.from_node in node.hierarchy_dependencies:
  238. continue
  239. if "MANTIS_AUTOGENERATED" in l.from_node.signature:
  240. deps.extend([l.from_node]) # why we need this lol
  241. if inp.name in prepare_links_to:
  242. deps.append(l.from_node)
  243. deps.extend(get_all_dependencies(l.from_node))
  244. def deps_filter(dep): # remove any nodes inside the schema
  245. if len(dep.signature) > len(node.signature):
  246. for i in range(len(node.signature)):
  247. dep_sig_elem, node_sig_elem = dep.signature[i], node.signature[i]
  248. if dep_sig_elem != node_sig_elem: break # they don't match, it isn't an inner-node
  249. else: # remove this, it didn't break, meaning it shares signature with outer node
  250. return False # this is an inner-node
  251. return True
  252. # this way we can handle Schema and Array Get nodes with one function
  253. extend_dependencies_from_inputs(node)
  254. if node.node_type == 'DUMMY_SCHEMA':
  255. trees = [(node.prototype.node_tree, node.signature)] # this is UI data
  256. while trees:
  257. tree, tree_signature = trees.pop()
  258. for sub_ui_node in tree.nodes:
  259. if sub_ui_node.bl_idname in ['NodeReroute', 'NodeFrame']:
  260. continue
  261. if sub_ui_node.bl_idname in schema_bl_idnames:
  262. sub_node = all_nodes[(*tree_signature, sub_ui_node.bl_idname)]
  263. else:
  264. sub_node = all_nodes[(*tree_signature, sub_ui_node.name)]
  265. if sub_node.node_type == 'DUMMY_SCHEMA':
  266. extend_dependencies_from_inputs(sub_node)
  267. trees.append((sub_node.prototype.node_tree, sub_node.signature))
  268. return list(filter(deps_filter, deps))
  269. def parse_tree(base_tree, error_popups=False):
  270. from uuid import uuid4
  271. base_tree.execution_id = uuid4().__str__() # set the unique id of this execution
  272. from .base_definitions import MantisExecutionContext
  273. mContext = MantisExecutionContext(base_tree=base_tree)
  274. import time
  275. data_start_time = time.time()
  276. # annoyingly I have to pass in values for all of the dicts because if I initialize them in the function call
  277. # then they stick around because the function definition inits them once and keeps a reference
  278. # so instead I have to supply them to avoid ugly code or bugs elsewhere
  279. # it's REALLY confusing when you run into this sort of problem. So it warrants four entire lines of comments!
  280. dummy_nodes, all_mantis_nodes, all_schema = data_from_tree(base_tree, tree_path = [None], dummy_nodes = {}, all_nc = {}, all_schema={})
  281. for dummy in dummy_nodes.values(): # reroute the links in the group nodes
  282. if (hasattr(dummy, "reroute_links")):
  283. dummy.reroute_links(dummy, all_mantis_nodes)
  284. prGreen(f"Pulling data from tree took {time.time() - data_start_time} seconds")
  285. start_time = time.time()
  286. solve_only_these = []; solve_only_these.extend(list(all_schema.values()))
  287. roots, array_nodes = [], []
  288. from collections import deque
  289. unsolved_schema = deque()
  290. from .base_definitions import array_output_types, GraphError
  291. for mantis_node in all_mantis_nodes.values():
  292. # add the Mantis Context here, so that it available during parsing.
  293. mantis_node.mContext = mContext
  294. if mantis_node.node_type in ["DUMMY"]: # clean up the groups
  295. if mantis_node.prototype.bl_idname in ("MantisNodeGroup", "NodeGroupOutput"):
  296. continue
  297. # Initialize the dependencies and connections (from/to links) for each node.
  298. # we record & store it because using a getter is much slower (according to profiling)
  299. init_dependencies(mantis_node); init_connections(mantis_node)
  300. check_and_add_root(mantis_node, roots, include_non_hierarchy=True)
  301. # Array nodes need a little special treatment, they're quasi-schemas
  302. if mantis_node.__class__.__name__ in array_output_types:
  303. solve_only_these.append(mantis_node)
  304. array_nodes.append(mantis_node)
  305. from itertools import chain
  306. for schema in chain(all_schema.values(), array_nodes):
  307. # We must remove the schema/array nodes that are inside a schema tree.
  308. for i in range(len(schema.signature)-1): # -1, we don't want to check this node, obviously
  309. if parent := all_schema.get(schema.signature[:i+1]):
  310. # This will be solved along with its parent schema.
  311. solve_only_these.remove(schema)
  312. break
  313. for schema in all_schema.values():
  314. if schema not in solve_only_these: continue
  315. init_schema_dependencies(schema, all_mantis_nodes)
  316. solve_only_these.extend(get_schema_length_dependencies(schema, all_mantis_nodes))
  317. unsolved_schema.append(schema)
  318. for array in array_nodes:
  319. if array not in solve_only_these: continue
  320. solve_only_these.extend(get_schema_length_dependencies(array))
  321. solve_only_these.extend(array_nodes)
  322. schema_solve_done = set()
  323. solve_only_these = set(solve_only_these)
  324. solve_layer = unsolved_schema.copy(); solve_layer.extend(roots)
  325. while(solve_layer):
  326. n = solve_layer.pop()
  327. if n not in solve_only_these:
  328. continue
  329. if n.signature in all_schema.keys():
  330. for dep in n.hierarchy_dependencies:
  331. if dep not in schema_solve_done and (dep in solve_only_these):
  332. if dep.prepared:
  333. continue
  334. solve_layer.appendleft(n)
  335. break
  336. else:
  337. try:
  338. solved_nodes = solve_schema_to_tree(n, all_mantis_nodes, roots, error_popups=error_popups)
  339. except Exception as e:
  340. e = execution_error_cleanup(n, e, show_error=error_popups)
  341. solved_nodes = {}
  342. if error_popups == False:
  343. raise e
  344. return # break out of this function regardless.
  345. unsolved_schema.remove(n)
  346. schema_solve_done.add(n)
  347. for node in solved_nodes.values():
  348. init_dependencies(node); init_connections(node)
  349. solve_layer.appendleft(node)
  350. schema_solve_done.add(node) # CRITICAL to prevent freezes.
  351. for conn in n.hierarchy_connections:
  352. if conn not in schema_solve_done and conn not in solve_layer:
  353. solve_layer.appendleft(conn)
  354. continue
  355. else:
  356. for dep in n.hierarchy_dependencies:
  357. if dep not in schema_solve_done:
  358. break
  359. else:
  360. try:
  361. n.bPrepare()
  362. except Exception as e:
  363. e = execution_error_cleanup(n, e, show_error=error_popups)
  364. if error_popups == False:
  365. raise e
  366. schema_solve_done.add(n)
  367. for conn in n.hierarchy_connections:
  368. if conn not in schema_solve_done and conn not in solve_layer:
  369. solve_layer.appendleft(conn)
  370. continue
  371. if unsolved_schema:
  372. raise RuntimeError("Failed to resolve all schema declarations")
  373. # I had a problem with this looping forever. I think it is resolved... but I don't know lol
  374. all_mantis_nodes = list(all_mantis_nodes.values())
  375. kept_nc = {}
  376. while (all_mantis_nodes):
  377. nc = all_mantis_nodes.pop()
  378. if nc in array_nodes:
  379. continue
  380. if nc.node_type in ["DUMMY", 'SCHEMA', 'DUMMY_SCHEMA']:
  381. continue # screen out the prototype schema nodes, group in/out, and group placeholders
  382. # cleanup autogen nodes
  383. if nc.signature[0] == "MANTIS_AUTOGENERATED" and len(nc.inputs) == 0 and len(nc.outputs) == 1:
  384. from .base_definitions import can_remove_socket_for_autogen
  385. output=list(nc.outputs.values())[0]
  386. value=list(nc.parameters.values())[0] # IDEA modify the dependecy get function to exclude these nodes completely
  387. keep_me = False
  388. for l in output.links:
  389. to_node = l.to_node; to_socket = l.to_socket
  390. # do not remove the socket if it is a custom property.
  391. if not can_remove_socket_for_autogen(to_node, to_socket):
  392. keep_me = True; continue
  393. l.die()
  394. to_node.parameters[to_socket] = value
  395. del to_node.inputs[to_socket]
  396. init_dependencies(to_node) # to remove the autogen node we no longer need.
  397. if not keep_me:
  398. continue
  399. init_connections(nc) # because we have removed many connections.
  400. if (nc.node_type in ['XFORM']) and ("Relationship" in nc.inputs.keys()):
  401. if (new_nc := insert_lazy_parents(nc)):
  402. kept_nc[new_nc.signature]=new_nc
  403. # be sure to add the Mantis context.
  404. new_nc.mContext =mContext
  405. kept_nc[nc.signature]=nc
  406. prWhite(f"Parsing tree took {time.time()-start_time} seconds.")
  407. prWhite("Number of Nodes: %s" % (len(kept_nc)))
  408. return kept_nc
  409. from .utilities import switch_mode
  410. def execution_error_cleanup(node, exception, switch_objects = [], show_error=False ):
  411. from bpy import context
  412. ui_sig = None
  413. if show_error: # show a popup and select the relevant nodes
  414. if node:
  415. if node.mContext:
  416. if node.mContext.execution_failed==True:
  417. # already have an error, pass it to avoid printing
  418. return # a second error (it's confusing to users.)
  419. node.mContext.execution_failed=True
  420. ui_sig = node.ui_signature
  421. # TODO: see about zooming-to-node.
  422. base_tree = node.base_tree
  423. tree = base_tree
  424. try:
  425. pass
  426. space = context.space_data
  427. for name in ui_sig[1:]:
  428. for n in tree.nodes: n.select = False
  429. n = tree.nodes[name]
  430. n.select = True
  431. tree.nodes.active = n
  432. if hasattr(n, "node_tree"):
  433. tree = n.node_tree
  434. except AttributeError: # not being run in node graph
  435. pass
  436. finally:
  437. def error_popup_draw(self, context):
  438. self.layout.label(text=f"Error: {exception}")
  439. self.layout.label(text=f"see node: {ui_sig[1:]}.")
  440. context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  441. switch_mode(mode='OBJECT', objects=switch_objects)
  442. for ob in switch_objects:
  443. ob.data.pose_position = 'POSE'
  444. prRed(f"Error: {exception} in node {ui_sig}")
  445. return exception
  446. def sort_execution(nodes, xForm_pass):
  447. execution_failed=False
  448. sorted_nodes = []
  449. from .node_container_common import GraphError
  450. # check for cycles here by keeping track of the number of times a node has been visited.
  451. visited={}
  452. 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.
  453. max_iterations = len(nodes)**2
  454. i = 0
  455. while(xForm_pass):
  456. if execution_failed: break
  457. if i >= max_iterations:
  458. execution_failed = True
  459. raise GraphError("There is probably a cycle somewhere in the graph. "
  460. "Or a connection missing in a Group/Schema Input")
  461. i+=1
  462. n = xForm_pass.pop()
  463. if visited.get(n.signature) is not None:
  464. visited[n.signature]+=1
  465. else:
  466. visited[n.signature]=0
  467. if visited[n.signature] > check_max_len:
  468. execution_failed = True
  469. raise GraphError("There is a probably a cycle in the graph somewhere. "
  470. "Or a connection missing in a Group/Schema Input")
  471. # we're trying to solve the halting problem at this point.. don't do that.
  472. # TODO find a better way! there are algo's for this but they will require using a different solving algo, too
  473. if n.execution_prepared:
  474. continue
  475. if n.node_type not in ['XFORM', 'UTILITY']:
  476. for dep in n.hierarchy_dependencies:
  477. if not dep.execution_prepared:
  478. xForm_pass.appendleft(n) # hold it
  479. break
  480. else:
  481. n.execution_prepared=True
  482. sorted_nodes.append(n)
  483. for conn in n.hierarchy_connections:
  484. if not conn.execution_prepared:
  485. xForm_pass.appendleft(conn)
  486. else:
  487. for dep in n.hierarchy_dependencies:
  488. if not dep.execution_prepared:
  489. break
  490. else:
  491. n.execution_prepared=True
  492. sorted_nodes.append(n)
  493. for conn in n.hierarchy_connections:
  494. if not conn.execution_prepared:
  495. xForm_pass.appendleft(conn)
  496. return sorted_nodes, execution_failed
  497. def execute_tree(nodes, base_tree, context, error_popups = False):
  498. assert nodes is not None, "Failed to parse tree."
  499. assert len(nodes) > 0, "No parsed nodes for execution."\
  500. " Mantis probably failed to parse the tree."
  501. import bpy
  502. from time import time
  503. from .node_container_common import GraphError
  504. original_active = context.view_layer.objects.active
  505. start_execution_time = time()
  506. mContext = None
  507. from collections import deque
  508. xForm_pass = deque()
  509. for nc in nodes.values():
  510. if not mContext: # just grab one of these. this is a silly way to do this.
  511. mContext = nc.mContext
  512. mContext.b_objects = {} # clear the objects and recreate them
  513. nc.reset_execution()
  514. check_and_add_root(nc, xForm_pass)
  515. mContext.execution_failed = False
  516. switch_me = [] # switch the mode on these objects
  517. active = None # only need it for switching modes
  518. select_me = []
  519. try:
  520. sorted_nodes, execution_failed = sort_execution(nodes, xForm_pass)
  521. for n in sorted_nodes:
  522. try:
  523. if not n.prepared:
  524. n.bPrepare(context)
  525. if not n.executed:
  526. n.bTransformPass(context)
  527. if (n.__class__.__name__ == "xFormArmature" ):
  528. ob = n.bGetObject()
  529. switch_me.append(ob)
  530. active = ob
  531. if not (n.__class__.__name__ == "xFormBone" ) and hasattr(n, "bGetObject"):
  532. ob = n.bGetObject()
  533. if isinstance(ob, bpy.types.Object):
  534. select_me.append(ob)
  535. except Exception as e:
  536. e = execution_error_cleanup(n, e, show_error=error_popups)
  537. if error_popups == False:
  538. raise e
  539. execution_failed = True; break
  540. switch_mode(mode='POSE', objects=switch_me)
  541. for n in sorted_nodes:
  542. try:
  543. if not n.prepared:
  544. n.bPrepare(context)
  545. if not n.executed:
  546. n.bRelationshipPass(context)
  547. except Exception as e:
  548. e = execution_error_cleanup(n, e, show_error=error_popups)
  549. if error_popups == False:
  550. raise e
  551. execution_failed = True; break
  552. switch_mode(mode='OBJECT', objects=switch_me)
  553. # switch to pose mode here so that the nodes can use the final pose data
  554. # this will require them to update the depsgraph.
  555. for ob in switch_me:
  556. ob.data.pose_position = 'POSE'
  557. for n in sorted_nodes:
  558. try:
  559. n.bFinalize(context)
  560. except Exception as e:
  561. e = execution_error_cleanup(n, e, show_error=error_popups)
  562. if error_popups == False:
  563. raise e
  564. execution_failed = True; break
  565. # REST pose for deformer bind, so everything is in the rest position
  566. for ob in switch_me:
  567. ob.data.pose_position = 'REST'
  568. # finally, apply modifiers and bind stuff
  569. for n in sorted_nodes:
  570. try:
  571. n.bModifierApply(context)
  572. except Exception as e:
  573. e = execution_error_cleanup(n, e, show_error=error_popups)
  574. if error_popups == False:
  575. raise e
  576. execution_failed = True; break
  577. for ob in switch_me:
  578. ob.data.pose_position = 'POSE'
  579. tot_time = (time() - start_execution_time)
  580. if not execution_failed:
  581. prGreen(f"Executed tree of {len(sorted_nodes)} nodes in {tot_time} seconds")
  582. if (original_active):
  583. context.view_layer.objects.active = original_active
  584. original_active.select_set(True)
  585. except Exception as e:
  586. e = execution_error_cleanup(None, e, switch_me, show_error=error_popups)
  587. if error_popups == False:
  588. raise e
  589. prRed(f"Failed to execute tree.")
  590. finally:
  591. context.view_layer.objects.active = active
  592. # clear the selection first.
  593. from itertools import chain
  594. for ob in context.selected_objects:
  595. try:
  596. ob.select_set(False)
  597. except RuntimeError: # it isn't in the view layer
  598. pass
  599. for ob in chain(select_me, mContext.b_objects.values()):
  600. try:
  601. ob.select_set(True)
  602. except RuntimeError: # it isn't in the view layer
  603. pass