readtree.py 35 KB

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