overlays.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. from ..utilities.utilities import (prRed, prGreen, prPurple, prWhite,
  2. prOrange,
  3. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  4. wrapOrange,)
  5. from ..base_definitions import OverlayApplyError
  6. # For now, this is not yet implemented. lol
  7. def parser_handle_text(text):
  8. return '$' + text
  9. def get_socket_idname_data_type(socket_idname):
  10. data_type = str
  11. match socket_idname:
  12. case "IntSocket" | "UnsignedIntSocket":
  13. data_type = int
  14. case "FloatSocket" | "FloatPositiveSocket" | "FloatFactorSocket" | "FloatAngleSocket":
  15. data_type = float
  16. return (data_type)
  17. # If a $ character is in a value, it is an overlay request
  18. # in the root tree, supply it immediately, otherwise tag this node
  19. # once we finish pulling data from the tree we handle the overlay.
  20. def handle_overlay_detect(node, socket_id, socket_idname, value) -> str:
  21. mContext = node.mContext
  22. if node.signature[0] is None and len(node.signature) == 2:
  23. value = fill_root_tree_overlays(mContext, socket_idname, value)
  24. else: # since it is not root, we have to tag it.
  25. mContext.tagged_for_overlay.append((node.signature, socket_id))
  26. return value
  27. # The root tree doesn't have any interfaces to look up so we can fill it immediately
  28. def fill_root_tree_overlays(mContext, socket_idname, value):
  29. root_tree = mContext.base_tree
  30. root_items_tree = root_tree.interface.items_tree
  31. socket_data_type = get_socket_idname_data_type(socket_idname)
  32. for key, interface_item in root_items_tree.items():
  33. if interface_item.item_type != "SOCKET": continue
  34. if interface_item.in_out != "INPUT": continue
  35. # then what the interface provides is determined by its idname in turn
  36. match interface_item.bl_socket_idname:
  37. case "IntSocket" | "BooleanSocket":
  38. if socket_data_type in {int, float} and '$'+key == value:
  39. # TODO this is the wrong way to do this, replace this with parser later
  40. value = socket_data_type(interface_item.default_int)
  41. case "FloatSocket":
  42. if socket_data_type in {int, float} and '$'+key == value:
  43. value = socket_data_type(interface_item.default_float)
  44. case "StringSocket" | 'BoneCollectionSocket':
  45. if socket_data_type == str:
  46. value = socket_data_type(value.replace("$"+key, interface_item.default_string))
  47. return value
  48. STRING_PADDING = 4
  49. overlay_valid_socket_types = [
  50. "FloatSocket", "FloatPositiveSocket", "FloatFactorSocket",
  51. "FloatAngleSocket", "UnsignedIntSocket", "IntSocket", "StringSocket",
  52. ]
  53. # Do not use these input names as overlay keys:
  54. forbidden_key_names = ["",]
  55. forbidden_in_key_name = ['$',]
  56. def node_scan_overlays(node, socket_id,):
  57. from ..misc_nodes import SimpleInputNode
  58. from ..internal_nodes import AutoGenNode
  59. from ..utilities.utilities import get_ui_node
  60. from ..utilities.node_common import GraphError
  61. interface_nodes = node.mContext.interface_nodes
  62. if not isinstance(node, AutoGenNode):
  63. ui_node = get_ui_node(node.ui_signature, node.base_tree)
  64. # we'll assume that the overlay tag system checked if this is linked.
  65. # TODO this is probably redundant with the check above this
  66. # First let's check if it is a simple input node, by checking outputs that are marked "input"
  67. for socket in ui_node.outputs:
  68. # weird edge case for simple input nodes with unnamed sockets
  69. # the socket.identifier is not used by Mantis but it defaults to 'socket'\
  70. if socket.identifier == socket_id and socket.input == True: break
  71. else:
  72. for socket in ui_node.inputs:
  73. if socket.identifier == socket_id: break
  74. else:
  75. raise KeyError(f"Socket not found by ID {socket_id} in node {node.ui_signature}\n"
  76. f"Candidates: {[socket.identifier for socket in ui_node.inputs]}")
  77. value = socket.default_value # get the ACTUAL UI value
  78. if hasattr(socket, 'overlay_text'):
  79. value = socket.overlay_text
  80. if get_socket_idname_data_type(socket.bl_idname) != str:
  81. value = parser_handle_text(value)
  82. else: # since it doesn't have a UI node
  83. value = node.parameters[socket_id]
  84. overlay_data_type = str
  85. if isinstance(node, (AutoGenNode) ):
  86. overlay_data_type = type(node.parameters[list(node.outputs.values())[0].name])
  87. else: # we have the UI socket
  88. overlay_data_type = get_socket_idname_data_type(socket.bl_idname)
  89. if not isinstance(value, str): return
  90. # First step: get the interface nodes and the overlay keys
  91. # this should only check interfaces that are ancestors of this node
  92. my_interfaces = []
  93. for index in range(len(node.signature)-1):
  94. if index == 0: continue # root
  95. # we add one here because the node inside the schema references the schema's interface...
  96. current_schema_interface_index = node.generated_at_schema_index[index+1]
  97. if current_schema_interface_index < 0: # this indicates that it is not in a schema
  98. interface = interface_nodes.get(
  99. interface_signature := (None, *node.signature[1:index+1], "InputInterface"))
  100. else: # First we get the interface that enters the schema (index 0)
  101. interface = interface_nodes.get(
  102. interface_signature := (None, *node.signature[1:index+1],
  103. "InputInterface."+str( 0 ).zfill(4)))
  104. if interface and interface not in my_interfaces: my_interfaces.append(interface)
  105. if current_schema_interface_index == 0: continue # just did it
  106. # we need to get the schema of the current index
  107. interface = interface_nodes.get(
  108. interface_signature := (None, *node.signature[1:index+1],
  109. "InputInterface."+str(current_schema_interface_index).zfill(4)))
  110. if interface:
  111. my_interfaces.append( interface )
  112. # the my_interfaces list is sorted in REVERSE order of importance
  113. # Next, get all the overlay providers.
  114. name_to_id_map = {}
  115. name_to_type_map = {} # Just for printing reasonable error messages
  116. overlay_keys = set()
  117. root_overlay_values = {}
  118. # First, we'll get the base tree's default inputs
  119. for interface_item in node.mContext.base_tree.interface.items_tree:
  120. if interface_item.item_type != "SOCKET": continue
  121. if interface_item.in_out != "INPUT": continue
  122. base_value=None
  123. match interface_item.bl_socket_idname:
  124. case "IntSocket" | "BooleanSocket":
  125. # TODO parser for number types
  126. base_value = interface_item.default_int
  127. case "FloatSocket":
  128. base_value = interface_item.default_float
  129. case "StringSocket" | "BoneCollectionSocket":
  130. base_value = interface_item.default_string
  131. if base_value:
  132. root_overlay_values[interface_item.name] = base_value
  133. overlay_keys.add(interface_item.name)
  134. name_to_id_map[interface_item.name] = None # don't worry about it
  135. name_to_type_map[interface_item.name] = interface_item.bl_socket_idname
  136. # BUG? should this be my_interfaces ? why bother with interfaces this may not be a part of?
  137. for interface_node in interface_nodes.values():
  138. # problem: the interface node stores socket identifiers as keys
  139. # so in reality we need to get the group UI node and ask for its input names
  140. # if there is a duplicate name, too bad!
  141. group_ui_node = get_ui_node(interface_node.ui_signature[:-1], node.base_tree)
  142. for interface_item in group_ui_node.node_tree.interface.items_tree:
  143. if interface_item.item_type != 'SOCKET': continue
  144. if interface_item.in_out != 'INPUT': continue
  145. if interface_item.name in forbidden_key_names: continue
  146. for substr in forbidden_in_key_name:
  147. if substr in interface_item.name:
  148. break
  149. else: # if we do not find a bad substr
  150. name_to_id_map[interface_item.name]=interface_item.identifier
  151. name_to_type_map[interface_item.name] = interface_item.bl_socket_idname
  152. overlay_keys.add(interface_item.name)
  153. # For schema interfaces, we also need to get the length and index.
  154. if 'Index' in interface_node.outputs:
  155. overlay_keys.add('Index'); overlay_keys.add('Length')
  156. if 'Index' in overlay_keys:
  157. name_to_id_map['Index']='Index'
  158. name_to_type_map['Index']= "IntSocket"
  159. name_to_id_map['Length']='Length'
  160. name_to_type_map['Length']= "IntSocket"
  161. # sort by reverse length so we find "CatsAndFrogs" before "Cats"
  162. overlay_keys = sorted(overlay_keys, key= lambda a :-1*len(a))
  163. # First I need to break it into substrings based on quotation marks
  164. from ..utilities.utilities import split_quoted_substrings_to_strings
  165. quoted_substrings = split_quoted_substrings_to_strings(value)
  166. overlay_tries = []
  167. for quoted_substring in quoted_substrings:
  168. overlay_tries.extend(quoted_substring.split("$"))
  169. if overlay_data_type == str:
  170. result = overlay_tries[0] # the 0th element is always before the split character
  171. else: # TODO HACK later use the parser feature
  172. result = 0
  173. # the reason for the difference between overlay_try and key is because
  174. # we don't actually know if the $text part has a key in it
  175. for overlay_try in overlay_tries[1:]:
  176. if not overlay_try: continue # some of these are empty
  177. overlay_resolved_value = "$" + overlay_try
  178. for key in overlay_keys:
  179. if key in overlay_try:
  180. overlay_resolved_value = "$" + key
  181. for interface in reversed(my_interfaces): # since this is reversed when we build it
  182. actual_key = name_to_id_map.get(key)
  183. socket = interface.inputs.get(actual_key)
  184. if key in ['Index', 'Length']:
  185. socket = interface.outputs.get(actual_key)
  186. if socket:
  187. overlay_value = None
  188. try:
  189. overlay_value = interface.evaluate_input(actual_key)
  190. except KeyError:
  191. if (socket_type := name_to_type_map.get(key) or 'NOT FOUND') in overlay_valid_socket_types:
  192. raise GraphError(f"Error: Variable {key} is not supported because it has "
  193. f"an invalid input in the node group: {interface.signature[:-1]}.")
  194. raise GraphError( f"Error: Variable {key} is not supported because it is "
  195. f"type {socket_type}" )
  196. # NOTE that the above can also be caused by any BUG occuring in node group update
  197. # because it causes the interface to be invalid for the UI node that spawns the interface node.
  198. if overlay_data_type == str:
  199. if isinstance(overlay_value, (float, int)):
  200. overlay_value = str(overlay_value).zfill(STRING_PADDING)
  201. assert (isinstance(overlay_value, str)), f"Error: Variable {key} is not supported because it is type {type(overlay_value)}"
  202. overlay_resolved_value = overlay_try.replace(key, overlay_value)
  203. else:
  204. overlay_resolved_value = overlay_value
  205. break
  206. else: # we'll try the base tree
  207. if base_tree_result := root_overlay_values.get(key):
  208. if overlay_data_type == str and not isinstance(base_tree_result, str):
  209. base_tree_result = str(base_tree_result).zfill(STRING_PADDING)
  210. overlay_resolved_value = base_tree_result
  211. else:
  212. prOrange(f"WARN: no overlay value applied for {node.ui_signature} for key {key}")
  213. break # we found the key and are done here. One found Key per overlay-try
  214. # this is where we can catch the errors if the type of the resolved value was wrong
  215. if type(overlay_resolved_value) != overlay_data_type:
  216. raise OverlayApplyError( f"Could not apply overlay variable to {node}::{socket_id}.")
  217. result += overlay_resolved_value
  218. # Simple Input sockets with unnamed sockets assign this ID automatically
  219. # But Mantis uses the name instead. Usually the name and ID are the same.
  220. if socket_id == 'socket' and ui_node.outputs[0].name == "":
  221. socket_id = ''
  222. node.parameters[socket_id] = result
  223. return result # because sometimes I need to get the result, too