readtree.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. # Recurse!
  36. downlink.to_node.reroute_links(downlink.to_node, all_nc)
  37. in_link.die()
  38. def reroute_links_grp(nc, all_nc):
  39. if (nc_to := all_nc.get( ( *nc.signature, "NodeGroupInput") )):
  40. reroute_common(nc, nc_to, all_nc)
  41. else:
  42. raise RuntimeError("Cannot read graph for some goshblamed son of a reason")
  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?)... TODO: this should still work")
  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 .xForm_containers import xFormArmature
  54. from .node_container_common import NodeLink
  55. inherit_nc = None
  56. if nc.inputs["Relationship"].is_connected:
  57. link = nc.inputs["Relationship"].links[0]
  58. # print(nc)
  59. from_nc = link.from_node
  60. if from_nc.node_type in ["XFORM"] and link.from_socket in ["xForm Out"]:
  61. inherit_nc = LinkInherit(("MANTIS_AUTOGENERATED", *nc.signature[1:], "LAZY_INHERIT"), nc.base_tree)
  62. for from_link in from_nc.outputs["xForm Out"].links:
  63. if from_link.to_node == nc and from_link.to_socket == "Relationship":
  64. break # this is it
  65. from_link.to_node = inherit_nc; from_link.to_socket="Parent"
  66. links=[]
  67. while (nc.inputs["Relationship"].links):
  68. to_link = nc.inputs["Relationship"].links.pop()
  69. if to_link.from_node == from_nc and to_link.from_socket == "xForm Out":
  70. continue # don't keep this one
  71. links.append(to_link)
  72. nc.inputs["Relationship"].links=links
  73. link=NodeLink(from_node=inherit_nc, from_socket="Inheritance", to_node=nc, to_socket="Relationship")
  74. inherit_nc.inputs["Parent"].links.append(from_link)
  75. inherit_nc.parameters = {
  76. "Parent":None,
  77. "Inherit Rotation":True,
  78. "Inherit Scale":'FULL',
  79. "Connected":False,
  80. }
  81. # because the from node may have already been done.
  82. init_connections(from_nc)
  83. init_dependencies(from_nc)
  84. init_connections(inherit_nc)
  85. init_dependencies(inherit_nc)
  86. return inherit_nc
  87. from_name_filter = ["Driver", ]
  88. to_name_filter = [
  89. "Custom Object xForm Override",
  90. "Custom Object",
  91. "Deform Bones"
  92. ]
  93. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  94. # DATA FROM NODES #
  95. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  96. from .base_definitions import replace_types
  97. # TODO: investigate whether I can set the properties in the downstream nodes directly.
  98. # I am doing this in Schema Solver and it seems to work quite efficiently.
  99. def make_connections_to_ng_dummy(base_tree, tree_path_names, local_nc, all_nc, np):
  100. from .node_container_common import NodeSocket
  101. nc_to = local_nc[(None, *tree_path_names, np.name)]
  102. for inp in np.inputs:
  103. nc_from = None
  104. if inp.bl_idname in ['WildcardSocket']:
  105. continue # it isn't a real input so I don't think it is good to check it.
  106. to_s = inp.identifier
  107. if not inp.is_linked: # make an autogenerated NC for the inputs of the group node
  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: # should this be an error instead?
  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 SchemaNode
  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, SchemaNode):
  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
  178. else:
  179. current_tree = base_tree
  180. #
  181. from .utilities import clear_reroutes
  182. links = clear_reroutes(list(current_tree.links))
  183. gen_node_containers(base_tree, current_tree, tree_path_names, all_nc, local_nc, dummy_nodes, group_nodes, all_schema)
  184. from .utilities import link_node_containers
  185. for link in links:
  186. link_node_containers((None, *tree_path_names), link, local_nc)
  187. # Now, descend into the Node Groups and recurse
  188. for nc in group_nodes:
  189. # ng = get_node_prototype(nc.signature, base_tree)
  190. data_from_tree(base_tree, tree_path+[nc.prototype], dummy_nodes, all_nc, all_schema)
  191. return dummy_nodes, all_nc, all_schema
  192. from .utilities import check_and_add_root, init_connections, init_dependencies, init_schema_dependencies
  193. def delete_nc(nc):
  194. return
  195. # this doesn't seem to work actually
  196. for socket in nc.inputs.values():
  197. for l in socket.links:
  198. if l is not None:
  199. l.__del__()
  200. for socket in nc.outputs.values():
  201. for l in socket.links:
  202. if l is not None:
  203. l.__del__()
  204. def is_signature_in_other_signature(sig_a, sig_b):
  205. # this is the easiest but not the best way to do this:
  206. # this function is hideous but it does not seem to have any significant effect on timing
  207. # tested it with profiling on a full character rig.
  208. # OK. Had another test in a more extreme situation and this one came out on top for time spent and calls
  209. # gotta optimize this one.
  210. sig_a = list(sig_a)
  211. sig_a = ['MANTIS_NONE' if val is None else val for val in sig_a]
  212. sig_b = list(sig_b)
  213. sig_b = ['MANTIS_NONE' if val is None else val for val in sig_b]
  214. string_a = "".join(sig_a)
  215. string_b = "".join(sig_b)
  216. return string_a in string_b
  217. def solve_schema_to_tree(nc, all_nc, roots=[]):
  218. from .utilities import get_node_prototype
  219. np = get_node_prototype(nc.signature, nc.base_tree)
  220. # if not hasattr(np, 'node_tree'):
  221. # nc.bPrepare()
  222. # nc.prepared=True
  223. # return {}
  224. from .schema_solve import SchemaSolver
  225. length = nc.evaluate_input("Schema Length")
  226. tree = np.node_tree
  227. prOrange(f"Expanding schema {tree.name} in node {nc} with length {length}.")
  228. for inp in nc.inputs.values():
  229. inp.links.sort(key=lambda a : -a.multi_input_sort_id)
  230. solver = SchemaSolver(nc, all_nc, np)
  231. solved_nodes = solver.solve(length)
  232. # prGreen(f"Finished solving schema {tree.name} in node {nc}.")
  233. prWhite(f"Schema declared {len(solved_nodes)} nodes.")
  234. nc.prepared = True
  235. # TODO this should be handled by the schema's finalize() function
  236. del_me = []
  237. for k, v in all_nc.items():
  238. # delete all the schema's internal nodes. The links have already been deleted by the solver.
  239. if v.signature[0] not in ['MANTIS_AUTOGENERATED'] and is_signature_in_other_signature(nc.signature, k):
  240. # print (wrapOrange("Culling: ")+wrapRed(v))
  241. delete_nc(v)
  242. del_me.append(k)
  243. for k in del_me:
  244. del all_nc[k]
  245. for k,v in solved_nodes.items():
  246. all_nc[k]=v
  247. init_connections(v)
  248. check_and_add_root(v, roots, include_non_hierarchy=True)
  249. # end TODO
  250. return solved_nodes
  251. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  252. # PARSE NODE TREE #
  253. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  254. from .utilities import get_all_dependencies
  255. def get_schema_length_dependencies(node):
  256. """ Find all of the nodes that the Schema Length input depends on. """
  257. # the deps recursively from the from_nodes connected to Schema Length
  258. deps = []
  259. # return get_all_dependencies(node)
  260. inp = node.inputs.get("Schema Length")
  261. if not inp:
  262. inp = node.inputs.get("Array")
  263. # this way we can handle Schema and Array Get nodes with one function
  264. # ... since I may add more in the future this is not a robust solution HACK
  265. for l in inp.links:
  266. deps.extend(get_all_dependencies(l.from_node))
  267. if inp := node.inputs.get("Index"):
  268. for l in inp.links:
  269. deps.extend(get_all_dependencies(l.from_node))
  270. # now get the auto-generated simple inputs. These should not really be there but I haven't figured out how to set things directly yet lol
  271. for inp in node.inputs.values():
  272. for l in inp.links:
  273. if "MANTIS_AUTOGENERATED" in l.from_node.signature:
  274. # l.from_node.bPrepare() # try this...
  275. # l.from_node.prepared = True; l.from_node.executed = True
  276. deps.extend([l.from_node]) # why we need this lol
  277. return deps
  278. def parse_tree(base_tree):
  279. from uuid import uuid4 # do this here?
  280. base_tree.execution_id = uuid4().__str__() # set this, it may be used by nodes during execution
  281. # annoyingly I have to pass in values for all of the dicts because if I initialize them in the function call
  282. # then they stick around because the function definition inits them once and keeps a reference
  283. # so instead I have to supply them to avoid ugly code or bugs elsewhere
  284. # it's REALLY confusing when you run into this sort of problem. So it warrants four entire lines of comments!
  285. import time
  286. data_start_time = time.time()
  287. dummy_nodes, all_nc, all_schema = data_from_tree(base_tree, tree_path = [None], dummy_nodes = {}, all_nc = {}, all_schema={})
  288. # return
  289. prGreen(f"Pulling data from tree took {time.time() - data_start_time} seconds")
  290. for sig, dummy in dummy_nodes.items():
  291. if (hasattr(dummy, "reroute_links")):
  292. dummy.reroute_links(dummy, all_nc)
  293. # TODO
  294. # MODIFY BELOW to use hierarchy_dependencies instead
  295. # SCHEMA DUMMY nodes will need to gather the hierarchy and non-hierarchy dependencies
  296. # so SCHEMA DUMMY will not make their dependencies all hierarchy
  297. # since they will need to be able to send drivers and such
  298. start_time = time.time()
  299. sig_check = (None, 'Node Group.001', 'switch_thigh')
  300. roots = []
  301. arrays = []
  302. from .misc_containers import UtilityArrayGet
  303. for nc in all_nc.values():
  304. # clean up the groups
  305. if nc.node_type in ["DUMMY"]:
  306. if nc.prototype.bl_idname in ("MantisNodeGroup", "NodeGroupOutput"):
  307. continue
  308. from .base_definitions import from_name_filter, to_name_filter
  309. init_dependencies(nc)
  310. init_connections(nc)
  311. check_and_add_root(nc, roots, include_non_hierarchy=True)
  312. if isinstance(nc, UtilityArrayGet):
  313. arrays.append(nc)
  314. from collections import deque
  315. unsolved_schema = deque()
  316. solve_only_these = []; solve_only_these.extend(list(all_schema.values()))
  317. for schema in all_schema.values():
  318. # so basically we need to check every parent node if it is a schema
  319. # this is a fairly slapdash solution but it works and I won't change it
  320. for i in range(len(schema.signature)-1): # -1, we don't want to check this node, obviously
  321. if parent := all_schema.get(schema.signature[:i+1]):
  322. solve_only_these.remove(schema)
  323. break
  324. else:
  325. init_schema_dependencies(schema, all_nc)
  326. solve_only_these.extend(get_schema_length_dependencies(schema))
  327. unsolved_schema.append(schema)
  328. for array in arrays:
  329. solve_only_these.extend(get_schema_length_dependencies(array))
  330. solve_only_these.extend(arrays)
  331. schema_solve_done = set()
  332. solve_only_these = set(solve_only_these)
  333. solve_layer = unsolved_schema.copy(); solve_layer.extend(roots)
  334. while(solve_layer):
  335. n = solve_layer.pop()
  336. if n not in solve_only_these: # removes the unneeded node from the solve-layer
  337. continue
  338. if n.signature in all_schema.keys():
  339. for dep in n.hierarchy_dependencies:
  340. if dep not in schema_solve_done and (dep in solve_only_these):
  341. solve_layer.appendleft(n)
  342. break
  343. else:
  344. solved_nodes = solve_schema_to_tree(n, all_nc, roots)
  345. unsolved_schema.remove(n)
  346. schema_solve_done.add(n)
  347. for node in solved_nodes.values():
  348. #
  349. init_dependencies(node)
  350. init_connections(node)
  351. #
  352. solve_layer.appendleft(node)
  353. for conn in n.hierarchy_connections:
  354. if conn not in schema_solve_done and conn not in solve_layer:
  355. solve_layer.appendleft(conn)
  356. else:
  357. for dep in n.hierarchy_dependencies:
  358. if dep not in schema_solve_done:
  359. break
  360. else:
  361. n.bPrepare()
  362. schema_solve_done.add(n)
  363. for conn in n.hierarchy_connections:
  364. if conn not in schema_solve_done and conn not in solve_layer:
  365. solve_layer.appendleft(conn)
  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_nc = list(all_nc.values()).copy()
  370. kept_nc = {}
  371. while (all_nc):
  372. nc = all_nc.pop()
  373. if nc in arrays:
  374. continue
  375. if nc.node_type in ["DUMMY"]:
  376. if nc.prototype.bl_idname in ["MantisNodeGroup", "NodeGroupOutput"]:
  377. continue
  378. # continue
  379. # cleanup autogen nodes
  380. if nc.signature[0] == "MANTIS_AUTOGENERATED" and len(nc.inputs) == 0 and len(nc.outputs) == 1:
  381. output=list(nc.outputs.values())[0]
  382. value=list(nc.parameters.values())[0] # TODO modify the dependecy get function to exclude these nodes completely
  383. for l in output.links:
  384. to_node = l.to_node; to_socket = l.to_socket
  385. l.die()
  386. to_node.parameters[to_socket] = value
  387. del to_node.inputs[to_socket]
  388. init_dependencies(to_node)
  389. # init_connections(from_node)
  390. # it seems safe, and more importantly, fast, not to update the dependencies of these nodes.
  391. continue # in my test case this reduced the time cost by 33% by removing a large number of root nodes.
  392. # it went from 18.9 seconds to 9-10 seconds
  393. if (nc.node_type in ['XFORM']) and ("Relationship" in nc.inputs.keys()):
  394. if (new_nc := insert_lazy_parents(nc)):
  395. kept_nc[new_nc.signature]=new_nc
  396. kept_nc[nc.signature]=nc
  397. prWhite(f"Parsing tree took {time.time()-start_time} seconds.")
  398. prWhite("Number of Nodes: %s" % (len(kept_nc)))
  399. return kept_nc
  400. def sort_tree_into_layers(nodes, context):
  401. from time import time
  402. from .node_container_common import (get_depth_lines,
  403. node_depth)
  404. # All this function needs to do is sort out the hierarchy and
  405. # get things working in order of their dependencies.
  406. roots, drivers = [], []
  407. start = time()
  408. for n in nodes.values():
  409. if n.node_type == 'DRIVER': drivers.append(n)
  410. # ugly but necesary to ensure that drivers are always connected.
  411. check_and_add_root(n, roots)
  412. layers, nodes_heights = {}, {}
  413. #Possible improvement: unify roots if they represent the same data
  414. all_sorted_nodes = []
  415. for root in roots:
  416. nodes_heights[root.signature] = 0
  417. depth_lines = get_depth_lines(root)[0]
  418. for n in nodes.values():
  419. if n.signature not in (depth_lines.keys()):
  420. continue #belongs to a different root
  421. d = nodes_heights.get(n.signature, 0)
  422. if (new_d := node_depth(depth_lines[n.signature])) > d:
  423. d = new_d
  424. nodes_heights[n.signature] = d
  425. for k, v in nodes_heights.items():
  426. if (layer := layers.get(v, None)):
  427. layer.append(nodes[k]) # add it to the existing layer
  428. else: layers[v] = [nodes[k]] # or make a new layer with the node
  429. all_sorted_nodes.append(nodes[k]) # add it to the sorted list
  430. # TODO: investigate whether I can treat driver conenctions as an inverted hierarchy connection
  431. # as in, a hieraarchy connection from the to_node to the from_node in the link instead of the other way around.
  432. # because it looks like I am just putting the driver node one layer higher than the other one
  433. for drv in drivers:
  434. for out in drv.outputs.values():
  435. for l in out.links:
  436. n = l.to_node
  437. if n in all_sorted_nodes: continue
  438. depth = nodes_heights[drv.signature] + 1
  439. nodes_heights[n.signature] = depth
  440. if (layer := layers.get(depth, None)):
  441. layer.append(n)
  442. else: layers[v] = [n]
  443. #
  444. #
  445. prGreen("Sorting depth for %d nodes finished in %s seconds" %
  446. (len(nodes), time() - start))
  447. keys = list(layers.keys())
  448. keys.sort()
  449. num_nodes=0
  450. print_missed=nodes.copy()
  451. for i in keys:
  452. print_layer = [l_item for l_item in layers[i]]
  453. for k in print_layer:
  454. if k.node_type == "DUMMY":
  455. print (k, k.prototype.bl_idname, i)
  456. if (False): # True to print the layers
  457. for i in keys:
  458. # print_layer = [l_item for l_item in layers[i] if l_item.node_type in ["XFORM",]]# "LINK", "DRIVER"]]
  459. print_layer = [l_item for l_item in layers[i]]
  460. for k in print_layer:
  461. num_nodes+=1
  462. del print_missed[k.signature]
  463. print(wrapGreen("%d: " % i), wrapWhite("%s" % print_layer))
  464. prWhite(f"Final node count: {num_nodes}")
  465. prOrange("The following nodes have been culled:")
  466. for p in print_missed.values():
  467. prWhite (p, p.dependencies)
  468. return layers
  469. def error_popup_draw(self, context):
  470. self.layout.label(text="Error executing tree. There is an illegal cycle somewhere in the tree.")
  471. #execute tree is really slow overall, but still completes 1000s of nodes in only
  472. def execute_tree(nodes, base_tree, context):
  473. # return
  474. import bpy
  475. from time import time
  476. from .node_container_common import GraphError
  477. from uuid import uuid4
  478. original_active = context.view_layer.objects.active
  479. start_execution_time = time()
  480. from collections import deque
  481. xForm_pass = deque()
  482. for nc in nodes.values():
  483. nc.prepared = False
  484. nc.executed = False
  485. check_and_add_root(nc, xForm_pass)
  486. execute_pass = xForm_pass.copy()
  487. # exe_order = {}; i=0
  488. executed = []
  489. # check for cycles here by keeping track of the number of times a node has been visited.
  490. visited={}
  491. 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.
  492. max_iterations = len(nodes)**2
  493. i = 0
  494. while(xForm_pass):
  495. if i >= max_iterations:
  496. raise GraphError("There is a cycle somewhere in the graph.")
  497. bpy.context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  498. break
  499. i+=1
  500. n = xForm_pass.pop()
  501. if visited.get(n.signature):
  502. visited[n.signature]+=1
  503. else:
  504. visited[n.signature]=0
  505. if visited[n.signature] > check_max_len:
  506. raise GraphError("There is a cycle in the graph somewhere. Fix it!")
  507. bpy.context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  508. break
  509. # we're trying to solve the halting problem at this point.. don't do that.
  510. # TODO find a better way! there are algo's for this but they will require using a different solving algo, too
  511. if n.prepared:
  512. continue
  513. if n.node_type not in ['XFORM', 'UTILITY']:
  514. for dep in n.hierarchy_dependencies:
  515. if not dep.prepared:
  516. xForm_pass.appendleft(n) # hold it
  517. break
  518. else:
  519. n.prepared=True
  520. executed.append(n)
  521. for conn in n.hierarchy_connections:
  522. if not conn.prepared:
  523. xForm_pass.appendleft(conn)
  524. else:
  525. for dep in n.hierarchy_dependencies:
  526. if not dep.prepared:
  527. break
  528. else:
  529. n.bPrepare(context)
  530. if not n.executed:
  531. n.bExecute(context)
  532. n.prepared=True
  533. executed.append(n)
  534. for conn in n.hierarchy_connections:
  535. if not conn.prepared:
  536. xForm_pass.appendleft(conn)
  537. active = None
  538. switch_me = []
  539. for n in nodes.values():
  540. # if it is a armature, switch modes
  541. # total hack #kinda dumb
  542. if ((hasattr(n, "bGetObject")) and (n.__class__.__name__ == "xFormArmature" )):
  543. try:
  544. ob = n.bGetObject()
  545. except KeyError: # for bones
  546. ob = None
  547. # TODO this will be a problem if and when I add mesh/curve stuff
  548. if (hasattr(ob, 'mode') and ob.mode == 'EDIT'):
  549. switch_me.append(ob)
  550. active = ob
  551. context.view_layer.objects.active = ob# need to have an active ob, not None, to switch modes.
  552. # we override selected_objects to prevent anyone else from mode-switching
  553. # TODO it's possible but unlikely that the user will try to run a
  554. # graph with no armature nodes in it.
  555. if (active):
  556. with context.temp_override(**{'active_object':active, 'selected_objects':switch_me}):
  557. bpy.ops.object.mode_set(mode='POSE')
  558. for n in executed:
  559. n.bPrepare(context)
  560. if not n.executed:
  561. n.bExecute(context)
  562. for n in executed:
  563. n.bFinalize(context)
  564. for n in nodes.values(): # if it is a armature, switch modes
  565. if ((hasattr(n, "bGetObject")) and (n.__class__.__name__ == "xFormArmature" )):
  566. if (hasattr(ob, 'mode') and ob.mode == 'POSE'):
  567. switch_me.append(ob)
  568. active = ob
  569. if (active):
  570. with context.temp_override(**{'active_object':active, 'selected_objects':switch_me}):
  571. bpy.ops.object.mode_set(mode='OBJECT')
  572. for ob in switch_me:
  573. ob.data.pose_position = 'POSE'
  574. tot_time = (time() - start_execution_time)
  575. prGreen(f"Executed tree of {len(executed)} nodes in {tot_time} seconds")
  576. if (original_active):
  577. context.view_layer.objects.active = original_active
  578. original_active.select_set(True)