internal_nodes.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. from .utilities.node_common import *
  2. from bpy.types import Node
  3. from .base_definitions import MantisNode, MantisSocketTemplate
  4. from uuid import uuid4
  5. # this function is kind of confusing and is very important,
  6. # so it bears a full explanation: its purpose is to connect
  7. # the links going into a group to the nodes in that group.
  8. # FIRST we connect all the incoming links into the Group Node to
  9. # a Group Interface node that does nothing but mark the entrance.
  10. # Then, we connect all the outgoing links back to the nodes
  11. # that had incoming links, so the nodes OUTSIDE the Node Group
  12. # are connected directly to BOTH the GroupInterface and the
  13. # nodes INSIDE the node group.
  14. # we give the GroupInterface nodes an obscenely high
  15. # multi_input_sort_id so that they are always last.
  16. # but since these links are going IN, they shouldn't cause any problems.
  17. # the sub_sort_id is set here in case there are UI links which represent
  18. # multiple Mantis links - the mantis links are sorted within the UI links
  19. # and the UI links are sorted as normal, so all the links are in the right
  20. # order.... probably. BUG here?
  21. # I want the Group Interface nodes to be part of the hierarchy...
  22. # but I want to cut the links. hmmm what to do? Fix it if it causes problems.
  23. # solution to hypothetical BUG could be to do traversal on the links
  24. # instead of the sockets.
  25. # NOTE: using NodeSocket.links is slow, it should be cached
  26. def grp_node_reroute_common(in_node, out_node, interface):
  27. from .base_definitions import links_sort_key
  28. for in_node_input in in_node.inputs:
  29. i = 0
  30. if len(in_node_input.links)>1: # sort here to ensure correct sub_sort_id
  31. in_node_input.links.sort(key=links_sort_key)
  32. while (in_node_input.links):
  33. in_link = in_node_input.links.pop()
  34. from_node = in_link.from_node; from_socket = in_link.from_socket
  35. link = from_node.outputs[from_socket].connect(
  36. interface,in_node_input.name, sort_id = 2**16, sub_sort_id=i)
  37. i += 1; in_link.die()
  38. for out_node_output in out_node.outputs:
  39. while (out_node_output.links):
  40. out_link = out_node_output.links.pop()
  41. to_node = out_link.to_node; to_socket = out_link.to_socket
  42. for j, l in enumerate(interface.inputs[out_node_output.name].links):
  43. # we are connecting the link from the ORIGINAL output to the FINAL input.
  44. link = l.from_node.outputs[l.from_socket].connect(
  45. to_node, to_socket, sort_id = out_link.multi_input_sort_id)
  46. link.sub_sort_id = j
  47. out_link.die()
  48. def reroute_links_grp(group, all_nodes):
  49. interface = all_nodes.get( ( *group.signature, "InputInterface") )
  50. if group.inputs:
  51. if group_input := all_nodes.get(( *group.signature, "NodeGroupInput")):
  52. grp_node_reroute_common(group, group_input, interface)
  53. else:
  54. raise RuntimeError("internal error: failed to enter a node group ")
  55. def reroute_links_grpout(group_output, all_nodes):
  56. if (group_output_node := all_nodes.get( ( *group_output.signature[:-1],) )):
  57. interface = all_nodes.get( ( *group_output_node.signature, "OutputInterface") )
  58. grp_node_reroute_common(group_output, group_output_node, interface)
  59. else:
  60. prOrange(f"WARN: unconnected outputs from a node group "
  61. "(maybe you are running the tree from inside a node group?)")
  62. # TODO: make node_type a class property like it is for everything else
  63. # I can't do this without making some changes to schema and anything that
  64. # checks for DUMMY SCHEMA
  65. class DummyNode(MantisNode):
  66. __slots__ = ("node_type", "ui_node", "solver", "uuid", "reroute_links_type")
  67. def __init__(self, signature, base_tree, ui_node = None, ui_signature=None):
  68. super().__init__(signature, base_tree)
  69. self.ui_node = ui_node
  70. self.prepared = True
  71. self.uuid = uuid4()
  72. self.solver = None
  73. self.node_type = 'DUMMY'
  74. self.reroute_links_type=""
  75. if ui_node:
  76. if ui_node.bl_idname in ["MantisSchemaGroup"]:
  77. self.node_type = 'DUMMY_SCHEMA'
  78. self.prepared = False
  79. for sock in ui_node.inputs:
  80. if sock.identifier == "__extend__" or sock.name == "__extend__":
  81. continue
  82. self.inputs[sock.identifier] = NodeSocket(is_input = True, name = sock.identifier, node = self)
  83. for sock in ui_node.outputs:
  84. if sock.identifier == "__extend__" or sock.name == "__extend__":
  85. continue
  86. self.outputs[sock.identifier] = NodeSocket(is_input = False, name = sock.identifier, node = self)
  87. self.parameters[sock.identifier]=None
  88. # keep track of the "natural signature" of Schema nodes - so that they are unambiguous
  89. self.ui_signature=self.signature
  90. if ui_signature:
  91. self.ui_signature=ui_signature
  92. # This is necessary for Schema to work if there are multiple Schema nodes using the same Schema tree.
  93. # this is ugly and I hate it.
  94. self.execution_prepared=True # in case it gets left behind in the tree as a dependency
  95. def reroute_links(self, all_nodes):
  96. match self.reroute_links_type:
  97. case "group":
  98. reroute_links_grp(self, all_nodes)
  99. case "out":
  100. reroute_links_grpout(self, all_nodes)
  101. class NoOpNode(MantisNode):
  102. __slots__ = ()
  103. node_type = 'UTILITY'
  104. def __init__(self, signature, base_tree):
  105. super().__init__(signature, base_tree)
  106. self.inputs['Input'] = NodeSocket(is_input=True, node=self, name='Input')
  107. self.outputs['Output'] = NodeSocket(is_input=False, node=self, name='Output')
  108. self.init_parameters()
  109. self.set_traverse([("Input", "Output")])
  110. self.prepared, self.executed = True, True
  111. self.execution_prepared=True
  112. # this node is useful for me to insert in the tree and use for debugging especially connections.
  113. from .socket_definitions import no_default_value
  114. from .execution.overlays import handle_overlay_detect, get_socket_idname_data_type, parser_handle_text
  115. from mathutils import Matrix
  116. class AutoGenNode(MantisNode):
  117. __slots__ = ()
  118. node_type = 'UTILITY'
  119. def __init__(self, signature, base_tree):
  120. super().__init__(signature, base_tree)
  121. self.prepared, self.executed = True, True
  122. self.execution_prepared=True
  123. def reset_execution(self):
  124. super().reset_execution()
  125. self.prepared, self.executed = True, True
  126. # This is a re-implementation of the fill parameters in the base class
  127. # but it is possible to streamline a few things here
  128. # so rather than add another branch in the main class I have
  129. # decided to duplicate some code. This isn't great but it's a little faster.
  130. def fill_parameters(self, ui_node=None) -> None:
  131. ui_inputs = ui_node.inputs
  132. for key in self.parameters.keys():
  133. if node_socket := ui_inputs.get(key):
  134. if node_socket.bl_idname in no_default_value: continue
  135. elif node_socket.is_linked: continue
  136. # unlike the general case, we don't need to bother with outputs at all for autogen nodes
  137. if node_socket.bl_idname == 'MatrixSocket':
  138. v = node_socket.default_value
  139. self.parameters[key] = Matrix(( tuple(v[0:4]),
  140. tuple(v[4:8]),
  141. tuple(v[8:12]),
  142. tuple(v[12:16]) ))
  143. elif (value := node_socket.default_value) is not None:
  144. if hasattr(node_socket, 'use_overlay') and node_socket.use_overlay:
  145. value = node_socket.overlay_text
  146. if get_socket_idname_data_type(node_socket.bl_idname) != str:
  147. value = parser_handle_text(value)
  148. # THIS is the most important reason I am using a custom fill here:
  149. # The overlay for this kind of node must use the identifier, not the name
  150. if isinstance(value, str) and "$" in value:
  151. value = handle_overlay_detect(self,
  152. node_socket.identifier, node_socket.bl_idname, value)
  153. self.parameters[key] = value
  154. else:
  155. raise RuntimeError(wrapRed("No value found for " + self.__repr__() + " when filling out node parameters for " + ui_node.name + "::"+node_socket.name))
  156. # The Group Interface node is responsible for gathering node connections
  157. # going in or out of the group and connecting back out the other side
  158. # this is also where caching and overlays live
  159. class GroupInterface(MantisNode):
  160. __slots__ = ("in_out", "tree_name")
  161. node_type = 'INTERFACE'
  162. def __init__(self, signature, base_tree, in_out, mContext, ui_node = None, items_tree = None, ):
  163. super().__init__(signature, base_tree)
  164. self.prepared, self.executed = True, True
  165. self.in_out = in_out
  166. if hasattr(ui_node, "node_tree"):
  167. self.tree_name = ui_node.node_tree.name
  168. else: # It is an output node
  169. self.tree_name = ui_node.id_data.name
  170. # init the sockets based on in/out, then set up traversal
  171. # the index and length are like constant inputs.
  172. if self.in_out == 'SCHEMA_INPUT':
  173. self.outputs["Schema Length"] = NodeSocket(is_input=False, node=self, name="Schema Length")
  174. if 'SCHEMA' in self.in_out:
  175. self.outputs["Index"] = NodeSocket(is_input=False, node=self, name="Index")
  176. for i, item in enumerate(items_tree):
  177. if item.item_type == 'PANEL': continue
  178. is_connection = False; is_array = False
  179. if hasattr(item, 'is_connection'): # in older files and for some types this happens
  180. is_connection = item.is_connection # BUG really every socket should be a Mantis interface type
  181. is_array = item.is_array
  182. if (self.in_out in {'INPUT', 'OUTPUT'} and item.in_out == self.in_out):
  183. source = self.inputs[item.identifier] = NodeSocket(is_input=True, node=self, name=item.identifier)
  184. target = self.outputs[item.identifier] = NodeSocket(is_input=False, node=self, name=item.identifier)
  185. self.set_traverse( [(source.name, target.name)] )
  186. elif self.in_out == 'SCHEMA_INPUT':
  187. if is_array: continue # I'll skip these for now
  188. source = self.inputs[item.identifier] = NodeSocket(is_input=True, node=self, name=item.identifier)
  189. target = self.outputs[item.identifier] = NodeSocket(is_input=False, node=self, name=item.identifier)
  190. self.set_traverse( [(source.name, target.name)] )
  191. elif self.in_out == 'SCHEMA_BETWEEN':
  192. if is_connection: # we need these at every in-between because they are modified between
  193. source = self.inputs[item.identifier] = NodeSocket(is_input=True, node=self, name=item.identifier)
  194. target = self.outputs[item.identifier] = NodeSocket(is_input=False, node=self, name=item.identifier)
  195. self.set_traverse( [(source.name, target.name)] )
  196. if self.in_out in {'INPUT', 'SCHEMA_INPUT', 'SCHEMA_BETWEEN'}:
  197. # We need to store the input interface nodes for looking up overlay variables
  198. # Important to set the mContext's interface stuff up so the rest of the tree has access to this
  199. # Why not include the name of the node? It's easier to look up based on tree path
  200. # And in order to prevent ambiguity, we make lists for each one so that schema interfaces come together
  201. if mContext.input_interface_nodes.get(self.signature[:-1], None) is None:
  202. mContext.input_interface_nodes[ self.signature[:-1] ] = [ self ]
  203. else: # it's a schema so we add the next interface to the list
  204. mContext.input_interface_nodes[ self.signature[:-1] ].append(self)
  205. self.execution_prepared=True
  206. def get_tree_interface_items(self):
  207. from bpy import data as bpy_data
  208. if tree := bpy_data.node_groups.get(self.tree_name):
  209. return tree.interface.items_tree
  210. def evaluate_input(self, input_name, index=0):
  211. # I'm hardcoding this so that the schema length overlay is available as just 'length'
  212. if input_name == 'Length': input_name = 'Schema'
  213. value = super().evaluate_input(input_name, index)
  214. # This node should cache the result for faster lookup later
  215. self.parameters[input_name] = value
  216. return value