deformer_nodes.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. from .utilities.node_common import *
  2. from .xForm_nodes import xFormGeometryObject, xFormObjectInstance
  3. from .misc_nodes import InputExistingGeometryObject
  4. from .base_definitions import MantisNode
  5. from .mantis_dataclasses import MantisSocketTemplate
  6. from .utilities.utilities import (prRed, prGreen, prPurple, prWhite, prOrange,
  7. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  8. wrapOrange,)
  9. from .deformer_socket_templates import *
  10. from bpy.types import NodeTree
  11. def TellClasses():
  12. return [
  13. DeformerArmature,
  14. DeformerHook,
  15. DeformerMorphTarget,
  16. DeformerMorphTargetDeform,
  17. DeformerSurfaceDeform,
  18. DeformerMeshDeform,
  19. DeformerLatticeDeform,
  20. DeformerSmoothCorrectiveDeform,
  21. ]
  22. # object instance probably can't use the deformer but it doesn't hurt to try.
  23. deformable_types= (xFormGeometryObject, InputExistingGeometryObject, xFormObjectInstance)
  24. def trace_xForm_back(mantis_node, socket):
  25. if (trace := trace_single_line(mantis_node, socket)[0] ) :
  26. for i in range(len(trace)): # have to look in reverse, actually
  27. if ( isinstance(trace[ i ], deformable_types ) ):
  28. return trace[ i ].bGetObject()
  29. raise GraphError(wrapRed(f"No other object found for {mantis_node}."))
  30. class MantisDeformerNode(MantisNode):
  31. node_type = 'LINK'
  32. __slots__ = ()
  33. def __init__(self, signature : tuple,
  34. base_tree : NodeTree,
  35. socket_templates : list[MantisSocketTemplate]=[]):
  36. super().__init__(signature, base_tree, socket_templates,
  37. additional_parameters= {"Name":None})
  38. self.prepared = True
  39. self.bObject=[]
  40. # we need evaluate_input to have the same behaviour as links.
  41. def evaluate_input(self, input_name, index=0):
  42. if (input_name in ['Target', 'Object', 'Hook Target']):
  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. def GetxForm(mantis_node, output_name="Deformer"):
  50. break_condition= lambda node : node.__class__ in deformable_types
  51. xforms = trace_line_up_branching(mantis_node, output_name, break_condition)
  52. return_me=[]
  53. for xf in xforms:
  54. if xf.node_type != 'XFORM':
  55. continue
  56. if xf in return_me:
  57. continue
  58. return_me.append(xf)
  59. return return_me
  60. def reset_execution(self):
  61. super().reset_execution()
  62. self.bObject=[]; self.prepared=True
  63. def fill_parameters(self, ui_node=None):
  64. super().fill_parameters(ui_node)
  65. self.parameters["Name"] = ui_node.label if ui_node.label else ui_node.name
  66. def standard_modifier_bind(self, bContext=None, operator=None):
  67. for d in self.bObject:
  68. # we'll only bind it if it is un-muted.
  69. if self.evaluate_input("Enable in Viewport") == False:
  70. continue
  71. from .utilities.utilities import bind_modifier_operator
  72. bind_modifier_operator(d, operator)
  73. class DeformerArmature(MantisDeformerNode):
  74. '''A node representing an armature deformer'''
  75. __slots__ = ()
  76. socket_templates = DeformArmatureSockets
  77. def GetxForm(self, socket="Deformer"):
  78. if socket == "Deformer":
  79. return super().GetxForm()
  80. else:
  81. trace_xForm_back(self, socket)
  82. # DUPLICATED FROM xForm_nodes::xFormBone
  83. # DEDUP HACK HACK HACK HACK HACK
  84. def bGetParentArmature(self):
  85. from .xForm_nodes import xFormArmature
  86. from .misc_nodes import InputExistingGeometryObject
  87. from bpy.types import Object
  88. if (trace := trace_single_line(self, "Armature Object")[0] ) :
  89. for i in range(len(trace)):
  90. # have to look in reverse, actually
  91. if ( isinstance(trace[ i ], xFormArmature ) ):
  92. return trace[ i ].bGetObject()
  93. elif ( isinstance(trace[i], InputExistingGeometryObject)):
  94. if (ob := trace[i].bGetObject()).type == "ARMATURE":
  95. return ob
  96. raise RuntimeError(f"Cannot find armature for node {self}")
  97. return None
  98. #should do the trick...
  99. def bRelationshipPass(self, bContext = None,):
  100. self.executed = True
  101. def initialize_vgroups(self, xf):
  102. ob = xf.bGetObject()
  103. armOb = self.bGetParentArmature()
  104. for b in armOb.data.bones:
  105. if b.use_deform == False:
  106. continue
  107. vg = ob.vertex_groups.get(b.name)
  108. if not vg:
  109. vg = ob.vertex_groups.new(name=b.name)
  110. if ob.type == 'MESH':
  111. num_verts = len(ob.data.vertices)
  112. elif ob.type == 'LATTICE':
  113. num_verts = len(ob.data.points)
  114. vg.add(range(num_verts), 0, 'REPLACE')
  115. def copy_weights(self, xf):
  116. # we'll use modifiers for this, maybe use GN for it in the future tho
  117. import bpy
  118. ob = xf.bGetObject()
  119. try:
  120. copy_from = self.GetxForm(socket="Copy Skin Weights From")
  121. except GraphError:
  122. copy_from = None
  123. prRed(f"No object found for copying weights in {self}, continuing anyway.")
  124. m = ob.modifiers.new(type="DATA_TRANSFER", name="Mantis_temp_data_transfer")
  125. m.object = None; m.use_vert_data = True
  126. m.data_types_verts = {'VGROUP_WEIGHTS'}
  127. m.vert_mapping = 'POLYINTERP_NEAREST'
  128. m.layers_vgroup_select_src = 'ALL'
  129. m.layers_vgroup_select_dst = 'NAME'
  130. m.object = copy_from
  131. # m.use_object_transform = False # testing reveals that this is undesirable - since the objects may not have their transforms applied.
  132. ob.modifiers.move(len(ob.modifiers)-1, 0)
  133. # ob.data = ob.data.copy()
  134. if False: #MAYBE the mouse needs to be in the 3D viewport, no idea how to set this in an override
  135. # TODO: figure out how to apply this, context is incorrect because armature is still in pose mode
  136. original_active = bpy.context.active_object
  137. original_mode = original_active.mode
  138. bpy.ops.object.mode_set(mode='OBJECT')
  139. with bpy.context.temp_override(**{'active_object':ob, 'selected_objects':[ob, copy_from]}):
  140. # bpy.ops.object.datalayout_transfer(modifier=m.name) # note: this operator is used by the modifier or stand-alone in the UI
  141. # the poll for this operator is defined in blender/source/blender/editors/object/object_data_transfer.cc
  142. # and blender/source/blender/editors/object/object_modifier.cc
  143. # bpy.ops.object.modifier_apply(modifier=m.name, single_user=True)
  144. bpy.ops.object.datalayout_transfer(data_type='VGROUP_WEIGHTS')
  145. bpy.ops.object.data_transfer(data_type='VGROUP_WEIGHTS')
  146. bpy.ops.object.mode_set(mode=original_mode)
  147. def do_automatic_skinning_mesh(self, ob, xf, bContext):
  148. # This is bad and leads to somewhat unpredictable
  149. # behaviour, e.g. what object will be selected? What mode?
  150. # also bpy.ops is ugly and prone to error when used in
  151. # scripts. I don't intend to use bpy.ops when I can avoid it.
  152. import bpy
  153. self.initialize_vgroups(xf)
  154. armOb = self.bGetParentArmature()
  155. armOb.data.pose_position = 'REST'
  156. bContext.view_layer.depsgraph.update()
  157. deform_bones = []
  158. for pb in armOb.pose.bones:
  159. if pb.bone.use_deform == True:
  160. deform_bones.append(pb)
  161. if not deform_bones:
  162. prPurple("Warning: No deform bones in armature. Cancelling.")
  163. return
  164. context_override = {
  165. 'active_object':ob,
  166. 'selected_objects':[ob, armOb],
  167. 'active_pose_bone':deform_bones[0],
  168. 'selected_pose_bones':deform_bones,}
  169. from .utilities.utilities import set_bone_selection
  170. for pb in armOb.pose.bones:
  171. set_bone_selection(pose_bone=pb, selection_state=True)
  172. with bContext.temp_override(**context_override):
  173. bpy.ops.paint.weight_paint_toggle()
  174. bpy.ops.paint.weight_from_bones(type='AUTOMATIC')
  175. bpy.ops.paint.weight_paint_toggle()
  176. for pb in armOb.pose.bones:
  177. set_bone_selection(pose_bone=pb, selection_state=False)
  178. armOb.data.pose_position = 'POSE'
  179. # TODO: modify Blender to make this available as a Python API function.
  180. def do_automatic_skinning_lattice(self, ob, xf, bContext):
  181. # Temporarily, I am making a very simple and ugly automatic skinning algo for lattice points
  182. import bpy
  183. from mathutils.geometry import intersect_point_line
  184. self.initialize_vgroups(xf)
  185. armOb = self.bGetParentArmature()
  186. armOb.data.pose_position = 'REST'
  187. bContext.view_layer.depsgraph.update()
  188. deform_bones = []
  189. for pb in armOb.pose.bones:
  190. if pb.bone.use_deform == True: deform_bones.append(pb)
  191. # How this works:
  192. # - Calculates the weights based on proximity and angle
  193. # - we'll make a vector of the point and the nearest point on the bone
  194. # - dot (point_displacement, bone_y_axis) to get the angle
  195. # - weight the bone's value by this dot product and distance
  196. # - distance should prevail when both bones are within the angle
  197. mat = ob.matrix_world; mat_arm = armOb.matrix_world
  198. for p_index, p in enumerate(ob.data.points):
  199. loc = mat @ p.co_deform # co_deform is the position in edit mode
  200. pt_distance, pt_dot = {}, {}
  201. for b in deform_bones:
  202. bone_vec = ((mat_arm @ b.tail) - (mat_arm @ b.head)).normalized()
  203. nearest_point_on_bone, factor = intersect_point_line(
  204. loc, mat_arm @ b.head, mat_arm @ b.tail) # 0 is point, 1 is factor
  205. if factor > 1.0: nearest_point_on_bone = mat_arm @ b.tail
  206. if factor < 0.0: nearest_point_on_bone = mat_arm @ b.head
  207. point_vec = nearest_point_on_bone - loc
  208. distance = point_vec.length_squared # no need to sqrt, this is faster and
  209. # the quadratic falloff is better than linear falloff.
  210. dot = 1-abs(point_vec.normalized().dot(bone_vec))
  211. # we want to weight zero at 1.0 so that it favors points in its "envelope"
  212. pt_distance[b.name]=distance; pt_dot[b.name] = dot
  213. # now we can assign weights
  214. distance_pairs = [(k,v) for k,v in pt_distance.items()]
  215. distance_pairs.sort(key = lambda a : a[1])
  216. i=0; max_distance = 0.0; near_enough_bones = []
  217. while (i < 4): # TODO: limit-total should be exposed to the user.
  218. if i+1 > len(distance_pairs): break # in case there are fewer than 4 deform bones
  219. near_enough_bones.append(distance_pairs[i][0])
  220. if distance_pairs[i][1] > max_distance: max_distance = distance_pairs[i][1]
  221. i+=1
  222. max_pre_normalized_weight = 0.0
  223. weights = {}
  224. if max_distance == 0.0: max_distance = 1.0
  225. for b_name in near_enough_bones:
  226. w = 1.0
  227. if pt_distance[b_name] > 0:
  228. w*= 1/(pt_distance[b_name]/max_distance) # weight by inverse-distance
  229. w*= pt_dot[b_name]**4 # NOTE: **4 is arbitrary but feels good to me.
  230. if w > max_pre_normalized_weight: max_pre_normalized_weight = w
  231. weights[b_name] = w
  232. if max_pre_normalized_weight == 0.0: max_pre_normalized_weight = 1.0
  233. for b_name in near_enough_bones:
  234. vg = ob.vertex_groups.get(b_name)
  235. vg.add([p_index], weights[b_name]/max_pre_normalized_weight, 'REPLACE')
  236. armOb.data.pose_position = 'POSE'
  237. def bFinalize(self, bContext=None):
  238. prGreen("Executing Armature Deform Node")
  239. mod_name = self.evaluate_input("Name")
  240. for xf in self.GetxForm():
  241. ob = xf.bGetObject()
  242. d = ob.modifiers.new(mod_name, type='ARMATURE')
  243. if d is None:
  244. raise RuntimeError(f"Modifier was not created in node {self} -- the object is invalid.")
  245. self.bObject.append(d)
  246. d.object = self.bGetParentArmature()
  247. props_sockets = self.property_socket_map
  248. evaluate_sockets(self, d, props_sockets)
  249. #
  250. if (skin_method := self.evaluate_input("Skinning Method")) == "AUTOMATIC_HEAT":
  251. match ob.type:
  252. case "MESH":
  253. self.do_automatic_skinning_mesh(ob, xf, bContext)
  254. case "LATTICE":
  255. self.do_automatic_skinning_lattice(ob, xf, bContext)
  256. elif skin_method == "COPY_FROM_OBJECT":
  257. self.initialize_vgroups(xf)
  258. self.copy_weights(xf)
  259. # elif skin_method == "EXISTING_GROUPS":
  260. # pass
  261. class DeformerHook(MantisDeformerNode):
  262. '''A node representing a hook deformer'''
  263. __slots__ = ()
  264. socket_templates = HookSockets
  265. def driver_for_radius(self, object, hook, index, influence, bezier=True):
  266. """ Creates a driver to control the radius of a curve point with the hook."""
  267. from bpy.types import Bone, PoseBone
  268. var_template = {"owner":hook,
  269. "name":"a",
  270. "type":"TRANSFORMS",
  271. "space":'WORLD_SPACE',
  272. "channel":'SCALE_X',}
  273. var1_template = {"owner":hook.id_data,
  274. "name":"b",
  275. "type":"TRANSFORMS",
  276. "space":'WORLD_SPACE',
  277. "channel":'SCALE_X',}
  278. keys_template = [{"co":(0,0),
  279. "interpolation": "LINEAR",
  280. "type":"KEYFRAME",},
  281. {"co":(1,influence),
  282. "interpolation": "LINEAR",
  283. "type":"KEYFRAME",},]
  284. if bezier:
  285. owner=object.data.splines[0].bezier_points
  286. else:
  287. owner=object.data.splines[0].points
  288. driver = {
  289. "owner":owner[index],
  290. "prop":"radius",
  291. "ind":-1,
  292. "extrapolation":"LINEAR",
  293. "type":"AVERAGE",
  294. "vars":[],
  295. "keys":keys_template,
  296. }
  297. if isinstance(hook, (Bone, PoseBone)):
  298. driver['type']='SCRIPTED'
  299. driver['expression']="(((1/b)*a)+((1/b_001)*a_001)+((1/b_002)*a_002))/3"
  300. from .utilities.drivers import CreateDrivers
  301. axes='XYZ'
  302. for i in range(3):
  303. suffix = "" if i == 0 else f"_{i:03d}" # explicit names -- 5.2 no longer uniquifies duplicates
  304. var = var_template.copy()
  305. var["name"]="a"+suffix
  306. var["channel"]="SCALE_"+axes[i]
  307. driver["vars"].append(var)
  308. if isinstance(hook, (Bone, PoseBone)):
  309. var1=var1_template.copy()
  310. var1['name']="b"+suffix
  311. var1['channel']="SCALE_"+axes[i]
  312. driver['vars'].append(var1)
  313. CreateDrivers([driver])
  314. def bRelationshipPass(self, bContext = None,):
  315. self.executed = True
  316. def bFinalize(self, bContext=None):
  317. from bpy.types import Bone, PoseBone, Object
  318. prGreen(f"Executing Hook Deform Node: {self}")
  319. mod_name = self.evaluate_input("Name")
  320. affect_radius = self.evaluate_input("Affect Curve Radius")
  321. auto_bezier = self.evaluate_input("Auto-Bezier")
  322. target_node = self.evaluate_input('Hook Target')
  323. target = target_node.bGetObject(); subtarget = ""
  324. props_sockets = self.property_socket_map
  325. if isinstance(target, Bone) or isinstance(target, PoseBone):
  326. subtarget = target.name; target = target.id_data
  327. for xf in self.GetxForm():
  328. ob=xf.bGetObject()
  329. if ob.type == 'CURVE':
  330. spline_index = self.evaluate_input("Spline Index")
  331. from .utilities.utilities import get_extracted_spline_object
  332. ob = get_extracted_spline_object(ob, spline_index, self.mContext)
  333. reuse = False
  334. for m in ob.modifiers:
  335. if m.type == 'HOOK' and m.object == target and m.subtarget == subtarget:
  336. if self.evaluate_input("Influence") != m.strength:
  337. continue # make a new modifier so they can have different strengths
  338. if ob.animation_data: # this can be None
  339. drivers = ob.animation_data.drivers
  340. for k in props_sockets.keys():
  341. if driver := drivers.find(k):
  342. # TODO: I should check to see if the drivers are the same...
  343. break # continue searching for an equivalent modifier
  344. else: # There was no driver - use this one.
  345. d = m; reuse = True; break
  346. else: # use this one, there can't be drivers without animation_data.
  347. d = m; reuse = True; break
  348. else:
  349. d = ob.modifiers.new(mod_name, type='HOOK')
  350. if d is None:
  351. raise RuntimeError(f"Modifier was not created in node {self} -- the object is invalid.")
  352. self.bObject.append(d)
  353. self.get_target_and_subtarget(d, input_name="Hook Target")
  354. vertices_used=[]
  355. if reuse: # Get the verts in the list... filter out all the unneeded 0's
  356. vertices_used = list(d.vertex_indices)
  357. include_0 = 0 in vertices_used
  358. vertices_used = list(filter(lambda a : a != 0, vertices_used))
  359. if include_0: vertices_used.append(0)
  360. # now we add the selected vertex to the list, too
  361. vertex = self.evaluate_input("Point Index")
  362. if ob.type == 'CURVE' and ob.data.splines[0].type == 'BEZIER' and auto_bezier:
  363. if affect_radius:
  364. self.driver_for_radius(ob, target_node.bGetObject(), vertex, d.strength)
  365. vertex*=3
  366. vertices_used.extend([vertex, vertex+1, vertex+2])
  367. else:
  368. vertices_used.append(vertex)
  369. # if we have a curve and it is NOT using auto-bezier for the verts..
  370. if ob.type == 'CURVE' and ob.data.splines[0].type == 'BEZIER' and affect_radius and not auto_bezier:
  371. print (f"WARN: {self}: \"Affect Radius\" may not behave as expected"
  372. " when used on Bezier curves without Auto-Bezier")
  373. #bezier point starts at 1, and then every third vert, so 4, 7, 10...
  374. if vertex%3==1:
  375. self.driver_for_radius(ob, target_node.bGetObject(), vertex, d.strength)
  376. if ob.type == 'CURVE' and ob.data.splines[0].type != 'BEZIER' and \
  377. affect_radius:
  378. self.driver_for_radius(ob, target_node.bGetObject(), vertex, d.strength, bezier=False)
  379. d.vertex_indices_set(vertices_used)
  380. evaluate_sockets(self, d, props_sockets)
  381. finish_drivers(self)
  382. # todo: this node should be able to take many indices in the future.
  383. # Also: I have a Geometry Nodes implementation of this I can use... maybe...
  384. class DeformerMorphTarget(MantisDeformerNode):
  385. '''A node representing an armature deformer'''
  386. __slots__ = ()
  387. socket_templates = MorphTargetSockets
  388. def GetxForm(self, trace_input="Object"):
  389. trace = trace_single_line(self, trace_input)
  390. for node in trace[0]:
  391. if (isinstance(node, deformable_types)):
  392. return node
  393. raise GraphError("%s is not connected to an upstream xForm" % self)
  394. def bRelationshipPass(self, bContext = None,):
  395. prGreen("Executing Morph Target Node")
  396. ob = None; relative = None
  397. # do NOT check if the object exists here. Just let the next node deal with that.
  398. try:
  399. ob = self.GetxForm().bGetObject().name
  400. except Exception as e: # this will and should throw an error if it fails
  401. ob = self.GetxForm().evaluate_input("Name")
  402. if self.inputs["Relative to"].is_linked:
  403. try:
  404. relative = self.GetxForm("Relative to").bGetObject().name
  405. except Exception as e: # same here
  406. prRed(f"Execution failed at {self}: no relative object found for morph target, despite link existing.")
  407. raise e
  408. vg = self.evaluate_input("Vertex Group") if self.evaluate_input("Vertex Group") else "" # just make sure it is a string
  409. mt={"object":ob, "vertex_group":vg, "relative_shape":relative}
  410. self.parameters["Morph Target"] = mt
  411. self.parameters["Name"] = ob # this is redundant but it's OK since accessing the mt is tedious
  412. self.executed = True
  413. class DeformerMorphTargetDeform(MantisDeformerNode):
  414. '''A node representing an armature deformer'''
  415. __slots__ = ()
  416. socket_templates = MorphTargetDeformSockets
  417. def __init__(self, signature, base_tree):
  418. super().__init__(signature, base_tree, self.socket_templates)
  419. self.executed = True
  420. setup_custom_property_inputs_outputs(self)
  421. def reset_execution(self):
  422. return super().reset_execution()
  423. self.executed=True
  424. def gen_morph_target_modifier(self, xf, context):
  425. # first let's see if this is a no-op
  426. targets = []
  427. for k,v in self.inputs.items():
  428. if "Target" in k:
  429. targets.append(v)
  430. if not targets:
  431. return # nothing to do here.
  432. # at this point we make the node tree
  433. from .utilities.geometry_node_graphgen import gen_morph_target_nodes
  434. m, props_sockets = gen_morph_target_nodes(
  435. self.evaluate_input("Name"),
  436. xf.bGetObject(),
  437. targets,
  438. context,
  439. use_offset=self.evaluate_input("Use Offset"))
  440. self.bObject.append(m)
  441. evaluate_sockets(self, m, props_sockets)
  442. finish_drivers(self)
  443. def gen_shape_key_lattice(self, xf, context):
  444. # first check if we need to do anything
  445. targets = []
  446. for k,v in self.inputs.items():
  447. if "Target" in k:
  448. targets.append(v)
  449. if not targets:
  450. return # nothing to do here
  451. # TODO: deduplicate the code above here
  452. from time import time
  453. start_time = time()
  454. from bpy import data
  455. ob = xf.bGetObject()
  456. dg = context.view_layer.depsgraph
  457. dg.update()
  458. if xf.has_shape_keys == False:
  459. lat = ob.data.copy()
  460. ob.data = lat
  461. ob.add_rest_position_attribute = True
  462. ob.shape_key_clear()
  463. ob.shape_key_add(name='Basis', from_mix=False)
  464. else:
  465. lat = ob.data
  466. xf.has_shape_keys = True
  467. # first make a basis shape key
  468. keys, props_sockets, ={}, {}
  469. for i, t in enumerate(targets):
  470. mt_node = t.links[0].from_node; sk_ob = mt_node.GetxForm().bGetObject()
  471. if sk_ob is None:
  472. sk_ob = data.objects.new(mt_node.evaluate_input("Name"), data.meshes.new_from_object(ob))
  473. context.collection.objects.link(sk_ob)
  474. prOrange(f"WARN: no object found for f{mt_node}; creating duplicate of current object ")
  475. sk_ob = dg.id_eval_get(sk_ob)
  476. mt_name = sk_ob.name
  477. vg = mt_node.parameters["Morph Target"]["vertex_group"]
  478. if vg: mt_name = mt_name+"."+vg
  479. sk = ob.shape_key_add(name=mt_name, from_mix=False)
  480. # the shapekey data is absolute point data for each vertex, in order, very simple
  481. # SERIOUSLY IMPORTANT:
  482. # use the current position of the vertex AFTER SHAPE KEYS AND DEFORMERS
  483. # easiest way to do it is to eval the depsgraph
  484. # TODO: try and get it without depsgraph update, since that may be (very) slow
  485. sk_m = sk_ob.data#data.meshes.new_from_object(sk_ob, preserve_all_data_layers=True, depsgraph=dg)
  486. for j in range(len(m.vertices)):
  487. sk.data[j].co = sk_m.vertices[j].co # assume they match
  488. # data.meshes.remove(sk_m)
  489. sk.vertex_group = vg
  490. sk.slider_min = -10
  491. sk.slider_max = 10
  492. keys[mt_name]=sk
  493. from .mantis_dataclasses import MantisSocketFiller
  494. socket_value = MantisSocketFiller(
  495. property_name=mt_name,
  496. socket_name = "Value."+str(i).zfill(3),
  497. default_value= 1.0,
  498. )
  499. props_sockets[mt_name]= socket_value
  500. for i, t in enumerate(targets):
  501. mt_node = t.links[0].from_node; sk_ob = mt_node.GetxForm().bGetObject()
  502. if sk_ob is None: continue
  503. if rel := mt_node.parameters["Morph Target"]["relative_shape"]:
  504. sk = keys.get(mt_name)
  505. sk.relative_key = keys.get(rel)
  506. self.bObject.append(sk.id_data)
  507. evaluate_sockets(self, sk.id_data, props_sockets)
  508. finish_drivers(self)
  509. prWhite(f"Initializing morph target took {time() -start_time} seconds")
  510. def gen_shape_key(self, xf, context):
  511. # TODO: make this a feature of the node definition that appears only when there are no prior deformers - and shows a warning!
  512. # 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.
  513. # there are a number of things I need to fix here
  514. # - reuse shape keys if possible
  515. # - figure out how to make this a lot faster
  516. # - edit the xForm stuff to delete drivers from shape key ID's, since they belong to the Key, not the Object.
  517. # first check if we need to do anythign
  518. targets = []
  519. for k,v in self.inputs.items():
  520. if "Target" in k:
  521. targets.append(v)
  522. if not targets:
  523. return # nothing to do here
  524. from time import time
  525. start_time = time()
  526. from bpy import data
  527. ob = xf.bGetObject()
  528. dg = context.view_layer.depsgraph
  529. dg.update()
  530. if xf.has_shape_keys == False:
  531. match ob.type:
  532. case 'MESH':
  533. ob_data = data.meshes.new_from_object(ob, preserve_all_data_layers=True, depsgraph=dg)
  534. case 'LATTICE':
  535. ob_data = ob.data.copy()
  536. ob.data = ob_data
  537. ob.add_rest_position_attribute = True
  538. ob.shape_key_clear()
  539. ob.shape_key_add(name='Basis', from_mix=False)
  540. else:
  541. ob_data = ob.data
  542. xf.has_shape_keys = True
  543. # using the built-in shapekey feature is actually a lot harder in terms of programming because I need...
  544. # min/max, as it is just not a feature of the GN version
  545. # to carry info from the morph target node regarding relative shapes and vertex groups and all that
  546. # the drivers may be more difficult to apply, too.
  547. # hafta make new geometry for the object and add shape keys and all that
  548. # the benefit to all this being exporting to game engines via .fbx
  549. # first make a basis shape key
  550. keys={}
  551. props_sockets={}
  552. for i, t in enumerate(targets):
  553. mt_node = t.links[0].from_node; sk_ob = mt_node.GetxForm().bGetObject()
  554. if sk_ob is None:
  555. sk_ob = data.objects.new(mt_node.evaluate_input("Name"), data.meshes.new_from_object(ob))
  556. context.collection.objects.link(sk_ob)
  557. prOrange(f"WARN: no object found for f{mt_node}; creating duplicate of current object ")
  558. sk_ob = dg.id_eval_get(sk_ob)
  559. mt_name = sk_ob.name
  560. vg = mt_node.parameters["Morph Target"]["vertex_group"]
  561. if vg: mt_name = mt_name+"."+vg
  562. sk = ob.shape_key_add(name=mt_name, from_mix=False)
  563. # the shapekey data is absolute point data for each vertex, in order, very simple
  564. # SERIOUSLY IMPORTANT:
  565. # use the current position of the vertex AFTER SHAPE KEYS AND DEFORMERS
  566. # easiest way to do it is to eval the depsgraph
  567. # TODO: try and get it without depsgraph update, since that may be (very) slow
  568. sk_m = sk_ob.data#data.meshes.new_from_object(sk_ob, preserve_all_data_layers=True, depsgraph=dg)
  569. match ob.type:
  570. case 'MESH':
  571. for j in range(len(ob_data.vertices)):
  572. sk.data[j].co = sk_m.vertices[j].co # assume they match
  573. case 'LATTICE':
  574. for j in range(len(ob.data.points)):
  575. sk.data[j].co = sk_m.points[j].co_deform
  576. # data.meshes.remove(sk_m)
  577. sk.vertex_group = vg
  578. sk.slider_min = -10
  579. sk.slider_max = 10
  580. keys[mt_name]=sk
  581. from .mantis_dataclasses import MantisSocketFiller
  582. socket_value = MantisSocketFiller(
  583. property_name=mt_name,
  584. socket_name = "Value."+str(i).zfill(3),
  585. default_value= 1.0,
  586. )
  587. props_sockets[mt_name]= socket_value
  588. for i, t in enumerate(targets):
  589. mt_node = t.links[0].from_node; sk_ob = mt_node.GetxForm().bGetObject()
  590. if sk_ob is None: continue
  591. if rel := mt_node.parameters["Morph Target"]["relative_shape"]:
  592. sk = keys.get(mt_name)
  593. sk.relative_key = keys.get(rel)
  594. self.bObject.append(sk.id_data)
  595. evaluate_sockets(self, sk.id_data, props_sockets)
  596. finish_drivers(self)
  597. prWhite(f"Initializing morph target took {time() -start_time} seconds")
  598. def bFinalize(self, bContext=None):
  599. prGreen(f"Executing Morph Deform node {self}")
  600. use_shape_keys = self.evaluate_input("Use Shape Key")
  601. # if there is a not a prior deformer then there should be an option to use plain 'ol shape keys
  602. # GN is always desirable as an option though because it can be baked & many other reasons
  603. if use_shape_keys: # check and see if we can.
  604. if self.inputs.get("Deformer"): # I guess this isn't available in some node group contexts... bad. FIXME
  605. if (links := self.inputs["Deformer"].links):
  606. if not links[0].from_node.parameters.get("Use Shape Key"):
  607. use_shape_keys = False
  608. elif links[0].from_node.parameters.get("Use Shape Key") == False:
  609. use_shape_keys = False
  610. self.parameters["Use Shape Key"] = use_shape_keys
  611. for xf in self.GetxForm():
  612. # Lattice objects do not support geometry nodes at this time.
  613. ob = xf.bGetObject()
  614. if ob and ob.type == 'LATTICE':
  615. if not use_shape_keys:
  616. raise NotImplementedError("Blender does not support Geometry Nodes for Lattices. "
  617. "Enable 'Shape Key' and execute again.")
  618. self.gen_shape_key(xf, bContext)
  619. elif use_shape_keys:
  620. self.gen_shape_key(xf, bContext)
  621. else:
  622. self.gen_morph_target_modifier(xf, bContext)
  623. class DeformerSurfaceDeform(MantisDeformerNode):
  624. '''A node representing an surface deform modifier'''
  625. __slots__ = ()
  626. socket_templates = SurfaceDeformSockets
  627. def GetxForm(self, socket="Deformer"):
  628. if socket == "Deformer":
  629. return super().GetxForm()
  630. else:
  631. trace_xForm_back(self, socket)
  632. def bRelationshipPass(self, bContext = None,):
  633. self.executed = True
  634. def bFinalize(self, bContext=None):
  635. prGreen("Executing Surface Deform Node")
  636. mod_name = self.evaluate_input("Name")
  637. for xf in self.GetxForm():
  638. ob = xf.bGetObject()
  639. d = ob.modifiers.new(mod_name, type='SURFACE_DEFORM')
  640. if d is None:
  641. raise RuntimeError(f"Modifier was not created in node {self} -- the object is invalid.")
  642. self.bObject.append(d)
  643. self.get_target_and_subtarget(d, input_name="Target")
  644. props_sockets = self.property_socket_map
  645. evaluate_sockets(self, d, props_sockets)
  646. def bModifierApply(self, bContext=None):
  647. from bpy import ops
  648. standard_modifier_bind(self, bContext, ops.object.surfacedeform_bind)
  649. class DeformerMeshDeform(MantisDeformerNode):
  650. '''A node representing a mesh deform modifier'''
  651. __slots__ = ()
  652. socket_templates = MeshDeformSockets
  653. def GetxForm(self, socket="Deformer"):
  654. if socket == "Deformer":
  655. return super().GetxForm()
  656. else:
  657. trace_xForm_back(self, socket)
  658. def bRelationshipPass(self, bContext = None,):
  659. self.executed = True
  660. def bFinalize(self, bContext=None):
  661. prGreen("Executing Mesh Deform Node")
  662. mod_name = self.evaluate_input("Name")
  663. for xf in self.GetxForm():
  664. ob = xf.bGetObject()
  665. d = ob.modifiers.new(mod_name, type='MESH_DEFORM')
  666. if d is None:
  667. raise RuntimeError(f"Modifier was not created in node {self} -- the object is invalid.")
  668. self.bObject.append(d)
  669. self.get_target_and_subtarget(d, input_name="Object")
  670. props_sockets = self.property_socket_map
  671. evaluate_sockets(self, d, props_sockets)
  672. def bModifierApply(self, bContext=None):
  673. from bpy import ops
  674. standard_modifier_bind(self, bContext, ops.object.meshdeform_bind)
  675. class DeformerLatticeDeform(MantisDeformerNode):
  676. '''A node representing a lattice deform modifier'''
  677. __slots__ = ()
  678. socket_templates = LatticeDeformSockets
  679. def GetxForm(self, socket="Deformer"):
  680. if socket == "Deformer":
  681. return super().GetxForm()
  682. else:
  683. trace_xForm_back(self, socket)
  684. def bRelationshipPass(self, bContext = None,):
  685. self.executed = True
  686. def bFinalize(self, bContext=None):
  687. prGreen("Executing Lattice Deform Node")
  688. mod_name = self.evaluate_input("Name")
  689. for xf in self.GetxForm():
  690. ob = xf.bGetObject()
  691. d = ob.modifiers.new(mod_name, type='LATTICE')
  692. if d is None:
  693. raise RuntimeError(f"Modifier was not created in node {self} -- the object is invalid.")
  694. self.bObject.append(d)
  695. self.get_target_and_subtarget(d, input_name="Object")
  696. props_sockets = self.property_socket_map
  697. evaluate_sockets(self, d, props_sockets)
  698. class DeformerSmoothCorrectiveDeform(MantisDeformerNode):
  699. '''A node representing a corrective smooth deform modifier'''
  700. __slots__ = ()
  701. socket_templates = SmoothDeformSockets
  702. def GetxForm(self, socket="Deformer"):
  703. if socket == "Deformer":
  704. return super().GetxForm()
  705. else:
  706. trace_xForm_back(self, socket)
  707. def bRelationshipPass(self, bContext = None,):
  708. self.executed = True
  709. def bFinalize(self, bContext=None):
  710. prGreen("Executing Smooth Deform Node")
  711. mod_name = self.evaluate_input("Name")
  712. for xf in self.GetxForm():
  713. ob = xf.bGetObject()
  714. d = ob.modifiers.new(mod_name, type='CORRECTIVE_SMOOTH')
  715. if d is None:
  716. raise RuntimeError(f"Modifier was not created in node {self} -- the object is invalid.")
  717. self.bObject.append(d)
  718. # self.get_target_and_subtarget(d, input_name="Object")
  719. props_sockets = self.property_socket_map
  720. evaluate_sockets(self, d, props_sockets)