deformer_containers.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. from .node_container_common import *
  2. from .xForm_containers import xFormGeometryObject
  3. from .misc_nodes import InputExistingGeometryObject
  4. from .base_definitions import MantisNode, MantisSocketTemplate
  5. from .utilities import (prRed, prGreen, prPurple, prWhite, prOrange,
  6. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  7. wrapOrange,)
  8. from .deformer_socket_templates import *
  9. from bpy.types import NodeTree
  10. def TellClasses():
  11. return [
  12. DeformerArmature,
  13. DeformerHook,
  14. DeformerMorphTarget,
  15. DeformerMorphTargetDeform,
  16. ]
  17. def trace_xForm_back(nc, socket):
  18. from .xForm_containers import xFormGeometryObject
  19. from .misc_nodes import InputExistingGeometryObject
  20. from bpy.types import Object
  21. if (trace := trace_single_line(nc, socket)[0] ) :
  22. for i in range(len(trace)): # have to look in reverse, actually
  23. if ( isinstance(trace[ i ], xFormGeometryObject ) ) or ( isinstance(trace[ i ], InputExistingGeometryObject ) ):
  24. return trace[ i ].bGetObject()
  25. raise GraphError(wrapRed(f"No other object found for {nc}."))
  26. # semi-duplicated from link_containers
  27. def GetxForm(nc):
  28. trace = trace_single_line_up(nc, "Deformer")
  29. for node in trace[0]:
  30. if (node.__class__ in [xFormGeometryObject, InputExistingGeometryObject]):
  31. return node
  32. raise GraphError("%s is not connected to a downstream xForm" % nc)
  33. class MantisDeformerNode(MantisNode):
  34. def __init__(self, signature : tuple,
  35. base_tree : NodeTree,
  36. socket_templates : list[MantisSocketTemplate]=[]):
  37. super().__init__(signature, base_tree, socket_templates)
  38. self.node_type = 'LINK'
  39. self.prepared = True
  40. # we need evaluate_input to have the same behaviour as links.
  41. def evaluate_input(self, input_name, index=0):
  42. if ('Target' in input_name):
  43. socket = self.inputs.get(input_name)
  44. if socket.is_linked:
  45. return socket.links[0].from_node
  46. return None
  47. else:
  48. return super().evaluate_input(input_name, index)
  49. class DeformerArmature(MantisDeformerNode):
  50. '''A node representing an armature deformer'''
  51. def __init__(self, signature, base_tree):
  52. super().__init__(signature, base_tree)
  53. inputs = [
  54. "Input Relationship",
  55. "Armature Object",
  56. "Blend Vertex Group",
  57. "Invert Vertex Group",
  58. "Preserve Volume",
  59. "Use Multi Modifier",
  60. "Use Envelopes",
  61. "Use Vertex Groups",
  62. "Skinning Method",
  63. "Deformer",
  64. "Copy Skin Weights From"
  65. ]
  66. outputs = [
  67. "Deformer"
  68. ]
  69. self.outputs.init_sockets(outputs)
  70. self.inputs.init_sockets(inputs)
  71. self.init_parameters(additional_parameters={"Name":None})
  72. self.set_traverse([("Deformer", "Deformer")])
  73. self.node_type = "LINK"
  74. self.prepared = True
  75. def GetxForm(self, socket="Deformer"):
  76. if socket == "Deformer":
  77. return GetxForm(self)
  78. else:
  79. trace_xForm_back(self, socket)
  80. # DUPLICATED FROM xForm_containers::xFormBone
  81. # DEDUP HACK HACK HACK HACK HACK
  82. def bGetParentArmature(self):
  83. from .xForm_containers import xFormArmature
  84. from .misc_nodes import InputExistingGeometryObject
  85. from bpy.types import Object
  86. if (trace := trace_single_line(self, "Armature Object")[0] ) :
  87. for i in range(len(trace)):
  88. # have to look in reverse, actually
  89. if ( isinstance(trace[ i ], xFormArmature ) ):
  90. return trace[ i ].bGetObject()
  91. elif ( isinstance(trace[i], InputExistingGeometryObject)):
  92. if (ob := trace[i].bGetObject()).type == "ARMATURE":
  93. return ob
  94. raise RuntimeError(f"Cannot find armature for node {self}")
  95. return None
  96. #should do the trick...
  97. def bExecute(self, bContext = None,):
  98. self.executed = True
  99. def initialize_vgroups(self,):
  100. ob = self.GetxForm().bGetObject()
  101. armOb = self.bGetParentArmature()
  102. for b in armOb.data.bones:
  103. if b.use_deform == False:
  104. continue
  105. vg = ob.vertex_groups.get(b.name)
  106. if not vg:
  107. vg = ob.vertex_groups.new(name=b.name)
  108. num_verts = len(ob.data.vertices)
  109. vg.add(range(num_verts), 0, 'REPLACE')
  110. def copy_weights(self):
  111. # we'll use modifiers for this, maybe use GN for it in the future tho
  112. import bpy
  113. ob = self.GetxForm().bGetObject()
  114. try:
  115. copy_from = self.GetxForm(socket="Copy Skin Weights From")
  116. except GraphError:
  117. copy_from = None
  118. prRed(f"No object found for copying weights in {self}, continuing anyway.")
  119. m = ob.modifiers.new(type="DATA_TRANSFER", name="Mantis_temp_data_transfer")
  120. m.object = None; m.use_vert_data = True
  121. m.data_types_verts = {'VGROUP_WEIGHTS'}
  122. m.vert_mapping = 'POLYINTERP_NEAREST'
  123. m.layers_vgroup_select_src = 'ALL'
  124. m.layers_vgroup_select_dst = 'NAME'
  125. m.object = copy_from
  126. # m.use_object_transform = False # testing reveals that this is undesirable - since the objects may not have their transforms applied.
  127. ob.modifiers.move(len(ob.modifiers)-1, 0)
  128. # ob.data = ob.data.copy()
  129. if False: #MAYBE the mouse needs to be in the 3D viewport, no idea how to set this in an override
  130. # TODO: figure out how to apply this, context is incorrect because armature is still in pose mode
  131. original_active = bpy.context.active_object
  132. original_mode = original_active.mode
  133. bpy.ops.object.mode_set(mode='OBJECT')
  134. with bpy.context.temp_override(**{'active_object':ob, 'selected_objects':[ob, copy_from]}):
  135. # bpy.ops.object.datalayout_transfer(modifier=m.name) # note: this operator is used by the modifier or stand-alone in the UI
  136. # the poll for this operator is defined in blender/source/blender/editors/object/object_data_transfer.cc
  137. # and blender/source/blender/editors/object/object_modifier.cc
  138. # bpy.ops.object.modifier_apply(modifier=m.name, single_user=True)
  139. bpy.ops.object.datalayout_transfer(data_type='VGROUP_WEIGHTS')
  140. bpy.ops.object.data_transfer(data_type='VGROUP_WEIGHTS')
  141. bpy.ops.object.mode_set(mode=original_mode)
  142. def bFinalize(self, bContext=None):
  143. prGreen("Executing Armature Deform Node")
  144. mod_name = self.evaluate_input("Name")
  145. d = self.GetxForm().bGetObject().modifiers.new(mod_name, type='ARMATURE')
  146. if d is None:
  147. raise RuntimeError(f"Modifier was not created in node {self} -- the object is invalid.")
  148. self.bObject = d
  149. d.object = self.bGetParentArmature()
  150. props_sockets = {
  151. 'vertex_group' : ("Blend Vertex Group", ""),
  152. 'invert_vertex_group' : ("Invert Vertex Group", ""),
  153. 'use_deform_preserve_volume' : ("Preserve Volume", False),
  154. 'use_multi_modifier' : ("Use Multi Modifier", False),
  155. 'use_bone_envelopes' : ("Use Envelopes", False),
  156. 'use_vertex_groups' : ("Use Vertex Groups", False),
  157. }
  158. evaluate_sockets(self, d, props_sockets)
  159. #
  160. if (skin_method := self.evaluate_input("Skinning Method")) == "AUTOMATIC_HEAT":
  161. # This is bad and leads to somewhat unpredictable
  162. # behaviour, e.g. what object will be selected? What mode?
  163. # also bpy.ops is ugly and prone to error when used in
  164. # scripts. I don't intend to use bpy.ops when I can avoid it.
  165. import bpy
  166. self.initialize_vgroups()
  167. bContext.view_layer.depsgraph.update()
  168. ob = self.GetxForm().bGetObject()
  169. armOb = self.bGetParentArmature()
  170. deform_bones = []
  171. for pb in armOb.pose.bones:
  172. if pb.bone.use_deform == True:
  173. deform_bones.append(pb)
  174. context_override = {
  175. 'active_object':ob,
  176. 'selected_objects':[ob, armOb],
  177. 'active_pose_bone':deform_bones[0],
  178. 'selected_pose_bones':deform_bones,}
  179. #
  180. # with bContext.temp_override(**{'active_object':armOb}):
  181. # bpy.ops.object.mode_set(mode='POSE')
  182. # bpy.ops.pose.select_all(action='SELECT')
  183. for b in armOb.data.bones:
  184. b.select = True
  185. with bContext.temp_override(**context_override):
  186. bpy.ops.paint.weight_paint_toggle()
  187. bpy.ops.paint.weight_from_bones(type='AUTOMATIC')
  188. bpy.ops.paint.weight_paint_toggle()
  189. for b in armOb.data.bones:
  190. b.select = False
  191. #
  192. # with bContext.temp_override(**{'active_object':armOb}):
  193. # bpy.ops.object.mode_set(mode='POSE')
  194. # bpy.ops.pose.select_all(action='DESELECT')
  195. # bpy.ops.object.mode_set(mode='OBJECT')
  196. # TODO: modify Blender to make this available as a Python API function.
  197. elif skin_method == "EXISTING_GROUPS":
  198. pass
  199. elif skin_method == "COPY_FROM_OBJECT":
  200. self.initialize_vgroups()
  201. self.copy_weights()
  202. class DeformerHook(MantisDeformerNode):
  203. '''A node representing a hook deformer'''
  204. def __init__(self, signature, base_tree):
  205. super().__init__(signature, base_tree, HookSockets)
  206. # now set up the traverse target...
  207. self.init_parameters(additional_parameters={"Name":None})
  208. self.set_traverse([("Deformer", "Deformer")])
  209. self.prepared = True
  210. def driver_for_radius(self, object, hook, index, influence, bezier=True):
  211. """ Creates a driver to control the radius of a curve point with the hook."""
  212. from bpy.types import Bone, PoseBone
  213. var_template = {"owner":hook,
  214. "name":"a",
  215. "type":"TRANSFORMS",
  216. "space":'WORLD_SPACE',
  217. "channel":'SCALE_X',}
  218. var1_template = {"owner":hook.id_data,
  219. "name":"b",
  220. "type":"TRANSFORMS",
  221. "space":'WORLD_SPACE',
  222. "channel":'SCALE_X',}
  223. keys_template = [{"co":(0,0),
  224. "interpolation": "LINEAR",
  225. "type":"KEYFRAME",},
  226. {"co":(1,influence),
  227. "interpolation": "LINEAR",
  228. "type":"KEYFRAME",},]
  229. if bezier:
  230. owner=object.data.splines[0].bezier_points
  231. else:
  232. owner=object.data.splines[0].points
  233. driver = {
  234. "owner":owner[index],
  235. "prop":"radius",
  236. "ind":-1,
  237. "extrapolation":"LINEAR",
  238. "type":"AVERAGE",
  239. "vars":[],
  240. "keys":keys_template,
  241. }
  242. if isinstance(hook, (Bone, PoseBone)):
  243. driver['type']='SCRIPTED'
  244. driver['expression']="(((1/b)*a)+((1/b_001)*a_001)+((1/b_002)*a_002))/3"
  245. from .drivers import CreateDrivers
  246. axes='XYZ'
  247. for i in range(3):
  248. var = var_template.copy()
  249. var["channel"]="SCALE_"+axes[i]
  250. driver["vars"].append(var)
  251. if isinstance(hook, (Bone, PoseBone)):
  252. var1=var1_template.copy()
  253. var1['channel']="SCALE_"+axes[i]
  254. driver['vars'].append(var1)
  255. CreateDrivers([driver])
  256. def GetxForm(self, socket="Deformer"):
  257. if socket == "Deformer":
  258. return GetxForm(self)
  259. else:
  260. trace_xForm_back(self, socket)
  261. def bExecute(self, bContext = None,):
  262. self.executed = True
  263. def bFinalize(self, bContext=None):
  264. from bpy.types import Bone, PoseBone, Object
  265. prGreen(f"Executing Hook Deform Node: {self}")
  266. mod_name = self.evaluate_input("Name")
  267. affect_radius = self.evaluate_input("Affect Curve Radius")
  268. auto_bezier = self.evaluate_input("Auto-Bezier")
  269. target_node = self.evaluate_input('Hook Target')
  270. target = target_node.bGetObject(); subtarget = ""
  271. props_sockets = self.gen_property_socket_map()
  272. if isinstance(target, Bone) or isinstance(target, PoseBone):
  273. subtarget = target.name; target = target.id_data
  274. ob=self.GetxForm().bGetObject()
  275. if ob.type == 'CURVE':
  276. spline_index = self.evaluate_input("Spline Index")
  277. from .utilities import get_extracted_spline_object
  278. ob = get_extracted_spline_object(ob, spline_index, self.mContext)
  279. reuse = False
  280. for m in ob.modifiers:
  281. if m.type == 'HOOK' and m.object == target and m.subtarget == subtarget:
  282. if self.evaluate_input("Influence") != m.strength:
  283. continue # make a new modifier so they can have different strengths
  284. if ob.animation_data: # this can be None
  285. drivers = ob.animation_data.drivers
  286. for k in props_sockets.keys():
  287. if driver := drivers.find(k):
  288. # TODO: I should check to see if the drivers are the same...
  289. break # continue searching for an equivalent modifier
  290. else: # There was no driver - use this one.
  291. d = m; reuse = True; break
  292. else: # use this one, there can't be drivers without animation_data.
  293. d = m; reuse = True; break
  294. else:
  295. d = ob.modifiers.new(mod_name, type='HOOK')
  296. if d is None:
  297. raise RuntimeError(f"Modifier was not created in node {self} -- the object is invalid.")
  298. self.bObject = d
  299. self.get_target_and_subtarget(d, input_name="Hook Target")
  300. vertices_used=[]
  301. if reuse: # Get the verts in the list... filter out all the unneeded 0's
  302. vertices_used = list(d.vertex_indices)
  303. include_0 = 0 in vertices_used
  304. vertices_used = list(filter(lambda a : a != 0, vertices_used))
  305. if include_0: vertices_used.append(0)
  306. # now we add the selected vertex to the list, too
  307. vertex = self.evaluate_input("Point Index")
  308. if ob.type == 'CURVE' and ob.data.splines[0].type == 'BEZIER' and auto_bezier:
  309. if affect_radius:
  310. self.driver_for_radius(ob, target_node.bGetObject(), vertex, d.strength)
  311. vertex*=3
  312. vertices_used.extend([vertex, vertex+1, vertex+2])
  313. else:
  314. vertices_used.append(vertex)
  315. # if we have a curve and it is NOT using auto-bezier for the verts..
  316. if ob.type == 'CURVE' and ob.data.splines[0].type == 'BEZIER' and affect_radius and not auto_bezier:
  317. print (f"WARN: {self}: \"Affect Radius\" may not behave as expected"
  318. " when used on Bezier curves without Auto-Bezier")
  319. #bezier point starts at 1, and then every third vert, so 4, 7, 10...
  320. if vertex%3==1:
  321. self.driver_for_radius(ob, target_node.bGetObject(), vertex, d.strength)
  322. if ob.type == 'CURVE' and ob.data.splines[0].type != 'BEZIER' and \
  323. affect_radius:
  324. self.driver_for_radius(ob, target_node.bGetObject(), vertex, d.strength, bezier=False)
  325. d.vertex_indices_set(vertices_used)
  326. evaluate_sockets(self, d, props_sockets)
  327. finish_drivers(self)
  328. # todo: this node should be able to take many indices in the future.
  329. # Also: I have a Geometry Nodes implementation of this I can use... maybe...
  330. class DeformerMorphTarget(MantisDeformerNode):
  331. '''A node representing an armature deformer'''
  332. def __init__(self, signature, base_tree):
  333. super().__init__(signature, base_tree)
  334. inputs = [
  335. "Relative to",
  336. "Object",
  337. "Deformer",
  338. "Vertex Group",
  339. ]
  340. outputs = [
  341. "Deformer",
  342. "Morph Target",
  343. ]
  344. # now set up the traverse target...
  345. self.outputs.init_sockets(outputs)
  346. self.inputs.init_sockets(inputs)
  347. self.init_parameters(additional_parameters={"Name":None})
  348. self.set_traverse([("Deformer", "Deformer")])
  349. self.node_type = "LINK"
  350. self.prepared = True
  351. def GetxForm(self, trace_input="Object"):
  352. trace = trace_single_line(self, trace_input)
  353. for node in trace[0]:
  354. if (node.__class__ in [xFormGeometryObject, InputExistingGeometryObject]):
  355. return node
  356. raise GraphError("%s is not connected to an upstream xForm" % self)
  357. def bExecute(self, bContext = None,):
  358. prGreen("Executing Morph Target Node")
  359. ob = None; relative = None
  360. # do NOT check if the object exists here. Just let the next node deal with that.
  361. try:
  362. ob = self.GetxForm().bGetObject().name
  363. except Exception as e: # this will and should throw an error if it fails
  364. ob = self.GetxForm().evaluate_input("Name")
  365. if self.inputs["Relative to"].is_linked:
  366. try:
  367. relative = self.GetxForm("Relative to").bGetObject().name
  368. except Exception as e: # same here
  369. prRed(f"Execution failed at {self}: no relative object found for morph target, despite link existing.")
  370. raise e
  371. vg = self.evaluate_input("Vertex Group") if self.evaluate_input("Vertex Group") else "" # just make sure it is a string
  372. mt={"object":ob, "vertex_group":vg, "relative_shape":relative}
  373. self.parameters["Morph Target"] = mt
  374. self.parameters["Name"] = ob # this is redundant but it's OK since accessing the mt is tedious
  375. self.executed = True
  376. class DeformerMorphTargetDeform(MantisDeformerNode):
  377. '''A node representing an armature deformer'''
  378. def __init__(self, signature, base_tree):
  379. super().__init__(signature, base_tree)
  380. inputs = [
  381. "Deformer",
  382. "Use Shape Key",
  383. "Use Offset",
  384. ]
  385. outputs = [
  386. "Deformer",
  387. ]
  388. self.outputs.init_sockets(outputs)
  389. self.inputs.init_sockets(inputs)
  390. self.init_parameters(additional_parameters={"Name":None})
  391. self.set_traverse([("Deformer", "Deformer")])
  392. self.node_type = "LINK"
  393. self.prepared = True
  394. self.executed = True
  395. self.bObject = None
  396. setup_custom_props(self)
  397. def GetxForm(self):
  398. return GetxForm(self)
  399. # bpy.data.node_groups["Morph Deform.045"].nodes["Named Attribute.020"].data_type = 'FLOAT_VECTOR'
  400. # bpy.context.object.add_rest_position_attribute = True
  401. def gen_morph_target_modifier(self, context):
  402. # first let's see if this is a no-op
  403. targets = []
  404. for k,v in self.inputs.items():
  405. if "Target" in k:
  406. targets.append(v)
  407. if not targets:
  408. return # nothing to do here.
  409. # at this point we make the node tree
  410. from .geometry_node_graphgen import gen_morph_target_nodes
  411. m, props_sockets = gen_morph_target_nodes(
  412. self.evaluate_input("Name"),
  413. self.GetxForm().bGetObject(),
  414. targets,
  415. context,
  416. use_offset=self.evaluate_input("Use Offset"))
  417. self.bObject = m
  418. evaluate_sockets(self, m, props_sockets)
  419. finish_drivers(self)
  420. def gen_shape_key(self, context): # TODO: make this a feature of the node definition that appears only when there are no prior deformers - and shows a warning!
  421. # TODO: the below works well, but it is quite slow. It does not seem to have better performence. Its only advantage is export to FBX.
  422. # there are a number of things I need to fix here
  423. # - reuse shape keys if possible
  424. # - figure out how to make this a lot faster
  425. # - edit the xForm stuff to delete drivers from shape key ID's, since they belong to the Key, not the Object.
  426. # first check if we need to do anythign
  427. targets = []
  428. for k,v in self.inputs.items():
  429. if "Target" in k:
  430. targets.append(v)
  431. if not targets:
  432. return # nothing to do here
  433. from time import time
  434. start_time = time()
  435. from bpy import data
  436. xf = self.GetxForm()
  437. ob = xf.bGetObject()
  438. dg = context.view_layer.depsgraph
  439. dg.update()
  440. if xf.has_shape_keys == False:
  441. m = data.meshes.new_from_object(ob, preserve_all_data_layers=True, depsgraph=dg)
  442. ob.data = m
  443. ob.add_rest_position_attribute = True
  444. ob.shape_key_clear()
  445. ob.shape_key_add(name='Basis', from_mix=False)
  446. else:
  447. m = ob.data
  448. xf.has_shape_keys = True
  449. # using the built-in shapekey feature is actually a lot harder in terms of programming because I need...
  450. # min/max, as it is just not a feature of the GN version
  451. # to carry info from the morph target node regarding relative shapes and vertex groups and all that
  452. # the drivers may be more difficult to apply, too.
  453. # hafta make new geometry for the object and add shape keys and all that
  454. # the benefit to all this being exporting to game engines via .fbx
  455. # first make a basis shape key
  456. keys={}
  457. props_sockets={}
  458. for i, t in enumerate(targets):
  459. mt_node = t.links[0].from_node; sk_ob = mt_node.GetxForm().bGetObject()
  460. if sk_ob is None:
  461. sk_ob = data.objects.new(mt_node.evaluate_input("Name"), data.meshes.new_from_object(ob))
  462. context.collection.objects.link(sk_ob)
  463. prOrange(f"WARN: no object found for f{mt_node}; creating duplicate of current object ")
  464. sk_ob = dg.id_eval_get(sk_ob)
  465. mt_name = sk_ob.name
  466. vg = mt_node.parameters["Morph Target"]["vertex_group"]
  467. if vg: mt_name = mt_name+"."+vg
  468. sk = ob.shape_key_add(name=mt_name, from_mix=False)
  469. # the shapekey data is absolute point data for each vertex, in order, very simple
  470. # SERIOUSLY IMPORTANT:
  471. # use the current position of the vertex AFTER SHAPE KEYS AND DEFORMERS
  472. # easiest way to do it is to eval the depsgraph
  473. # TODO: try and get it without depsgraph update, since that may be (very) slow
  474. sk_m = sk_ob.data#data.meshes.new_from_object(sk_ob, preserve_all_data_layers=True, depsgraph=dg)
  475. for j in range(len(m.vertices)):
  476. sk.data[j].co = sk_m.vertices[j].co # assume they match
  477. # data.meshes.remove(sk_m)
  478. sk.vertex_group = vg
  479. sk.slider_min = -10
  480. sk.slider_max = 10
  481. keys[mt_name]=sk
  482. props_sockets[mt_name]= ("Value."+str(i).zfill(3), 1.0)
  483. for i, t in enumerate(targets):
  484. mt_node = t.links[0].from_node; sk_ob = mt_node.GetxForm().bGetObject()
  485. if sk_ob is None: continue
  486. if rel := mt_node.parameters["Morph Target"]["relative_shape"]:
  487. sk = keys.get(mt_name)
  488. sk.relative_key = keys.get(rel)
  489. self.bObject = sk.id_data
  490. evaluate_sockets(self, sk.id_data, props_sockets)
  491. finish_drivers(self)
  492. prWhite(f"Initializing morph target took {time() -start_time} seconds")
  493. def bFinalize(self, bContext=None):
  494. prGreen(f"Executing Morph Deform node {self}")
  495. # if there is a not a prior deformer then there should be an option to use plain 'ol shape keys
  496. # GN is always desirable as an option though because it can be baked & many other reasons
  497. use_shape_keys = self.evaluate_input("Use Shape Key")
  498. if use_shape_keys: # check and see if we can.
  499. if self.inputs.get("Deformer"): # I guess this isn't available in some node group contexts... bad. FIXME
  500. if (links := self.inputs["Deformer"].links):
  501. if not links[0].from_node.parameters.get("Use Shape Key"):
  502. use_shape_keys = False
  503. elif links[0].from_node.parameters.get("Use Shape Key") == False:
  504. use_shape_keys = False
  505. self.parameters["Use Shape Key"] = use_shape_keys
  506. if use_shape_keys:
  507. self.gen_shape_key(bContext)
  508. else:
  509. self.gen_morph_target_modifier(bContext)