readtree.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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. from_name_filter = ["Driver", ]
  83. to_name_filter = [
  84. "Custom Object xForm Override",
  85. "Custom Object",
  86. "Deform Bones"
  87. ]
  88. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  89. # DATA FROM NODES #
  90. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  91. from .base_definitions import replace_types, NodeSocket
  92. # TODO: investigate whether I can set the properties in the downstream nodes directly.
  93. # I am doing this in Schema Solver and it seems to work quite efficiently.
  94. def make_connections_to_ng_dummy(base_tree, tree_path_names, local_nc, all_nc, nc_to):
  95. np = nc_to.prototype
  96. for inp in np.inputs:
  97. nc_from = None
  98. if inp.bl_idname in ['WildcardSocket']:
  99. continue # it isn't a real input so I don't think it is good to check it.
  100. to_s = inp.identifier
  101. if not inp.is_linked: # make an autogenerated NC for the inputs of the group node
  102. if inp.bl_idname in ['xFormSocket']:
  103. continue
  104. from .node_container_common import get_socket_value
  105. nc_cls = gen_nc_input_for_data(inp)
  106. if (nc_cls):
  107. sig = ("MANTIS_AUTOGENERATED", *tree_path_names, np.name, inp.name, inp.identifier)
  108. nc_from = nc_cls(sig, base_tree)
  109. # ugly! maybe even a HACK!
  110. nc_from.inputs = {}
  111. nc_from.outputs = {inp.name:NodeSocket(name = inp.name, node=nc_from)}
  112. nc_from.parameters = {inp.name:get_socket_value(inp)}
  113. #
  114. local_nc[sig] = nc_from; all_nc[sig] = nc_from
  115. from_s = inp.name
  116. else:
  117. prRed("No available auto-generated class for input", *tree_path_names, np.name, inp.name)
  118. nc_from.outputs[from_s].connect(node=nc_to, socket=to_s, sort_id=0)
  119. def gen_node_containers(base_tree, current_tree, tree_path_names, all_nc, local_nc, dummy_nodes, group_nodes, schema_nodes ):
  120. from .internal_containers import DummyNode
  121. for ui_node in current_tree.nodes:
  122. if ui_node.bl_idname in ["NodeFrame", "NodeReroute"]:
  123. continue # not a Mantis Node
  124. if ui_node.bl_idname in ["NodeGroupInput", "NodeGroupOutput"]:
  125. # we only want ONE dummy in/out per tree_path, so use the bl_idname to make a Dummy node
  126. sig = (None, *tree_path_names, ui_node.bl_idname)
  127. if not local_nc.get(sig):
  128. nc = DummyNode( signature=sig , base_tree=base_tree, prototype=ui_node )
  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. else:
  152. nc = None
  153. prRed(f"Can't make nc for.. {ui_node.bl_idname}")
  154. # this should be done at init
  155. if nc.signature[0] not in ['MANTIS_AUTOGENERATED'] and nc.node_type not in ['SCHEMA', 'DUMMY', 'DUMMY_SCHEMA']:
  156. nc.fill_parameters()
  157. def data_from_tree(base_tree, tree_path, dummy_nodes, all_nc, all_schema):#
  158. # TODO: it should be relatively easy to make this use a while loop instead of recursion.
  159. local_nc, group_nodes = {}, []
  160. tree_path_names = [tree.name for tree in tree_path if hasattr(tree, "name")]
  161. if tree_path[-1]:
  162. current_tree = tree_path[-1].node_tree # this may be None.
  163. else:
  164. current_tree = base_tree
  165. #
  166. if current_tree: # the node-group may not have a tree set - if so, ignore it.
  167. from .utilities import clear_reroutes
  168. links = clear_reroutes(list(current_tree.links))
  169. gen_node_containers(base_tree, current_tree, tree_path_names, all_nc, local_nc, dummy_nodes, group_nodes, all_schema)
  170. from .utilities import link_node_containers
  171. for link in links:
  172. link_node_containers((None, *tree_path_names), link, local_nc)
  173. # Now, descend into the Node Groups and recurse
  174. for nc in group_nodes:
  175. data_from_tree(base_tree, tree_path+[nc.prototype], dummy_nodes, all_nc, all_schema)
  176. return dummy_nodes, all_nc, all_schema
  177. from .utilities import check_and_add_root, init_connections, init_dependencies, init_schema_dependencies
  178. def is_signature_in_other_signature(parent_signature, child_signature):
  179. # If the other signature is shorter, it isn't a child node
  180. if len(parent_signature) > len(child_signature):
  181. return False
  182. return parent_signature[0:] == child_signature[:len(parent_signature)]
  183. def solve_schema_to_tree(nc, all_nc, roots=[]):
  184. from .utilities import get_node_prototype
  185. np = get_node_prototype(nc.signature, nc.base_tree)
  186. from .schema_solve import SchemaSolver
  187. tree = np.node_tree
  188. length = nc.evaluate_input("Schema Length")
  189. prOrange(f"Expanding schema {tree.name} in node {nc} with length {length}.")
  190. solver = SchemaSolver(nc, all_nc, np)
  191. solved_nodes = solver.solve()
  192. prWhite(f"Schema declared {len(solved_nodes)} nodes.")
  193. # maybe this should be done in schema solver. TODO invesitigate a more efficient way
  194. del_me = []
  195. for k, v in all_nc.items():
  196. # delete all the schema's internal nodes. The links have already been deleted by the solver.
  197. if v.signature[0] not in ['MANTIS_AUTOGENERATED'] and is_signature_in_other_signature(nc.signature, k):
  198. del_me.append(k)
  199. for k in del_me:
  200. del all_nc[k]
  201. for k,v in solved_nodes.items():
  202. all_nc[k]=v
  203. init_connections(v)
  204. check_and_add_root(v, roots, include_non_hierarchy=True)
  205. return solved_nodes
  206. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  207. # PARSE NODE TREE #
  208. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  209. schema_bl_idnames = [ "SchemaIndex",
  210. "SchemaArrayInput",
  211. "SchemaArrayInputGet",
  212. "SchemaArrayInputAll",
  213. "SchemaArrayOutput",
  214. "SchemaConstInput",
  215. "SchemaConstOutput",
  216. "SchemaOutgoingConnection",
  217. "SchemaIncomingConnection",
  218. ]
  219. from .utilities import get_all_dependencies
  220. def get_schema_length_dependencies(node, all_nodes={}):
  221. """ Get a list of all dependencies for the given node's length or array properties.
  222. This function will also recursively search for dependencies in its sub-trees.
  223. """
  224. deps = []
  225. prepare_links_to = ['Schema Length', 'Array', 'Index']
  226. if node.node_type == "DUMMY_SCHEMA":
  227. for item in node.prototype.node_tree.interface.items_tree:
  228. if item.item_type == 'PANEL': continue
  229. if item.parent:# and item.parent.name == 'Array':
  230. prepare_links_to.append(item.identifier)
  231. def extend_dependencies_from_inputs(node):
  232. for inp in node.inputs.values():
  233. for l in inp.links:
  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):
  265. from uuid import uuid4
  266. base_tree.execution_id = uuid4().__str__() # set the unique id of this execution
  267. import time
  268. data_start_time = time.time()
  269. # annoyingly I have to pass in values for all of the dicts because if I initialize them in the function call
  270. # then they stick around because the function definition inits them once and keeps a reference
  271. # so instead I have to supply them to avoid ugly code or bugs elsewhere
  272. # it's REALLY confusing when you run into this sort of problem. So it warrants four entire lines of comments!
  273. dummy_nodes, all_mantis_nodes, all_schema = data_from_tree(base_tree, tree_path = [None], dummy_nodes = {}, all_nc = {}, all_schema={})
  274. for dummy in dummy_nodes.values(): # reroute the links in the group nodes
  275. if (hasattr(dummy, "reroute_links")):
  276. dummy.reroute_links(dummy, all_mantis_nodes)
  277. prGreen(f"Pulling data from tree took {time.time() - data_start_time} seconds")
  278. start_time = time.time()
  279. solve_only_these = []; solve_only_these.extend(list(all_schema.values()))
  280. roots, array_nodes = [], []
  281. from collections import deque
  282. unsolved_schema = deque()
  283. from .base_definitions import array_output_types
  284. for mantis_node in all_mantis_nodes.values():
  285. if mantis_node.node_type in ["DUMMY"]: # clean up the groups
  286. if mantis_node.prototype.bl_idname in ("MantisNodeGroup", "NodeGroupOutput"):
  287. continue
  288. # Initialize the dependencies and connections (from/to links) for each node.
  289. # we record & store it because using a getter is much slower (according to profiling)
  290. init_dependencies(mantis_node); init_connections(mantis_node)
  291. check_and_add_root(mantis_node, roots, include_non_hierarchy=True)
  292. # Array nodes need a little special treatment, they're quasi-schemas
  293. if mantis_node.__class__.__name__ in array_output_types:
  294. solve_only_these.append(mantis_node)
  295. array_nodes.append(mantis_node)
  296. from itertools import chain
  297. for schema in chain(all_schema.values(), array_nodes):
  298. # We must remove the schema/array nodes that are inside a schema tree.
  299. for i in range(len(schema.signature)-1): # -1, we don't want to check this node, obviously
  300. if parent := all_schema.get(schema.signature[:i+1]):
  301. # This will be solved along with its parent schema.
  302. solve_only_these.remove(schema)
  303. break
  304. for schema in all_schema.values():
  305. if schema not in solve_only_these: continue
  306. init_schema_dependencies(schema, all_mantis_nodes)
  307. solve_only_these.extend(get_schema_length_dependencies(schema, all_mantis_nodes))
  308. unsolved_schema.append(schema)
  309. for array in array_nodes:
  310. if array not in solve_only_these: continue
  311. solve_only_these.extend(get_schema_length_dependencies(array))
  312. solve_only_these.extend(array_nodes)
  313. schema_solve_done = set()
  314. solve_only_these = set(solve_only_these)
  315. solve_layer = unsolved_schema.copy(); solve_layer.extend(roots)
  316. while(solve_layer):
  317. n = solve_layer.pop()
  318. if n not in solve_only_these: # removes the unneeded node from the solve-layer
  319. continue
  320. if n.signature in all_schema.keys():
  321. for dep in n.hierarchy_dependencies:
  322. if dep not in schema_solve_done and (dep in solve_only_these):
  323. if dep.prepared: # HACK HACK HACK
  324. continue
  325. # For some reason, the Schema Solver is able to detect and resolve
  326. # dependencies outside of solve_only_these. So I have to figure out why.
  327. solve_layer.appendleft(n)
  328. break
  329. else:
  330. solved_nodes = solve_schema_to_tree(n, all_mantis_nodes, roots)
  331. unsolved_schema.remove(n)
  332. schema_solve_done.add(n)
  333. for node in solved_nodes.values():
  334. #
  335. init_dependencies(node)
  336. init_connections(node)
  337. #
  338. solve_layer.appendleft(node)
  339. for conn in n.hierarchy_connections:
  340. if conn not in schema_solve_done and conn not in solve_layer:
  341. solve_layer.appendleft(conn)
  342. else:
  343. for dep in n.hierarchy_dependencies:
  344. if dep not in schema_solve_done:
  345. break
  346. else:
  347. try:
  348. n.bPrepare()
  349. except Exception as e:
  350. raise execution_error_cleanup(n, e)
  351. schema_solve_done.add(n)
  352. for conn in n.hierarchy_connections:
  353. if conn not in schema_solve_done and conn not in solve_layer:
  354. solve_layer.appendleft(conn)
  355. if unsolved_schema:
  356. raise RuntimeError("Failed to resolve all schema declarations")
  357. # I had a problem with this looping forever. I think it is resolved... but I don't know lol
  358. all_mantis_nodes = list(all_mantis_nodes.values())
  359. kept_nc = {}
  360. while (all_mantis_nodes):
  361. nc = all_mantis_nodes.pop()
  362. if nc in array_nodes:
  363. continue
  364. if nc.node_type in ["DUMMY"]:
  365. continue
  366. # cleanup autogen nodes
  367. if nc.signature[0] == "MANTIS_AUTOGENERATED" and len(nc.inputs) == 0 and len(nc.outputs) == 1:
  368. output=list(nc.outputs.values())[0]
  369. value=list(nc.parameters.values())[0] # IDEA modify the dependecy get function to exclude these nodes completely
  370. for l in output.links:
  371. to_node = l.to_node; to_socket = l.to_socket
  372. l.die()
  373. to_node.parameters[to_socket] = value
  374. del to_node.inputs[to_socket]
  375. init_dependencies(to_node)
  376. continue
  377. if (nc.node_type in ['XFORM']) and ("Relationship" in nc.inputs.keys()):
  378. if (new_nc := insert_lazy_parents(nc)):
  379. kept_nc[new_nc.signature]=new_nc
  380. kept_nc[nc.signature]=nc
  381. prWhite(f"Parsing tree took {time.time()-start_time} seconds.")
  382. prWhite("Number of Nodes: %s" % (len(kept_nc)))
  383. return kept_nc
  384. def switch_mode(mode='OBJECT', objects = []):
  385. active = None
  386. if objects:
  387. from bpy import context, ops
  388. active = objects[-1]
  389. context.view_layer.objects.active = active
  390. if (active):
  391. with context.temp_override(**{'active_object':active, 'selected_objects':objects}):
  392. ops.object.mode_set(mode=mode)
  393. return active
  394. def execution_error_cleanup(node, exception, switch_objects = [] ):
  395. from bpy import context
  396. if node:
  397. # TODO: see about zooming-to-node.
  398. base_tree = node.base_tree
  399. tree = base_tree
  400. try:
  401. pass
  402. space = context.space_data
  403. for name in node.signature[1:]:
  404. for n in tree.nodes: n.select = False
  405. n = tree.nodes[name]
  406. n.select = True
  407. tree.nodes.active = n
  408. if hasattr(n, "node_tree"):
  409. tree = n.node_tree
  410. except AttributeError: # not being run in node graph
  411. pass
  412. finally:
  413. def error_popup_draw(self, context):
  414. self.layout.label(text=f"Error: {exception}")
  415. self.layout.label(text=f"see node: {node.signature[1:]}.")
  416. context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  417. switch_mode(mode='OBJECT', objects=switch_objects)
  418. for ob in switch_objects:
  419. ob.data.pose_position = 'POSE'
  420. prRed(f"Error: {exception} in node {node}")
  421. return exception
  422. def execute_tree(nodes, base_tree, context, error_popups = False):
  423. import bpy
  424. from time import time
  425. from .node_container_common import GraphError
  426. original_active = context.view_layer.objects.active
  427. start_execution_time = time()
  428. from collections import deque
  429. xForm_pass = deque()
  430. for nc in nodes.values():
  431. nc.prepared = False
  432. nc.executed = False
  433. check_and_add_root(nc, xForm_pass)
  434. executed = []
  435. # check for cycles here by keeping track of the number of times a node has been visited.
  436. visited={}
  437. 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.
  438. max_iterations = len(nodes)**2
  439. i = 0
  440. switch_me = [] # switch the mode on these objects
  441. active = None # only need it for switching modes
  442. select_me = []
  443. try:
  444. while(xForm_pass):
  445. if i >= max_iterations:
  446. raise GraphError("There is probably a cycle somewhere in the graph.")
  447. i+=1
  448. n = xForm_pass.pop()
  449. if visited.get(n.signature) is not None:
  450. visited[n.signature]+=1
  451. else:
  452. visited[n.signature]=0
  453. if visited[n.signature] > check_max_len:
  454. raise GraphError("There is a probably a cycle in the graph somewhere. Fix it!")
  455. # we're trying to solve the halting problem at this point.. don't do that.
  456. # TODO find a better way! there are algo's for this but they will require using a different solving algo, too
  457. if n.prepared:
  458. continue
  459. if n.node_type not in ['XFORM', 'UTILITY']:
  460. for dep in n.hierarchy_dependencies:
  461. if not dep.prepared:
  462. xForm_pass.appendleft(n) # hold it
  463. break
  464. else:
  465. n.prepared=True
  466. executed.append(n)
  467. for conn in n.hierarchy_connections:
  468. if not conn.prepared:
  469. xForm_pass.appendleft(conn)
  470. else:
  471. for dep in n.hierarchy_dependencies:
  472. if not dep.prepared:
  473. break
  474. else:
  475. try:
  476. n.bPrepare(context)
  477. if not n.executed:
  478. n.bExecute(context)
  479. if (n.__class__.__name__ == "xFormArmature" ):
  480. ob = n.bGetObject()
  481. switch_me.append(ob)
  482. active = ob
  483. if not (n.__class__.__name__ == "xFormBone" ) and hasattr(n, "bGetObject"):
  484. ob = n.bGetObject()
  485. if isinstance(ob, bpy.types.Object):
  486. select_me.append(ob)
  487. except Exception as e:
  488. if error_popups:
  489. raise execution_error_cleanup(n, e,)
  490. else:
  491. raise e
  492. n.prepared=True
  493. executed.append(n)
  494. for conn in n.hierarchy_connections:
  495. if not conn.prepared:
  496. xForm_pass.appendleft(conn)
  497. switch_mode(mode='POSE', objects=switch_me)
  498. if (active):
  499. with context.temp_override(**{'active_object':active, 'selected_objects':switch_me}):
  500. bpy.ops.object.mode_set(mode='POSE')
  501. for n in executed:
  502. try:
  503. n.bPrepare(context)
  504. if not n.executed:
  505. n.bExecute(context)
  506. except Exception as e:
  507. if error_popups:
  508. raise execution_error_cleanup(n, e,)
  509. else:
  510. raise e
  511. switch_mode(mode='OBJECT', objects=switch_me)
  512. for ob in switch_me:
  513. ob.data.pose_position = 'POSE'
  514. # switch to pose mode here so that the nodes can use the final pose data
  515. # this will require them to update the depsgraph.
  516. for n in executed:
  517. try:
  518. n.bFinalize(context)
  519. except Exception as e:
  520. if error_popups:
  521. raise execution_error_cleanup(n, e,)
  522. else:
  523. raise e
  524. tot_time = (time() - start_execution_time)
  525. prGreen(f"Executed tree of {len(executed)} nodes in {tot_time} seconds")
  526. if (original_active):
  527. context.view_layer.objects.active = original_active
  528. original_active.select_set(True)
  529. except Exception as e:
  530. execution_error_cleanup(None, e, switch_me)
  531. if error_popups == False:
  532. raise e
  533. finally:
  534. context.view_layer.objects.active = active
  535. # clear the selection first.
  536. for ob in context.selected_objects:
  537. try:
  538. ob.select_set(False)
  539. except RuntimeError: # it isn't in the view layer
  540. pass
  541. for ob in select_me:
  542. try:
  543. ob.select_set(True)
  544. except RuntimeError: # it isn't in the view layer
  545. pass