node_common.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. from bpy.app import version as bpy_version
  11. # Utility to print links nicely for end user.
  12. def print_link_list(links):
  13. ret_str = ""
  14. for link in links:
  15. ret_str+= link.__repr__() + '\n'
  16. return ret_str
  17. # I've moved this to a separate function because the trace functions
  18. # are kind of hard to understand and the cycle check breaks the flow
  19. # of the code.
  20. def detect_cycle_in_trace(link, link_circle):
  21. if link.is_hierarchy:
  22. if link in link_circle:
  23. raise GraphError( "There is a cycle in the following links:\n" +
  24. print_link_list(link_circle))
  25. link_circle.append(link)
  26. # NOTE this is a dupe of trace_single_line, and it must be used
  27. # at any time before the tree is parsed (to check for cycles)
  28. # I don't want or need to pay the performance cost to check this everywhere
  29. def trace_single_line_safe(mantis_node, input_name, link_index=0):
  30. # DO: refactor this for new link class
  31. """Traces a line to its input."""
  32. nodes = [mantis_node]
  33. # a test for cyclic connections
  34. link_circle = []
  35. # Trace a single line
  36. if (socket := mantis_node.inputs.get(input_name) ):
  37. while (socket.is_linked):
  38. link = socket.links[link_index]; link_index = 0
  39. # should throw an error if it is in the set
  40. if detect_cycle_in_trace(link, link_circle):
  41. return
  42. if (socket := link.from_node.outputs.get(link.from_socket)):
  43. nodes.append(socket.node)
  44. if socket.can_traverse:
  45. socket = socket.traverse_target
  46. else: # this is an output.
  47. break
  48. else:
  49. break
  50. return nodes, socket
  51. def trace_single_line(mantis_node, input_name, link_index=0):
  52. # DO: refactor this for new link class
  53. """Traces a line to its input."""
  54. nodes = [mantis_node]
  55. # a test for cyclic connections
  56. if (socket := mantis_node.inputs.get(input_name) ):
  57. while (socket.is_linked):
  58. link = socket.links[link_index]; link_index = 0
  59. if (socket := link.from_node.outputs.get(link.from_socket)):
  60. nodes.append(socket.node)
  61. if socket.can_traverse:
  62. socket = socket.traverse_target
  63. else: # this is an output.
  64. break
  65. else:
  66. break
  67. return nodes, socket
  68. def trace_single_line_up(mantis_node, output_name,):
  69. """I use this to get the xForm from a link node."""
  70. nodes = [mantis_node]
  71. if hasattr(mantis_node, "outputs"):
  72. # Trace a single line
  73. if (socket := mantis_node.outputs.get(output_name) ):
  74. while (socket.is_linked):
  75. # This is bad, but it's efficient for nodes that only expect
  76. # one path along the given line
  77. link = socket.links[0] # TODO: find out if this is wise.
  78. other = link.to_node.inputs.get(link.to_socket)
  79. if (other):
  80. socket = other
  81. if socket.can_traverse:
  82. socket = socket.traverse_target
  83. nodes.append(socket.node)
  84. else: # this is an input.
  85. nodes.append(socket.node)
  86. break
  87. else:
  88. break
  89. return nodes, socket
  90. def trace_line_up_branching(mantis_node : MantisNode, output_name : str,
  91. break_condition : Callable = lambda mantis_node : False):
  92. """ Returns all leaf nodes at the ends of branching lines from an output."""
  93. leaf_nodes = []
  94. if hasattr(mantis_node, "outputs"):
  95. # Trace a single line
  96. if (socket := mantis_node.outputs.get(output_name) ):
  97. check_sockets={socket}
  98. while (check_sockets):
  99. # This is bad, but it's efficient for nodes that only expect
  100. # one path along the given line
  101. socket = check_sockets.pop()
  102. for link in socket.links:
  103. other = link.to_node.inputs.get(link.to_socket)
  104. if (other):
  105. socket = other
  106. if break_condition(socket.node):
  107. leaf_nodes.append(socket.node)
  108. elif socket.is_input and socket.can_traverse:
  109. check_sockets.add(socket.traverse_target)
  110. else: # this is an input.
  111. leaf_nodes.append(socket.node)
  112. return leaf_nodes
  113. # this function exists to walk back to the first ancestor node of XFORM or LINK without
  114. # breaking the traverse behaviour which I still need for various reasons.
  115. def get_parent_xForm_info(mantis_node, socket_name = 'Relationship'):
  116. from ..mantis_dataclasses import xForm_info
  117. # we re-implement the trace logic here for performance.
  118. # because this kind of connection has traversal (for Links to find their children), we must
  119. # simply seek back to the first available xForm or Link and get its xForm info.\
  120. parent_node = None
  121. if (socket := mantis_node.inputs.get(socket_name) ):
  122. while (socket.is_linked):
  123. link = socket.links[0]
  124. if (socket := link.from_node.outputs.get(link.from_socket)):
  125. if socket.node.node_type in ['LINK', 'XFORM']:
  126. parent_node = socket.node; break
  127. if socket.can_traverse:
  128. socket = socket.traverse_target
  129. else: # this is an output.
  130. break
  131. else:
  132. break
  133. parent_xForm_info = None
  134. if parent_node:
  135. if parent_node.node_type == 'XFORM':
  136. parent_xForm_info = parent_node.parameters['xForm Out']
  137. else:
  138. if 'Output Relationship' in parent_node.parameters.keys():
  139. parent_xForm_info = parent_node.parameters['Output Relationship']
  140. else: # TODO refactor Inherit Node to have the same output as the other link nodes.
  141. parent_xForm_info = parent_node.parameters['Inheritance']
  142. if parent_xForm_info is None: parent_xForm_info = xForm_info() # default to empty
  143. return parent_xForm_info
  144. def setup_custom_property_inputs_outputs(mantis_node):
  145. from .utilities import get_ui_node
  146. if mantis_node.signature[0] == 'SCHEMA_AUTOGENERATED':
  147. from ..base_definitions import custom_props_types
  148. if mantis_node.__class__.__name__ not in custom_props_types:
  149. raise RuntimeError(wrapRed(f"Custom Properties not allowed for class {mantis_node.__class__.__name__}"))
  150. return
  151. else:
  152. ui_node = get_ui_node(mantis_node.ui_signature, mantis_node.base_tree)
  153. if ui_node:
  154. setup_custom_props_from_np(mantis_node, ui_node)
  155. else:
  156. prRed(f"Failed to setup custom properties for: {mantis_node.ui_signature}")
  157. def setup_custom_props_from_np(mantis_node, ui_node):
  158. for inp in ui_node.inputs:
  159. if inp.identifier == "__extend__": continue
  160. if not (inp.name in mantis_node.inputs.keys()) :
  161. socket = NodeSocket(is_input = True, name = inp.name, node = mantis_node,)
  162. mantis_node.inputs[inp.name] = socket
  163. mantis_node.parameters[inp.name] = None
  164. for attr_name in ["min", "max", "soft_min", "soft_max", "description"]:
  165. try:
  166. setattr(socket, attr_name, getattr(inp, attr_name))
  167. except AttributeError:
  168. pass
  169. for out in ui_node.outputs:
  170. if out.identifier == "__extend__": continue
  171. if not (out.name in mantis_node.outputs.keys()) :
  172. mantis_node.outputs[out.name] = NodeSocket(is_input = False, name = out.name, node = mantis_node,)
  173. def prepare_parameters(mantis_node):
  174. # some nodes add new parameters at runtime, e.g. Drivers
  175. # so we need to take that stuff from the mantis_nodes that have
  176. # been executed prior to this node.
  177. for s_name, sock in mantis_node.inputs.items():
  178. if not (sock.is_linked):
  179. continue
  180. if (sock.name in sock.links[0].from_node.parameters.keys()):
  181. mantis_node.parameters[s_name] = sock.links[0].from_node.parameters[sock.name]
  182. # should work, this is ugly.
  183. def check_for_driver(mantis_node, input_name, value_index = None, array_index = 0, combo_property=False):
  184. prop = mantis_node.evaluate_input(input_name, array_index)
  185. if (value_index is not None):
  186. try:
  187. prop = prop[value_index]
  188. except KeyError: # We'll try to use the driver for all three channels.
  189. pass
  190. # TODO an Index or Key error here should have a reasonable error message
  191. return (prop.__class__.__name__ == 'MantisDriver')
  192. def print_driver_item(mantis_node, b_object, original_prop):
  193. if mantis_node.node_type in ['LINK',]:
  194. printname = wrapOrange(b_object.id_data.name)
  195. elif mantis_node.node_type in ['XFORM',]:
  196. printname = wrapOrange(mantis_node.bGetObject().name)
  197. else:
  198. printname = wrapOrange(mantis_node)
  199. print("Adding driver %s to %s in %s" % (wrapPurple(original_prop), wrapWhite(mantis_node.signature[-1]), printname))
  200. # HACK This is the most hideous voodoo black magic fucntion in the entire program
  201. # but everything depends on it and it works
  202. def evaluate_sockets(mantis_node, b_object, props_sockets,):
  203. # this is neccesary because some things use dict properties for dynamic properties and setattr doesn't work
  204. def safe_setattr(ob, att_name, val):
  205. if ob.__class__.__name__ in ["NodesModifier"]:
  206. ob[att_name]=val
  207. elif b_object.__class__.__name__ in ["Key"]:
  208. if not val: val=0
  209. ob.key_blocks[att_name].value=val
  210. elif "]." in att_name:
  211. # it is of the form prop[int].prop2
  212. prop=att_name.split('[')[0]
  213. prop1=att_name.split('.')[1]
  214. get_index = int(att_name.split('[')[1][0])
  215. setattr(getattr(b_object, prop)[get_index], prop1, val)
  216. else:
  217. try:
  218. setattr(ob, att_name, val)
  219. except Exception as e:
  220. print ("ob, att_name, val")
  221. prRed(ob, att_name, val)
  222. raise e
  223. for prop, filler_item in props_sockets.items():
  224. if isinstance(filler_item, tuple):
  225. raise NotImplementedError(mantis_node)
  226. sock = filler_item.socket_name
  227. default = filler_item.default_value
  228. value_index = filler_item.value_index
  229. array_index = filler_item.array_index
  230. combo_property = filler_item.combo_property
  231. driver_key = (sock, value_index, array_index)
  232. if (check_for_driver(mantis_node, sock, value_index, array_index, combo_property)):
  233. original_prop = prop
  234. # TODO: deduplicate this terrible hack
  235. if ("." in prop) and not b_object.__class__.__name__ in ["Key"]: # this is a property of a property...
  236. sub_props = [b_object]
  237. while ("." in prop):
  238. split_prop = prop.split(".")
  239. prop = split_prop[1]
  240. sub_prop = (split_prop[0])
  241. if ("[" in sub_prop):
  242. sub_prop, sub_index = sub_prop.split("[")
  243. sub_prop_index = int(sub_index[0])
  244. sub_props.append(getattr(sub_props[-1], sub_prop)[sub_prop_index])
  245. else:
  246. sub_props.append(getattr(sub_props[-1], sub_prop))
  247. safe_setattr(sub_props[-1], prop, default)
  248. # this is really stupid
  249. else:
  250. safe_setattr(b_object, prop, default)
  251. print_driver_item( mantis_node, b_object, original_prop)
  252. if b_object.__class__.__name__ in ["NodesModifier"]:
  253. mantis_node.drivers[driver_key] = "[\""+original_prop+"\"]" # lol. It is a dict element not a "true" property
  254. elif b_object.__class__.__name__ in ["Key"]:
  255. mantis_node.drivers[driver_key] = "key_blocks[\""+original_prop+"\"].value"
  256. else:
  257. mantis_node.drivers[driver_key] = original_prop
  258. else: # here we can do error checking for the socket if needed
  259. if (value_index is not None):
  260. safe_setattr(b_object, prop, mantis_node.evaluate_input(sock)[value_index])
  261. else: # 'mute' is better than 'enabled'
  262. # UGLY HACK # because it is available in older
  263. if (prop == 'mute'): # Blenders.
  264. safe_setattr(b_object, prop, not bool(mantis_node.evaluate_input(sock)))
  265. elif (prop == 'hide'): # this will not cast it for me, annoying.
  266. safe_setattr(b_object, prop, bool(mantis_node.evaluate_input(sock)))
  267. else:
  268. try:
  269. # just wanna see if we are dealing with some collection
  270. # check hasattr in case it is one of those ["such-and-such"] props, and ignore those
  271. if hasattr(b_object, prop) and (not isinstance(getattr(b_object, prop), str)) and hasattr(getattr(b_object, prop), "__getitem__"):
  272. # prGreen("Doing the thing")
  273. for val_index, value in enumerate(mantis_node.evaluate_input(sock)):
  274. # assume this will work, both because val should have the right number of elements, and because this should be the right data type.
  275. from .drivers import MantisDriver
  276. if isinstance(value, MantisDriver):
  277. getattr(b_object,prop)[val_index] = default[val_index]
  278. print("Adding driver %s to %s in %s" % (wrapPurple(prop), wrapWhite(mantis_node.signature[-1]), mantis_node))
  279. try:
  280. mantis_node.drivers[sock].append((prop, val_index))
  281. except:
  282. mantis_node.drivers[sock] = [(prop, val_index)]
  283. else:
  284. getattr(b_object,prop)[val_index] = value
  285. else:
  286. safe_setattr(b_object, prop, mantis_node.evaluate_input(sock))
  287. except Exception as e:
  288. prRed(b_object, mantis_node, prop, sock, mantis_node.evaluate_input(sock))
  289. raise e
  290. def finish_driver(mantis_node, b_object, driver_item, prop):
  291. try:
  292. driver_sock = driver_item[0]; index = driver_item[1]; array_index =driver_item[2]
  293. except Exception as e:
  294. print (wrapGreen(mantis_node), wrapOrange(b_object), wrapRed(driver_item), wrapWhite(prop),)
  295. raise e
  296. driver_trace = trace_single_line(mantis_node, driver_sock, array_index)
  297. driver_provider, driver_socket = driver_trace[0][-1], driver_trace[1]
  298. combo_property = False
  299. # try to detect combo properties
  300. if mantis_node.socket_templates:
  301. for st in mantis_node.socket_templates:
  302. if st.name == driver_sock:
  303. if isinstance(st.blender_property, tuple):
  304. combo_property = True
  305. break
  306. if index is not None:
  307. try:
  308. driver = driver_provider.parameters[driver_socket.name][index].copy()
  309. except KeyError as e: # try single driver, it should still work fine.
  310. if combo_property:
  311. driver = driver_provider.parameters[driver_socket.name].copy()
  312. else:
  313. raise e
  314. # this is harmless and necessary for the weird ones where the property is a vector too
  315. if not combo_property:
  316. driver["ind"] = index
  317. else:
  318. driver = driver_provider.parameters[driver_socket.name].copy()
  319. if driver:
  320. socket_template = None
  321. if mantis_node.socket_templates:
  322. for socket_template in mantis_node.socket_templates:
  323. if socket_template.name == driver_sock: break
  324. if socket_template:
  325. if socket_template.is_animatable == False:
  326. raise RuntimeError(f"Driver is not allowed for {driver_sock} in node {mantis_node}")
  327. if ("." in prop) and mantis_node.__class__.__name__ != "DeformerMorphTargetDeform": # this is a property of a property...
  328. sub_props = [b_object]
  329. while ("." in prop):
  330. split_prop = prop.split(".")
  331. prop = split_prop[1]
  332. sub_prop = (split_prop[0])
  333. if ("[" in sub_prop):
  334. sub_prop, index = sub_prop.split("[")
  335. index = int(index[0])
  336. sub_props.append(getattr(sub_props[-1], sub_prop)[index])
  337. else:
  338. sub_props.append(getattr(sub_props[-1], sub_prop))
  339. driver["owner"] = sub_props[-1]
  340. elif mantis_node.node_type in ['XFORM',] and mantis_node.__class__.__name__ in ['xFormBone']:
  341. # TODO: I really shouldn't have to hardcode this. Look into better solutions.
  342. # NOTE: VERSIONING in Blender 5.0 we have to use pose bone for this, too.
  343. # default to pose bone, it's usually what we want
  344. bone_col = mantis_node.bGetParentArmature().pose.bones
  345. from ..xForm_socket_templates import attributes_shared_by_bone_and_pose_bone
  346. if socket_template.prop_owner_group == 'bone':
  347. bone_col = mantis_node.bGetParentArmature().data.bones
  348. # this is a little bit clumsy. TODO clean up here
  349. if prop in attributes_shared_by_bone_and_pose_bone:
  350. # we want to use the pose bone for this...only if it has a driver
  351. bone_col = mantis_node.bGetParentArmature().pose.bones
  352. driver["owner"] = bone_col[b_object] # we use "unsafe" brackets instead of get() because we want to see any errors that occur
  353. # HACK having special cases here is indicitave of a deeper problem that should be refactored
  354. elif mantis_node.__class__.__name__ in ['xFormCurvePin'] and \
  355. prop in ['offset_factor', 'forward_axis', 'up_axis']:
  356. driver["owner"] = b_object.constraints['Curve Pin']
  357. else:
  358. driver["owner"] = b_object
  359. driver["prop"] = prop
  360. return driver
  361. else:
  362. prOrange("Provider", driver_provider)
  363. prGreen("socket", driver_socket)
  364. print (index)
  365. prPurple(driver_provider.parameters[driver_socket.name])
  366. prRed("Failed to create driver for %s" % prop)
  367. return None
  368. def finish_drivers(mantis_node):
  369. drivers = []
  370. if not hasattr(mantis_node, "drivers"):
  371. return # HACK
  372. for driver_item, prop in mantis_node.drivers.items():
  373. b_objects = [mantis_node.bObject]
  374. if mantis_node.node_type == 'LINK':
  375. b_objects = mantis_node.bObject # this is already a list
  376. for b_object in b_objects:
  377. # Mutating the driver_item here is the WORST THING I HAVE EVER SEEN
  378. # HACK UGLY BUG TERRIBLE BAD CODE
  379. if isinstance(prop, list):
  380. for sub_item in prop:
  381. drivers.append(finish_driver(mantis_node, b_object, (driver_item, sub_item[1], 0), sub_item[0]))
  382. else:
  383. drivers.append(finish_driver(mantis_node, b_object, (driver_item, sub_item[1], 0), sub_item[0]))
  384. else:
  385. drivers.append(finish_driver(mantis_node, b_object, driver_item, prop))
  386. from .drivers import CreateDrivers
  387. CreateDrivers(drivers)