node_container_common.py 13 KB

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