deformer_nodes.py 36 KB

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