link_nodes.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. from .utilities.node_common import *
  2. from bpy.types import Bone, NodeTree
  3. from .base_definitions import MantisNode, GraphError, FLOAT_EPSILON
  4. from .link_socket_templates import *
  5. def TellClasses():
  6. return [
  7. # special
  8. LinkInherit,
  9. # copy
  10. LinkCopyLocation,
  11. LinkCopyRotation,
  12. LinkCopyScale,
  13. LinkCopyTransforms,
  14. LinkTransformation,
  15. # limit
  16. LinkLimitLocation,
  17. LinkLimitRotation,
  18. LinkLimitScale,
  19. LinkLimitDistance,
  20. # tracking
  21. LinkStretchTo,
  22. LinkDampedTrack,
  23. LinkLockedTrack,
  24. LinkTrackTo,
  25. #misc
  26. LinkInheritConstraint,
  27. LinkArmature,
  28. # IK
  29. LinkInverseKinematics,
  30. LinkSplineIK,
  31. # stuff that snaps or limits a bone
  32. LinkFloor,
  33. LinkShrinkWrap,
  34. LinkGeometryAttribute,
  35. # Drivers
  36. LinkDrivenParameter,
  37. ]
  38. # In order to save time and give users a little more control, we'll cache
  39. # the IK Pole Vector solution for a given set of bone matrices
  40. IK_POLE_VECTOR_CACHE = {}
  41. def make_ik_pole_vector_cache_key(start_effector, end_effector, pole_location, knee_location):
  42. return frozenset({ tuple( start_effector[:]),
  43. tuple( end_effector[:]),
  44. tuple( pole_location[:]),
  45. tuple( knee_location[:]), })
  46. # set the name if it is available, otherwise just use the constraint's nice name
  47. set_constraint_name = lambda mantis_node : mantis_node.evaluate_input("Name") if mantis_node.evaluate_input("Name") else mantis_node.__class__.__name__
  48. class MantisLinkNode(MantisNode):
  49. __slots__ = ()
  50. node_type = 'LINK'
  51. passes=frozenset({'bRelationship', 'bTransform', 'bFinalize',})
  52. def __init__(self, signature : tuple,
  53. base_tree : NodeTree,):
  54. super().__init__(signature, base_tree, self.socket_templates,
  55. additional_parameters= {'Name':None})
  56. self.prepared = True; self.bObject=[]
  57. def bTransformPass(self, bContext=None):
  58. parent_xForm_info = get_parent_xForm_info(self, 'Input Relationship')
  59. self.parameters['Output Relationship'] = parent_xForm_info
  60. def evaluate_input(self, input_name, index=0):
  61. # should catch 'Target', 'Pole Target' and ArmatureConstraint targets, too
  62. if ('Target' in input_name) and input_name not in ["Target Space", "Use Target Z"]:
  63. socket = self.inputs.get(input_name)
  64. if socket.is_linked:
  65. node_line, _last_socket = trace_single_line(self, input_name, index)
  66. for other_node in node_line:
  67. if other_node.node_type == 'XFORM':
  68. return other_node
  69. return None
  70. else:
  71. return super().evaluate_input(input_name, index)
  72. def gen_property_socket_map(self) -> dict:
  73. if self.property_socket_map:
  74. props_sockets = self.property_socket_map.copy()
  75. else:
  76. props_sockets = super().gen_property_socket_map()
  77. if (os := self.inputs.get("Owner Space")) and os.is_connected:
  78. node_line, _last_socket = trace_single_line(self, "Owner Space")
  79. for other_node in node_line:
  80. if other_node.node_type == 'XFORM':
  81. del props_sockets['owner_space']; break
  82. if (ts := self.inputs.get("Target Space")) and ts.is_connected:
  83. node_line, _last_socket = trace_single_line(self, "Target Space")
  84. for other_node in node_line:
  85. if other_node.node_type == 'XFORM':
  86. del props_sockets['target_space']; break
  87. return props_sockets
  88. def set_custom_space(self):
  89. for c in self.bObject:
  90. if (os := self.inputs.get("Owner Space")) and os.is_connected:
  91. node_line, _last_socket = trace_single_line(self, "Owner Space")
  92. owner_space_target = None
  93. for other_node in node_line:
  94. if other_node.node_type == 'XFORM':
  95. owner_space_target = other_node; break
  96. if owner_space_target:
  97. c.owner_space='CUSTOM'
  98. xf = owner_space_target.bGetObject(mode="OBJECT")
  99. if isinstance(xf, Bone):
  100. c.space_object=owner_space_target.bGetParentArmature(); c.space_subtarget=xf.name
  101. else:
  102. c.space_object=xf
  103. if (ts := self.inputs.get("Target Space")) and ts.is_connected:
  104. node_line, _last_socket = trace_single_line(self, "Target Space")
  105. target_space_target = None
  106. for other_node in node_line:
  107. if other_node.node_type == 'XFORM':
  108. target_space_target = other_node; break
  109. if target_space_target:
  110. c.target_space='CUSTOM'
  111. xf = target_space_target.bGetObject(mode="OBJECT")
  112. if isinstance(xf, Bone):
  113. c.space_object=target_space_target.bGetParentArmature(); c.space_subtarget=xf.name
  114. else:
  115. c.space_object=xf
  116. def GetxForm(mantis_node, output_name="Output Relationship"):
  117. break_condition= lambda node : node.node_type=='XFORM'
  118. xforms = trace_line_up_branching(mantis_node, output_name, break_condition)
  119. return_me=[]
  120. for xf in xforms:
  121. if xf.node_type != 'XFORM':
  122. continue
  123. if xf in return_me:
  124. continue
  125. return_me.append(xf)
  126. return return_me
  127. def reset_execution(self):
  128. super().reset_execution()
  129. self.prepared = True; self.bObject = []
  130. def bFinalize(self, bContext=None):
  131. finish_drivers(self)
  132. def fill_parameters(self, ui_node=None):
  133. super().fill_parameters(ui_node)
  134. self.parameters["Name"] = ui_node.label if ui_node.label else ui_node.name
  135. #*#-------------------------------#++#-------------------------------#*#
  136. # L I N K N O D E S
  137. #*#-------------------------------#++#-------------------------------#*#
  138. class LinkInherit(MantisLinkNode):
  139. '''A node representing inheritance'''
  140. __slots__ = ()
  141. socket_templates = LinkInheritSockets
  142. def bTransformPass(self, bContext=None):
  143. parent_xForm_info = get_parent_xForm_info(self, 'Parent')
  144. self.parameters['Inheritance'] = parent_xForm_info
  145. self.executed = True
  146. def GetxForm(self):
  147. # I think this is only run in display update.
  148. trace = trace_single_line_up(self, "Inheritance")
  149. for node in trace[0]:
  150. if (node.node_type == 'XFORM'):
  151. return node
  152. raise GraphError("%s is not connected to a downstream xForm" % self)
  153. class LinkCopyLocation(MantisLinkNode):
  154. '''A node representing Copy Location'''
  155. __slots__ = ()
  156. socket_templates = LinkCopyLocationSockets
  157. def bRelationshipPass(self, context):
  158. prepare_parameters(self)
  159. for xf in self.GetxForm():
  160. c = xf.bGetObject().constraints.new('COPY_LOCATION')
  161. self.get_target_and_subtarget(c)
  162. print(wrapGreen("Creating ")+wrapWhite("Copy Location")+
  163. wrapGreen(" Constraint for bone: ") +
  164. wrapOrange(xf.bGetObject().name))
  165. if constraint_name := self.evaluate_input("Name"):
  166. c.name = constraint_name
  167. self.bObject.append(c)
  168. self.set_custom_space()
  169. props_sockets = self.gen_property_socket_map()
  170. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  171. self.executed = True
  172. class LinkCopyRotation(MantisLinkNode):
  173. '''A node representing Copy Rotation'''
  174. __slots__ = ()
  175. socket_templates = LinkCopyRotationSockets
  176. def bRelationshipPass(self, context):
  177. prepare_parameters(self)
  178. for xf in self.GetxForm():
  179. c = xf.bGetObject().constraints.new('COPY_ROTATION')
  180. self.get_target_and_subtarget(c)
  181. print(wrapGreen("Creating ")+wrapWhite("Copy Rotation")+
  182. wrapGreen(" Constraint for bone: ") +
  183. wrapOrange(xf.bGetObject().name))
  184. rotation_order = self.evaluate_input("RotationOrder")
  185. if ((rotation_order == 'QUATERNION') or (rotation_order == 'AXIS_ANGLE')):
  186. c.euler_order = 'AUTO'
  187. else:
  188. try:
  189. c.euler_order = rotation_order
  190. except TypeError: # it's a driver or incorrect
  191. c.euler_order = 'AUTO'
  192. if constraint_name := self.evaluate_input("Name"):
  193. c.name = constraint_name
  194. self.bObject.append(c)
  195. self.set_custom_space()
  196. props_sockets = self.gen_property_socket_map()
  197. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  198. self.executed = True
  199. class LinkCopyScale(MantisLinkNode):
  200. '''A node representing Copy Scale'''
  201. __slots__ = ()
  202. socket_templates = LinkCopyScaleSockets
  203. def bRelationshipPass(self, context):
  204. prepare_parameters(self)
  205. for xf in self.GetxForm():
  206. c = xf.bGetObject().constraints.new('COPY_SCALE')
  207. self.get_target_and_subtarget(c)
  208. print(wrapGreen("Creating ")+wrapWhite("Copy Scale")+
  209. wrapGreen(" Constraint for bone: ") +
  210. wrapOrange(xf.bGetObject().name))
  211. if constraint_name := self.evaluate_input("Name"):
  212. c.name = constraint_name
  213. self.bObject.append(c)
  214. self.set_custom_space()
  215. props_sockets = self.gen_property_socket_map()
  216. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  217. self.executed = True
  218. class LinkCopyTransforms(MantisLinkNode):
  219. '''A node representing Copy Transfoms'''
  220. __slots__ = ()
  221. socket_templates = LinkCopyTransformsSockets
  222. def bRelationshipPass(self, context):
  223. prepare_parameters(self)
  224. for xf in self.GetxForm():
  225. c = xf.bGetObject().constraints.new('COPY_TRANSFORMS')
  226. self.get_target_and_subtarget(c)
  227. print(wrapGreen("Creating ")+wrapWhite("Copy Transforms")+
  228. wrapGreen(" Constraint for bone: ") +
  229. wrapOrange(xf.bGetObject().name))
  230. if constraint_name := self.evaluate_input("Name"):
  231. c.name = constraint_name
  232. self.bObject.append(c)
  233. self.set_custom_space()
  234. props_sockets = self.gen_property_socket_map()
  235. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  236. self.executed = True
  237. class LinkTransformation(MantisLinkNode):
  238. '''A node representing Copy Transfoms'''
  239. __slots__ = ()
  240. socket_templates = LinkTransformationSockets
  241. def ui_modify_socket(self, ui_socket, socket_name=None):
  242. from_suffix, to_suffix = '', ''
  243. if self.evaluate_input("Map From") == 'ROTATION': from_suffix='_rot'
  244. elif self.evaluate_input("Map From") == 'SCALE': from_suffix='_scale'
  245. if self.evaluate_input("Map To") == 'ROTATION': to_suffix='_rot'
  246. elif self.evaluate_input("Map To") == 'SCALE': to_suffix='_scale'
  247. if ('To' in ui_socket.name or 'From' in ui_socket.name) and (from_suffix or to_suffix):
  248. for s_temp in self.socket_templates:
  249. if s_temp.name == ui_socket.name: break
  250. if 'from' in s_temp.blender_property:
  251. socket_name=s_temp.blender_property+from_suffix
  252. else:
  253. socket_name=s_temp.blender_property+to_suffix
  254. return self.update_socket_value(socket_name, ui_socket.default_value)
  255. return super().ui_modify_socket(ui_socket, socket_name)
  256. def bRelationshipPass(self, context):
  257. prepare_parameters(self)
  258. for xf in self.GetxForm():
  259. c = xf.bGetObject().constraints.new('TRANSFORM')
  260. self.get_target_and_subtarget(c)
  261. print(wrapGreen("Creating ")+wrapWhite("Transformation")+
  262. wrapGreen(" Constraint for bone: ") +
  263. wrapOrange(xf.bGetObject().name))
  264. if constraint_name := self.evaluate_input("Name"):
  265. c.name = constraint_name
  266. self.bObject.append(c)
  267. self.set_custom_space()
  268. props_sockets = self.gen_property_socket_map()
  269. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  270. self.executed = True
  271. class LinkLimitLocation(MantisLinkNode):
  272. __slots__ = ()
  273. socket_templates = LinkLimitLocationSockets
  274. def bRelationshipPass(self, context):
  275. prepare_parameters(self)
  276. for xf in self.GetxForm():
  277. c = xf.bGetObject().constraints.new('LIMIT_LOCATION')
  278. print(wrapGreen("Creating ")+wrapWhite("Limit Location")+
  279. wrapGreen(" Constraint for bone: ") +
  280. wrapOrange(xf.bGetObject().name))
  281. if constraint_name := self.evaluate_input("Name"):
  282. c.name = constraint_name
  283. self.bObject.append(c)
  284. self.set_custom_space()
  285. props_sockets = self.gen_property_socket_map()
  286. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  287. self.executed = True
  288. class LinkLimitRotation(MantisLinkNode):
  289. __slots__ = ()
  290. socket_templates = LinkLimitRotationSockets
  291. def bRelationshipPass(self, context):
  292. prepare_parameters(self)
  293. for xf in self.GetxForm():
  294. c = xf.bGetObject().constraints.new('LIMIT_ROTATION')
  295. print(wrapGreen("Creating ")+wrapWhite("Limit Rotation")+
  296. wrapGreen(" Constraint for bone: ") +
  297. wrapOrange(xf.bGetObject().name))
  298. if constraint_name := self.evaluate_input("Name"):
  299. c.name = constraint_name
  300. self.bObject.append(c)
  301. self.set_custom_space()
  302. props_sockets = self.gen_property_socket_map()
  303. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  304. self.executed = True
  305. class LinkLimitScale(MantisLinkNode):
  306. __slots__ = ()
  307. socket_templates = LinkLimitScaleSockets
  308. def bRelationshipPass(self, context):
  309. prepare_parameters(self)
  310. for xf in self.GetxForm():
  311. c = xf.bGetObject().constraints.new('LIMIT_SCALE')
  312. print(wrapGreen("Creating ")+wrapWhite("Limit Scale")+
  313. wrapGreen(" Constraint for bone: ") +
  314. wrapOrange(xf.bGetObject().name))
  315. if constraint_name := self.evaluate_input("Name"):
  316. c.name = constraint_name
  317. self.bObject.append(c)
  318. self.set_custom_space()
  319. props_sockets = self.gen_property_socket_map()
  320. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  321. self.executed = True
  322. class LinkLimitDistance(MantisLinkNode):
  323. __slots__ = ()
  324. socket_templates = LinkLimitDistanceSockets
  325. def bRelationshipPass(self, context):
  326. prepare_parameters(self)
  327. for xf in self.GetxForm():
  328. print(wrapGreen("Creating ")+wrapWhite("Limit Distance")+
  329. wrapGreen(" Constraint for bone: ") +
  330. wrapOrange(xf.bGetObject().name))
  331. c = xf.bGetObject().constraints.new('LIMIT_DISTANCE')
  332. self.get_target_and_subtarget(c)
  333. if constraint_name := self.evaluate_input("Name"):
  334. c.name = constraint_name
  335. self.bObject.append(c)
  336. self.set_custom_space()
  337. props_sockets = self.gen_property_socket_map()
  338. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  339. self.executed = True
  340. # Tracking
  341. class LinkStretchTo(MantisLinkNode):
  342. __slots__ = ()
  343. socket_templates = LinkStretchToSockets
  344. def bRelationshipPass(self, context):
  345. prepare_parameters(self)
  346. for xf in self.GetxForm():
  347. print(wrapGreen("Creating ")+wrapWhite("Stretch-To")+
  348. wrapGreen(" Constraint for bone: ") +
  349. wrapOrange(xf.bGetObject().name))
  350. c = xf.bGetObject().constraints.new('STRETCH_TO')
  351. self.get_target_and_subtarget(c)
  352. if constraint_name := self.evaluate_input("Name"):
  353. c.name = constraint_name
  354. self.bObject.append(c)
  355. props_sockets = self.gen_property_socket_map()
  356. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  357. if (self.evaluate_input("Original Length") == 0):
  358. # this is meant to be set automatically.
  359. c.rest_length = xf.bGetObject().bone.length
  360. self.executed = True
  361. class LinkDampedTrack(MantisLinkNode):
  362. __slots__ = ()
  363. socket_templates = LinkDampedTrackSockets
  364. def bRelationshipPass(self, context):
  365. prepare_parameters(self)
  366. for xf in self.GetxForm():
  367. print(wrapGreen("Creating ")+wrapWhite("Damped Track")+
  368. wrapGreen(" Constraint for bone: ") +
  369. wrapOrange(xf.bGetObject().name))
  370. c = xf.bGetObject().constraints.new('DAMPED_TRACK')
  371. self.get_target_and_subtarget(c)
  372. if constraint_name := self.evaluate_input("Name"):
  373. c.name = constraint_name
  374. self.bObject.append(c)
  375. props_sockets = self.gen_property_socket_map()
  376. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  377. self.executed = True
  378. class LinkLockedTrack(MantisLinkNode):
  379. __slots__ = ()
  380. socket_templates = LinkLockedTrackSockets
  381. def bRelationshipPass(self, context):
  382. prepare_parameters(self)
  383. for xf in self.GetxForm():
  384. print(wrapGreen("Creating ")+wrapWhite("Locked Track")+
  385. wrapGreen(" Constraint for bone: ") +
  386. wrapOrange(xf.bGetObject().name))
  387. c = xf.bGetObject().constraints.new('LOCKED_TRACK')
  388. self.get_target_and_subtarget(c)
  389. if constraint_name := self.evaluate_input("Name"):
  390. c.name = constraint_name
  391. self.bObject.append(c)
  392. props_sockets = self.gen_property_socket_map()
  393. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  394. self.executed = True
  395. class LinkTrackTo(MantisLinkNode):
  396. __slots__ = ()
  397. socket_templates = LinkTrackToSockets
  398. def bRelationshipPass(self, context):
  399. prepare_parameters(self)
  400. for xf in self.GetxForm():
  401. print(wrapGreen("Creating ")+wrapWhite("Track-To")+
  402. wrapGreen(" Constraint for bone: ") +
  403. wrapOrange(xf.bGetObject().name))
  404. c = xf.bGetObject().constraints.new('TRACK_TO')
  405. self.get_target_and_subtarget(c)
  406. if constraint_name := self.evaluate_input("Name"):
  407. c.name = constraint_name
  408. self.bObject.append(c)
  409. props_sockets = self.gen_property_socket_map()
  410. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  411. self.executed = True
  412. class LinkInheritConstraint(MantisLinkNode):
  413. __slots__ = ()
  414. socket_templates = LinkInheritConstraintSockets
  415. def bRelationshipPass(self, context):
  416. prepare_parameters(self)
  417. for xf in self.GetxForm():
  418. print(wrapGreen("Creating ")+wrapWhite("Child-Of")+
  419. wrapGreen(" Constraint for bone: ") +
  420. wrapOrange(xf.bGetObject().name))
  421. c = xf.bGetObject().constraints.new('CHILD_OF')
  422. self.get_target_and_subtarget(c)
  423. if constraint_name := self.evaluate_input("Name"):
  424. c.name = constraint_name
  425. self.bObject.append(c)
  426. props_sockets = self.gen_property_socket_map()
  427. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  428. c.set_inverse_pending
  429. self.executed = True
  430. class LinkInverseKinematics(MantisLinkNode):
  431. __slots__ = ("cache_available", "cache_key")
  432. socket_templates = LinkInverseKinematicsSockets
  433. def get_base_ik_bone(self, ik_bone):
  434. chain_length : int = (self.evaluate_input("Chain Length"))
  435. if not isinstance(chain_length, (int, float)):
  436. raise GraphError(f"Chain Length must be an integer number in {self}::Chain Length")
  437. if chain_length == 0:
  438. chain_length = int("inf")
  439. base_ik_bone = ik_bone; i=1
  440. while (i<chain_length) and (base_ik_bone.parent):
  441. base_ik_bone=base_ik_bone.parent; i+=1
  442. return base_ik_bone
  443. # We need to do the calculation in a "full circle", meaning the pole_angle
  444. # can go over pi or less than -pi - but the actuall constraint value must
  445. # be clamped in that range.
  446. # so we simply wrap the value.
  447. # not very efficient but it's OK
  448. def set_pole_angle(self, constraint, angle: float) -> None:
  449. from math import pi
  450. from .utilities.utilities import wrap
  451. constraint.pole_angle = wrap(-pi, pi, angle)
  452. def calc_pole_angle_pre(self, c, ik_bone):
  453. """
  454. This function gets us most of the way to a correct IK pole angle. Unfortunately,
  455. due to the unpredictable nature of the iterative IK calculation, I can't figure
  456. out an exact solution. So we do a bisect search in calc_pole_angle_post().
  457. """
  458. # TODO: instead of these checks, convert all to armature local space. But this is tedious.
  459. if not c.target:
  460. raise GraphError(f"IK Constraint {self} must have target.")
  461. elif c.target.type != "ARMATURE":
  462. raise NotImplementedError(f"Currently, IK Constraint Target for {self} must be a bone within the same armature.")
  463. if c.pole_target.type != "ARMATURE":
  464. raise NotImplementedError(f"Currently, IK Constraint Pole Target for {self} must be a bone within the same armature.")
  465. ik_handle = c.target.pose.bones[c.subtarget]
  466. if ik_handle.id_data != ik_bone.id_data:
  467. raise NotImplementedError(f"Currently, IK Constraint Target for {self} must be a bone within the same armature.")
  468. ik_pole = c.pole_target.pose.bones[c.pole_subtarget]
  469. if ik_pole.id_data != ik_bone.id_data:
  470. raise NotImplementedError(f"Currently,IK Constraint Pole Target for {self} must be a bone within the same armature.")
  471. base_ik_bone = self.get_base_ik_bone(ik_bone)
  472. start_effector = base_ik_bone.bone.head_local
  473. end_effector = ik_handle.bone.head_local
  474. pole_location = ik_pole.bone.head_local
  475. # this is the X-Axis of the bone's rest-pose, added to its bone
  476. knee_location = base_ik_bone.bone.matrix_local.col[0].xyz+start_effector
  477. # At this point we can check the cache for the correct IK pole angle
  478. cache_key = make_ik_pole_vector_cache_key(start_effector,
  479. end_effector,
  480. pole_location,
  481. knee_location)
  482. self.cache_key.append(cache_key)
  483. if pole_angle := IK_POLE_VECTOR_CACHE.get(cache_key):
  484. self.cache_available.append(True)
  485. return pole_angle
  486. self.cache_available.append(False)
  487. ik_axis = (end_effector-start_effector).normalized()
  488. from .utilities.utilities import project_point_to_plane
  489. pole_planar_projection = project_point_to_plane(pole_location, start_effector, ik_axis)
  490. # this planar projection is necessary because the IK axis is different than the base_bone's y axis
  491. planar_projection = project_point_to_plane(knee_location, start_effector, ik_axis)
  492. knee_direction =(planar_projection - start_effector).normalized()
  493. pole_direction =(pole_planar_projection - start_effector).normalized()
  494. return knee_direction.angle(pole_direction)
  495. def calc_pole_angle_post(self, c, ik_bone, context):
  496. """
  497. This function should give us a completely accurate result for IK.
  498. """
  499. from time import time
  500. start_time=time()
  501. def signed_angle(vector_u, vector_v, normal):
  502. # it seems that this fails if the vectors are exactly aligned under certain circumstances.
  503. angle = vector_u.angle(vector_v, 0.0) # So we use a fallback of 0
  504. # Normal specifies orientation
  505. if angle != 0 and vector_u.cross(vector_v).angle(normal) < 1:
  506. angle = -angle
  507. return angle
  508. # we have already checked for valid data.
  509. ik_handle = c.target.pose.bones[c.subtarget]
  510. base_ik_bone = self.get_base_ik_bone(ik_bone)
  511. start_effector = base_ik_bone.bone.head_local
  512. angle = c.pole_angle
  513. dg = context.view_layer.depsgraph
  514. dg.update()
  515. ik_axis = (ik_handle.bone.head_local-start_effector).normalized()
  516. center_point = start_effector +(ik_axis*base_ik_bone.bone.length)
  517. knee_direction = base_ik_bone.bone.tail_local - center_point
  518. current_knee_direction = base_ik_bone.tail-center_point
  519. error=signed_angle(current_knee_direction, knee_direction, ik_axis)
  520. if error == 0:
  521. prGreen("No Fine-tuning needed."); return
  522. # Flip it if needed
  523. dot_before=current_knee_direction.dot(knee_direction)
  524. if dot_before < 0 and angle!=0: # then it is not aligned and we should check the inverse
  525. angle = -angle; c.pole_angle=angle
  526. dg.update()
  527. current_knee_direction = base_ik_bone.tail-center_point
  528. dot_after=current_knee_direction.dot(knee_direction)
  529. if dot_after < dot_before: # they are somehow less aligned
  530. prPurple("Mantis has gone down an unexpected code path. Please report this as a bug.")
  531. angle = -angle; self.set_pole_angle(c, angle)
  532. dg.update()
  533. # now we can do a bisect search to find the best value.
  534. error_threshhold = FLOAT_EPSILON
  535. max_iterations=600
  536. error=signed_angle(current_knee_direction, knee_direction, ik_axis)
  537. if error == 0:
  538. prGreen("No Fine-tuning needed."); return
  539. angle+=error
  540. alt_angle = angle+(error*-2) # should be very near the center when flipped here
  541. # we still need to bisect search because the relationship of pole_angle <==> error is somewhat unpredictable
  542. upper_bounds = alt_angle if alt_angle > angle else angle
  543. lower_bounds = alt_angle if alt_angle < angle else angle
  544. i, error_identical = 0, 0
  545. while ( True ):
  546. if (i>=max_iterations):
  547. prOrange(f"IK Pole Angle Set reached max iterations of {i-error_identical} in {time()-start_time} seconds")
  548. break
  549. if (abs(error)<error_threshhold) or (upper_bounds<=lower_bounds) or (error_identical > 3):
  550. prPurple(f"IK Pole Angle Set converged after {i-error_identical} iterations with error={error} in {time()-start_time} seconds")
  551. break
  552. # get the center-point betweeen the bounds
  553. try_angle = lower_bounds + (upper_bounds-lower_bounds)/2
  554. self.set_pole_angle(c, try_angle); dg.update()
  555. prev_error = error
  556. error = signed_angle((base_ik_bone.tail-center_point), knee_direction, ik_axis)
  557. error_identical+= int(error == prev_error)
  558. if error>0: upper_bounds=try_angle
  559. if error<0: lower_bounds=try_angle
  560. i+=1
  561. def bRelationshipPass(self, context):
  562. self.cache_available = []
  563. self.cache_key = []
  564. prepare_parameters(self)
  565. for xf in self.GetxForm():
  566. print(wrapGreen("Creating ")+wrapOrange("Inverse Kinematics")+
  567. wrapGreen(" Constraint for bone: ") +
  568. wrapOrange(xf.bGetObject().name))
  569. ik_bone = xf.bGetObject()
  570. c = xf.bGetObject().constraints.new('IK')
  571. self.get_target_and_subtarget(c)
  572. self.get_target_and_subtarget(c, input_name = 'Pole Target')
  573. if constraint_name := self.evaluate_input("Name"):
  574. c.name = constraint_name
  575. self.bObject.append(c)
  576. c.chain_count = 1 # so that, if there are errors, this doesn't print
  577. # a whole bunch of circular dependency crap from having infinite chain length
  578. if (c.pole_target):
  579. self.set_pole_angle(c, self.calc_pole_angle_pre(c, ik_bone))
  580. else: # no need for cache
  581. self.cache_available.append(False)
  582. self.cache_key.append(None)
  583. props_sockets = self.gen_property_socket_map()
  584. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  585. c.use_location = self.evaluate_input("Position") > 0
  586. c.use_rotation = self.evaluate_input("Rotation") > 0
  587. self.executed = True
  588. def bFinalize(self, bContext = None):
  589. if bContext:
  590. for i, constraint in enumerate(self.bObject):
  591. # retrieve the cached result if it is available
  592. ik_bone = self.GetxForm()[i].bGetObject(mode='POSE')
  593. if constraint.pole_target:
  594. if self.cache_available[i]:
  595. prWhite(f"Retrieving fine-tuned IK Pole Angle for {self} from cache.")
  596. self.set_pole_angle(constraint, IK_POLE_VECTOR_CACHE[self.cache_key[i]])
  597. else:
  598. prWhite(f"Fine-tuning IK Pole Angle for {self}")
  599. # make sure to enable it first
  600. enabled_before = constraint.mute
  601. constraint.mute = False
  602. self.calc_pole_angle_post(constraint, ik_bone, bContext)
  603. constraint.mute = enabled_before
  604. IK_POLE_VECTOR_CACHE[self.cache_key[i]] = constraint.pole_angle
  605. super().bFinalize(bContext)
  606. def ik_report_error(pb, context, do_print=False):
  607. dg = context.view_layer.depsgraph
  608. dg.update()
  609. loc1, rot_quaternion1, scl1 = pb.matrix.decompose()
  610. loc2, rot_quaternion2, scl2 = pb.bone.matrix_local.decompose()
  611. location_error=(loc1-loc2).length
  612. rotation_error = rot_quaternion1.rotation_difference(rot_quaternion2).angle
  613. scale_error = (scl1-scl2).length
  614. if location_error < FLOAT_EPSILON: location_error = 0
  615. if abs(rotation_error) < FLOAT_EPSILON: rotation_error = 0
  616. if scale_error < FLOAT_EPSILON: scale_error = 0
  617. if do_print:
  618. print (f"IK Location Error: {location_error}")
  619. print (f"IK Rotation Error: {rotation_error}")
  620. print (f"IK Scale Error : {scale_error}")
  621. return (location_error, rotation_error, scale_error)
  622. # This is kinda a weird design decision?
  623. class LinkDrivenParameter(MantisLinkNode):
  624. '''A node representing an armature object'''
  625. __slots__ = ()
  626. socket_templates = LinkDrivenParameterSockets
  627. def bRelationshipPass(self, bContext = None,):
  628. prepare_parameters(self)
  629. prGreen("Executing Driven Parameter node")
  630. prop = self.evaluate_input("Parameter")
  631. index = self.evaluate_input("Index")
  632. value = self.evaluate_input("Value")
  633. for xf in self.GetxForm():
  634. ob = xf.bGetObject(mode="POSE")
  635. # IMPORTANT: this node only works on pose bone attributes.
  636. self.bObject.append(ob)
  637. length=1
  638. if hasattr(ob, prop):
  639. try:
  640. length = len(getattr(ob, prop))
  641. except TypeError:
  642. pass
  643. except AttributeError:
  644. pass
  645. else:
  646. raise AttributeError(f"Cannot Set value {prop} on object because it does not exist.")
  647. def_value = 0.0
  648. if length>1:
  649. def_value=[0.0]*length
  650. self.parameters["Value"] = tuple( 0.0 if i != index else value for i in range(length))
  651. from .mantis_dataclasses import MantisSocketFiller
  652. props_sockets = {
  653. prop: MantisSocketFiller( property_name=prop,
  654. socket_name="Value",
  655. default_value=def_value)
  656. }
  657. evaluate_sockets(self, {"DEFAULT":ob}, props_sockets)
  658. self.executed = True
  659. def bFinalize(self, bContext = None):
  660. driver = self.evaluate_input("Value")
  661. try:
  662. for i, val in enumerate(self.parameters["Value"]):
  663. from .utilities.drivers import MantisDriver
  664. if isinstance(val, MantisDriver):
  665. driver["ind"] = i
  666. val = driver
  667. except AttributeError:
  668. self.parameters["Value"] = driver
  669. except TypeError:
  670. self.parameters["Value"] = driver
  671. super().bFinalize(bContext)
  672. class LinkArmature(MantisLinkNode):
  673. '''A node representing an armature object'''
  674. __slots__ = ()
  675. socket_templates = LinkArmatureSockets
  676. def bRelationshipPass(self, bContext = None,):
  677. prepare_parameters(self)
  678. for xf in self.GetxForm():
  679. print(wrapGreen("Creating ")+wrapOrange("Armature")+
  680. wrapGreen(" Constraint for bone: ") +
  681. wrapOrange(xf.bGetObject().name))
  682. c = xf.bGetObject().constraints.new('ARMATURE')
  683. b_objects = {"DEFAULT":c}
  684. if constraint_name := self.evaluate_input("Name"):
  685. c.name = constraint_name
  686. self.bObject.append(c)
  687. # get number of targets
  688. num_targets = len( self.inputs['Targets'].links )
  689. props_sockets = self.gen_property_socket_map()
  690. # TODO: currently this will only work if the constraint bones
  691. # are all in the same armature
  692. # Mantis should intelligently provide a working armature constraint
  693. # even if the user supplies targets that would not work in vanilla Blender
  694. targets_weights = {}
  695. # NOTE: Mantis does not generally sort links because it is slow
  696. # so it is the responsibility of array types to do this.
  697. from .base_definitions import links_sort_key
  698. for inp in {'Targets', 'Weights'}:
  699. self.inputs[inp].links.sort(key=links_sort_key)
  700. for i in range(num_targets):
  701. target = c.targets.new()
  702. self.get_target_and_subtarget(target, 'Targets', i)
  703. weight_value=self.evaluate_input("Weights", i)
  704. default_value = 1.0
  705. if self.inputs['Weights'].links:
  706. default_value = 1/len(self.inputs['Weights'].links)
  707. if not isinstance(weight_value, float):
  708. weight_value=default_value
  709. targets_weights[i]=weight_value
  710. from .mantis_dataclasses import MantisSocketFiller
  711. property_group=f"target.{str(i).zfill(4)}"
  712. prop_name = 'weight'
  713. filler = MantisSocketFiller(
  714. property_group = property_group,
  715. property_name = prop_name,
  716. socket_name = "Weights",
  717. array_index=i,
  718. default_value=weight_value,
  719. )
  720. b_objects[property_group] = target
  721. props_sockets[prop_name+str(i)] = filler
  722. evaluate_sockets(self, b_objects, props_sockets)
  723. for target, value in targets_weights.items():
  724. c.targets[target].weight=value
  725. self.executed = True
  726. class LinkSplineIK(MantisLinkNode):
  727. '''A node representing an armature object'''
  728. __slots__ = ()
  729. socket_templates = LinkSplineIKSockets
  730. def bRelationshipPass(self, bContext = None,):
  731. prepare_parameters(self)
  732. if not self.inputs['Target'].is_linked:
  733. raise GraphError(f"ERROR: {self} is not connected to a target curve.")
  734. for xf in self.GetxForm():
  735. print(wrapGreen("Creating ")+wrapOrange("Spline-IK")+
  736. wrapGreen(" Constraint for bone: ") +
  737. wrapOrange(xf.bGetObject().name))
  738. c = xf.bGetObject().constraints.new('SPLINE_IK')
  739. # set the spline - we need to get the right one
  740. spline_index = self.evaluate_input("Spline Index")
  741. proto_curve = None
  742. node_line, _last_socket = trace_single_line(self, "Target")
  743. for other_node in node_line: # trace and get the input
  744. if other_node.node_type == 'XFORM':
  745. proto_curve = other_node.bGetObject(); break
  746. from .utilities.utilities import get_extracted_spline_object
  747. curve = get_extracted_spline_object(proto_curve, spline_index, self.mContext)
  748. # link it to the view layer
  749. if (curve.name not in bContext.view_layer.active_layer_collection.collection.objects):
  750. bContext.view_layer.active_layer_collection.collection.objects.link(curve)
  751. c.target=curve
  752. if constraint_name := self.evaluate_input("Name"):
  753. c.name = constraint_name
  754. self.bObject.append(c)
  755. props_sockets = self.gen_property_socket_map()
  756. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  757. self.executed = True
  758. class LinkFloor(MantisLinkNode):
  759. '''A node representing an armature object'''
  760. __slots__ = ()
  761. socket_templates = LinkFloorSockets
  762. def bRelationshipPass(self, bContext = None,):
  763. prepare_parameters(self)
  764. for xf in self.GetxForm():
  765. print(wrapGreen("Creating ")+wrapOrange("Floor")+
  766. wrapGreen(" Constraint for bone: ") +
  767. wrapOrange(xf.bGetObject().name))
  768. c = xf.bGetObject().constraints.new('FLOOR')
  769. self.get_target_and_subtarget(c)
  770. if constraint_name := self.evaluate_input("Name"):
  771. c.name = constraint_name
  772. self.bObject.append(c)
  773. self.set_custom_space()
  774. props_sockets = self.gen_property_socket_map()
  775. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  776. self.executed = True
  777. class LinkShrinkWrap(MantisLinkNode):
  778. '''A node representing a shrinkwrap relationship.'''
  779. __slots__ = ()
  780. socket_templates = LinkShrinkWrapSockets
  781. def bRelationshipPass(self, bContext = None,):
  782. prepare_parameters(self)
  783. for xf in self.GetxForm():
  784. print(wrapGreen("Creating ")+wrapOrange("Shrinkwrap")+
  785. wrapGreen(" Constraint for bone: ") +
  786. wrapOrange(xf.bGetObject().name))
  787. c = xf.bGetObject().constraints.new('SHRINKWRAP')
  788. self.bObject.append(c)
  789. self.get_target_and_subtarget(c)
  790. if constraint_name := self.evaluate_input("Name"):
  791. c.name = constraint_name
  792. props_sockets = self.gen_property_socket_map()
  793. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  794. # self.set_custom_space() # this needs to be overridden for me TODO
  795. self.executed = True
  796. class LinkGeometryAttribute(MantisLinkNode):
  797. '''A node representing a geometry attribute relationship.'''
  798. __slots__ = ()
  799. socket_templates = LinkGeometryAttributeSockets
  800. def bRelationshipPass(self, bContext = None,):
  801. from bpy.app import version
  802. from .base_definitions import BlenderVersionError
  803. if version < (5,0,0):
  804. raise BlenderVersionError("Geometry Attribute Constraint is supported only in Blender 5.0 or greater.")
  805. prepare_parameters(self)
  806. for xf in self.GetxForm():
  807. print
  808. c = xf.bGetObject().constraints.new('GEOMETRY_ATTRIBUTE')
  809. self.bObject.append(c)
  810. self.get_target_and_subtarget(c)
  811. if constraint_name := self.evaluate_input("Name"):
  812. c.name = constraint_name
  813. props_sockets = self.gen_property_socket_map()
  814. evaluate_sockets(self, {"DEFAULT":c}, props_sockets)
  815. self.executed = True