readtree.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. from ..utilities.utilities import prRed, prGreen, prPurple, prWhite, prOrange, \
  2. wrapRed, wrapGreen, wrapPurple, wrapWhite, wrapOrange
  3. # FIXME I don't think these signatures are unique.
  4. # TODO this is a really silly and bad and also really dumb way to do this
  5. def insert_lazy_parents(mantis_node):
  6. from ..link_nodes import LinkInherit
  7. inherit_node = None
  8. if mantis_node.inputs["Relationship"].is_connected:
  9. from ..utilities.node_common import trace_single_line_safe
  10. # BUG this line can create infinite loops
  11. node_line, last_socket = trace_single_line_safe(mantis_node, 'Relationship')
  12. # if last_socket is from a valid XFORM, it is the relationship in
  13. # because it was traversed from the xForm Out... so get the traverse target.
  14. if last_socket.traverse_target is None:
  15. return # this is not a valid lazy parent.
  16. for other_node in node_line[1:]: # skip the first one, it is the same node
  17. if other_node.node_type == 'LINK':
  18. return # this one has a realtionship connection.
  19. elif other_node.node_type == 'XFORM':
  20. break
  21. if other_node.node_type in ["XFORM"] and last_socket.traverse_target.name in ["xForm Out"]:
  22. for link in other_node.outputs['xForm Out'].links:
  23. if link.to_node == mantis_node: link.die()
  24. inherit_node = LinkInherit(("MANTIS_AUTOGENERATED", *mantis_node.signature[1:], "LAZY_INHERIT"), mantis_node.base_tree)
  25. l = other_node.outputs['xForm Out'].connect(inherit_node, 'Parent')
  26. l1 = inherit_node.outputs['Inheritance'].connect(mantis_node, 'Relationship')
  27. inherit_node.parameters = { "Parent":None,
  28. "Inherit Rotation":True,
  29. "Inherit Scale":'FULL',
  30. "Connected":False, }
  31. # because the from node may have already been done.
  32. init_connections(other_node); init_dependencies(other_node)
  33. init_connections(inherit_node); init_dependencies(inherit_node)
  34. return inherit_node
  35. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  36. # DATA FROM NODES #
  37. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  38. from ..base_definitions import replace_types, NodeSocket
  39. def autogen_node(base_tree, ui_socket, signature, mContext):
  40. mantis_node=None
  41. from ..internal_nodes import AutoGenNode
  42. mantis_node = AutoGenNode(signature, base_tree)
  43. mantis_node.mContext = mContext
  44. mantis_node.outputs[ui_socket.identifier] = NodeSocket(is_input=False, name=ui_socket.identifier, node=mantis_node)
  45. mantis_node.parameters[ui_socket.identifier] = None
  46. mantis_node.ui_signature = None # does not exist in the UI
  47. return mantis_node
  48. def make_connections_to_ng_dummy(base_tree, tree_path_names, local_mantis_nodes, all_mantis_nodes, to_mantis_node):
  49. from ..socket_definitions import no_default_value
  50. for inp in to_mantis_node.ui_node.inputs:
  51. if inp.bl_idname in no_default_value:
  52. continue
  53. from_mantis_node = None
  54. to_s = inp.identifier
  55. if not inp.is_linked: # make an autogenerated NC for the inputs of the group node
  56. # This can be run inside schema. Make it unique with uuid() to be safe.
  57. from uuid import uuid4
  58. signature = (None, *tree_path_names, to_mantis_node.ui_signature[-1]+"_"+inp.name+"_"+inp.identifier+"_"+str(uuid4()) )
  59. from_mantis_node = all_mantis_nodes.get(signature) # creating this without checking and
  60. # using UUID signature leads to TERRIBLE CONFUSING BUGS.
  61. if from_mantis_node is None:
  62. from_mantis_node = autogen_node(base_tree, inp, signature, to_mantis_node.mContext)
  63. local_mantis_nodes[signature]=from_mantis_node
  64. all_mantis_nodes[signature]=from_mantis_node
  65. if from_mantis_node: # autogen can fail and we should catch it.
  66. from_mantis_node.fill_parameters(ui_node=to_mantis_node.ui_node)
  67. from_mantis_node.outputs[inp.identifier].connect(node=to_mantis_node, socket=to_s, sort_id=0)
  68. else:
  69. prRed("No available auto-generated class for input %s in %s" % (inp.name, to_mantis_node.ui_node.name))
  70. def gen_mantis_nodes(base_tree, current_tree, tree_path_names, mContext, all_mantis_nodes, local_mantis_nodes, dummy_nodes, group_nodes, schema_nodes, in_schema ):
  71. from ..internal_nodes import DummyNode, GroupInterface
  72. for ui_node in current_tree.nodes:
  73. mantis_node = None
  74. if ui_node.bl_idname in ["NodeFrame", "NodeReroute"]:
  75. continue # not a Mantis Node
  76. if ui_node.bl_idname in ["NodeGroupInput", "NodeGroupOutput"]:
  77. # we only want ONE dummy in/out per tree_path, so use the bl_idname to make a Dummy node
  78. sig = (None, *tree_path_names, ui_node.bl_idname)
  79. ui_sig = (None, *tree_path_names, ui_node.name)
  80. if not local_mantis_nodes.get(sig):
  81. mantis_node = DummyNode( signature=sig , base_tree=base_tree, ui_node=ui_node, ui_signature=ui_sig )
  82. local_mantis_nodes[sig] = mantis_node; all_mantis_nodes[sig] = mantis_node; dummy_nodes[sig] = mantis_node
  83. if ui_node.bl_idname in {"NodeGroupOutput"}:
  84. # We need an interface node, let's make it now.
  85. items_tree = ui_node.id_data.interface.items_tree
  86. interface = GroupInterface(
  87. # we'll clip the 'NodeGroupOutput' from the signature
  88. ( *mantis_node.signature[:-1], "OutputInterface"),
  89. mantis_node.base_tree, 'OUTPUT', ui_node=mantis_node.ui_node,
  90. items_tree=items_tree,)
  91. interface.mContext = mContext
  92. all_mantis_nodes[interface.signature] = interface; local_mantis_nodes[interface.signature] = interface
  93. mantis_node.reroute_links_type = 'out'
  94. elif ui_node.bl_idname in ["MantisNodeGroup", "MantisSchemaGroup"]:
  95. mantis_node = DummyNode( signature= (sig := (None, *tree_path_names, ui_node.name) ), base_tree=base_tree, ui_node=ui_node )
  96. mantis_node.mContext = mContext
  97. local_mantis_nodes[sig] = mantis_node; all_mantis_nodes[sig] = mantis_node; dummy_nodes[sig] = mantis_node
  98. items_tree = ui_node.node_tree.interface.items_tree
  99. if ui_node.bl_idname == "MantisNodeGroup":
  100. mantis_node.reroute_links_type = 'group'
  101. name = 'InputInterface'
  102. interface_in_out = 'INPUT'
  103. else:
  104. schema_nodes[sig] = mantis_node
  105. name = 'InputInterface.0000'
  106. interface_in_out = 'SCHEMA_INPUT'
  107. # let's make the interface node for this now
  108. interface = GroupInterface(
  109. ( *mantis_node.signature, name), mantis_node.base_tree,
  110. interface_in_out, mantis_node.ui_node, items_tree=items_tree )
  111. interface.mContext = mContext
  112. all_mantis_nodes[interface.signature] = interface; local_mantis_nodes[interface.signature] = interface
  113. group_nodes.append(mantis_node)
  114. # This function depends on generating the interface
  115. make_connections_to_ng_dummy(base_tree, tree_path_names, local_mantis_nodes, all_mantis_nodes, mantis_node)
  116. # if it wasn't the types we ignore or the types we make a Dummy for, use this to catch all non-special cases.
  117. elif (mantis_class := ui_node.mantis_class):
  118. sig = (None, *tree_path_names, ui_node.name)
  119. if ui_node.bl_idname in replace_types:
  120. sig = (None, *tree_path_names, ui_node.bl_idname)
  121. if local_mantis_nodes.get(sig):
  122. continue # already made
  123. mantis_node = mantis_class( sig , base_tree)
  124. local_mantis_nodes[sig] = mantis_node; all_mantis_nodes[sig] = mantis_node
  125. mantis_node.ui_signature = (*mantis_node.ui_signature[:-1], ui_node.name) # just to ensure it points to a real node.
  126. else:
  127. mantis_node = None
  128. prRed(f"Can't make mantis_node for.. {ui_node.bl_idname}")
  129. if mantis_node is not None:
  130. # this should be done at init
  131. mantis_node.mContext = mContext
  132. if mantis_node.signature[0] != 'MANTIS_AUTOGENERATED' and mantis_node.node_type not in {'SCHEMA', 'DUMMY', 'DUMMY_SCHEMA'}:
  133. mantis_node.fill_parameters(ui_node)
  134. mantis_node.is_schema_prototype = in_schema
  135. def data_from_tree(base_tree, tree_path, mContext, dummy_nodes, all_mantis_nodes, all_schema, in_schema):#
  136. # TODO: it should be relatively easy to make this use a while loop instead of recursion.
  137. local_mantis_nodes, group_nodes = {}, []
  138. tree_path_names = [tree.name for tree in tree_path if hasattr(tree, "name")]
  139. if tree_path[-1]:
  140. current_tree = tree_path[-1].node_tree # this may be None.
  141. else:
  142. current_tree = base_tree
  143. #
  144. if current_tree: # the node-group may not have a tree set - if so, ignore it.
  145. if not in_schema:
  146. in_schema = current_tree.bl_idname in ['SchemaTree']
  147. from ..utilities.utilities import clear_reroutes
  148. links = clear_reroutes(list(current_tree.links))
  149. gen_mantis_nodes(base_tree, current_tree, tree_path_names, mContext, all_mantis_nodes, local_mantis_nodes, dummy_nodes, group_nodes, all_schema, in_schema)
  150. from ..utilities.utilities import link_mantis_nodes
  151. for link in links:
  152. link_mantis_nodes((None, *tree_path_names), link, local_mantis_nodes)
  153. if current_tree == base_tree:
  154. # in the base tree, we need to auto-gen the default values in a slightly different way to node groups.
  155. insert_default_values_base_tree(base_tree, all_mantis_nodes)
  156. # Now, descend into the Node Groups and recurse
  157. for mantis_node in group_nodes:
  158. data_from_tree(base_tree, tree_path+[mantis_node.ui_node], mContext, dummy_nodes, all_mantis_nodes, all_schema, in_schema)
  159. return dummy_nodes, all_mantis_nodes, all_schema
  160. STRING_PADDING = 4
  161. overlay_valid_socket_types = [
  162. "FloatSocket", "FloatPositiveSocket", "FloatFactorSocket",
  163. "FloatAngleSocket", "UnsignedIntSocket", "IntSocket", "StringSocket",
  164. ]
  165. # Do not use these input names as overlay keys:
  166. forbidden_key_names = ["",]
  167. forbidden_in_key_name = ['$',]
  168. def node_scan_overlays(node, socket_id,):
  169. from ..misc_nodes import SimpleInputNode
  170. from ..internal_nodes import AutoGenNode
  171. from ..utilities.utilities import get_ui_node
  172. from ..utilities.node_common import GraphError
  173. interface_nodes = node.mContext.interface_nodes
  174. if not isinstance(node, AutoGenNode):
  175. ui_node = get_ui_node(node.ui_signature, node.base_tree)
  176. # we'll assume that the overlay tag system checked if this is linked.
  177. # TODO this is probably redundant with the check above this
  178. # First let's check if it is a simple input node, by checking outputs that are marked "input"
  179. for socket in ui_node.outputs:
  180. # weird edge case for simple input nodes with unnamed sockets
  181. # the socket.identifier is not used by Mantis but it defaults to 'socket'\
  182. if socket.identifier == socket_id and socket.input == True: break
  183. else:
  184. for socket in ui_node.inputs:
  185. if socket.identifier == socket_id: break
  186. else:
  187. raise KeyError(f"Socket not found by ID {socket_id} in node {node.ui_signature}\n"
  188. f"Candidates: {[socket.identifier for socket in ui_node.inputs]}")
  189. value = socket.default_value # get the ACTUAL UI value
  190. if hasattr(socket, 'overlay_text'): # TODO this is all wrong but for now
  191. value = "$"+socket.overlay_text # I am not implementing the Parser feature
  192. else: # since it doesn't have a UI node
  193. value = node.parameters[socket_id]
  194. overlay_data_type = str
  195. if isinstance(node, (AutoGenNode) ):
  196. overlay_data_type = type(node.parameters[list(node.outputs.values())[0].name])
  197. else: # we have the UI socket
  198. match socket.bl_idname:
  199. case "IntSocket" | "UnsignedIntSocket":
  200. overlay_data_type = int
  201. case "FloatSocket" | "FloatPositiveSocket" | "FloatFactorSocket" | "FloatAngleSocket":
  202. overlay_data_type = float
  203. if not isinstance(value, str): return
  204. # First step: get the interface nodes and the overlay keys
  205. # this should only check interfaces that are ancestors of this node
  206. my_interfaces = []
  207. for index in range(len(node.signature)-1):
  208. if index == 0: continue # root
  209. # we add one here because the node inside the schema references the schema's interface...
  210. current_schema_interface_index = node.generated_at_schema_index[index+1]
  211. if current_schema_interface_index < 0: # this indicates that it is not in a schema
  212. interface = interface_nodes.get(
  213. interface_signature := (None, *node.signature[1:index+1], "InputInterface"))
  214. else: # First we get the interface that enters the schema (index 0)
  215. interface = interface_nodes.get(
  216. interface_signature := (None, *node.signature[1:index+1],
  217. "InputInterface."+str( 0 ).zfill(4)))
  218. if interface and interface not in my_interfaces: my_interfaces.append(interface)
  219. if current_schema_interface_index == 0: continue # just did it
  220. # we need to get the schema of the current index
  221. interface = interface_nodes.get(
  222. interface_signature := (None, *node.signature[1:index+1],
  223. "InputInterface."+str(current_schema_interface_index).zfill(4)))
  224. if interface:
  225. my_interfaces.append( interface )
  226. # the my_interfaces list is sorted in REVERSE order of importance
  227. # Next, get all the overlay providers.
  228. name_to_id_map = {}
  229. name_to_type_map = {} # Just for printing reasonable error messages
  230. overlay_keys = set()
  231. root_overlay_values = {}
  232. # First, we'll get the base tree's default inputs
  233. for interface_item in node.mContext.base_tree.interface.items_tree:
  234. if interface_item.item_type != "SOCKET": continue
  235. if interface_item.in_out != "INPUT": continue
  236. base_value=None
  237. match interface_item.bl_socket_idname:
  238. case "IntSocket" | "BooleanSocket":
  239. # TODO parser for number types
  240. base_value = interface_item.default_int
  241. case "FloatSocket":
  242. base_value = interface_item.default_float
  243. case "StringSocket" | "BoneCollectionSocket":
  244. base_value = interface_item.default_string
  245. if base_value:
  246. root_overlay_values[interface_item.name] = base_value
  247. overlay_keys.add(interface_item.name)
  248. name_to_id_map[interface_item.name] = None # don't worry about it
  249. name_to_type_map[interface_item.name] = interface_item.bl_socket_idname
  250. # BUG? should this be my_interfaces ? why bother with interfaces this may not be a part of?
  251. for interface_node in interface_nodes.values():
  252. # problem: the interface node stores socket identifiers as keys
  253. # so in reality we need to get the group UI node and ask for its input names
  254. # if there is a duplicate name, too bad!
  255. group_ui_node = get_ui_node(interface_node.ui_signature[:-1], node.base_tree)
  256. for interface_item in group_ui_node.node_tree.interface.items_tree:
  257. if interface_item.item_type != 'SOCKET': continue
  258. if interface_item.in_out != 'INPUT': continue
  259. if interface_item.name in forbidden_key_names: continue
  260. for substr in forbidden_in_key_name:
  261. if substr in interface_item.name:
  262. break
  263. else: # if we do not find a bad substr
  264. name_to_id_map[interface_item.name]=interface_item.identifier
  265. name_to_type_map[interface_item.name] = interface_item.bl_socket_idname
  266. overlay_keys.add(interface_item.name)
  267. # For schema interfaces, we also need to get the length and index.
  268. if 'Index' in interface.outputs:
  269. overlay_keys.add('Index'); overlay_keys.add('Length')
  270. if 'Index' in overlay_keys:
  271. name_to_id_map['Index']='Index'
  272. name_to_type_map['Index']= "IntSocket"
  273. name_to_id_map['Length']='Length'
  274. name_to_type_map['Length']= "IntSocket"
  275. # sort by reverse length so we find "CatsAndFrogs" before "Cats"
  276. overlay_keys = sorted(overlay_keys, key= lambda a :-1*len(a))
  277. # First I need to break it into substrings based on quotation marks
  278. from ..utilities.utilities import split_quoted_substrings_to_strings
  279. quoted_substrings = split_quoted_substrings_to_strings(value)
  280. overlay_tries = []
  281. for quoted_substring in quoted_substrings:
  282. overlay_tries.extend(quoted_substring.split("$"))
  283. if overlay_data_type == str:
  284. result = overlay_tries[0] # the 0th element is always before the split character
  285. else: # TODO HACK later use the parser feature
  286. result = 0
  287. # the reason for the difference between overlay_try and key is because
  288. # we don't actually know if the $text part has a key in it
  289. for overlay_try in overlay_tries[1:]:
  290. if not overlay_try: continue # some of these are empty
  291. overlay_resolved_value = "$" + overlay_try
  292. for key in overlay_keys:
  293. if key in overlay_try:
  294. overlay_resolved_value = "$" + key
  295. for interface in reversed(my_interfaces): # since this is reversed when we build it
  296. actual_key = name_to_id_map.get(key)
  297. socket = interface.inputs.get(actual_key)
  298. if key in ['Index', 'Length']:
  299. socket = interface.outputs.get(actual_key)
  300. if socket:
  301. overlay_value = None
  302. try:
  303. overlay_value = interface.evaluate_input(actual_key)
  304. except KeyError:
  305. if (socket_type := name_to_type_map.get(key) or 'NOT FOUND') in overlay_valid_socket_types:
  306. raise GraphError(f"Error: Variable {key} is not supported because it has "
  307. f"an invalid input in the node group: {interface.signature[:-1]}.")
  308. raise GraphError( f"Error: Variable {key} is not supported because it is "
  309. f"type {socket_type}" )
  310. # NOTE that the above can also be caused by any BUG occuring in node group update
  311. # because it causes the interface to be invalid for the UI node that spawns the interface node.
  312. if overlay_data_type == str:
  313. if isinstance(overlay_value, (float, int)):
  314. overlay_value = str(overlay_value).zfill(STRING_PADDING)
  315. assert (isinstance(overlay_value, str)), f"Error: Variable {key} is not supported because it is type {type(overlay_value)}"
  316. overlay_resolved_value = overlay_try.replace(key, overlay_value)
  317. else:
  318. overlay_resolved_value = overlay_value
  319. break
  320. else: # we'll try the base tree
  321. if base_tree_result := root_overlay_values.get(key):
  322. if overlay_data_type == str and not isinstance(base_tree_result, str):
  323. base_tree_result = str(base_tree_result).zfill(STRING_PADDING)
  324. overlay_resolved_value = base_tree_result
  325. else:
  326. prOrange(f"WARN: no overlay value applied for {node.ui_signature} for key {key}")
  327. break # we found the key and are done here. One found Key per overlay-try
  328. result += overlay_resolved_value
  329. # Simple Input sockets with unnamed sockets assign this ID automatically
  330. # But Mantis uses the name instead. Usually the name and ID are the same.
  331. if socket_id == 'socket' and ui_node.outputs[0].name == "":
  332. socket_id = ''
  333. node.parameters[socket_id] = result
  334. return result # because sometimes I need to get the result, too
  335. from ..utilities.utilities import check_and_add_root, init_connections, init_dependencies, init_schema_dependencies
  336. def solve_schema_to_tree(mantis_node, all_mantis_nodes, roots=[], error_popups=False):
  337. from ..utilities.utilities import get_ui_node
  338. np = get_ui_node(mantis_node.signature, mantis_node.base_tree)
  339. from .schema_solve import SchemaSolver
  340. solver = SchemaSolver(mantis_node, all_mantis_nodes.copy(), np, error_popups=error_popups)
  341. try:
  342. solved_nodes = solver.solve()
  343. except Exception as e:
  344. # # the schema will run the error cleanup code, we just need to raise or not
  345. solved_nodes = {}
  346. mantis_node.base_tree.hash_recursive=''
  347. raise execution_error_cleanup(mantis_node, e, show_error=error_popups)
  348. for k,v in solved_nodes.items():
  349. all_mantis_nodes[k]=v
  350. init_connections(v)
  351. check_and_add_root(v, roots, include_non_hierarchy=True)
  352. return solved_nodes
  353. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  354. # PARSE NODE TREE #
  355. # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** # *** #
  356. schema_bl_idnames = [ "SchemaIndex",
  357. "SchemaArrayInput",
  358. "SchemaArrayInputGet",
  359. "SchemaArrayInputAll",
  360. "SchemaArrayOutput",
  361. "SchemaConstInput",
  362. "SchemaConstOutput",
  363. "SchemaOutgoingConnection",
  364. "SchemaIncomingConnection",
  365. ]
  366. from ..utilities.utilities import get_all_dependencies, read_schema_type
  367. def get_schema_length_dependencies(node, all_nodes={}):
  368. """ Get a list of all dependencies for the given node's length or array properties.
  369. This function will also recursively search for dependencies in its sub-trees.
  370. """
  371. deps = []
  372. prepare_links_to = ['Schema Length', 'Array', 'Index']
  373. def extend_dependencies_from_inputs(node):
  374. for inp in node.inputs.values():
  375. for l in inp.links:
  376. if not l.from_node in node.hierarchy_dependencies:
  377. continue
  378. if "MANTIS_AUTOGENERATED" in l.from_node.signature:
  379. deps.extend([l.from_node]) # why we need this lol
  380. if inp.name in prepare_links_to:
  381. deps.append(l.from_node)
  382. deps.extend(get_all_dependencies(l.from_node))
  383. # we also always need to prepare these inputs because they create links.
  384. # HACK below until I can be less stupid and solve this the right way
  385. if l.from_node.__class__.__name__ in 'UtilityMatricesFromCurve':
  386. deps.append(l.from_node)
  387. deps.extend(get_all_dependencies(l.from_node))
  388. def deps_filter(dep): # remove any nodes inside the schema
  389. if len(dep.signature) > len(node.signature):
  390. for i in range(len(node.signature)):
  391. dep_sig_elem, node_sig_elem = dep.signature[i], node.signature[i]
  392. if dep_sig_elem != node_sig_elem: break # they don't match, it isn't an inner-node
  393. else: # remove this, it didn't break, meaning it shares signature with outer node
  394. return False # this is an inner-node
  395. return True
  396. # this way we can handle Schema and Array Get nodes with one function
  397. extend_dependencies_from_inputs(node)
  398. if node.node_type == 'DUMMY_SCHEMA':
  399. trees = [(node.ui_node.node_tree, node.signature)] # this is UI data
  400. while trees:
  401. tree, tree_signature = trees.pop()
  402. for sub_ui_node in tree.nodes:
  403. if sub_ui_node.bl_idname in ['NodeReroute', 'NodeFrame']:
  404. continue
  405. if sub_ui_node.bl_idname in schema_bl_idnames:
  406. sub_node = all_nodes[(*tree_signature, sub_ui_node.bl_idname)]
  407. else:
  408. sub_node = all_nodes[(*tree_signature, sub_ui_node.name)]
  409. if sub_node.node_type == 'DUMMY_SCHEMA':
  410. extend_dependencies_from_inputs(sub_node)
  411. trees.append((sub_node.ui_node.node_tree, sub_node.signature))
  412. return list(filter(deps_filter, deps))
  413. def insert_default_values_base_tree(base_tree, all_mantis_nodes):
  414. # we can get this by name because group inputs are gathered to the bl_idname
  415. InputNode = all_mantis_nodes.get((None, 'NodeGroupInput'))
  416. if InputNode is None: return # nothing to do here.
  417. ui_node = InputNode.ui_node
  418. for i, output in enumerate(InputNode.outputs):
  419. ui_output = ui_node.outputs[i] # I need this for the error messages to make sense
  420. assert ui_output.identifier == output.name, "Cannot find UI Socket for Default Value"
  421. for interface_item in base_tree.interface.items_tree:
  422. if interface_item.item_type == 'PANEL': continue
  423. if interface_item.identifier == output.name: break
  424. else:
  425. raise RuntimeError(f"Default value {ui_output.name} does not exist in {base_tree.name} ")
  426. if interface_item.item_type == "PANEL":
  427. raise RuntimeError(f"Cannot get default value for {ui_output.name} in {base_tree.name} ")
  428. default_value = None
  429. from bpy.types import bpy_prop_array
  430. from mathutils import Vector
  431. val_type = None
  432. if hasattr(ui_output, 'default_value'):
  433. val_type = type(ui_output.default_value) # why tf can't I match/case here?
  434. if val_type is bool: default_value = interface_item.default_bool
  435. elif val_type is int: default_value = interface_item.default_int
  436. elif val_type is float: default_value = interface_item.default_float
  437. elif val_type is Vector: default_value = interface_item.default_vector
  438. elif val_type is str: default_value = interface_item.default_string
  439. elif val_type is bpy_prop_array: default_value = interface_item.default_bool_vector
  440. elif interface_item.bl_socket_idname == "xFormSocket":
  441. if interface_item.default_xForm == 'ARMATURE':
  442. default_value = 'MANTIS_DEFAULT_ARMATURE'
  443. else:
  444. raise RuntimeError(f"No xForm connected for {ui_output.name} in {base_tree.name}.")
  445. else:
  446. raise RuntimeError(f"Cannot get default value for {ui_output.name} in {base_tree.name} ")
  447. output_name = output.name
  448. if interface_item.bl_socket_idname not in ['xFormSocket']:
  449. signature = ("MANTIS_AUTOGENERATED", f"Default Value {output.name}",)
  450. autogen_mantis_node = all_mantis_nodes.get(signature)
  451. if autogen_mantis_node is None:
  452. autogen_mantis_node = autogen_node(base_tree, output, signature, InputNode.mContext)
  453. autogen_mantis_node.parameters[output_name]=default_value
  454. elif interface_item.bl_socket_idname == 'xFormSocket' \
  455. and default_value == 'MANTIS_DEFAULT_ARMATURE':
  456. signature = ("MANTIS_AUTOGENERATED", "MANTIS_DEFAULT_ARMATURE",)
  457. autogen_mantis_node = all_mantis_nodes.get(signature)
  458. if autogen_mantis_node is None:
  459. from ..xForm_nodes import xFormArmature
  460. autogen_mantis_node = xFormArmature(signature, base_tree)
  461. autogen_mantis_node.parameters['Name']=base_tree.name+'_MANTIS_AUTOGEN'
  462. autogen_mantis_node.mContext = InputNode.mContext
  463. from mathutils import Matrix
  464. autogen_mantis_node.parameters['Matrix'] = Matrix.Identity(4)
  465. output_name = 'xForm Out'
  466. while output.links:
  467. l = output.links.pop()
  468. to_node = l.to_node; to_socket = l.to_socket
  469. l.die()
  470. autogen_mantis_node.outputs[output_name].connect(to_node, to_socket)
  471. init_connections(l.from_node); init_dependencies(l.from_node)
  472. all_mantis_nodes[autogen_mantis_node.signature]=autogen_mantis_node
  473. def parse_tree(base_tree, error_popups=False):
  474. from uuid import uuid4
  475. base_tree.execution_id = uuid4().__str__() # set the unique id of this execution
  476. from ..base_definitions import MantisExecutionContext
  477. from ..utilities.node_common import GraphError
  478. mContext = MantisExecutionContext(base_tree=base_tree)
  479. import time
  480. data_start_time = time.time()
  481. # annoyingly I have to pass in values for all of the dicts because if I initialize them in the function call
  482. # then they stick around because the function definition inits them once and keeps a reference
  483. # so instead I have to supply them to avoid ugly code or bugs elsewhere
  484. # it's REALLY confusing when you run into this sort of problem. So it warrants four entire lines of comments!
  485. try:
  486. dummy_nodes, all_mantis_nodes, all_schema = data_from_tree(
  487. base_tree,
  488. tree_path = [None],
  489. mContext=mContext,
  490. dummy_nodes = {},
  491. all_mantis_nodes = {},
  492. all_schema={},
  493. in_schema=False
  494. )
  495. except GraphError as e:
  496. base_tree.tree_valid = False; base_tree.hash_recursive=""
  497. if error_popups:
  498. from bpy import context
  499. def error_popup_draw(self, context):
  500. error_popup_draw_inner(self.layout, e, ())
  501. context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  502. else: raise e
  503. return # it is not possible to parse the tree until GraphErrors are resolved.
  504. for dummy in dummy_nodes.values(): # reroute the links in the group nodes
  505. dummy.reroute_links(all_mantis_nodes)
  506. prGreen(f"Pulling data from tree took {time.time() - data_start_time} seconds")
  507. start_time = time.time()
  508. solve_only_these = []; solve_only_these.extend(list(all_schema.values()))
  509. roots, array_nodes = [], []
  510. from collections import deque
  511. unsolved_schema = deque()
  512. from ..base_definitions import array_output_types, GraphError
  513. for mantis_node in all_mantis_nodes.values():
  514. # TODO I still need to assign mContext here because of autogen_node
  515. # so I have to do a deeper refactor to ensure autogen nodes get this at creation time.
  516. mantis_node.mContext = mContext
  517. if mantis_node.node_type in ["DUMMY"]: # clean up the groups
  518. if mantis_node.ui_node.bl_idname in ("MantisNodeGroup", "NodeGroupOutput"):
  519. continue
  520. # Initialize the dependencies and connections (from/to links) for each node.
  521. # we record & store it because using a getter is much slower (according to profiling)
  522. init_dependencies(mantis_node); init_connections(mantis_node)
  523. check_and_add_root(mantis_node, roots, include_non_hierarchy=True)
  524. # Array nodes need a little special treatment, they're quasi-schemas
  525. if mantis_node.__class__.__name__ in array_output_types:
  526. solve_only_these.append(mantis_node)
  527. array_nodes.append(mantis_node)
  528. if mantis_node.node_type == 'INTERFACE': # strip the SCHEMA/AUTOGEN tag if it is there
  529. mContext.interface_nodes[( None, *mantis_node.signature[1:]) ] = mantis_node
  530. from itertools import chain
  531. for schema in chain(all_schema.values(), array_nodes):
  532. # We must remove the schema/array nodes that are inside a schema tree.
  533. for i in range(len(schema.signature)-1): # -1, we don't want to check this node, obviously
  534. if parent := all_schema.get(schema.signature[:i+1]):
  535. # This will be solved along with its parent schema.
  536. solve_only_these.remove(schema)
  537. break
  538. for schema in all_schema.values():
  539. if schema not in solve_only_these: continue
  540. init_schema_dependencies(schema, all_mantis_nodes)
  541. solve_only_these.extend(get_schema_length_dependencies(schema, all_mantis_nodes))
  542. unsolved_schema.append(schema)
  543. for array in array_nodes:
  544. if array not in solve_only_these: continue
  545. solve_only_these.extend(get_schema_length_dependencies(array))
  546. solve_only_these.extend(array_nodes)
  547. schema_solve_done = set()
  548. solve_only_these = set(solve_only_these)
  549. overlay_tagged_nodes = {}
  550. for node_signature, socket_id in mContext.tagged_for_overlay:
  551. if overlay_tagged_nodes.get(node_signature):
  552. overlay_tagged_nodes[node_signature].append(socket_id)
  553. else:
  554. overlay_tagged_nodes[node_signature] = [socket_id]
  555. def check_and_apply_overlay(n):
  556. if overlays_for_this_node := overlay_tagged_nodes.get(n.signature):
  557. for socket_id in overlays_for_this_node:
  558. node_scan_overlays(n, socket_id,)
  559. solve_layer = unsolved_schema.copy(); solve_layer.extend(roots)
  560. while(solve_layer):
  561. n = solve_layer.pop()
  562. if n not in solve_only_these:
  563. continue
  564. if n.signature in all_schema.keys():
  565. for dep in n.hierarchy_dependencies:
  566. if dep not in schema_solve_done and (dep in solve_only_these):
  567. if dep.prepared:
  568. continue
  569. solve_layer.appendleft(n)
  570. break
  571. else:
  572. try:
  573. solved_nodes = solve_schema_to_tree(n, all_mantis_nodes, roots, error_popups=error_popups)
  574. except Exception as e:
  575. e = execution_error_cleanup(n, e, show_error=error_popups)
  576. solved_nodes = {}
  577. if error_popups == False:
  578. raise e
  579. return # it is not possible to parse the tree.
  580. unsolved_schema.remove(n)
  581. schema_solve_done.add(n)
  582. for node in solved_nodes.values():
  583. init_dependencies(node); init_connections(node)
  584. solve_layer.appendleft(node)
  585. schema_solve_done.add(node) # CRITICAL to prevent freezes.
  586. for conn in n.hierarchy_connections:
  587. if conn not in schema_solve_done and conn not in solve_layer:
  588. solve_layer.appendleft(conn)
  589. continue
  590. else:
  591. for dep in n.hierarchy_dependencies:
  592. if dep not in schema_solve_done:
  593. break
  594. else:
  595. check_and_apply_overlay(n)
  596. try:
  597. n.bPrepare()
  598. except Exception as e:
  599. e = execution_error_cleanup(n, e, show_error=error_popups)
  600. if error_popups == False:
  601. raise e
  602. schema_solve_done.add(n)
  603. for conn in n.hierarchy_connections:
  604. if conn not in schema_solve_done and conn not in solve_layer:
  605. solve_layer.appendleft(conn)
  606. continue
  607. if unsolved_schema:
  608. raise RuntimeError("Failed to resolve all schema declarations")
  609. # I had a problem with this looping forever. I think it is resolved... but I don't know lol
  610. all_mantis_nodes = list(all_mantis_nodes.values())
  611. kept_mantis_node = {}
  612. while (all_mantis_nodes):
  613. mantis_node = all_mantis_nodes.pop()
  614. if mantis_node.node_type in ["DUMMY", 'SCHEMA', 'DUMMY_SCHEMA']:
  615. continue # screen out the ui_node schema nodes, group in/out, and group placeholders
  616. # cleanup autogen nodes
  617. if mantis_node.signature[0] == "MANTIS_AUTOGENERATED" and len(mantis_node.inputs) == 0 and len(mantis_node.outputs) == 1:
  618. from ..base_definitions import can_remove_socket_for_autogen
  619. output=list(mantis_node.outputs.values())[0]
  620. value=list(mantis_node.parameters.values())[0]
  621. # We can remove this node if it is safe to push it into the other node's socket.
  622. keep_me = False
  623. for l in output.links:
  624. to_node = l.to_node; to_socket = l.to_socket
  625. # do not remove the socket if it is a custom property.
  626. if not can_remove_socket_for_autogen(to_node, to_socket):
  627. keep_me = True; continue
  628. l.die()
  629. to_node.parameters[to_socket] = value
  630. del to_node.inputs[to_socket]
  631. init_dependencies(to_node) # to remove the autogen node we no longer need.
  632. if not keep_me:
  633. continue
  634. init_connections(mantis_node) # because we have removed many connections.
  635. if (mantis_node.node_type in ['XFORM']) and ("Relationship" in mantis_node.inputs.keys()):
  636. from ..utilities.node_common import GraphError
  637. try:
  638. if (new_mantis_node := insert_lazy_parents(mantis_node)):
  639. kept_mantis_node[new_mantis_node.signature]=new_mantis_node
  640. # be sure to add the Mantis context.
  641. new_mantis_node.mContext =mContext
  642. except GraphError as e:
  643. e = execution_error_cleanup(mantis_node, e, show_error=error_popups)
  644. if error_popups == False:
  645. raise e
  646. return # it is not possible to parse the tree.
  647. kept_mantis_node[mantis_node.signature]=mantis_node
  648. prWhite(f"Parsing tree took {time.time()-start_time} seconds.")
  649. prWhite("Number of Nodes: %s" % (len(kept_mantis_node)))
  650. return kept_mantis_node
  651. from ..utilities.utilities import switch_mode
  652. def error_popup_draw_inner(layout, exception, ui_sig = ()):
  653. node_string = f"See node: {ui_sig[1:]}." if ui_sig else ""
  654. message = f"Error: {exception}\n" + node_string
  655. lines = message.splitlines()
  656. for line in lines:
  657. layout.label(text=line)
  658. def execution_error_cleanup(node, exception, switch_objects = [], show_error=False ):
  659. from bpy import context
  660. ui_sig = None
  661. if show_error: # show a popup and select the relevant nodes
  662. if node:
  663. if node.mContext:
  664. if node.mContext.execution_failed==True:
  665. # already have an error, pass it to avoid printing
  666. return # a second error (it's confusing to users.)
  667. node.mContext.execution_failed=True
  668. ui_sig = node.ui_signature
  669. # TODO: see about zooming-to-node.
  670. base_tree = node.base_tree
  671. tree = base_tree
  672. try:
  673. for name in ui_sig[1:]:
  674. for n in tree.nodes: n.select = False
  675. n = tree.nodes[name]
  676. n.select = True
  677. tree.nodes.active = n
  678. if hasattr(n, "node_tree"):
  679. tree = n.node_tree
  680. except AttributeError: # not being run in node graph
  681. pass
  682. finally:
  683. def error_popup_draw(self, context):
  684. error_popup_draw_inner(self.layout, exception, ui_sig)
  685. context.window_manager.popup_menu(error_popup_draw, title="Error", icon='ERROR')
  686. switch_mode(mode='OBJECT', objects=switch_objects)
  687. for ob in switch_objects:
  688. ob.data.pose_position = 'POSE'
  689. prRed(f"Error: {exception} in node {ui_sig}")
  690. return exception
  691. def print_cycle(nodes):
  692. ret_str = ""
  693. for node in nodes:
  694. ret_str+= node.__repr__() + '\n'
  695. return ret_str
  696. def sort_execution(nodes, error_popups):
  697. from ..utilities.node_common import GraphError
  698. from collections import deque
  699. xForm_pass = deque()
  700. execution_failed = False
  701. sorted_nodes = []
  702. # initialize the hierarchy dependency count. We'll use this to ensure there
  703. # are no cycles (using Kahn's algorithm).
  704. expected_sort_quantity = len(nodes)
  705. for mantis_node in nodes.values():
  706. if mantis_node.node_type in ['DUMMY', 'DUMMY_SCHEMA', 'INTERFACE']:
  707. expected_sort_quantity -=1 ; continue
  708. if mantis_node.is_schema_prototype:
  709. expected_sort_quantity -= 1; continue
  710. mantis_node.unmet_hierarchy_dependency_count = len(mantis_node.hierarchy_dependencies)
  711. if mantis_node.unmet_hierarchy_dependency_count == 0 :
  712. xForm_pass.append(mantis_node)
  713. processed_count = 0
  714. while(xForm_pass):
  715. n = xForm_pass.popleft()
  716. # if n.execution_prepared: continue
  717. n.execution_prepared = True
  718. sorted_nodes.append(n)
  719. processed_count+=1
  720. for child in n.hierarchy_connections:
  721. child.unmet_hierarchy_dependency_count-= 1
  722. if child.unmet_hierarchy_dependency_count == 0:
  723. xForm_pass.append(child)
  724. if processed_count < expected_sort_quantity:
  725. cycle = []
  726. for n in nodes.values():
  727. if n.execution_prepared == False:
  728. cycle.append(n)
  729. execution_failed = True
  730. e = GraphError("Detected a cycle in the tree, containing at "
  731. "least one of the following nodes: " + print_cycle(cycle))
  732. e = execution_error_cleanup(cycle[-1], e, show_error=error_popups)
  733. prRed(processed_count, expected_sort_quantity)
  734. raise e
  735. return sorted_nodes, execution_failed
  736. def execute_tree(nodes, base_tree, context, error_popups = False, profile=False):
  737. assert nodes is not None, "Failed to parse tree."
  738. assert len(nodes) > 0, "No parsed nodes for execution."\
  739. " Mantis probably failed to parse the tree."
  740. from bpy.types import Object as bpy_object
  741. from time import time
  742. original_active = context.view_layer.objects.active
  743. start_execution_time = time()
  744. mContext = None
  745. for mantis_node in nodes.values():
  746. if not mContext: # just grab one of these. this is a silly way to do this.
  747. mContext = mantis_node.mContext
  748. mContext.b_objects = {} # clear the objects and recreate them
  749. mantis_node.reset_execution()
  750. mContext.execution_failed = False
  751. interface_nodes = {}
  752. from ..internal_nodes import GroupInterface
  753. for node in nodes.values():
  754. if isinstance(node, GroupInterface):
  755. interface_nodes[node.signature] = node
  756. overlay_tagged_nodes = {}
  757. for node_signature, socket_id in mContext.tagged_for_overlay:
  758. if overlay_tagged_nodes.get(node_signature):
  759. overlay_tagged_nodes[node_signature].append(socket_id)
  760. else:
  761. overlay_tagged_nodes[node_signature] = [socket_id]
  762. def check_and_apply_overlay(n):
  763. if overlays_for_this_node := overlay_tagged_nodes.get(n.signature):
  764. for socket_id in overlays_for_this_node:
  765. node_scan_overlays(n, socket_id,)
  766. select_me, switch_me = [], [] # switch the mode on these objects
  767. active = None # only need it for switching modes
  768. select_me = []
  769. profiler = None
  770. if profile:
  771. from ..dev_helpers.profile_nodes import NodeProfiler
  772. profiler = NodeProfiler()
  773. profiler.new_session(mContext.execution_id)
  774. sort_key = 'total'
  775. try:
  776. sorted_nodes, execution_failed = sort_execution(nodes, error_popups=error_popups)
  777. except Exception as e:
  778. # We'll fire the popup in sort_execution because it has the node in scope
  779. if error_popups == False:
  780. raise e
  781. execution_failed = True
  782. try:
  783. for n in sorted_nodes:
  784. if execution_failed: break
  785. try:
  786. check_and_apply_overlay(n)
  787. if not n.prepared and 'bPrepare' in n.passes:
  788. if profiler: profiler.record(n, "bPrepare", context)
  789. else: n.bPrepare(context)
  790. if not n.executed and 'bTransform' in n.passes:
  791. if profiler: profiler.record(n, "bTransformPass", context)
  792. else: n.bTransformPass(context)
  793. if (n.__class__.__name__ == "xFormArmature" ):
  794. ob = n.bGetObject()
  795. switch_me.append(ob)
  796. active = ob
  797. if not (n.__class__.__name__ == "xFormBone" ) and hasattr(n, "bGetObject"):
  798. ob = n.bGetObject()
  799. if isinstance(ob, bpy_object):
  800. select_me.append(ob)
  801. except Exception as e:
  802. e = execution_error_cleanup(n, e, show_error=error_popups)
  803. if error_popups == False:
  804. raise e
  805. execution_failed = True; break
  806. switch_mode(mode='POSE', objects=switch_me)
  807. for n in sorted_nodes:
  808. try:
  809. check_and_apply_overlay(n)
  810. if not n.prepared and 'bPrepare' in n.passes:
  811. if profiler: profiler.record(n, "bPrepare", context)
  812. else: n.bPrepare(context)
  813. if not n.executed and 'bRelationship' in n.passes:
  814. if profiler: profiler.record(n, "bRelationshipPass", context)
  815. else: n.bRelationshipPass(context)
  816. except Exception as e:
  817. e = execution_error_cleanup(n, e, show_error=error_popups)
  818. if error_popups == False:
  819. raise e
  820. execution_failed = True; break
  821. switch_mode(mode='OBJECT', objects=switch_me)
  822. # switch to pose mode here so that the nodes can use the final pose data
  823. # this will require them to update the depsgraph.
  824. for ob in switch_me:
  825. ob.data.pose_position = 'POSE'
  826. for n in sorted_nodes:
  827. if 'bFinalize' in n.passes:
  828. try:
  829. if profiler: profiler.record(n, "bFinalize", context)
  830. else: n.bFinalize(context)
  831. except Exception as e:
  832. e = execution_error_cleanup(n, e, show_error=error_popups)
  833. if error_popups == False:
  834. raise e
  835. execution_failed = True; break
  836. # REST pose for deformer bind, so everything is in the rest position
  837. for ob in switch_me:
  838. ob.data.pose_position = 'REST'
  839. # finally, apply modifiers and bind stuff
  840. for n in sorted_nodes:
  841. if 'bModifierApply' in n.passes:
  842. try:
  843. if profiler: profiler.record(n, "bModifierApply", context)
  844. else: n.bModifierApply(context)
  845. except Exception as e:
  846. e = execution_error_cleanup(n, e, show_error=error_popups)
  847. if error_popups == False:
  848. raise e
  849. execution_failed = True; break
  850. for ob in switch_me:
  851. ob.data.pose_position = 'POSE'
  852. tot_time = (time() - start_execution_time)
  853. if not execution_failed:
  854. prGreen(f"Executed tree of {len(sorted_nodes)} nodes in {tot_time} seconds")
  855. if profiler:
  856. from ..dev_helpers.profile_nodes import summarize_profile
  857. summarize_profile(profiler._current, pass_name='bPrepare', sort_key = sort_key)
  858. summarize_profile(profiler._current, pass_name='bTransformPass', sort_key = sort_key)
  859. summarize_profile(profiler._current, pass_name='bRelationshipPass', sort_key = sort_key)
  860. summarize_profile(profiler._current, pass_name='bFinalize', sort_key = sort_key)
  861. summarize_profile(profiler._current, pass_name='bModifierApply', sort_key = sort_key)
  862. if (original_active):
  863. context.view_layer.objects.active = original_active
  864. original_active.select_set(True)
  865. except Exception as e:
  866. e = execution_error_cleanup(None, e, switch_me, show_error=error_popups)
  867. if error_popups == False:
  868. raise e
  869. prRed(f"Failed to execute tree.")
  870. finally:
  871. context.view_layer.objects.active = active
  872. # clear the selection first.
  873. from itertools import chain
  874. for ob in context.selected_objects:
  875. try:
  876. ob.select_set(False)
  877. except RuntimeError: # it isn't in the view layer
  878. pass
  879. for ob in chain(select_me, mContext.b_objects.values()):
  880. try:
  881. ob.select_set(True)
  882. except RuntimeError: # it isn't in the view layer
  883. pass