readtree.py 36 KB

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