node_container_common.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. from .utilities import (prRed, prGreen, prPurple, prWhite,
  2. prOrange,
  3. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  4. wrapOrange,)
  5. from .base_definitions import GraphError, NodeSocket, MantisNode
  6. from collections.abc import Callable
  7. # BE VERY CAREFUL
  8. # the x_containers files import * from this file
  9. # so all the top-level imports are carried over
  10. #TODO: refactor the socket definitions so this becomes unnecessary.
  11. def get_socket_value(node_socket):
  12. value = None
  13. if hasattr(node_socket, "default_value"):
  14. value = node_socket.default_value
  15. if node_socket.bl_idname == 'MatrixSocket':
  16. value = node_socket.TellValue()
  17. return value
  18. # TODO: modify this to work with multi-input nodes
  19. def trace_single_line(node_container, input_name, link_index=0):
  20. """Traces a line to its input."""
  21. nodes = [node_container]
  22. # Trace a single line
  23. if (socket := node_container.inputs.get(input_name) ):
  24. while (socket.is_linked):
  25. link = socket.links[link_index]; link_index = 0
  26. if (socket := link.from_node.outputs.get(link.from_socket)):
  27. nodes.append(socket.node)
  28. if socket.can_traverse:
  29. socket = socket.traverse_target
  30. else: # this is an output.
  31. break
  32. else:
  33. break
  34. return nodes, socket
  35. # this is same as the other, just flip from/to and in/out
  36. def trace_single_line_up(node_container, output_name,):
  37. """I use this to get the xForm from a link node."""
  38. nodes = [node_container]
  39. if hasattr(node_container, "outputs"):
  40. # Trace a single line
  41. if (socket := node_container.outputs.get(output_name) ):
  42. while (socket.is_linked):
  43. # This is bad, but it's efficient for nodes that only expect
  44. # one path along the given line
  45. link = socket.links[0] # TODO: find out if this is wise.
  46. other = link.to_node.inputs.get(link.to_socket)
  47. if (other):
  48. socket = other
  49. if socket.can_traverse:
  50. socket = socket.traverse_target
  51. nodes.append(socket.node)
  52. else: # this is an input.
  53. nodes.append(socket.node)
  54. break
  55. else:
  56. break
  57. return nodes, socket
  58. def trace_line_up_branching(node : MantisNode, output_name : str,
  59. break_condition : Callable = lambda node : False):
  60. """ Returns all leaf nodes at the ends of branching lines from an output."""
  61. leaf_nodes = []
  62. if hasattr(node, "outputs"):
  63. # Trace a single line
  64. if (socket := node.outputs.get(output_name) ):
  65. check_sockets={socket}
  66. while (check_sockets):
  67. # This is bad, but it's efficient for nodes that only expect
  68. # one path along the given line
  69. socket = check_sockets.pop()
  70. for link in socket.links:
  71. other = link.to_node.inputs.get(link.to_socket)
  72. if (other):
  73. socket = other
  74. if break_condition(socket.node):
  75. leaf_nodes.append(socket.node)
  76. elif socket.is_input and socket.can_traverse:
  77. check_sockets.add(socket.traverse_target)
  78. else: # this is an input.
  79. leaf_nodes.append(socket.node)
  80. return leaf_nodes
  81. def setup_custom_props(nc):
  82. from .utilities import get_node_prototype
  83. if nc.signature[0] == 'SCHEMA_AUTOGENERATED':
  84. from .base_definitions import custom_props_types
  85. if nc.__class__.__name__ not in custom_props_types:
  86. # prRed(f"Reminder: figure out how to deal with custom property setting for Schema Node {nc}")
  87. raise RuntimeError(wrapRed(f"Custom Properties not set up for node {nc}"))
  88. return
  89. else:
  90. np = get_node_prototype(nc.signature, nc.base_tree)
  91. if np:
  92. setup_custom_props_from_np(nc, np)
  93. else:
  94. prRed("Failed to setup custom properties for: nc")
  95. def setup_custom_props_from_np(nc, np):
  96. for inp in np.inputs:
  97. if inp.identifier == "__extend__": continue
  98. if not (inp.name in nc.inputs.keys()) :
  99. socket = NodeSocket(is_input = True, name = inp.name, node = nc,)
  100. nc.inputs[inp.name] = socket
  101. nc.parameters[inp.name] = None
  102. for attr_name in ["min", "max", "soft_min", "soft_max", "description"]:
  103. try:
  104. setattr(socket, attr_name, getattr(inp, attr_name))
  105. except AttributeError:
  106. pass
  107. for out in np.outputs:
  108. if out.identifier == "__extend__": continue
  109. if not (out.name in nc.outputs.keys()) :
  110. nc.outputs[out.name] = NodeSocket(is_input = False, name = out.name, node = nc,)
  111. def prepare_parameters(nc):
  112. # some nodes add new parameters at runtime, e.g. Drivers
  113. # so we need to take that stuff from the node_containers that have
  114. # been executed prior to this node.
  115. for s_name, sock in nc.inputs.items():
  116. if not (sock.is_linked):
  117. continue
  118. if (sock.name in sock.links[0].from_node.parameters.keys()):
  119. nc.parameters[s_name] = sock.links[0].from_node.parameters[sock.name]
  120. # should work, this is ugly.
  121. def check_for_driver(node_container, input_name, index = None):
  122. prop = node_container.evaluate_input(input_name)
  123. if (index is not None):
  124. prop = prop[index]
  125. return (prop.__class__.__name__ == 'MantisDriver')
  126. # TODO: this should handle sub-properties better
  127. def evaluate_sockets(nc, b_object, props_sockets,):
  128. # this is neccesary because some things use dict properties for dynamic properties and setattr doesn't work
  129. def safe_setattr(ob, att_name, val):
  130. if ob.__class__.__name__ in ["NodesModifier"]:
  131. ob[att_name]=val
  132. elif b_object.__class__.__name__ in ["Key"]:
  133. if not val: val=0
  134. ob.key_blocks[att_name].value=val
  135. elif "]." in att_name:
  136. # it is of the form prop[int].prop2
  137. prop=att_name.split('[')[0]
  138. prop1=att_name.split('.')[1]
  139. index = int(att_name.split('[')[1][0])
  140. setattr(getattr(b_object, prop)[index], prop1, val)
  141. else:
  142. try:
  143. setattr(ob, att_name, val)
  144. except Exception as e:
  145. prRed(ob, att_name, val); raise e
  146. for prop, (sock, default) in props_sockets.items():
  147. # annoyingly, sometimes the socket is an array
  148. index = None
  149. if isinstance(sock, tuple):
  150. index = sock[1]; sock = sock[0]
  151. if (check_for_driver(nc, sock, index)):
  152. sock = (sock, index)
  153. original_prop = prop
  154. # TODO: deduplicate this terrible hack
  155. if ("." in prop) and not b_object.__class__.__name__ in ["Key"]: # this is a property of a property...
  156. sub_props = [b_object]
  157. while ("." in prop):
  158. split_prop = prop.split(".")
  159. prop = split_prop[1]
  160. sub_prop = (split_prop[0])
  161. if ("[" in sub_prop):
  162. sub_prop, index = sub_prop.split("[")
  163. index = int(index[0])
  164. sub_props.append(getattr(sub_props[-1], sub_prop)[index])
  165. else:
  166. sub_props.append(getattr(sub_props[-1], sub_prop))
  167. safe_setattr(sub_props[-1], prop, default)
  168. # this is really stupid
  169. else:
  170. safe_setattr(b_object, prop, default)
  171. if nc.node_type in ['LINK',]:
  172. printname = wrapOrange(b_object.id_data.name)
  173. elif nc.node_type in ['XFORM',]:
  174. printname = wrapOrange(nc.bGetObject().name)
  175. else:
  176. printname = wrapOrange(nc)
  177. print("Adding driver %s to %s in %s" % (wrapPurple(original_prop), wrapWhite(nc.signature[-1]), printname))
  178. if b_object.__class__.__name__ in ["NodesModifier"]:
  179. nc.drivers[sock] = "[\""+original_prop+"\"]" # lol. It is a dict element not a "true" property
  180. elif b_object.__class__.__name__ in ["Key"]:
  181. nc.drivers[sock] = "key_blocks[\""+original_prop+"\"].value"
  182. else:
  183. nc.drivers[sock] = original_prop
  184. else: # here we can do error checking for the socket if needed
  185. if (index is not None):
  186. safe_setattr(b_object, prop, nc.evaluate_input(sock)[index])
  187. else: # 'mute' is better than 'enabled'
  188. # UGLY HACK # because it is available in older
  189. if (prop == 'mute'): # Blenders.
  190. safe_setattr(b_object, prop, not bool(nc.evaluate_input(sock)))
  191. elif (prop == 'hide'): # this will not cast it for me, annoying.
  192. safe_setattr(b_object, prop, bool(nc.evaluate_input(sock)))
  193. else:
  194. try:
  195. # prRed(b_object.name, nc, prop, nc.evaluate_input(sock) )
  196. # print( nc.evaluate_input(sock))
  197. # value_eval = nc.evaluate_input(sock)
  198. # just wanna see if we are dealing with some collection
  199. # check hasattr in case it is one of those ["such-and-such"] props, and ignore those
  200. if hasattr(b_object, prop) and (not isinstance(getattr(b_object, prop), str)) and hasattr(getattr(b_object, prop), "__getitem__"):
  201. # prGreen("Doing the thing")
  202. for val_index, value in enumerate(nc.evaluate_input(sock)):
  203. # assume this will work, both because val should have the right number of elements, and because this should be the right data type.
  204. from .drivers import MantisDriver
  205. if isinstance(value, MantisDriver):
  206. getattr(b_object,prop)[val_index] = default[val_index]
  207. print("Adding driver %s to %s in %s" % (wrapPurple(prop), wrapWhite(nc.signature[-1]), nc))
  208. try:
  209. nc.drivers[sock].append((prop, val_index))
  210. except:
  211. nc.drivers[sock] = [(prop, val_index)]
  212. else:
  213. getattr(b_object,prop)[val_index] = value
  214. else:
  215. # prOrange("Skipping the Thing", getattr(b_object, prop))
  216. safe_setattr(b_object, prop, nc.evaluate_input(sock))
  217. except Exception as e:
  218. prRed(b_object, nc, prop, sock, nc.evaluate_input(sock))
  219. raise e
  220. def finish_driver(nc, b_object, driver_item, prop):
  221. # prWhite(nc, prop)
  222. index = driver_item[1]; driver_sock = driver_item[0]
  223. node_line, last_socket = trace_single_line(nc, driver_sock)
  224. driver_provider, driver_socket = node_line[-1], last_socket
  225. if index is not None:
  226. driver = driver_provider.parameters[driver_socket.name][index].copy()
  227. # this is harmless and necessary for the weird ones where the property is a vector too
  228. driver["ind"] = index
  229. else:
  230. driver = driver_provider.parameters[driver_socket.name].copy()
  231. if driver:
  232. if ("." in prop) and nc.__class__.__name__ != "DeformerMorphTargetDeform": # this is a property of a property...
  233. sub_props = [b_object]
  234. while ("." in prop):
  235. split_prop = prop.split(".")
  236. prop = split_prop[1]
  237. sub_prop = (split_prop[0])
  238. if ("[" in sub_prop):
  239. sub_prop, index = sub_prop.split("[")
  240. index = int(index[0])
  241. sub_props.append(getattr(sub_props[-1], sub_prop)[index])
  242. else:
  243. sub_props.append(getattr(sub_props[-1], sub_prop))
  244. driver["owner"] = sub_props[-1]
  245. elif nc.node_type in ['XFORM',] and nc.__class__.__name__ in ['xFormBone']:
  246. # TODO: I really shouldn't have to hardcode this. Look into better solutions.
  247. if prop in ['hide', 'show_wire']: # we need to get the bone, not the pose bone.
  248. bone_col = nc.bGetParentArmature().data.bones
  249. else:
  250. bone_col = nc.bGetParentArmature().pose.bones
  251. driver["owner"] = bone_col[b_object] # we use "unsafe" brackets instead of get() because we want to see any errors that occur
  252. # HACK having special cases here is indicitave of a deeper problem that should be refactored
  253. elif nc.__class__.__name__ in ['xFormCurvePin'] and \
  254. prop in ['offset_factor', 'forward_axis', 'up_axis']:
  255. driver["owner"] = b_object.constraints['Curve Pin']
  256. else:
  257. driver["owner"] = b_object
  258. driver["prop"] = prop
  259. return driver
  260. else:
  261. prOrange("Provider", driver_provider)
  262. prGreen("socket", driver_socket)
  263. print (index)
  264. prPurple(driver_provider.parameters[driver_socket.name])
  265. prRed("Failed to create driver for %s" % prop)
  266. return None
  267. def finish_drivers(nc):
  268. drivers = []
  269. if not hasattr(nc, "drivers"):
  270. return # HACK
  271. for driver_item, prop in nc.drivers.items():
  272. b_objects = [nc.bObject]
  273. if nc.node_type == 'LINK':
  274. b_objects = nc.bObject # this is already a list
  275. for b_object in b_objects:
  276. if isinstance(prop, list):
  277. for sub_item in prop:
  278. drivers.append(finish_driver(nc, b_object, (driver_item, sub_item[1]), sub_item[0]))
  279. else:
  280. drivers.append(finish_driver(nc, b_object, (driver_item, sub_item[1]), sub_item[0]))
  281. else:
  282. drivers.append(finish_driver(nc, b_object, driver_item, prop))
  283. from .drivers import CreateDrivers
  284. CreateDrivers(drivers)