deformer_containers.py 26 KB

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