schema_solve.py 43 KB

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