deformer_nodes.py 36 KB

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