xForm_nodes.py 41 KB

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