readtree.py 35 KB

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