readtree.py 36 KB

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