readtree.py 29 KB

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