xForm_nodes.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. from .utilities.node_common import *
  2. from .base_definitions import MantisNode, NodeSocket
  3. from .xForm_socket_templates import *
  4. from .mantis_dataclasses import xForm_info
  5. def TellClasses():
  6. return [
  7. # xForm
  8. xFormArmature,
  9. xFormBone,
  10. xFormGeometryObject,
  11. xFormObjectInstance,
  12. xFormCurvePin,
  13. xFormGetBone,
  14. ]
  15. #*#-------------------------------#++#-------------------------------#*#
  16. # X - F O R M N O D E S
  17. #*#-------------------------------#++#-------------------------------#*#
  18. def reset_object_data(ob):
  19. # moving this to a common function so I can figure out the details later
  20. ob.id_properties_clear() # we must remove the custom properties so we can make them again.
  21. ob.constraints.clear()
  22. ob.animation_data_clear() # this is a little dangerous. TODO find a better solution since this can wipe animation the user wants to keep
  23. ob.modifiers.clear() # I would also like a way to copy modifiers and their settings, or bake them down. oh well
  24. def get_parent_node(mantis_node, type = 'XFORM'):
  25. # type variable for selecting whether to get either
  26. # the parent xForm or the inheritance node
  27. node_line, _last_socket = trace_single_line(mantis_node, "Relationship")
  28. for i in range(len(node_line)):
  29. # check each of the possible parent types.
  30. if ( (node_line[ i ].__class__.__name__ == 'LinkInherit') ):
  31. try: # it's the next one
  32. if (type == 'XFORM'):
  33. return node_line[ i + 1 ]
  34. else: # type = 'LINK'
  35. return node_line[ i ]
  36. except IndexError: # if there is no next one...
  37. return None # then there's no parent!
  38. return None
  39. def get_matrix(node):
  40. matrix = node.evaluate_input('Matrix')
  41. if matrix is None:
  42. node_line, socket = trace_single_line(node, "Matrix")
  43. raise RuntimeError(wrapRed(f"No matrix found for Armature {node}"))
  44. return matrix
  45. def set_object_parent(node):
  46. from bpy import data
  47. parent_xForm_info = get_parent_xForm_info(node)
  48. if parent_xForm_info.object_type == '':
  49. return # no parent
  50. elif parent_xForm_info.object_type in ['armature', 'object']:
  51. parent = data.objects.get(parent_xForm_info.self_edit_name)
  52. if parent_xForm_info.parent_edit_name and parent is None:
  53. raise GraphError(f"Could not get parent object for node {node}.")
  54. node.bGetObject().parent = parent
  55. else: # it is a bone
  56. armOb = data.objects.get(parent_xForm_info.root_armature)
  57. node_ob = node.bGetObject()
  58. node_ob.parent = armOb; node_ob.parent_type = 'BONE'
  59. # this one expects a string.
  60. node_ob.parent_bone = parent_xForm_info.self_edit_name
  61. class xFormNode(MantisNode):
  62. __slots__ = ()
  63. node_type = 'XFORM'
  64. def __init__(self, signature, base_tree, socket_templates=[]):
  65. super().__init__(signature, base_tree, socket_templates)
  66. self.bObject=None
  67. # because new objects are created during prep phase
  68. def reset_execution(self):
  69. super().reset_execution()
  70. self.prepared=False
  71. def check_drivers(self):
  72. for st in self.socket_templates:
  73. try:
  74. if st.is_animatable == False:
  75. socket = st.name
  76. multi = st.use_multi_input
  77. vector = isinstance(st.default_value, tuple)
  78. # if single property
  79. if not multi and not vector:
  80. has_driver = check_for_driver(self, socket)
  81. elif not multi and vector:
  82. for i in range(len(st.default_value)):
  83. has_driver = check_for_driver(self, socket, i)
  84. if has_driver: break
  85. elif multi:
  86. # TODO: this is a HACK, try and understand this later
  87. if socket == 'Custom Properties':
  88. has_driver = check_for_driver(self, socket,)
  89. else:
  90. for i in range(len(self.inputs[socket].links)):
  91. has_driver = check_for_driver(self, socket, 0, i)
  92. if has_driver: break
  93. if has_driver:
  94. raise GraphError(f"Error: Socket \"{socket}\" is not animatable and cannot be driven.")
  95. except Exception as e:
  96. # This isn't really an error and the user should not see it.
  97. from .__init__ import DOERROR
  98. if DOERROR:
  99. raise e
  100. def setup_custom_props(self, ob, input):
  101. from .mantis_dataclasses import custom_prop_template
  102. # detect custom inputs
  103. for i, l in enumerate(self.inputs[input].links):
  104. # we need to trace back all inputs
  105. custom_prop_data = self.evaluate_input(input, i)
  106. if not isinstance(custom_prop_data, custom_prop_template): continue
  107. from .utilities.drivers import MantisDriver
  108. name = custom_prop_data.name
  109. if name in ob.keys():
  110. raise RuntimeError("Error: cannot create a custom property with "
  111. "the same name as an existing property.")
  112. prop_type = custom_prop_data.prop_type
  113. match prop_type:
  114. case 'BOOL':
  115. value = custom_prop_data.default_value_bool
  116. case 'INT':
  117. value = custom_prop_data.default_value_int
  118. case 'FLOAT':
  119. value = custom_prop_data.default_value_float
  120. case 'VECTOR':
  121. value = custom_prop_data.default_value_vector
  122. case 'STRING':
  123. value = custom_prop_data.default_value_string
  124. if (value is None):
  125. raise RuntimeError("Could not set value of custom parameter")
  126. # it creates a more confusing error later sometimes, better to catch it here.
  127. ob[name] = value
  128. ui_data = ob.id_properties_ui(name)
  129. ui_data.update(
  130. default=value,
  131. description=custom_prop_data.description)
  132. #if a number, set the min/max values. it may overflow on the C side
  133. if type(value) in [float, int]:
  134. for prop_name in ['min', 'max', 'soft_min', 'soft_max', ]:
  135. prop_value = getattr(custom_prop_data, prop_name)
  136. if type(value) == int: prop_value = int(prop_value)
  137. # DO: figure out the right way to prevent an oveflow
  138. try: # we have to do this as a keyword argument like this
  139. ui_data.update( **{prop_name:prop_value} )
  140. except OverflowError: #this occurs when the value is inf
  141. prRed(f"invalid value {prop_value} for custom prop {prop_name}"
  142. f" of type {type(value)} in {self}. It will remain unset.")
  143. ob.property_overridable_library_set(f"[\"{name}\"]", True)
  144. pass
  145. # TODO this should use the socket templates / prop_sockets system!
  146. class xFormArmature(xFormNode):
  147. '''A node representing an armature object'''
  148. __slots__ = ()
  149. def __init__(self, signature, base_tree):
  150. super().__init__(signature, base_tree, xFormArmatureSockets)
  151. self.init_parameters()
  152. self.set_traverse([("Relationship", "xForm Out")])
  153. setup_custom_property_inputs_outputs(self)
  154. def bPrepare(self, bContext=None):
  155. self.parameters['Matrix'] = get_matrix(self)
  156. self.prepared = True
  157. def bTransformPass(self, bContext = None,):
  158. # from .utilities import get_ui_node
  159. import bpy
  160. if (not isinstance(bContext, bpy.types.Context)):
  161. raise RuntimeError("Incorrect context")
  162. name = self.evaluate_input("Name")
  163. matrix = self.parameters['Matrix']
  164. reset_transforms = False
  165. #check if an object by the name exists
  166. if (name) and (ob := bpy.data.objects.get(name)):
  167. # Clear the drivers from BOTH the object/pose and the skeleton
  168. if (ob.animation_data):
  169. while (ob.animation_data.drivers):
  170. ob.animation_data.drivers.remove(ob.animation_data.drivers[-1])
  171. if (ob.data.animation_data):
  172. while (ob.data.animation_data.drivers):
  173. ob.data.animation_data.drivers.remove(ob.data.animation_data.drivers[-1])
  174. for pb in ob.pose.bones:
  175. # clear it, even after deleting the edit bones,
  176. # if we create them again the pose bones will be reused
  177. while (pb.constraints):
  178. pb.constraints.remove(pb.constraints[-1])
  179. if reset_transforms:
  180. pb.location = (0,0,0)
  181. pb.rotation_euler = (0,0,0)
  182. pb.rotation_quaternion = (1.0,0,0,0)
  183. pb.rotation_axis_angle = (0,0,1.0,0)
  184. pb.scale = (1.0,1.0,1.0)
  185. # feels ugly and bad, whatever
  186. collections = []
  187. for bc in ob.data.collections:
  188. collections.append(bc)
  189. for bc in collections:
  190. ob.data.collections.remove(bc)
  191. del collections
  192. # end ugly/bad
  193. else:
  194. # Create the Object
  195. ob = bpy.data.objects.new(name, bpy.data.armatures.new(name)) #create ob
  196. if (ob.name != name):
  197. raise RuntimeError("Could not create xForm object", name)
  198. # it seems this data sticks around even if the object was deleted, so clear it here.
  199. ob.id_properties_clear()
  200. self.bObject = ob.name
  201. self.bRegisterObject('OBJECT', ob)
  202. ob.matrix_world = matrix.copy()
  203. ob.data.pose_position = 'REST'
  204. set_object_parent(self)
  205. # Link to Scene:
  206. if (ob.name not in bContext.view_layer.active_layer_collection.collection.objects):
  207. bContext.view_layer.active_layer_collection.collection.objects.link(ob)
  208. print( wrapGreen("Created Armature object: ")+ wrapWhite(ob.name))
  209. # Finalize the action
  210. # oddly, overriding context doesn't seem to work
  211. try:
  212. bpy.ops.object.select_all(action='DESELECT')
  213. except RuntimeError:
  214. pass # we're already in edit mode, should be OK to do this.
  215. bContext.view_layer.objects.active = ob
  216. selected=[]
  217. for other_ob in bpy.data.objects:
  218. if other_ob.mode == "EDIT":
  219. selected.append(other_ob)
  220. selected.append(ob)
  221. context_override = {"active_object":ob, "selected_objects":selected}
  222. print("Changing Armature Mode to " +wrapPurple("EDIT"))
  223. with bContext.temp_override(**context_override):
  224. bpy.ops.object.mode_set(mode='EDIT')
  225. if ob.mode != "EDIT":
  226. prRed("eh?")
  227. # clear it
  228. while (len(ob.data.edit_bones) > 0):
  229. ob.data.edit_bones.remove(ob.data.edit_bones[0])
  230. # bContext.view_layer.objects.active = prevAct
  231. ob.data.display_type = self.evaluate_input('Display Type')
  232. # This will OVERWRITE the root armature since bones have to trace back to this one.
  233. root_armature = ob.name
  234. parent_xForm_info = get_parent_xForm_info(self)
  235. my_info = xForm_info(
  236. object_type='armature',
  237. root_armature= ob.name,
  238. parent_pose_name=parent_xForm_info.self_pose_name,
  239. parent_edit_name=parent_xForm_info.self_edit_name,
  240. self_pose_name=ob.name,
  241. self_edit_name=ob.name,
  242. )
  243. self.parameters['xForm Out'] = my_info
  244. self.executed = True
  245. def bFinalize(self, bContext = None):
  246. # custom properties
  247. self.setup_custom_props(self.bGetObject(), "Custom Properties")
  248. finish_drivers(self)
  249. def bGetObject(self, mode = ''):
  250. import bpy; return bpy.data.objects[self.parameters['xForm Out'].self_pose_name]
  251. class xFormBone(xFormNode):
  252. '''A node representing a bone in an armature'''
  253. __slots__ = ()
  254. # DO: make a way to identify which armature this belongs to
  255. def __init__(self, signature, base_tree):
  256. super().__init__(signature, base_tree, xFormBoneSockets)
  257. # TODO: implement socket templates completely for Bone
  258. # currently it is waiting on BBone and refactoring/cleanup.
  259. # the socket templates are being used now but not for mantis node execution.
  260. # because of edit/pose/objcet bone this will be a bit complex
  261. self.init_parameters()
  262. self.set_traverse([("Relationship", "xForm Out")])
  263. setup_custom_property_inputs_outputs(self)
  264. def bGetParentArmature(self):
  265. parent_xForm_info = get_parent_xForm_info(self)
  266. from bpy import data
  267. return data.objects.get(parent_xForm_info.root_armature)
  268. def bSetParent(self, eb):
  269. from bpy import data
  270. parent_xForm_info = get_parent_xForm_info(self)
  271. parent_armature = data.objects.get( parent_xForm_info.root_armature)
  272. if parent_xForm_info.self_edit_name != parent_xForm_info.root_armature:
  273. parent_bone = parent_armature.data.edit_bones.get( parent_xForm_info.self_edit_name)
  274. eb.parent = parent_bone
  275. parent_mantis_node = get_parent_node(self, type = 'LINK') # get the link node.
  276. # TODO probably need to send the parenting info or at least the signatures of intervening nodes.
  277. eb.use_connect = parent_mantis_node.evaluate_input("Connected")
  278. eb.use_inherit_rotation = parent_mantis_node.evaluate_input("Inherit Rotation")
  279. eb.inherit_scale = parent_mantis_node.evaluate_input("Inherit Scale")
  280. def bPrepare(self, bContext=None):
  281. self.check_drivers()
  282. self.parameters['Matrix'] = get_matrix(self)
  283. self.prepared = True
  284. def bTransformPass(self, bContext = None,): #possibly will need to pass context?
  285. import bpy
  286. from mathutils import Vector
  287. if not (name := self.evaluate_input("Name")):
  288. raise RuntimeError(wrapRed(f"Could not set name for bone in {self}"))
  289. if (not isinstance(bContext, bpy.types.Context)):
  290. raise RuntimeError("Incorrect context")
  291. if not (xF := self.bGetParentArmature()):
  292. raise RuntimeError("Could not create edit bone: ", name, " from node:", self, " Reason: No armature object to add bone to.")
  293. matrix = self.parameters['Matrix']
  294. length = matrix[3][3]
  295. if (xF):
  296. if (xF.mode != "EDIT"):
  297. raise RuntimeError("Armature Object Not in Edit Mode, exiting...")
  298. #
  299. # Create the Object
  300. d = xF.data
  301. eb = d.edit_bones.new(name)
  302. # Bone Collections:
  303. # We treat each separate string as a Bone Collection that this object belongs to
  304. # Bone Collections are fully qualified by their hierarchy.
  305. # Separate Strings with "|" and indicate hierarchy with ">". These are special characters.
  306. # NOTE: if the user names the collections differently at different times, this will take the FIRST definition and go with it
  307. if self.inputs['Bone Collection'].links:
  308. bCol_groups = []
  309. for i, l in enumerate(self.inputs['Bone Collection'].links):
  310. bCol_group = self.evaluate_input("Bone Collection", index=i)
  311. bCol_groups.append(bCol_group)
  312. bCols = '|'.join(bCol_groups)
  313. else:
  314. bCols = self.evaluate_input("Bone Collection")
  315. if bCols: # it is actually possible to add a bone to no collections. odd.
  316. bone_collections = bCols.split("|")
  317. for collection_list in bone_collections:
  318. hierarchy = collection_list.split(">")
  319. col_parent = None
  320. for bCol in hierarchy:
  321. if bCol is None: continue # I think this
  322. if bCol == '': continue
  323. if ( col := d.collections_all.get(bCol) ) is None:
  324. col = d.collections.new(bCol)
  325. col.parent = col_parent
  326. col_parent = col
  327. if hierarchy[-1]: # will be "" or None if the box is empty
  328. d.collections_all.get(hierarchy[-1]).assign(eb)
  329. if (eb.name != name):
  330. prRed(f"Expected bone of name: {name}, got {eb.name} instead.")
  331. raise RuntimeError("Could not create bone ", name, "; Perhaps there is a duplicate bone name in the node tree?")
  332. eb.matrix = matrix.copy()
  333. tailoffset = Vector((0,length,0)) #Vector((0,self.tailoffset, 0))
  334. tailoffset = matrix.copy().to_3x3() @ tailoffset
  335. eb.tail = eb.head + tailoffset
  336. if (eb.name != name):
  337. raise RuntimeError("Could not create edit bone: ", name)
  338. assert (eb.name), "Bone must have a name."
  339. self.bObject = eb.name
  340. self.bRegisterObject('BONE', xF, eb)
  341. # The bone should have relationships going in at this point.
  342. self.bSetParent(eb)
  343. if eb.head == eb.tail:
  344. raise RuntimeError(wrapRed(f"Could not create edit bone: {name} because bone head was located in the same place as bone tail."))
  345. # Setup Deform attributes...
  346. eb_props_sockets = self.gen_property_socket_map(prop_owner_group="edit_bone")
  347. evaluate_sockets(self, eb, eb_props_sockets)
  348. print( wrapGreen("Created Bone: ") + wrapOrange(eb.name) + wrapGreen(" in ") + wrapWhite(self.bGetParentArmature().name))
  349. parent_xForm_info = get_parent_xForm_info(self)
  350. my_info = xForm_info(
  351. object_type='bone',
  352. root_armature= xF.name,
  353. parent_pose_name=parent_xForm_info.self_pose_name,
  354. parent_edit_name=parent_xForm_info.self_edit_name,
  355. self_pose_name=eb.name,
  356. self_edit_name=eb.name,
  357. )
  358. self.parameters['xForm Out'] = my_info
  359. self.executed = True
  360. def set_bone_color(self, b, inherit_color, bContext):
  361. color_values = self.evaluate_input('Color')
  362. if color_values is None:
  363. prOrange(f"Warning: No color information found for {b.name}. This should not happen.")
  364. return
  365. if inherit_color and b.parent:
  366. b.color.palette=b.parent.color.palette
  367. if b.color.palette == 'CUSTOM':
  368. b.color.custom.active=b.parent.color.custom.active
  369. b.color.custom.normal=b.parent.color.custom.normal
  370. b.color.custom.select=b.parent.color.custom.select
  371. return
  372. from mathutils import Color
  373. color_active = Color(color_values[:3])
  374. color_normal = Color(color_values[3:6])
  375. color_select = Color(color_values[6:])
  376. is_theme_colors = False
  377. theme = bContext.preferences.themes[0]
  378. for i, color_set in enumerate(theme.bone_color_sets):
  379. if ((color_active == color_set.active) and
  380. (color_normal == color_set.normal) and
  381. (color_select == color_set.select) ):
  382. is_theme_colors=True; break
  383. if is_theme_colors: # add 1, not 0-indexed
  384. b.color.palette = 'THEME'+str(i+1).zfill(2)
  385. elif ((color_active == theme.view_3d.bone_pose_active) and
  386. (color_normal == theme.view_3d.bone_solid) and
  387. (color_select == theme.view_3d.bone_pose) ):
  388. b.color.palette = 'DEFAULT'
  389. else:
  390. b.color.palette = 'CUSTOM'
  391. b.color.custom.active=color_active
  392. b.color.custom.normal=color_normal
  393. b.color.custom.select=color_select
  394. def bFinalize(self, bContext = None):
  395. b = self.bGetParentArmature().data.bones[self.bObject]
  396. # let's do bone colors first
  397. inherit_color = self.evaluate_input("Inherit Color")
  398. if len(self.inputs['Color'].links) > 0:
  399. inherit_color = False # use the link instead
  400. self.set_bone_color(b, inherit_color, bContext)
  401. if self.evaluate_input("BBone HQ Deformation"):
  402. b.bbone_mapping_mode = "CURVED"
  403. if handle_type := self.evaluate_input("BBone Start Handle Type"):
  404. b.bbone_handle_type_start = handle_type
  405. if handle_type := self.evaluate_input("BBone End Handle Type"):
  406. b.bbone_handle_type_end = handle_type
  407. try:
  408. if (custom_handle := self.evaluate_input("BBone Custom Start Handle")):
  409. b.bbone_custom_handle_start = self.bGetParentArmature().data.bones[custom_handle]
  410. if (custom_handle := self.evaluate_input("BBone Custom End Handle")):
  411. b.bbone_custom_handle_end = self.bGetParentArmature().data.bones[custom_handle]
  412. except KeyError:
  413. prRed("Warning: BBone start or end handle not set because of missing bone in armature.")
  414. import bpy
  415. pb = self.bGetParentArmature().pose.bones[self.bObject]
  416. if check_for_driver(self, 'Rotation Order'):
  417. # this is stupid and a HACK
  418. from .mantis_dataclasses import MantisSocketFiller
  419. props_sockets = {"rotation_mode": MantisSocketFiller( socket_name="Rotation Order",
  420. property_name="rotation_mode", default_value='XYZ',)}
  421. evaluate_sockets(self, pb, props_sockets)
  422. else: # This is stupid, but I did it to myself and it will be annoying to fix
  423. rotation_mode = self.evaluate_input("Rotation Order")
  424. if rotation_mode == "AUTO": rotation_mode = "XYZ"
  425. pb.rotation_mode = rotation_mode
  426. pb.id_properties_clear()
  427. self.setup_custom_props(pb, "Custom Properties")
  428. pb_props_sockets = self.gen_property_socket_map(prop_owner_group='pose_bone')
  429. evaluate_sockets(self, pb, pb_props_sockets)
  430. bone_props_socket = self.gen_property_socket_map(prop_owner_group='bone')
  431. evaluate_sockets(self, pb.bone, bone_props_socket)
  432. # and in edit mode we need to explicitly set the bbone properties
  433. # I don't like this HACK but there seems to be no other way...
  434. # Better to ask forgiveness than permission. If anyone wants control over this, I'll solve the problem then
  435. # IN the near future, in fact, I think I'll make a BBone Rest Pose matrix thing
  436. # and allow users to set it from bezier curves
  437. pb.bone.bbone_easein = 1; pb.bone.bbone_easeout = 1
  438. finish_drivers(self)
  439. pb.custom_shape_transform = None
  440. pb.custom_shape = None
  441. if len(self.inputs["Custom Object xForm Override"].links) > 0:
  442. trace = trace_single_line(self, "Custom Object xForm Override")
  443. try:
  444. pb.custom_shape_transform = trace[0][1].bGetObject()
  445. except AttributeError:
  446. pass
  447. if len(self.inputs["Custom Object"].links) > 0:
  448. trace = trace_single_line(self, "Custom Object")
  449. try:
  450. ob = trace[0][1].bGetObject()
  451. except AttributeError:
  452. ob=None
  453. if type(ob) in [bpy.types.Object]:
  454. pb.custom_shape = ob
  455. def bGetObject(self, mode = 'POSE'):
  456. if self.bObject is None: return None
  457. if mode in ["POSE", "OBJECT"] and self.bGetParentArmature().mode == "EDIT":
  458. raise RuntimeError("Cannot get Bone or PoseBone in Edit mode.")
  459. elif mode == "EDIT" and self.bGetParentArmature().mode != "EDIT":
  460. raise RuntimeError("Cannot get EditBone except in Edit mode.")
  461. try:
  462. if (mode == 'EDIT'):
  463. return self.bGetParentArmature().data.edit_bones[self.bObject]
  464. elif (mode == 'OBJECT'):
  465. return self.bGetParentArmature().data.bones[self.bObject]
  466. elif (mode == 'POSE'):
  467. return self.bGetParentArmature().pose.bones[self.bObject]
  468. except Exception as e:
  469. prRed ("Cannot get bone for %s" % self)
  470. raise e
  471. class xFormGeometryObject(xFormNode):
  472. '''A node representing an armature object'''
  473. __slots__ = ("has_shape_keys")
  474. def __init__(self, signature, base_tree):
  475. super().__init__(signature, base_tree, xFormGeometryObjectSockets)
  476. self.init_parameters()
  477. self.set_traverse([("Relationship", "xForm Out")])
  478. self.has_shape_keys = False
  479. setup_custom_property_inputs_outputs(self)
  480. def bPrepare(self, bContext = None,):
  481. import bpy
  482. if not self.evaluate_input("Name"):
  483. self.prepared = True
  484. self.executed = True
  485. # and return an error if there are any dependencies:
  486. if self.hierarchy_connections:
  487. raise GraphError(wrapRed(f"Cannot Generate object {self} because the chosen name is empty or invalid."))
  488. return
  489. self.bObject = bpy.data.objects.get(self.evaluate_input("Name"))
  490. trace = trace_single_line(self, "Geometry")
  491. if (not self.bObject):
  492. if trace[-1]:
  493. self.bObject = bpy.data.objects.new(self.evaluate_input("Name"), trace[-1].node.bGetObject())
  494. # handle mismatched data.
  495. data_wrong = False; data = None
  496. if (self.inputs["Geometry"].is_linked and self.bObject.type == "EMPTY"):
  497. data_wrong = True; data = trace[-1].node.bGetObject()
  498. elif (not self.inputs["Geometry"].is_linked and not self.bObject.type == "EMPTY"):
  499. data_wrong = True
  500. # clumsy but functional
  501. if data_wrong:
  502. unlink_me = self.bObject
  503. unlink_me.name = "MANTIS_TRASH.000"
  504. for col in unlink_me.users_collection:
  505. col.objects.unlink(unlink_me)
  506. self.bObject = bpy.data.objects.new(self.evaluate_input("Name"), data)
  507. if self.bObject and (self.inputs["Geometry"].is_linked and self.bObject.type in ["MESH", "CURVE"]):
  508. self.bObject.data = trace[-1].node.bGetObject()
  509. # NOW: find out if we need to duplicate the object data.
  510. dupe_data=False
  511. node_line = trace_single_line(self, "Deformer")[0]
  512. from .deformer_nodes import DeformerHook
  513. for deformer in node_line:
  514. if isinstance(deformer, DeformerHook) and \
  515. deformer.evaluate_input("Affect Curve Radius") == True and \
  516. self.bObject.type == 'CURVE':
  517. print(f"INFO: Duplicating data {self.bObject.data.name} in {self} so it can be used for drivers.")
  518. dupe_data=True; break
  519. if dupe_data:
  520. name = self.bObject.data.name
  521. # it has to be a curve
  522. data = bpy.data.curves.get(self.bObject.data.name+"_MANTIS")
  523. if data: # Delete it and regenerate it if it exists.
  524. data.name+="_TRASH.000" # but we can't actually delete it here
  525. # since previous executions of the graph may be using it.
  526. # instead, we'll rename it and use a new copy. This will probably
  527. # be deleted on its own by Blender's garbage collector.
  528. # if it isn't, then it is still in use and I may NOT touch it.
  529. data=self.bObject.data.copy(); data.animation_data_clear()
  530. data.name = name+"_MANTIS"
  531. self.bObject.data = data
  532. reset_object_data(self.bObject)
  533. matrix= get_matrix(self)
  534. self.parameters['Matrix'] = matrix
  535. try:
  536. set_object_parent(self)
  537. except: # I guess it isn't ready yet. we'll do it later
  538. pass # (This can happen when solving schema.)
  539. self.bObject.matrix_world = matrix
  540. parent_xForm_info = get_parent_xForm_info(self)
  541. root_armature = parent_xForm_info.root_armature
  542. my_info = xForm_info(
  543. object_type='object',
  544. root_armature= root_armature,
  545. parent_pose_name=parent_xForm_info.self_edit_name,
  546. parent_edit_name=parent_xForm_info.self_pose_name,
  547. self_pose_name=self.bObject.name,
  548. self_edit_name=self.bObject.name,
  549. )
  550. self.parameters['xForm Out'] = my_info
  551. self.bRegisterObject('OBJECT', self.bObject)
  552. self.prepared = True
  553. def bTransformPass(self, bContext = None,):
  554. try:
  555. bContext.collection.objects.link(self.bObject)
  556. except RuntimeError: #already in; but a dangerous thing to pass.
  557. pass
  558. self.has_shape_keys = False
  559. # putting this in bTransformPass simply prevents it from being run more than once.
  560. # maybe I should do that with the rest of bPrepare, too.
  561. props_sockets = self.gen_property_socket_map()
  562. evaluate_sockets(self, self.bObject, props_sockets)
  563. self.executed = True
  564. def bFinalize(self, bContext = None):
  565. matrix= get_matrix(self)
  566. set_object_parent(self)
  567. self.bObject.matrix_world = matrix
  568. # custom properties
  569. self.setup_custom_props(self.bGetObject(), "Custom Properties")
  570. for i, (driver_key, driver_item) in enumerate(self.drivers.items()):
  571. print (wrapGreen(i), wrapWhite(self), wrapPurple(driver_key))
  572. prOrange(driver_item)
  573. finish_drivers(self)
  574. def bGetObject(self, mode = 'POSE'):
  575. return self.bObject
  576. class xFormObjectInstance(xFormNode):
  577. """Represents an instance of an existing geometry object."""
  578. __slots__ = ("has_shape_keys")
  579. def __init__(self, signature, base_tree):
  580. super().__init__(signature, base_tree, xFormGeometryObjectInstanceSockets)
  581. self.init_parameters()
  582. # TODO: I think this field is a leftover from a test or something. see if it can be removed.
  583. self.links = {} # leave this empty for now!
  584. self.set_traverse([("Relationship", "xForm Out")])
  585. self.has_shape_keys = False # Shape Keys will make a dupe so this is OK
  586. setup_custom_property_inputs_outputs(self)
  587. def ui_modify_socket(self, ui_socket, socket_name=None):
  588. if ui_socket.name == 'As Instance':
  589. change_handled = True
  590. try:
  591. self.bObject.modifiers[0]['Socket_1'] = ui_socket.default_value
  592. except Exception as e:
  593. print("Failed to update mantis socket because of %s" % e,
  594. "Updating tree instead.")
  595. return change_handled
  596. else:
  597. return super().ui_modify_socket(ui_socket, socket_name)
  598. def bPrepare(self, bContext = None,):
  599. from bpy import data
  600. empty_mesh = data.meshes.get("MANTIS_EMPTY_MESH")
  601. if not empty_mesh:
  602. empty_mesh = data.meshes.new("MANTIS_EMPTY_MESH")
  603. if not self.evaluate_input("Name"):
  604. self.prepared = True
  605. self.executed = True
  606. # and return an error if there are any dependencies:
  607. if self.hierarchy_connections:
  608. raise GraphError(wrapRed(f"Cannot Generate object {self} because the chosen name is empty or invalid."))
  609. return
  610. self.bObject = data.objects.get(self.evaluate_input("Name"))
  611. if (not self.bObject):
  612. self.bObject = data.objects.new(self.evaluate_input("Name"), empty_mesh)
  613. reset_object_data(self.bObject)
  614. matrix= get_matrix(self)
  615. self.parameters['Matrix'] = matrix
  616. set_object_parent(self)
  617. self.bObject.matrix_world = matrix
  618. parent_xForm_info = get_parent_xForm_info(self)
  619. root_armature = parent_xForm_info.root_armature
  620. my_info = xForm_info(
  621. object_type='object',
  622. root_armature= root_armature,
  623. parent_pose_name=parent_xForm_info.self_edit_name,
  624. parent_edit_name=parent_xForm_info.self_pose_name,
  625. self_pose_name=self.bObject.name,
  626. self_edit_name=self.bObject.name,
  627. )
  628. self.parameters['xForm Out'] = my_info
  629. self.bRegisterObject('OBJECT', self.bObject)
  630. self.prepared = True
  631. def bTransformPass(self, bContext = None,):
  632. try:
  633. bContext.collection.objects.link(self.bObject)
  634. except RuntimeError: #already in; but a dangerous thing to pass.
  635. pass
  636. self.has_shape_keys = False
  637. # putting this in bTransformPass simply prevents it from being run more than once.
  638. # maybe I should do that with the rest of bPrepare, too.
  639. props_sockets = {
  640. 'hide_viewport' : ("Hide in Viewport", False),
  641. 'hide_render' : ("Hide in Render", False),
  642. }
  643. evaluate_sockets(self, self.bObject, props_sockets)
  644. self.executed = True
  645. def bFinalize(self, bContext = None):
  646. # now we need to set the object instance up.
  647. from bpy import data
  648. trace = trace_single_line(self, "Source Object")
  649. for node in trace[0]:
  650. if node is self: continue # lol
  651. if (node.node_type == 'XFORM'):
  652. source_ob = node.bGetObject(); break
  653. modifier = self.bObject.modifiers.new("Object Instance", type='NODES')
  654. ng = data.node_groups.get("Object Instance")
  655. if ng is None:
  656. from .utilities.geometry_node_graphgen import gen_object_instance_node_group
  657. ng = gen_object_instance_node_group()
  658. modifier.node_group = ng
  659. modifier["Socket_0"] = source_ob
  660. modifier["Socket_1"] = self.evaluate_input("As Instance")
  661. # custom properties
  662. self.setup_custom_props(self.bGetObject(), "Custom Properties")
  663. for i, (driver_key, driver_item) in enumerate(self.drivers.items()):
  664. print (wrapGreen(i), wrapWhite(self), wrapPurple(driver_key))
  665. prOrange(driver_item)
  666. finish_drivers(self)
  667. def bGetObject(self, mode = 'POSE'):
  668. return self.bObject
  669. class xFormCurvePin(xFormNode):
  670. """An xForm pinned to a specific location on a curve."""
  671. __slots__ = ()
  672. def __init__(self, signature, base_tree):
  673. super().__init__(signature, base_tree,xFormCurvePinSockets)
  674. self.init_parameters(additional_parameters={"Matrix":None})
  675. setup_custom_property_inputs_outputs(self)
  676. def prep_driver_values(self, constraint):
  677. from .misc_nodes import UtilityDriver, UtilitySwitch
  678. for socket_name in ["Curve Pin Factor", "Forward Axis","Up Axis",]:
  679. if self.inputs.get(socket_name) is None: continue # in case it has been bypassed
  680. if self.inputs[socket_name].is_linked:
  681. node_line, _last_socket = trace_single_line(self, socket_name)
  682. driver = None
  683. for other_node in node_line:
  684. if other_node.node_type == 'DRIVER':
  685. driver = other_node; break
  686. if isinstance(driver, UtilityDriver):
  687. prop_amount = driver.evaluate_input("Property")
  688. elif isinstance(driver, UtilitySwitch):
  689. xf=driver.GetxForm()
  690. prop_amount = xf.evaluate_input(driver.evaluate_input('Parameter'))
  691. else:
  692. return
  693. for template in self.socket_templates:
  694. if template.name == socket_name: break
  695. setattr(constraint, template.blender_property, prop_amount )
  696. def bPrepare(self, bContext = None,):
  697. from bpy import data
  698. if not bContext: # lol
  699. import bpy
  700. bContext = bpy.context
  701. ob = data.objects.get(self.evaluate_input("Name"))
  702. if not ob:
  703. ob = data.objects.new(self.evaluate_input("Name"), None)
  704. ob.lock_location = [True, True, True]
  705. ob.lock_rotation = [True, True, True]
  706. ob.lock_scale = [True, True, True]
  707. ob.lock_rotation_w = True
  708. ob.empty_display_type = 'CONE'
  709. ob.empty_display_size = 0.10
  710. self.bObject = ob
  711. self.bRegisterObject('OBJECT', self.bObject)
  712. reset_object_data(ob)
  713. node_line = trace_single_line(self, "Parent Curve")[0][1:] # slice excludes self
  714. for other_node in node_line:
  715. if other_node.node_type == 'XFORM':
  716. break
  717. else:
  718. raise GraphError(f"ERROR: {self} is not connected to a parent curve")
  719. if isinstance(other_node, (xFormArmature, xFormBone, xFormObjectInstance,)):
  720. raise GraphError(f"ERROR: {self} must be connected to curve,"
  721. " not {other_node.__class__.__name__}")
  722. curve=other_node.bGetObject()
  723. if curve.type != 'CURVE':
  724. raise GraphError(f"ERROR: {self} must be connected to curve,"
  725. " not {curve.type}")
  726. # we'll limit all the transforms so we can parent it
  727. # because it is annoying to have a cluttered outliner.
  728. #
  729. # always do this so that everything stays consistent.
  730. spline_index = self.evaluate_input("Spline Index")
  731. from .utilities.utilities import get_extracted_spline_object
  732. curve = get_extracted_spline_object(curve, spline_index, self.mContext)
  733. # Link to Scene:
  734. for link_me in [ob, curve]:
  735. if (link_me.name not in bContext.view_layer.active_layer_collection.collection.objects):
  736. bContext.view_layer.active_layer_collection.collection.objects.link(link_me)
  737. c = ob.constraints.new("LIMIT_LOCATION")
  738. for max_min in ['max','min']:
  739. for axis in "xyz":
  740. setattr(c, "use_"+max_min+"_"+axis, True)
  741. setattr(c, max_min+"_"+axis, 0.0)
  742. c = ob.constraints.new("LIMIT_ROTATION")
  743. for axis in "xyz":
  744. setattr(c, "use_limit_"+axis, True)
  745. setattr(c, max_min+"_"+axis, 0.0)
  746. c = ob.constraints.new("LIMIT_SCALE")
  747. for max_min in ['max','min']:
  748. for axis in "xyz":
  749. setattr(c, "use_"+max_min+"_"+axis, True)
  750. setattr(c, max_min+"_"+axis, 1.0)
  751. c = ob.constraints.new("FOLLOW_PATH")
  752. c.target = curve
  753. c.use_fixed_location = True
  754. c.use_curve_radius = True
  755. c.use_curve_follow = True
  756. c.name = "Curve Pin"
  757. props_sockets = self.gen_property_socket_map()
  758. constraint_props_sockets = props_sockets.copy()
  759. del constraint_props_sockets['name']; del constraint_props_sockets['empty_display_size']
  760. del props_sockets['offset_factor']; del props_sockets['forward_axis']
  761. del props_sockets['up_axis']
  762. evaluate_sockets(self, c, constraint_props_sockets)
  763. evaluate_sockets(self, self.bObject, props_sockets)
  764. # this isn't usually run on xForm nodes so for now I need to set the
  765. # driver's default values manually if I want a matrix now.
  766. # because the drivers may not have initialized yet.
  767. self.prep_driver_values(c)
  768. # now if all goes well... the matrix will be correct.
  769. dg = bContext.view_layer.depsgraph
  770. dg.update()
  771. # and the matrix should be correct now - copy because it may be modified
  772. self.parameters['Matrix'] = ob.matrix_world.copy()
  773. ob.parent=curve
  774. print( wrapGreen("Created Curve Pin: ") + wrapOrange(self.bObject.name) )
  775. parent_xForm_info = get_parent_xForm_info(self)
  776. root_armature = parent_xForm_info.root_armature
  777. my_info = xForm_info(
  778. object_type='object',
  779. root_armature= root_armature,
  780. parent_pose_name=curve.name,
  781. parent_edit_name=curve.name,
  782. self_pose_name=self.bObject.name,
  783. self_edit_name=self.bObject.name,
  784. )
  785. self.parameters['xForm Out'] = my_info
  786. self.prepared = True; self.executed = True
  787. def bFinalize(self, bContext = None):
  788. # custom properties
  789. self.setup_custom_props(self.bGetObject(), "Custom Properties")
  790. finish_drivers(self)
  791. def bGetObject(self, mode = 'POSE'):
  792. return self.bObject
  793. # special thank-you to Natalie Cuthbert, who submitted a patch for this
  794. # it turned out, I already had this patch laying around
  795. # because I was too busy with grad school I didn't succeed in collaborating
  796. # so while I apologize for failing to get your name in the commit history
  797. # now you get a special thank-you in Mantis instead!
  798. class xFormGetBone(xFormNode):
  799. """Represents an instance of an existing geometry object."""
  800. __slots__ = ()
  801. def __init__(self, signature, base_tree):
  802. super().__init__(signature, base_tree, xFormGetBoneSockets)
  803. self.init_parameters()
  804. # this is just a getter
  805. self.prepared=True; self.executed=True; self.execution_prepared=True
  806. def bGetParentArmature(self):
  807. from bpy import data
  808. # the below function may return None, but data.objects.get expects a string
  809. return data.objects.get(self.evaluate_input("Parent Armature") or "")
  810. def bGetObject(self, mode = 'POSE'):
  811. bone = None
  812. self.bObject = self.evaluate_input("Bone")
  813. armature = self.bGetParentArmature()
  814. from bpy.types import Object
  815. assert armature is not None, f"{self} requires a parent armature input to operate."
  816. assert isinstance(armature, Object), f"{self}: The parent armature must be an armature object."
  817. if armature:
  818. assert armature.type == 'ARMATURE', f"{self}: The parent armature must be an armature object."
  819. match mode:
  820. case 'EDIT':
  821. bone = armature.data.edit_bones.get(self.evaluate_input("Bone"))
  822. case 'OBJECT':
  823. bone = armature.bones.get(self.evaluate_input("Bone"))
  824. case 'POSE':
  825. bone = armature.pose.bones.get(self.evaluate_input("Bone"))
  826. assert self.bObject is not None, f"{self} failed to get the desired bone. Check if the bone name exists."
  827. self.bRegisterObject('BONE', armature, bone)
  828. return bone