deformer_nodes.py 38 KB

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