schema_solve.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. from .utilities import (prRed, prGreen, prPurple, prWhite,
  2. prOrange,
  3. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  4. wrapOrange,)
  5. from .utilities import init_connections, init_dependencies, get_link_in_out
  6. from .base_definitions import (SchemaUINode, custom_props_types, \
  7. MantisNodeGroup, SchemaGroup, replace_types, GraphError, links_sort_key)
  8. from .node_container_common import setup_custom_props_from_np
  9. # a class that solves Schema nodes
  10. from bpy.types import NodeGroupInput, NodeGroupOutput
  11. from .readtree import execution_error_cleanup
  12. class SchemaSolver:
  13. def __init__(self, schema_dummy, nodes, prototype, signature=None, error_popups=False):
  14. self.all_nodes = nodes # this is the parsed tree from Mantis
  15. self.node = schema_dummy
  16. self.node.solver = self
  17. self.solved = False
  18. self.tree = prototype.node_tree
  19. self.uuid = self.node.uuid
  20. self.error_popups = error_popups
  21. if signature:
  22. self.signature = signature
  23. else:
  24. self.signature = self.node.signature
  25. self.schema_nodes={}
  26. self.solved_nodes = {}
  27. self.incoming_connections = {}
  28. self.outgoing_connections = {}
  29. self.constant_in = {}
  30. self.constant_out = {}
  31. self.array_input_connections = {}
  32. self.array_output_connections = {}
  33. self.nested_schemas = {}
  34. self.autogenerated_nodes = {}
  35. self.held_links = []
  36. self.tree_path_names = [*self.node.signature] # same tree as the schema node
  37. self.autogen_path_names = ['SCHEMA_AUTOGENERATED', *self.node.signature[1:]]
  38. self.is_node_group = False
  39. if self.node.prototype.bl_idname == "MantisNodeGroup":
  40. self.is_node_group = True
  41. if self.node.inputs['Schema Length'].links:
  42. self.index_link = self.node.inputs['Schema Length'].links[0]
  43. else:
  44. self.index_link = None
  45. # this should never happen, but it's OK to check.
  46. if self.node.inputs["Schema Length"].is_linked:
  47. if (other := self.node.inputs['Schema Length'].links[0].from_node).prepared == False:
  48. raise RuntimeError(f"Schema Length cannot be determined for {self.node} because {other} is not prepared.")
  49. self.solve_length = self.node.evaluate_input("Schema Length")
  50. # I'm making this a property of the solver because the solver's data is modified as it solves each iteration
  51. self.index = 0
  52. prWhite(f"\nExpanding schema {self.tree.name} in node {self.node.signature}"
  53. f" with length {self.solve_length}.")
  54. self.init_schema_links()
  55. self.set_index_strings()
  56. # Sort the multi-input nodes in reverse order of ID, this ensures that they are
  57. # read in the order they were created
  58. for inp in self.node.inputs.values():
  59. inp.links.sort(key=links_sort_key)
  60. from bpy.types import NodeGroupInput, NodeGroupOutput
  61. for ui_node in self.tree.nodes:
  62. # first we need to fill the parameters of the schema nodes.
  63. # we use the bl_idname because all schema nodes should be single-instance
  64. signature = (*self.tree_path_names, ui_node.bl_idname)
  65. if isinstance(ui_node, (SchemaUINode, NodeGroupInput, NodeGroupOutput)):
  66. # We use the schema node's "natural signature" here because it represents
  67. # the "original" signature of the schema UI group node since this schema
  68. # solver may be in a nested schema, and its node's signature may have
  69. # uuid/index attached.
  70. get_sig = (*self.node.ui_signature, ui_node.bl_idname)
  71. if not (mantis_node := self.all_nodes.get(get_sig)):
  72. raise RuntimeError(wrapRed(f"Not found: {get_sig}"))
  73. self.schema_nodes[signature] = mantis_node
  74. mantis_node.fill_parameters(ui_node)
  75. # HACK to make Group Nodes work
  76. if ui_node.bl_idname == "NodeGroupInput":
  77. from .schema_nodes import SchemaConstInput
  78. mantis_node = SchemaConstInput(signature=signature, base_tree=self.node.base_tree, parent_schema_node=self.node)
  79. self.schema_nodes[signature] = mantis_node
  80. mantis_node.fill_parameters(ui_node)
  81. if ui_node.bl_idname == "NodeGroupOutput":
  82. from .schema_nodes import SchemaConstOutput
  83. mantis_node = SchemaConstOutput(signature=signature, base_tree=self.node.base_tree, parent_schema_node=self.node)
  84. self.schema_nodes[signature] = mantis_node
  85. mantis_node.fill_parameters(ui_node)
  86. interface = self.setup_interface_node(signature=( *self.signature, "InputInterface"))
  87. def setup_interface_node(self, signature):
  88. from .internal_containers import GroupInterface
  89. interface = GroupInterface(
  90. signature,
  91. self.node.base_tree, self.node.prototype, 'INPUT',)
  92. # now we need to connect it up
  93. # adapted from readtree.grp_node_reroute_common
  94. from .base_definitions import links_sort_key
  95. for in_node_input in self.node.inputs:
  96. if in_node_input.name != 'Schema Length':
  97. for interface_socket in self.tree.interface.items_tree:
  98. if interface_socket.item_type == 'PANEL': continue
  99. if interface_socket.identifier == in_node_input.name: break
  100. if hasattr(interface_socket, "is_array") and interface_socket.is_array: continue
  101. if hasattr(interface_socket, "is_connection") and interface_socket.is_connection: continue
  102. # for now, do not try and connect to the array/connection inputs.
  103. i = 0
  104. if len(in_node_input.links)>1: # sort here to ensure correct sub_sort_id
  105. in_node_input.links.sort(key=links_sort_key)
  106. for in_link in in_node_input.links:
  107. from_node = in_link.from_node; from_socket = in_link.from_socket
  108. link = from_node.outputs[from_socket].connect(
  109. interface,in_node_input.name, sort_id = 2**16, sub_sort_id=i)
  110. i += 1
  111. in_node_input.links.sort(key=links_sort_key)
  112. return interface # I want to be able to set this up elsewhere
  113. def set_index_strings(self):
  114. self.index_str = lambda : '.'+str(self.uuid)+'.'+str(self.index).zfill(4)
  115. self.prev_index_str = lambda : '.'+str(self.uuid)+'.'+str(self.index-1).zfill(4)
  116. if self.is_node_group:
  117. self.index_str=lambda : ''
  118. self.prev_index_str=lambda : ''
  119. def init_schema_links(self,):
  120. """ Sort and store the links to/from the Schema group node."""
  121. for item in self.tree.interface.items_tree:
  122. if item.item_type == 'PANEL': continue
  123. from .utilities import read_schema_type
  124. parent_name = read_schema_type(item)
  125. # just gonna try and make the
  126. match parent_name:
  127. case 'Connection':
  128. if item.in_out == 'INPUT':
  129. if incoming_links := self.node.inputs[item.identifier].links:
  130. self.incoming_connections[item.name] = incoming_links[0]
  131. else:
  132. self.incoming_connections[item.name] = None
  133. else: # OUTPUT
  134. if outgoing_links := self.node.outputs[item.identifier].links:
  135. self.outgoing_connections[item.name] = outgoing_links.copy()
  136. else:
  137. self.outgoing_connections[item.name] = []
  138. case 'Constant':
  139. if item.in_out == 'INPUT':
  140. if constant_in_links := self.node.inputs[item.identifier].links:
  141. self.constant_in[item.name] = constant_in_links[0]
  142. else:
  143. self.constant_in[item.name] = None
  144. else: # OUTPUT
  145. if constant_out_links := self.node.outputs[item.identifier].links:
  146. self.constant_out[item.name] = constant_out_links.copy()
  147. else:
  148. self.constant_out[item.name] = []
  149. case 'Array':
  150. if item.in_out == 'INPUT':
  151. if item.identifier not in self.array_input_connections.keys():
  152. self.array_input_connections[item.identifier]=[]
  153. if in_links := self.node.inputs[item.identifier].links:
  154. self.array_input_connections[item.identifier]=in_links.copy()
  155. # I am tempted to put a check here, but it is sufficient to
  156. # rely on hierarchy links ensuring the arrays are prepared.
  157. # and testing here for un-prepared arrays will mess up schema
  158. # relationships in non-hierarchy situations.
  159. # Still, I'd like to have an easier time catching these problems.
  160. else: # OUTPUT
  161. if item.identifier not in self.array_output_connections.keys():
  162. self.array_output_connections[item.identifier]=[]
  163. if out_links := self.node.outputs[item.identifier].links:
  164. self.array_output_connections[item.identifier] = out_links.copy()
  165. def is_node_deeper_nested(self, queried_node, compare_node):
  166. return len(compare_node.signature) < len(queried_node.signature)
  167. def gen_solve_iteration_mantis_nodes(self, frame_mantis_nodes, unprepared):
  168. for prototype_ui_node in self.tree.nodes:
  169. mantis_node_name = prototype_ui_node.name
  170. index_str = self.index_str()
  171. mContext=self.node.mContext
  172. if isinstance(prototype_ui_node, SchemaUINode):
  173. continue # IGNORE the schema interface nodes, we already made them in __init__()
  174. # they are reused for each iteration.
  175. elif prototype_ui_node.bl_idname in ['NodeFrame', 'NodeReroute']:
  176. continue # IGNORE stuff that is purely UI - frames, reroutes.
  177. elif prototype_ui_node.bl_idname in ['NodeGroupInput', 'NodeGroupOutput']:
  178. continue # we converted these to Schema Nodes because they represent a Group input.
  179. signature = (*self.autogen_path_names, mantis_node_name+index_str)
  180. ui_signature=(*self.signature, mantis_node_name)
  181. prototype_mantis_node = self.all_nodes[ui_signature]
  182. # the prototype_mantis_node was generated inside the schema when we parsed the tree.
  183. # it is the prototype of the mantis node which we make for this iteration
  184. # for Schema sub-nodes ... they need a prototype to init.
  185. if prototype_mantis_node.node_type in ['DUMMY', 'DUMMY_SCHEMA']:
  186. # We stored the prototype ui_node when creating the Mantis node.
  187. ui_node = prototype_mantis_node.prototype
  188. # if prototype_mantis_node is a group or schema: TODO changes are needed elsewhere to make this easier to read. LEGIBILITY
  189. if ui_node.bl_idname in ["MantisNodeGroup", "MantisSchemaGroup"]:
  190. mantis_node = prototype_mantis_node.__class__(
  191. signature, prototype_mantis_node.base_tree, prototype=ui_node,
  192. ui_signature = prototype_mantis_node.signature)
  193. # establish string variables
  194. from .utilities import set_string_variables_at_creation_time
  195. set_string_variables_at_creation_time(mantis_node, prototype_ui_node, mContext)
  196. # now let's copy the links from the prototype node
  197. if ui_node.bl_idname in ["MantisNodeGroup"]:
  198. mantis_node.prepared = False
  199. mantis_node.node_type = 'DUMMY_SCHEMA' # we promote it to a schema for now
  200. mantis_node.inputs.init_sockets(['Schema Length']) # add a Schema Length socket
  201. mantis_node.parameters['Schema Length'] = 1 # set the length to 1 since it is a single group instance
  202. # we'll make the autogenerated nodes for constant inputs. It doesn't matter that there is technically
  203. # a prototype available for each one -- these are cheap and I want this to be easy.
  204. from .readtree import make_connections_to_ng_dummy
  205. make_connections_to_ng_dummy(self.node.base_tree, self.autogen_path_names, frame_mantis_nodes, self.all_nodes, mantis_node)
  206. else:
  207. mantis_node = prototype_mantis_node.__class__(signature, prototype_mantis_node.base_tree, prototype=ui_node)
  208. else:
  209. mantis_node = prototype_mantis_node.__class__(signature, prototype_mantis_node.base_tree)
  210. frame_mantis_nodes[mantis_node.signature] = mantis_node
  211. self.all_nodes[mantis_node.signature] = mantis_node
  212. mantis_node.ui_signature=ui_signature # set the natural signature to ensure we can access from the UI
  213. if mantis_node.prepared == False:
  214. unprepared.append(mantis_node)
  215. if mantis_node.__class__.__name__ in custom_props_types:
  216. setup_custom_props_from_np(mantis_node, prototype_ui_node)
  217. mantis_node.fill_parameters(prototype_ui_node)
  218. # be sure to pass on the Mantis Context to them
  219. mantis_node.mContext=mContext
  220. # set up an interface node at this point.
  221. interface = self.setup_interface_node(signature=( *self.signature, "InputInterface"+self.index_str() ))
  222. interface.mContext = mContext
  223. frame_mantis_nodes[interface.signature] = interface
  224. self.all_nodes[interface.signature] = interface
  225. def handle_link_from_index_input(self, index, frame_mantis_nodes, ui_link):
  226. from .base_definitions import can_remove_socket_for_autogen
  227. _from_name, to_name = get_link_in_out(ui_link)
  228. to_node = frame_mantis_nodes[ (*self.autogen_path_names, to_name+self.index_str()) ]
  229. if (not can_remove_socket_for_autogen(to_node, ui_link.to_socket.name)) or \
  230. to_node.node_type in ['DUMMY', 'DUMMY_SCHEMA']:
  231. from .readtree import autogen_node
  232. unique_name = "".join([
  233. ui_link.to_socket.node.name+self.index_str(),
  234. ui_link.from_socket.name, ui_link.from_socket.identifier,
  235. "==>", ui_link.to_socket.name, ui_link.to_socket.identifier,],)
  236. signature = ("MANTIS_AUTOGENERATED", *self.tree_path_names[1:-1], unique_name)
  237. from_node = self.all_nodes.get(signature)
  238. if not from_node:
  239. from_node = autogen_node(self.node.base_tree, ui_link.from_socket,
  240. signature=signature, mContext=self.node.mContext)
  241. from_node.parameters = {ui_link.from_socket.name:index}
  242. frame_mantis_nodes[signature]=from_node; self.solved_nodes[signature]=from_node
  243. self.all_nodes[signature]=from_node
  244. _connection = from_node.outputs[ui_link.from_socket.name].connect(node=to_node, socket=ui_link.to_socket.identifier)
  245. return
  246. # Since the index is already determined, it is safe to remove the socket and just keep the value.
  247. to_node.parameters[ui_link.to_socket.name] = index
  248. del to_node.inputs[ui_link.to_socket.name]
  249. def handle_link_from_schema_length_input(self, frame_mantis_nodes, ui_link):
  250. # see, here I can just use the schema node
  251. _from_name, to_name = get_link_in_out(ui_link)
  252. if to_name in replace_types:
  253. to_node = self.schema_nodes[(*self.autogen_path_names, to_name)]
  254. else:
  255. to_node = frame_mantis_nodes[(*self.autogen_path_names, to_name+self.index_str())]
  256. # this self.index_link is only used here?
  257. if self.index_link is None:
  258. # this should be impossible because the Schema gets an auto-generated Int input.
  259. raise NotImplementedError(" 241 This code should be unreachable. Please report this as a bug!")
  260. if (self.index_link.from_node):
  261. connection = self.index_link.from_node.outputs[self.index_link.from_socket].connect(node=to_node, socket=ui_link.to_socket.name)
  262. # otherwise we can autogen an int input I guess...?
  263. else:
  264. raise RuntimeError("247 I This code should be unreachable. Please report this as a bug!")
  265. # TODO: link the incoming connection to the current Interface node
  266. # It is complicated because the Interface needs the identifier
  267. # but most of this stuff uses the name and I donno how to get the ID
  268. # this isn't very important. I'll add this feature when someone tries
  269. # to use it and complains.
  270. def handle_link_from_incoming_connection_input(self, frame_mantis_nodes, ui_link):
  271. incoming = self.incoming_connections[ui_link.from_socket.name]
  272. if incoming is not None:
  273. from_node = incoming.from_node
  274. _from_name, to_name = get_link_in_out(ui_link)
  275. to_node = frame_mantis_nodes[ (*self.autogen_path_names, to_name+self.index_str()) ]
  276. socket_name=ui_link.to_socket.name
  277. if to_node.node_type in [ 'DUMMY_SCHEMA' ]:
  278. socket_name=ui_link.to_socket.identifier
  279. connection = from_node.outputs[incoming.from_socket].connect(node=to_node, socket=socket_name)
  280. init_connections(from_node)
  281. def handle_link_to_outgoing_connection_output(self, frame_mantis_nodes, ui_link,):
  282. mantis_incoming_node = self.schema_nodes[*self.tree_path_names, 'SchemaIncomingConnection']
  283. for mantis_link in mantis_incoming_node.outputs[ui_link.to_socket.name].links:
  284. to_mantis_node, to_socket_name = mantis_link.to_node, mantis_link.to_socket
  285. from_name = get_link_in_out(ui_link)[0]
  286. from_mantis_node = self.solved_nodes[ (*self.autogen_path_names, from_name+self.prev_index_str()) ]
  287. to_mantis_node_signature = ( *self.autogen_path_names,
  288. to_mantis_node.signature[-1] + self.index_str() )
  289. # we need to detect if the next node is in a group.
  290. # REMEMBER: at this point, nested groups haven't been solved yet.
  291. if to_mantis_node_signature not in frame_mantis_nodes.keys() and \
  292. self.is_node_deeper_nested(to_mantis_node, from_mantis_node):
  293. to_mantis_node = frame_mantis_nodes[ (
  294. *self.autogen_path_names, # the SCHEMA_AUTOGENERATED string
  295. to_mantis_node.signature[-2]+ self.index_str() ) ]
  296. # this connection was forbidden before, right? so this should be a safe assumption.
  297. assert to_mantis_node.node_type == 'DUMMY_SCHEMA', "I expected this to be a group/schema"
  298. # we need to get the identifier of the named socket now.
  299. to_socket_name = to_mantis_node.prototype.inputs[to_socket_name].identifier
  300. else:
  301. to_mantis_node = frame_mantis_nodes[ to_mantis_node_signature ] # add the index string
  302. from_socket_name = ui_link.from_socket.name
  303. if from_mantis_node.node_type in ['DUMMY_SCHEMA']:
  304. from_socket_name = ui_link.from_socket.identifier
  305. connection = from_mantis_node.outputs[from_socket_name].connect(node=to_mantis_node, socket=to_socket_name)
  306. # We want to delete the links from the tree into the schema node.
  307. # TODO: this is not robust enough and I do not feel sure this is doing the right thing.
  308. if existing_link := self.incoming_connections[ui_link.to_socket.name]:
  309. if existing_link.to_node == self.node:
  310. print ("INFO: Deleting...", existing_link)
  311. if self.node.signature[-1] in existing_link.to_node.signature:
  312. existing_link.die()
  313. # BUG may exist here.
  314. self.incoming_connections[ui_link.to_socket.name] = connection
  315. def handle_link_from_constant_input(self, frame_mantis_nodes, ui_link, to_ui_node):
  316. incoming = self.constant_in[ui_link.from_socket.name]
  317. if incoming is None:
  318. raise GraphError (f"{self.node} is missing a required input: {ui_link.from_socket.name}")
  319. from_node = incoming.from_node
  320. to_name = get_link_in_out(ui_link)[1]
  321. to_node = frame_mantis_nodes[(*self.autogen_path_names, to_name+self.index_str())]
  322. to_socket=ui_link.to_socket.name
  323. from .base_definitions import MantisNodeGroup, SchemaGroup
  324. if isinstance(to_ui_node, (SchemaGroup, MantisNodeGroup)):
  325. to_socket=ui_link.to_socket.identifier
  326. connection = from_node.outputs[incoming.from_socket].connect(node=to_node, socket=to_socket)
  327. init_connections(from_node)
  328. def handle_link_from_array_input_get(self, frame_mantis_nodes, ui_link ):
  329. from_ui_node = ui_link.from_socket.node
  330. from_node = self.schema_nodes[(*self.node.ui_signature, from_ui_node.bl_idname)]
  331. from collections import deque
  332. unprepared = deque(from_node.hierarchy_dependencies)
  333. self.prepare_nodes(unprepared)
  334. from .utilities import cap, wrap
  335. get_index = from_node.evaluate_input("Index", self.index) # get the most recent link
  336. # getting the link at self.index just saves the trouble of killing the old links
  337. # that are left because this node is reused in each iteration of the schema
  338. assert(get_index is not None), f"Cannot get index in {from_node}"
  339. oob = from_node.evaluate_input("OoB Behaviour")
  340. array_length = len(self.array_input_connections[ui_link.from_socket.identifier])-1
  341. if oob == 'WRAP':
  342. get_index = wrap(0, array_length+1, get_index)
  343. if oob == 'HOLD':
  344. get_index = cap(get_index, array_length)
  345. try:
  346. incoming = self.array_input_connections[ui_link.from_socket.identifier][get_index]
  347. except IndexError:
  348. raise RuntimeError(f"The array index {get_index} is out of bounds. Size: "
  349. f"{len(self.array_input_connections[ui_link.from_socket.identifier])}")
  350. to_name = get_link_in_out(ui_link)[1]
  351. to_node = frame_mantis_nodes[(*self.autogen_path_names, to_name+self.index_str())]
  352. from_socket = incoming.from_node.outputs[incoming.from_socket]
  353. connection = from_socket.connect(to_node, ui_link.to_socket.name)
  354. # TODO: kill links to the array get that are no longer needed
  355. # right now I inefficiently waste cpu-time solving extra nodes
  356. # because I took the lazy way out
  357. def handle_link_to_array_input_get(self, frame_mantis_nodes, ui_link):
  358. from_name, to_name = get_link_in_out(ui_link)
  359. from_nc = frame_mantis_nodes[(*self.autogen_path_names, from_name+self.index_str())]
  360. to_nc = self.schema_nodes[(*self.tree_path_names, to_name)]
  361. # this only needs to be done once:
  362. if self.index == 0: # BUG? HACK? TODO find out what is going on here.
  363. # Kill the link between the schema node group and the node connecting to it
  364. old_nc = self.all_nodes[(*self.tree_path_names, from_name)]
  365. # I am not sure about this!
  366. existing_link = old_nc.outputs[ui_link.from_socket.name].links[0]
  367. existing_link.die()
  368. #
  369. connection = from_nc.outputs[ui_link.from_socket.name].connect(node=to_nc, socket=ui_link.to_socket.name)
  370. connection.is_hierarchy = True # we have to mark this because links to Schema are not usually hierarchy (?)
  371. to_nc.hierarchy_dependencies.append(from_nc); from_nc.hierarchy_connections.append(to_nc)
  372. # TODO: review the wisdom of this default.
  373. def handle_link_from_array_input(self, frame_mantis_nodes, ui_link, index):
  374. get_index = index
  375. try:
  376. incoming = self.array_input_connections[ui_link.from_socket.identifier][get_index]
  377. except IndexError:
  378. if len(self.array_input_connections[ui_link.from_socket.identifier]) > 0:
  379. incoming = self.array_input_connections[ui_link.from_socket.identifier][0]
  380. # prOrange(incoming.from_node.node_type)
  381. if incoming.from_node.node_type not in ['DUMMY_SCHEMA']:
  382. raise NotImplementedError(wrapRed("dev: make it so Mantis checks if there are enough Array inputs."))
  383. else: # do nothing
  384. return
  385. else:
  386. raise RuntimeError(wrapRed("make it so Mantis checks if there are enough Array inputs!"))
  387. to_name = get_link_in_out(ui_link)[1]
  388. to_node = frame_mantis_nodes[(*self.autogen_path_names, to_name+self.index_str())]
  389. connection = incoming.from_node.outputs[incoming.from_socket].connect(node=to_node, socket=ui_link.to_socket.name)
  390. init_connections(incoming.from_node)
  391. def handle_link_from_array_input_all(self, frame_mantis_nodes, ui_link):
  392. all_links = self.array_input_connections[ui_link.from_socket.identifier]
  393. to_name = get_link_in_out(ui_link)[1]
  394. to_node = frame_mantis_nodes[(*self.autogen_path_names, to_name+self.index_str())]
  395. # connection = incoming.from_node.outputs[incoming.from_socket].connect(node=to_node, socket=ui_link.to_socket.name)
  396. for l in all_links:
  397. # we need to copy the link with the new from-node info
  398. from .base_definitions import NodeLink
  399. to_socket_name=ui_link.to_socket.name
  400. if to_node.node_type in ['DUMMY_SCHEMA']:
  401. to_socket_name=ui_link.to_socket.identifier
  402. connection = NodeLink(l.from_node, l.from_socket, to_node, to_socket_name,
  403. l.multi_input_sort_id, l.sub_sort_id)
  404. to_node.flush_links()
  405. def handle_link_to_constant_output(self, frame_mantis_nodes, index, ui_link, to_ui_node):
  406. to_node = self.schema_nodes[(*self.tree_path_names, to_ui_node.bl_idname)]
  407. expose_when = to_node.evaluate_input('Expose when N==')
  408. # this will be None for nested Groups that have ordinary Group Input and Group Output nodes.
  409. # and in that case we just do it no matter what
  410. if expose_when is not None and expose_when > self.solve_length-1:
  411. raise GraphError(f"The Schema has a constant output at index {expose_when}"
  412. f" but it terminates at index {self.solve_length-1}. "
  413. f"The Schema must have a length of at least {expose_when+1}.")
  414. from_name = get_link_in_out(ui_link)[0]
  415. from bpy.types import NodeSocket
  416. #use it directly if it is a mantis node; this happens when the previous node was a Schema
  417. if isinstance( ui_link.from_socket, NodeSocket): # normal
  418. from_node = frame_mantis_nodes[(*self.autogen_path_names, from_name+self.index_str()) ]
  419. else: # it's a mantis socket, set manually while looping though prepped links
  420. from_node = ui_link.from_socket.node
  421. from_socket_name = ui_link.from_socket.name
  422. if from_node.node_type == 'DUMMY_SCHEMA':
  423. if isinstance( ui_link.from_socket, NodeSocket): # normal
  424. from_socket_name = ui_link.from_socket.identifier
  425. else:
  426. from_socket_name = ui_link.from_socket.name
  427. # HACK here to force it to work with ordinary node groups, which don't seem to set this value correctly.
  428. if to_ui_node.bl_idname == "NodeGroupOutput":
  429. expose_when = index # the expose-when value is None because the GroupOutput doesn't have the socket.
  430. # end HACK
  431. if index == expose_when:
  432. for outgoing in self.constant_out[ui_link.to_socket.name]:
  433. to_node = outgoing.to_node
  434. connection = from_node.outputs[from_socket_name].connect(node=to_node, socket=outgoing.to_socket)
  435. def handle_link_from_subschema_to_output(self, frame_mantis_nodes, ui_link, to_ui_node):
  436. # wire the schema node itself to the output so it will push the connections when solving
  437. to_node = self.schema_nodes[(*self.tree_path_names, to_ui_node.bl_idname)]
  438. from_name = get_link_in_out(ui_link)[0]
  439. from_node = frame_mantis_nodes[ (*self.autogen_path_names, from_name+self.index_str()) ]
  440. connection = from_node.outputs[ui_link.from_socket.identifier].connect(node=to_node, socket=ui_link.to_socket.name)
  441. def handle_link_from_array_type_to_array_out(self, original_ui_link, dummy_link):
  442. # this is so annoyingly specific lol
  443. from_node = dummy_link.nc_from; from_socket_name=dummy_link.from_socket.name
  444. for outgoing in self.array_output_connections[original_ui_link.to_socket.identifier]:
  445. to_node = outgoing.to_node
  446. connection = from_node.outputs[from_socket_name].connect(node=to_node, socket=outgoing.to_socket)
  447. # WTF is even happening here?? TODO BUG HACK
  448. def handle_link_to_array_output(self, frame_mantis_nodes, index, ui_link, to_ui_node, from_ui_node):# if this duplicated code works, dedupe!
  449. to_node = self.schema_nodes[(*self.tree_path_names, to_ui_node.bl_idname)] # get it by [], we want a KeyError if this fails
  450. from_name = get_link_in_out(ui_link)[0]
  451. from bpy.types import NodeSocket
  452. #use it directly if it is a mantis node; this happens when the previous node was a Schema
  453. if isinstance( ui_link.from_socket, NodeSocket): # normal
  454. from_node = frame_mantis_nodes[(*self.autogen_path_names, from_name+self.index_str()) ]
  455. else: # it's a mantis socket, set manually while looping though prepped links
  456. from_node = ui_link.from_socket.node
  457. from_socket_name = ui_link.from_socket.name
  458. for outgoing in self.array_output_connections[ui_link.to_socket.identifier]:
  459. if not from_node:
  460. from_node = self.schema_nodes[(*self.tree_path_names, from_ui_node.bl_idname)]
  461. to_node = outgoing.to_node
  462. from .schema_nodes import SchemaIndex
  463. if isinstance(from_node, SchemaIndex):
  464. signature = ("MANTIS_AUTOGENERATED", *self.tree_path_names[1:-1], self.index_str(),
  465. ui_link.from_socket.name, ui_link.from_socket.identifier)
  466. from_node = self.all_nodes.get(signature)
  467. if not from_node:
  468. from .readtree import autogen_node
  469. from_node = autogen_node(self.node.base_tree, ui_link.from_socket,
  470. signature, self.node.mContext)
  471. if ui_link.from_socket.name in ['Index']:
  472. from_node.parameters = {ui_link.from_socket.name:index}
  473. else:
  474. from_node.parameters = {ui_link.from_socket.name:self.solve_length}
  475. frame_mantis_nodes[signature]=from_node; self.solved_nodes[signature]=from_node
  476. self.all_nodes[signature]=from_node
  477. elif from_node.node_type == 'DUMMY_SCHEMA':
  478. if isinstance( ui_link.from_socket, NodeSocket): # normal
  479. from_socket_name = ui_link.from_socket.identifier
  480. else:
  481. from_socket_name = ui_link.from_socket.name
  482. if to_node.node_type == 'DUMMY_SCHEMA' and to_node.prepared:
  483. other_stem = ('SCHEMA_AUTOGENERATED', *to_node.signature[1:])
  484. other_schema_np = to_node.prototype
  485. other_schema_tree = other_schema_np.node_tree
  486. for n in other_schema_tree.nodes:
  487. if n.bl_idname not in ["SchemaArrayInput", "SchemaArrayInputGet", "SchemaArrayInputAll"]:
  488. continue
  489. out = n.outputs[outgoing.to_socket]
  490. for l in out.links:
  491. other_index_str = lambda : '.'+str(to_node.uuid)+'.'+str(index).zfill(4)
  492. other_sig = (*other_stem, l.to_node.name+other_index_str())
  493. out_node = self.all_nodes.get(other_sig)
  494. if not out_node: # if it is a sub-schema, the other node is in the parent
  495. out_node = to_node.solver.all_nodes.get(other_sig)
  496. if not out_node:
  497. raise KeyError(f"Cannot find node: {other_sig}")
  498. connection = from_node.outputs[from_socket_name].connect(node=out_node, socket=l.to_socket.name)
  499. else:
  500. connection = from_node.outputs[from_socket_name].connect(node=to_node, socket=outgoing.to_socket)
  501. def spoof_link_for_subschema_to_output_edge_case(self, ui_link, ):
  502. to_ui_node = ui_link.to_socket.node
  503. # ui_link is the link between the Schema & the output but we have mantis_links
  504. # connected up correctly. between the output and the schema's generated nodes.
  505. # so seek BACK from the output node and grab the from-node that is connected to
  506. # the link. then modify the ui_link to point to that node.
  507. from .base_definitions import DummyLink
  508. if not isinstance(ui_link, DummyLink): # make it a Dummy so i can modify it
  509. ui_link = DummyLink(ui_link.from_socket, ui_link.to_socket,
  510. multi_input_sort_id=ui_link.multi_input_sort_id)
  511. to_node = self.schema_nodes[(*self.tree_path_names, to_ui_node.bl_idname)]
  512. for inp in to_node.inputs:
  513. if inp.name == ui_link.to_socket.name: # the most recent one is from
  514. l = inp.links[-1]; break # <---- this index of the outer schema
  515. ui_link.from_nc = l.from_node; ui_link.from_socket = l.from_node.outputs[l.from_socket]
  516. return ui_link
  517. def test_is_sub_schema(self, other):
  518. for i in range(len(other.ui_signature)-1): # -1, we don't want to check this node, obviously
  519. if self.node.ui_signature[:i+1]:
  520. return False
  521. return True
  522. def prepare_nodes(self, unprepared):
  523. # At this point, we've already run a pretty exhaustive preperation phase to prep the schema's dependencies
  524. # So we should not need to add any new dependencies unless there is a bug elsewhere.
  525. # and in fact, I could skip this in some cases, and should investigate if profiling reveals a slowdown here.
  526. forbidden=set()
  527. e = None
  528. # forbid some nodes - they aren't necessary to solve the schema & cause problems.
  529. while unprepared:
  530. nc = unprepared.pop()
  531. if nc.node_type == 'DUMMY_SCHEMA' and not self.test_is_sub_schema(nc):
  532. forbidden.add(nc) # do NOT add this as a dependency.
  533. if nc in forbidden: continue # trying to resolve dependencies for.
  534. if sum([dep.prepared for dep in nc.hierarchy_dependencies]) == len(nc.hierarchy_dependencies):
  535. try:
  536. nc.bPrepare()
  537. if nc.node_type == 'DUMMY_SCHEMA':
  538. self.solve_nested_schema(nc)
  539. except Exception as e:
  540. raise execution_error_cleanup(nc, e, show_error = False)
  541. break
  542. if not nc.prepared:
  543. raise RuntimeError( f"{nc} has failed to prepare."
  544. " Please report this as a bug in mantis." )
  545. else: # Keeping this for-loop as a fallback, it should never add dependencies though
  546. can_add_me = True
  547. for dep in nc.hierarchy_dependencies:
  548. if not dep.prepared and dep not in unprepared:
  549. if dep in forbidden:
  550. can_add_me=False
  551. forbidden.add(nc) # forbid the parent, too
  552. continue
  553. unprepared.appendleft(dep)
  554. if can_add_me:
  555. unprepared.appendleft(nc) # just rotate them until they are ready.
  556. def solve_iteration(self):
  557. """ Solve an iteration of the schema.
  558. - 1 Create the Mantis Node instances that represent this iteration of the schema
  559. - 2 Connect the links from the entrypoint or previous iteration.
  560. - 3 Connect the constant and array links, and any link between nodes entirely within the tree
  561. - 4 Prepare the nodes that modify data (in case of e.g. array get index or nested schema length input)
  562. - 5 Connect the final prepared nodes
  563. and return the nodes that were created in this schema iteration (frame).
  564. This function also adds to held_links to pass data between iterations.
  565. """
  566. from .schema_nodes_ui import (SchemaIndex,
  567. SchemaArrayInput,
  568. SchemaArrayInputGet,
  569. SchemaArrayInputAll,
  570. SchemaArrayOutput,
  571. SchemaConstInput,
  572. SchemaConstOutput,
  573. SchemaOutgoingConnection,
  574. SchemaIncomingConnection,)
  575. from .utilities import clear_reroutes, link_node_containers
  576. from .base_definitions import array_output_types
  577. self.set_index_strings()
  578. frame_mantis_nodes = {}
  579. # Later we have to run bPrepare() on these guys, so we make the deque and fill it now.
  580. from collections import deque
  581. unprepared= deque()
  582. self.gen_solve_iteration_mantis_nodes(frame_mantis_nodes, unprepared)
  583. # This is where we handle node connections BETWEEN frames
  584. while(self.held_links):
  585. ui_link = self.held_links.pop()
  586. to_ui_node = ui_link.to_socket.node; from_ui_node = ui_link.from_socket.node
  587. if isinstance(to_ui_node, SchemaOutgoingConnection):
  588. self.handle_link_to_outgoing_connection_output(frame_mantis_nodes, ui_link)
  589. # Get the rerouted links from the graph. We don't really need to do this every iteration.
  590. # TODO: use profiling to determine if this is slow; if so: copy & reuse the data, refactor the pop()'s out.
  591. ui_links = clear_reroutes(list(self.tree.links))
  592. # Now we handle ui_links in the current frame, including those ui_links between Schema nodes and "real" nodes
  593. links_to_output = []
  594. array_input_get_link = []
  595. for ui_link in ui_links:
  596. to_ui_node = ui_link.to_socket.node; from_ui_node = ui_link.from_socket.node
  597. if isinstance(from_ui_node, SchemaIndex):
  598. if ui_link.from_socket.name == "Index":
  599. self.handle_link_from_index_input(self.index, frame_mantis_nodes, ui_link)
  600. elif ui_link.from_socket.name == "Schema Length":
  601. self.handle_link_from_schema_length_input(frame_mantis_nodes, ui_link)
  602. continue
  603. if isinstance(from_ui_node, SchemaIncomingConnection):
  604. if ui_link.from_socket.name in self.incoming_connections.keys():
  605. self.handle_link_from_incoming_connection_input(frame_mantis_nodes, ui_link)
  606. continue
  607. if isinstance(from_ui_node, (SchemaConstInput, NodeGroupInput)):
  608. if ui_link.from_socket.name in self.constant_in.keys():
  609. self.handle_link_from_constant_input( frame_mantis_nodes, ui_link, to_ui_node)
  610. continue
  611. if isinstance(to_ui_node, SchemaArrayInputGet):
  612. self.handle_link_to_array_input_get( frame_mantis_nodes, ui_link)
  613. continue
  614. if isinstance(from_ui_node, SchemaArrayInput):
  615. self.handle_link_from_array_input(frame_mantis_nodes, ui_link, self.index)
  616. continue
  617. if isinstance(from_ui_node, SchemaArrayInputAll):
  618. self.handle_link_from_array_input_all(frame_mantis_nodes, ui_link)
  619. continue
  620. # HOLD these links to the next iteration:
  621. if isinstance(to_ui_node, SchemaOutgoingConnection):
  622. if isinstance(from_ui_node, (MantisNodeGroup, SchemaGroup)):
  623. self.handle_link_from_subschema_to_output(frame_mantis_nodes, ui_link, to_ui_node)
  624. self.held_links.append(ui_link) # is this wise? Why am I doing this?
  625. continue
  626. # HOLD these links until prep is done a little later
  627. if isinstance(to_ui_node, (SchemaConstOutput, NodeGroupOutput)) or isinstance(to_ui_node, SchemaArrayOutput):
  628. if isinstance(from_ui_node, (MantisNodeGroup, SchemaGroup)):
  629. self.handle_link_from_subschema_to_output(frame_mantis_nodes, ui_link, to_ui_node)
  630. # both links are desirable to create, so don't continue here
  631. if from_ui_node.bl_idname in array_output_types:
  632. self.handle_link_from_subschema_to_output(frame_mantis_nodes, ui_link, to_ui_node)
  633. # this one wires links around - we need to finish connecting it to the output
  634. # before we can prepare it. Otherwise, it will send a link from *itself* instead of
  635. # rewiring one of its *inputs* to the next node.
  636. # We have to prep it, and then deal with the links between it and the array. pain.
  637. links_to_output.append(ui_link)
  638. continue
  639. if isinstance(from_ui_node, SchemaArrayInputGet):
  640. array_input_get_link.append(ui_link)
  641. continue
  642. # for any of the special cases, we hit a 'continue' block. So this connection is not special, and is made here.
  643. connection = link_node_containers(self.autogen_path_names, ui_link,
  644. frame_mantis_nodes, from_suffix=self.index_str(),
  645. to_suffix=self.index_str())
  646. for signature, node in frame_mantis_nodes.items():
  647. self.solved_nodes[signature]=node
  648. if node.node_type == "DUMMY_SCHEMA":
  649. # make sure to add the nodes to the group's sockets if the user set them directly
  650. from .readtree import make_connections_to_ng_dummy
  651. make_connections_to_ng_dummy(
  652. self.node.base_tree,
  653. self.autogen_path_names,
  654. {}, # just pass an empty dict, this argument is not needed in this context
  655. self.all_nodes,
  656. node)
  657. from .utilities import init_schema_dependencies
  658. init_schema_dependencies(node, self.all_nodes)
  659. else:
  660. init_dependencies(node) # it is hard to overstate how important this single line of code is
  661. # We have to prepare the nodes leading to Schema Length
  662. unprepared=deque()
  663. for node in frame_mantis_nodes.values():
  664. if node.node_type == 'DUMMY_SCHEMA' and (schema_len_in := node.inputs.get("Schema Length")):
  665. for l in schema_len_in.links:
  666. unprepared.append(l.from_node)
  667. self.prepare_nodes(unprepared)
  668. # We have to prepare the nodes leading to Array Input Get
  669. for ui_link in array_input_get_link:
  670. from_name = get_link_in_out(ui_link)[0]
  671. # because this both provides and receives deps, it must be solved first.
  672. from_node = self.schema_nodes.get( (*self.node.ui_signature, ui_link.from_node.bl_idname) )
  673. self.handle_link_from_array_input_get(frame_mantis_nodes, ui_link )
  674. # Finally, we have to prepare nodes leading to outputs.
  675. for i in range(len(links_to_output)):
  676. unprepared=deque()
  677. ui_link = links_to_output[i]
  678. to_ui_node = ui_link.to_socket.node; from_ui_node = ui_link.from_socket.node
  679. # ugly workaround here in a very painful edge case...
  680. if isinstance(from_ui_node, (MantisNodeGroup, SchemaGroup)) or\
  681. from_ui_node.bl_idname in array_output_types:
  682. ui_link=self.spoof_link_for_subschema_to_output_edge_case(ui_link)
  683. links_to_output[i] = ui_link
  684. from_name = get_link_in_out(ui_link)[0]
  685. signature = (*self.autogen_path_names, from_name+self.index_str())
  686. #use it directly if it is a mantis node; this happens when the previous node was a Schema
  687. if hasattr(ui_link, "from_node") and (from_node := self.schema_nodes.get( (*self.node.ui_signature, ui_link.from_node.bl_idname))):
  688. unprepared.append(from_node)
  689. unprepared.extend(from_node.hierarchy_dependencies)
  690. elif from_node := frame_mantis_nodes.get(signature):
  691. unprepared.append(from_node)
  692. unprepared.extend(from_node.hierarchy_dependencies)
  693. else:
  694. raise RuntimeError(" 671 there has been an error parsing the tree. Please report this as a bug.")
  695. self.prepare_nodes(unprepared) # prepare only the dependencies we need for this link
  696. # and handle the output by the specific type
  697. if isinstance(to_ui_node, (SchemaConstOutput, NodeGroupOutput)):
  698. self.handle_link_to_constant_output(frame_mantis_nodes, self.index, ui_link, to_ui_node)
  699. if isinstance(to_ui_node, SchemaArrayOutput):
  700. if from_node.bl_idname in array_output_types:
  701. from .base_definitions import DummyLink
  702. for l in from_node.rerouted:
  703. new_link = DummyLink(
  704. from_socket=l.from_node.outputs[l.from_socket],
  705. to_socket=l.to_node.inputs[l.to_socket],
  706. nc_from=l.from_node, nc_to=l.to_node,
  707. multi_input_sort_id=l.multi_input_sort_id
  708. )
  709. self.handle_link_from_array_type_to_array_out(ui_link, new_link)
  710. else:
  711. self.handle_link_to_array_output(frame_mantis_nodes, self.index, ui_link, to_ui_node, from_ui_node)
  712. return frame_mantis_nodes
  713. def solve_nested_schema(self, schema_nc):
  714. """ Solves all schema node groups found in this Schema. This is a recursive function, which will
  715. solve all levels of nested schema - since this function is called by solver.solve().
  716. """
  717. solver=None
  718. if schema_nc.prepared == False:
  719. all_nodes = self.all_nodes.copy()
  720. ui_node = schema_nc.prototype
  721. length = schema_nc.evaluate_input("Schema Length")
  722. tree = ui_node.node_tree
  723. if schema_nc.prototype.bl_idname == "MantisNodeGroup":
  724. prOrange(f"Expanding Node Group {tree.name} in node {schema_nc}.")
  725. else:
  726. prOrange(f"Expanding schema {tree.name} in node {schema_nc} with length {length}.")
  727. solver = SchemaSolver(schema_nc, all_nodes, ui_node, schema_nc.ui_signature, error_popups=self.error_popups)
  728. solved_nodes = solver.solve()
  729. schema_nc.prepared = True
  730. for k,v in solved_nodes.items():
  731. self.solved_nodes[k]=v
  732. return solver
  733. def finalize(self, frame_nc):
  734. from .schema_nodes_ui import (SchemaOutgoingConnection,)
  735. for i in range(len(self.held_links)):
  736. link = self.held_links.pop()
  737. to_np = link.to_socket.node; from_np = link.from_socket.node
  738. if isinstance(to_np, SchemaOutgoingConnection):
  739. if link.to_socket.name in self.outgoing_connections.keys():
  740. if (outgoing_links := self.outgoing_connections[link.to_socket.name]) is None: continue
  741. for outgoing in outgoing_links:
  742. if outgoing:
  743. to_node = outgoing.to_node
  744. from_node =frame_nc[(*self.autogen_path_names, from_np.name+self.index_str()) ]
  745. from_socket_name = link.from_socket.name
  746. if from_node.node_type in ['DUMMY_SCHEMA']:
  747. from_socket_name = link.from_socket.identifier
  748. connection = from_node.outputs[from_socket_name].connect(node=to_node, socket=outgoing.to_socket)
  749. # we need to kill the link between the Schema itself and the next node and update the deps. Otherwise:confusing bugs.
  750. outgoing.die(); init_dependencies(to_node)
  751. # else: # the node just isn't connected out this socket.
  752. # # solve all unsolved nested schemas...
  753. for schema_sig, schema_nc in self.nested_schemas.items():
  754. self.solve_nested_schema(schema_nc)
  755. for n in self.autogenerated_nodes.values():
  756. init_connections(n)
  757. for c in n.connections:
  758. init_dependencies(c)
  759. all_outgoing_links = []
  760. for conn in self.outgoing_connections.values():
  761. for outgoing in conn:
  762. all_outgoing_links.append(outgoing)
  763. for conn in self.constant_out.values():
  764. for outgoing in conn:
  765. all_outgoing_links.append(outgoing)
  766. for conn in self.array_output_connections.values():
  767. for outgoing in conn:
  768. all_outgoing_links.append(outgoing)
  769. for outgoing in all_outgoing_links:
  770. to_node = outgoing.to_node
  771. for l in to_node.inputs[outgoing.to_socket].links:
  772. if self.node == l.from_node:
  773. l.die()
  774. for inp in self.node.inputs.values():
  775. for l in inp.links:
  776. init_connections(l.from_node) # to force it to have hierarchy connections with the new nodes.
  777. def solve(self):
  778. if self.solve_length < 1:
  779. from .base_definitions import GraphError
  780. for o in self.node.outputs:
  781. if o.is_linked:
  782. raise GraphError(f"ERROR: Schema {self} has a length"
  783. " of 0 but other nodes depend on it.")
  784. print (f"WARN: Schema {self} has a length of 0 or less and will not expand.")
  785. return {} # just don't do anything - it's OK to have a noop schema if it doesn't have dependencies.
  786. for index in range(self.solve_length):
  787. self.index = index
  788. frame_mantis_nodes = self.solve_iteration()
  789. for sig, nc in frame_mantis_nodes.items():
  790. if nc.node_type == 'DUMMY_SCHEMA':
  791. self.nested_schemas[sig] = nc
  792. self.finalize(frame_mantis_nodes)
  793. self.solved = True
  794. self.node.prepared = True
  795. prGreen(f"Schema declared {len(self.solved_nodes)} nodes.\n")
  796. return self.solved_nodes