schema_solve.py 36 KB

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