schema_solve.py 46 KB

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