readtree.py 28 KB

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