readtree.py 34 KB

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