xForm_nodes.py 40 KB

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