link_containers.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. from .node_container_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. # Drivers
  32. LinkDrivenParameter,
  33. ]
  34. # set the name if it is available, otherwise just use the constraint's nice name
  35. set_constraint_name = lambda nc : nc.evaluate_input("Name") if nc.evaluate_input("Name") else nc.__class__.__name__
  36. class MantisLinkNode(MantisNode):
  37. def __init__(self, signature : tuple,
  38. base_tree : NodeTree,
  39. socket_templates : list[SockTemplate]=[]):
  40. super().__init__(signature, base_tree, socket_templates)
  41. self.node_type = 'LINK'
  42. self.prepared = True
  43. def evaluate_input(self, input_name, index=0):
  44. # should catch 'Target', 'Pole Target' and ArmatureConstraint targets, too
  45. if ('Target' in input_name) and input_name not in ["Target Space", "Use Target Z"]:
  46. socket = self.inputs.get(input_name)
  47. if socket.is_linked:
  48. return socket.links[0].from_node
  49. return None
  50. else:
  51. return super().evaluate_input(input_name)
  52. def gen_property_socket_map(self) -> dict:
  53. props_sockets = super().gen_property_socket_map()
  54. if (os := self.inputs.get("Owner Space")) and os.is_connected and os.links[0].from_node.node_type == 'XFORM':
  55. del props_sockets['owner_space']
  56. if ts := self.inputs.get("Target_Space") and ts.is_connected and ts.links[0].from_node.node_type == 'XFORM':
  57. del props_sockets['target_space']
  58. return props_sockets
  59. def set_custom_space(self):
  60. c = self.bObject
  61. if (os := self.inputs.get("Owner Space")) and os.is_connected and os.links[0].from_node.node_type == 'XFORM':
  62. c.owner_space='CUSTOM'
  63. xf = self.inputs["Owner Space"].links[0].from_node.bGetObject(mode="OBJECT")
  64. if isinstance(xf, Bone):
  65. c.space_object=self.inputs["Owner Space"].links[0].from_node.bGetParentArmature(); c.space_subtarget=xf.name
  66. else:
  67. c.space_object=xf
  68. if ts := self.inputs.get("Target_Space") and ts.is_connected and ts.links[0].from_node.node_type == 'XFORM':
  69. c.owner_space='CUSTOM'
  70. xf = self.inputs["Target_Space Space"].links[0].from_node.bGetObject(mode="OBJECT")
  71. if isinstance(xf, Bone):
  72. c.space_object=self.inputs["Target_Space Space"].links[0].from_node.bGetParentArmature(); c.space_subtarget=xf.name
  73. else:
  74. c.space_object=xf
  75. def bFinalize(self, bContext=None):
  76. finish_drivers(self)
  77. #*#-------------------------------#++#-------------------------------#*#
  78. # L I N K N O D E S
  79. #*#-------------------------------#++#-------------------------------#*#
  80. def GetxForm(nc):
  81. trace = trace_single_line_up(nc, "Output Relationship")
  82. for node in trace[0]:
  83. if (node.node_type == 'XFORM'):
  84. return node
  85. raise GraphError("%s is not connected to a downstream xForm" % nc)
  86. class LinkInherit(MantisLinkNode):
  87. '''A node representing inheritance'''
  88. def __init__(self, signature, base_tree):
  89. super().__init__(signature, base_tree, LinkInheritSockets)
  90. self.init_parameters()
  91. self.set_traverse([('Parent', 'Inheritance')])
  92. self.executed = True
  93. def GetxForm(self): # DUPLICATED, TODO fix this
  94. # I think this is only run in display update.
  95. trace = trace_single_line_up(self, "Inheritance")
  96. for node in trace[0]:
  97. if (node.node_type == 'XFORM'):
  98. return node
  99. raise GraphError("%s is not connected to a downstream xForm" % self)
  100. class LinkCopyLocation(MantisLinkNode):
  101. '''A node representing Copy Location'''
  102. def __init__(self, signature : tuple,
  103. base_tree : NodeTree,):
  104. super().__init__(signature, base_tree, LinkCopyLocationSockets)
  105. additional_parameters = { "Name":None }
  106. self.init_parameters(additional_parameters=additional_parameters)
  107. self.set_traverse([("Input Relationship", "Output Relationship")])
  108. def GetxForm(self):
  109. return GetxForm(self)
  110. def bExecute(self, context):
  111. prepare_parameters(self)
  112. c = self.GetxForm().bGetObject().constraints.new('COPY_LOCATION')
  113. self.get_target_and_subtarget(c)
  114. print(wrapGreen("Creating ")+wrapWhite("Copy Location")+
  115. wrapGreen(" Constraint for bone: ") +
  116. wrapOrange(self.GetxForm().bGetObject().name))
  117. if constraint_name := self.evaluate_input("Name"):
  118. c.name = constraint_name
  119. self.bObject = c
  120. self.set_custom_space()
  121. props_sockets = self.gen_property_socket_map()
  122. evaluate_sockets(self, c, props_sockets)
  123. self.executed = True
  124. class LinkCopyRotation(MantisLinkNode):
  125. '''A node representing Copy Rotation'''
  126. def __init__(self, signature, base_tree):
  127. super().__init__(signature, base_tree, LinkCopyRotationSockets)
  128. additional_parameters = { "Name":None }
  129. self.init_parameters(additional_parameters=additional_parameters)
  130. self.set_traverse([("Input Relationship", "Output Relationship")])
  131. def GetxForm(self):
  132. return GetxForm(self)
  133. def bExecute(self, context):
  134. prepare_parameters(self)
  135. c = self.GetxForm().bGetObject().constraints.new('COPY_ROTATION')
  136. self.get_target_and_subtarget(c)
  137. print(wrapGreen("Creating ")+wrapWhite("Copy Rotation")+
  138. wrapGreen(" Constraint for bone: ") +
  139. wrapOrange(self.GetxForm().bGetObject().name))
  140. rotation_order = self.evaluate_input("RotationOrder")
  141. if ((rotation_order == 'QUATERNION') or (rotation_order == 'AXIS_ANGLE')):
  142. c.euler_order = 'AUTO'
  143. else:
  144. try:
  145. c.euler_order = rotation_order
  146. except TypeError: # it's a driver or incorrect
  147. c.euler_order = 'AUTO'
  148. if constraint_name := self.evaluate_input("Name"):
  149. c.name = constraint_name
  150. self.bObject = c
  151. self.set_custom_space()
  152. props_sockets = self.gen_property_socket_map()
  153. evaluate_sockets(self, c, props_sockets)
  154. self.executed = True
  155. class LinkCopyScale(MantisLinkNode):
  156. '''A node representing Copy Scale'''
  157. def __init__(self, signature, base_tree):
  158. super().__init__(signature, base_tree, LinkCopyScaleSockets)
  159. additional_parameters = { "Name":None }
  160. self.init_parameters(additional_parameters=additional_parameters)
  161. self.set_traverse([("Input Relationship", "Output Relationship")])
  162. def GetxForm(self):
  163. return GetxForm(self)
  164. def bExecute(self, context):
  165. prepare_parameters(self)
  166. c = self.GetxForm().bGetObject().constraints.new('COPY_SCALE')
  167. self.get_target_and_subtarget(c)
  168. print(wrapGreen("Creating ")+wrapWhite("Copy Scale")+
  169. wrapGreen(" Constraint for bone: ") +
  170. wrapOrange(self.GetxForm().bGetObject().name))
  171. if constraint_name := self.evaluate_input("Name"):
  172. c.name = constraint_name
  173. self.bObject = c
  174. if self.inputs["Owner Space"].is_connected and self.inputs["Owner Space"].links[0].from_node.node_type == 'XFORM':
  175. c.owner_space='CUSTOM'
  176. xf = self.inputs["Owner Space"].links[0].from_node.bGetObject(mode="OBJECT")
  177. if isinstance(xf, Bone):
  178. c.space_object=self.inputs["Owner Space"].links[0].from_node.bGetParentArmature(); c.space_subtarget=xf.name
  179. else:
  180. c.space_object=xf
  181. if self.inputs["Target Space"].is_connected and self.inputs["Target Space"].links[0].from_node.node_type == 'XFORM':
  182. c.target_space='CUSTOM'
  183. xf = self.inputs["Target Space"].links[0].from_node.bGetObject(mode="OBJECT")
  184. if isinstance(xf, Bone):
  185. c.space_object=self.inputs["Owner Space"].links[0].from_node.bGetParentArmature(); c.space_subtarget=xf.name
  186. else:
  187. c.space_object=xf
  188. props_sockets = self.gen_property_socket_map()
  189. evaluate_sockets(self, c, props_sockets)
  190. self.executed = True
  191. class LinkCopyTransforms(MantisLinkNode):
  192. '''A node representing Copy Transfoms'''
  193. def __init__(self, signature, base_tree):
  194. super().__init__(signature, base_tree, LinkCopyTransformsSockets)
  195. additional_parameters = { "Name":None }
  196. self.init_parameters(additional_parameters=additional_parameters)
  197. self.set_traverse([("Input Relationship", "Output Relationship")])
  198. def GetxForm(self):
  199. return GetxForm(self)
  200. def bExecute(self, context):
  201. prepare_parameters(self)
  202. c = self.GetxForm().bGetObject().constraints.new('COPY_TRANSFORMS')
  203. self.get_target_and_subtarget(c)
  204. print(wrapGreen("Creating ")+wrapWhite("Copy Transforms")+
  205. wrapGreen(" Constraint for bone: ") +
  206. wrapOrange(self.GetxForm().bGetObject().name))
  207. if constraint_name := self.evaluate_input("Name"):
  208. c.name = constraint_name
  209. self.bObject = c
  210. self.set_custom_space()
  211. props_sockets = self.gen_property_socket_map()
  212. evaluate_sockets(self, c, props_sockets)
  213. self.executed = True
  214. class LinkTransformation(MantisLinkNode):
  215. '''A node representing Copy Transfoms'''
  216. def __init__(self, signature, base_tree):
  217. super().__init__(signature, base_tree, LinkTransformationSockets)
  218. self.init_parameters(additional_parameters={"Name":None })
  219. self.set_traverse([("Input Relationship", "Output Relationship")])
  220. def GetxForm(self):
  221. return GetxForm(self)
  222. def bExecute(self, context):
  223. prepare_parameters(self)
  224. c = self.GetxForm().bGetObject().constraints.new('TRANSFORM')
  225. self.get_target_and_subtarget(c)
  226. print(wrapGreen("Creating ")+wrapWhite("Transformation")+
  227. wrapGreen(" Constraint for bone: ") +
  228. wrapOrange(self.GetxForm().bGetObject().name))
  229. if constraint_name := self.evaluate_input("Name"):
  230. c.name = constraint_name
  231. self.bObject = c
  232. self.set_custom_space()
  233. props_sockets = self.gen_property_socket_map()
  234. evaluate_sockets(self, c, props_sockets)
  235. self.executed = True
  236. class LinkLimitLocation(MantisLinkNode):
  237. def __init__(self, signature, base_tree):
  238. super().__init__(signature, base_tree, LinkLimitLocationScaleSockets)
  239. self.init_parameters(additional_parameters={ "Name":None })
  240. self.set_traverse([("Input Relationship", "Output Relationship")])
  241. def GetxForm(self):
  242. return GetxForm(self)
  243. def bExecute(self, context):
  244. prepare_parameters(self)
  245. c = self.GetxForm().bGetObject().constraints.new('LIMIT_LOCATION')
  246. #
  247. print(wrapGreen("Creating ")+wrapWhite("Limit Location")+
  248. wrapGreen(" Constraint for bone: ") +
  249. wrapOrange(self.GetxForm().bGetObject().name))
  250. if constraint_name := self.evaluate_input("Name"):
  251. c.name = constraint_name
  252. self.bObject = c
  253. self.set_custom_space()
  254. props_sockets = self.gen_property_socket_map()
  255. evaluate_sockets(self, c, props_sockets)
  256. self.executed = True
  257. class LinkLimitRotation(MantisLinkNode):
  258. def __init__(self, signature, base_tree):
  259. super().__init__(signature, base_tree, LinkLimitRotationSockets)
  260. self.init_parameters(additional_parameters={ "Name":None })
  261. self.set_traverse([("Input Relationship", "Output Relationship")])
  262. def GetxForm(self):
  263. return GetxForm(self)
  264. def bExecute(self, context):
  265. prepare_parameters(self)
  266. c = self.GetxForm().bGetObject().constraints.new('LIMIT_ROTATION')
  267. print(wrapGreen("Creating ")+wrapWhite("Limit Rotation")+
  268. wrapGreen(" Constraint for bone: ") +
  269. wrapOrange(self.GetxForm().bGetObject().name))
  270. if constraint_name := self.evaluate_input("Name"):
  271. c.name = constraint_name
  272. self.bObject = c
  273. self.set_custom_space()
  274. props_sockets = self.gen_property_socket_map()
  275. evaluate_sockets(self, c, props_sockets)
  276. self.executed = True
  277. class LinkLimitScale(MantisLinkNode):
  278. def __init__(self, signature, base_tree):
  279. super().__init__(signature, base_tree, LinkLimitLocationScaleSockets)
  280. self.init_parameters(additional_parameters={ "Name":None })
  281. self.set_traverse([("Input Relationship", "Output Relationship")])
  282. def GetxForm(self):
  283. return GetxForm(self)
  284. def bExecute(self, context):
  285. prepare_parameters(self)
  286. c = self.GetxForm().bGetObject().constraints.new('LIMIT_SCALE')
  287. print(wrapGreen("Creating ")+wrapWhite("Limit Scale")+
  288. wrapGreen(" Constraint for bone: ") +
  289. wrapOrange(self.GetxForm().bGetObject().name))
  290. if constraint_name := self.evaluate_input("Name"):
  291. c.name = constraint_name
  292. self.bObject = c
  293. self.set_custom_space()
  294. props_sockets = self.gen_property_socket_map()
  295. evaluate_sockets(self, c, props_sockets)
  296. self.executed = True
  297. class LinkLimitDistance(MantisLinkNode):
  298. def __init__(self, signature, base_tree):
  299. super().__init__(signature, base_tree, LinkLimitDistanceSockets)
  300. self.init_parameters(additional_parameters={ "Name":None })
  301. self.set_traverse([("Input Relationship", "Output Relationship")])
  302. def GetxForm(self):
  303. return GetxForm(self)
  304. def bExecute(self, context):
  305. prepare_parameters(self)
  306. print(wrapGreen("Creating ")+wrapWhite("Limit Distance")+
  307. wrapGreen(" Constraint for bone: ") +
  308. wrapOrange(self.GetxForm().bGetObject().name))
  309. c = self.GetxForm().bGetObject().constraints.new('LIMIT_DISTANCE')
  310. self.get_target_and_subtarget(c)
  311. if constraint_name := self.evaluate_input("Name"):
  312. c.name = constraint_name
  313. self.bObject = c
  314. self.set_custom_space()
  315. props_sockets = self.gen_property_socket_map()
  316. evaluate_sockets(self, c, props_sockets)
  317. self.executed = True
  318. # Tracking
  319. class LinkStretchTo(MantisLinkNode):
  320. def __init__(self, signature, base_tree):
  321. super().__init__(signature, base_tree, LinkStretchToSockets)
  322. self.init_parameters(additional_parameters={ "Name":None })
  323. self.set_traverse([("Input Relationship", "Output Relationship")])
  324. def GetxForm(self):
  325. return GetxForm(self)
  326. def bExecute(self, context):
  327. prepare_parameters(self)
  328. print(wrapGreen("Creating ")+wrapWhite("Stretch-To")+
  329. wrapGreen(" Constraint for bone: ") +
  330. wrapOrange(self.GetxForm().bGetObject().name))
  331. c = self.GetxForm().bGetObject().constraints.new('STRETCH_TO')
  332. self.get_target_and_subtarget(c)
  333. if constraint_name := self.evaluate_input("Name"):
  334. c.name = constraint_name
  335. self.bObject = c
  336. props_sockets = self.gen_property_socket_map()
  337. evaluate_sockets(self, c, props_sockets)
  338. if (self.evaluate_input("Original Length") == 0):
  339. # this is meant to be set automatically.
  340. c.rest_length = self.GetxForm().bGetObject().bone.length
  341. self.executed = True
  342. class LinkDampedTrack(MantisLinkNode):
  343. def __init__(self, signature, base_tree):
  344. super().__init__(signature, base_tree, LinkDampedTrackSockets)
  345. self.init_parameters(additional_parameters={ "Name":None })
  346. self.set_traverse([("Input Relationship", "Output Relationship")])
  347. def GetxForm(self):
  348. return GetxForm(self)
  349. def bExecute(self, context):
  350. prepare_parameters(self)
  351. print(wrapGreen("Creating ")+wrapWhite("Damped Track")+
  352. wrapGreen(" Constraint for bone: ") +
  353. wrapOrange(self.GetxForm().bGetObject().name))
  354. c = self.GetxForm().bGetObject().constraints.new('DAMPED_TRACK')
  355. self.get_target_and_subtarget(c)
  356. if constraint_name := self.evaluate_input("Name"):
  357. c.name = constraint_name
  358. self.bObject = c
  359. props_sockets = self.gen_property_socket_map()
  360. evaluate_sockets(self, c, props_sockets)
  361. self.executed = True
  362. class LinkLockedTrack(MantisLinkNode):
  363. def __init__(self, signature, base_tree):
  364. super().__init__(signature, base_tree,LinkLockedTrackSockets)
  365. self.init_parameters(additional_parameters={"Name":None })
  366. self.set_traverse([("Input Relationship", "Output Relationship")])
  367. def GetxForm(self):
  368. return GetxForm(self)
  369. def bExecute(self, context):
  370. prepare_parameters(self)
  371. print(wrapGreen("Creating ")+wrapWhite("Locked Track")+
  372. wrapGreen(" Constraint for bone: ") +
  373. wrapOrange(self.GetxForm().bGetObject().name))
  374. c = self.GetxForm().bGetObject().constraints.new('LOCKED_TRACK')
  375. self.get_target_and_subtarget(c)
  376. if constraint_name := self.evaluate_input("Name"):
  377. c.name = constraint_name
  378. self.bObject = c
  379. props_sockets = self.gen_property_socket_map()
  380. evaluate_sockets(self, c, props_sockets)
  381. self.executed = True
  382. class LinkTrackTo(MantisLinkNode):
  383. def __init__(self, signature, base_tree):
  384. super().__init__(signature, base_tree, LinkTrackToSockets)
  385. self.init_parameters(additional_parameters={"Name":None })
  386. self.set_traverse([("Input Relationship", "Output Relationship")])
  387. def GetxForm(self):
  388. return GetxForm(self)
  389. def bExecute(self, context):
  390. prepare_parameters(self)
  391. print(wrapGreen("Creating ")+wrapWhite("Track-To")+
  392. wrapGreen(" Constraint for bone: ") +
  393. wrapOrange(self.GetxForm().bGetObject().name))
  394. c = self.GetxForm().bGetObject().constraints.new('TRACK_TO')
  395. self.get_target_and_subtarget(c)
  396. if constraint_name := self.evaluate_input("Name"):
  397. c.name = constraint_name
  398. self.bObject = c
  399. props_sockets = self.gen_property_socket_map()
  400. evaluate_sockets(self, c, props_sockets)
  401. self.executed = True
  402. class LinkInheritConstraint(MantisLinkNode):
  403. def __init__(self, signature, base_tree):
  404. super().__init__(signature, base_tree, LinkInheritConstraintSockets)
  405. self.init_parameters(additional_parameters={"Name":None })
  406. self.set_traverse([("Input Relationship", "Output Relationship")])
  407. def GetxForm(self):
  408. return GetxForm(self)
  409. def bExecute(self, context):
  410. prepare_parameters(self)
  411. print(wrapGreen("Creating ")+wrapWhite("Child-Of")+
  412. wrapGreen(" Constraint for bone: ") +
  413. wrapOrange(self.GetxForm().bGetObject().name))
  414. c = self.GetxForm().bGetObject().constraints.new('CHILD_OF')
  415. self.get_target_and_subtarget(c)
  416. if constraint_name := self.evaluate_input("Name"):
  417. c.name = constraint_name
  418. self.bObject = c
  419. props_sockets = self.gen_property_socket_map()
  420. evaluate_sockets(self, c, props_sockets)
  421. c.set_inverse_pending
  422. self.executed = True
  423. class LinkInverseKinematics(MantisLinkNode):
  424. def __init__(self, signature, base_tree):
  425. super().__init__(signature, base_tree, LinkInverseKinematicsSockets)
  426. self.init_parameters(additional_parameters={"Name":None })
  427. self.set_traverse([("Input Relationship", "Output Relationship")])
  428. def GetxForm(self):
  429. return GetxForm(self)
  430. def get_base_ik_bone(self, ik_bone):
  431. chain_length : int = (self.evaluate_input("Chain Length"))
  432. if not isinstance(chain_length, (int, float)):
  433. raise GraphError(f"Chain Length must be an integer number in {self}::Chain Length")
  434. if chain_length == 0:
  435. chain_length = int("inf")
  436. base_ik_bone = ik_bone; i=1
  437. while (i<chain_length) and (base_ik_bone.parent):
  438. base_ik_bone=base_ik_bone.parent; i+=1
  439. return base_ik_bone
  440. # We need to do the calculation in a "full circle", meaning the pole_angle
  441. # can go over pi or less than -pi - but the actuall constraint value must
  442. # be clamped in that range.
  443. # so we simply wrap the value.
  444. # not very efficient but it's OK
  445. def set_pole_angle(self, angle: float) -> None:
  446. from math import pi
  447. def wrap(min : float, max : float, value: float) -> float:
  448. range = max-min; remainder = value % range
  449. if remainder > max: return min + remainder-max
  450. else: return remainder
  451. self.bObject.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. ik_axis = (end_effector-start_effector).normalized()
  478. from .utilities import project_point_to_plane
  479. pole_planar_projection = project_point_to_plane(pole_location, start_effector, ik_axis)
  480. # this planar projection is necessary because the IK axis is different than the base_bone's y axis
  481. planar_projection = project_point_to_plane(knee_location, start_effector, ik_axis)
  482. knee_direction =(planar_projection - start_effector).normalized()
  483. pole_direction =(pole_planar_projection - start_effector).normalized()
  484. return knee_direction.angle(pole_direction)
  485. def calc_pole_angle_post(self, c, ik_bone, context):
  486. """
  487. This function should give us a completely accurate result for IK.
  488. """
  489. from time import time
  490. start_time=time()
  491. def signed_angle(vector_u, vector_v, normal):
  492. # it seems that this fails if the vectors are exactly aligned under certain circumstances.
  493. angle = vector_u.angle(vector_v, 0.0) # So we use a fallback of 0
  494. # Normal specifies orientation
  495. if angle != 0 and vector_u.cross(vector_v).angle(normal) < 1:
  496. angle = -angle
  497. return angle
  498. # we have already checked for valid data.
  499. ik_handle = c.target.pose.bones[c.subtarget]
  500. base_ik_bone = self.get_base_ik_bone(ik_bone)
  501. start_effector = base_ik_bone.bone.head_local
  502. angle = c.pole_angle
  503. dg = context.view_layer.depsgraph
  504. dg.update()
  505. ik_axis = (ik_handle.bone.head_local-start_effector).normalized()
  506. center_point = start_effector +(ik_axis*base_ik_bone.bone.length)
  507. knee_direction = base_ik_bone.bone.tail_local - center_point
  508. current_knee_direction = base_ik_bone.tail-center_point
  509. error=signed_angle(current_knee_direction, knee_direction, ik_axis)
  510. if error == 0:
  511. prGreen("No Fine-tuning needed."); return
  512. # Flip it if needed
  513. dot_before=current_knee_direction.dot(knee_direction)
  514. if dot_before < 0 and angle!=0: # then it is not aligned and we should check the inverse
  515. angle = -angle; c.pole_angle=angle
  516. dg.update()
  517. current_knee_direction = base_ik_bone.tail-center_point
  518. dot_after=current_knee_direction.dot(knee_direction)
  519. if dot_after < dot_before: # they are somehow less aligned
  520. prPurple("Mantis has gone down an unexpected code path. Please report this as a bug.")
  521. angle = -angle; self.set_pole_angle(angle)
  522. dg.update()
  523. # now we can do a bisect search to find the best value.
  524. error_threshhold = FLOAT_EPSILON
  525. max_iterations=600
  526. error=signed_angle(current_knee_direction, knee_direction, ik_axis)
  527. if error == 0:
  528. prGreen("No Fine-tuning needed."); return
  529. angle+=error
  530. alt_angle = angle+(error*-2) # should be very near the center when flipped here
  531. # we still need to bisect search because the relationship of pole_angle <==> error is somewhat unpredictable
  532. upper_bounds = alt_angle if alt_angle > angle else angle
  533. lower_bounds = alt_angle if alt_angle < angle else angle
  534. i=0
  535. while ( True ):
  536. if (i>=max_iterations):
  537. prOrange(f"IK Pole Angle Set reached max iterations of {i} in {time()-start_time} seconds")
  538. break
  539. if (abs(error)<error_threshhold) or (upper_bounds<=lower_bounds):
  540. prPurple(f"IK Pole Angle Set converged after {i} iterations with error={error} in {time()-start_time} seconds")
  541. break
  542. # get the center-point betweeen the bounds
  543. try_angle = lower_bounds + (upper_bounds-lower_bounds)/2
  544. self.set_pole_angle(try_angle); dg.update()
  545. error=signed_angle((base_ik_bone.tail-center_point), knee_direction, ik_axis)
  546. if error>0: upper_bounds=try_angle
  547. if error<0: lower_bounds=try_angle
  548. i+=1
  549. def bExecute(self, context):
  550. prepare_parameters(self)
  551. print(wrapGreen("Creating ")+wrapOrange("Inverse Kinematics")+
  552. wrapGreen(" Constraint for bone: ") +
  553. wrapOrange(self.GetxForm().bGetObject().name))
  554. ik_bone = self.GetxForm().bGetObject()
  555. c = self.GetxForm().bGetObject().constraints.new('IK')
  556. self.get_target_and_subtarget(c)
  557. self.get_target_and_subtarget(c, input_name = 'Pole Target')
  558. if constraint_name := self.evaluate_input("Name"):
  559. c.name = constraint_name
  560. self.bObject = c
  561. c.chain_count = 1 # so that, if there are errors, this doesn't print
  562. # a whole bunch of circular dependency crap from having infinite chain length
  563. if (c.pole_target):
  564. self.set_pole_angle(self.calc_pole_angle_pre(c, ik_bone))
  565. props_sockets = self.gen_property_socket_map()
  566. evaluate_sockets(self, c, props_sockets)
  567. print (props_sockets)
  568. c.use_location = self.evaluate_input("Position") > 0
  569. c.use_rotation = self.evaluate_input("Rotation") > 0
  570. self.executed = True
  571. def bFinalize(self, bContext = None):
  572. # adding a test here
  573. if bContext:
  574. ik_bone = self.GetxForm().bGetObject(mode='POSE')
  575. if self.bObject.pole_target:
  576. prWhite(f"Fine-tuning IK Pole Angle for {self}")
  577. # make sure to enable it first
  578. enabled_before = self.bObject.mute
  579. self.bObject.mute = False
  580. self.calc_pole_angle_post(self.bObject, ik_bone, bContext)
  581. self.bObject.mute = enabled_before
  582. super().bFinalize(bContext)
  583. def ik_report_error(pb, context, do_print=False):
  584. dg = context.view_layer.depsgraph
  585. dg.update()
  586. loc1, rot_quaternion1, scl1 = pb.matrix.decompose()
  587. loc2, rot_quaternion2, scl2 = pb.bone.matrix_local.decompose()
  588. location_error=(loc1-loc2).length
  589. rotation_error = rot_quaternion1.rotation_difference(rot_quaternion2).angle
  590. scale_error = (scl1-scl2).length
  591. if location_error < FLOAT_EPSILON: location_error = 0
  592. if abs(rotation_error) < FLOAT_EPSILON: rotation_error = 0
  593. if scale_error < FLOAT_EPSILON: scale_error = 0
  594. if do_print:
  595. print (f"IK Location Error: {location_error}")
  596. print (f"IK Rotation Error: {rotation_error}")
  597. print (f"IK Scale Error : {scale_error}")
  598. return (location_error, rotation_error, scale_error)
  599. # This is kinda a weird design decision?
  600. class LinkDrivenParameter(MantisLinkNode):
  601. '''A node representing an armature object'''
  602. def __init__(self, signature, base_tree):
  603. super().__init__(signature, base_tree, LinkDrivenParameterSockets)
  604. self.init_parameters(additional_parameters={ "Name":None })
  605. self.set_traverse([("Input Relationship", "Output Relationship")])
  606. def GetxForm(self):
  607. return GetxForm(self)
  608. def bExecute(self, bContext = None,):
  609. prepare_parameters(self)
  610. prGreen("Executing Driven Parameter node")
  611. prop = self.evaluate_input("Parameter")
  612. index = self.evaluate_input("Index")
  613. value = self.evaluate_input("Value")
  614. xf = self.GetxForm()
  615. ob = xf.bGetObject(mode="POSE")
  616. # IMPORTANT: this node only works on pose bone attributes.
  617. self.bObject = ob
  618. length=1
  619. if hasattr(ob, prop):
  620. try:
  621. length = len(getattr(ob, prop))
  622. except TypeError:
  623. pass
  624. except AttributeError:
  625. pass
  626. else:
  627. raise AttributeError(f"Cannot Set value {prop} on object because it does not exist.")
  628. def_value = 0.0
  629. if length>1:
  630. def_value=[0.0]*length
  631. self.parameters["Value"] = tuple( 0.0 if i != index else value for i in range(length))
  632. props_sockets = {
  633. prop: ("Value", def_value)
  634. }
  635. evaluate_sockets(self, ob, props_sockets)
  636. self.executed = True
  637. def bFinalize(self, bContext = None):
  638. driver = self.evaluate_input("Value")
  639. try:
  640. for i, val in enumerate(self.parameters["Value"]):
  641. from .drivers import MantisDriver
  642. if isinstance(val, MantisDriver):
  643. driver["ind"] = i
  644. val = driver
  645. except AttributeError:
  646. self.parameters["Value"] = driver
  647. except TypeError:
  648. self.parameters["Value"] = driver
  649. super().bFinalize(bContext)
  650. class LinkArmature(MantisLinkNode):
  651. '''A node representing an armature object'''
  652. def __init__(self, signature, base_tree,):
  653. super().__init__(signature, base_tree, LinkArmatureSockets)
  654. self.init_parameters(additional_parameters={"Name":None })
  655. self.set_traverse([("Input Relationship", "Output Relationship")])
  656. setup_custom_props(self) # <-- this takes care of the runtime-added sockets
  657. def GetxForm(self):
  658. return GetxForm(self)
  659. def bExecute(self, bContext = None,):
  660. prGreen("Creating Armature Constraint for bone: \""+ self.GetxForm().bGetObject().name + "\"")
  661. prepare_parameters(self)
  662. c = self.GetxForm().bGetObject().constraints.new('ARMATURE')
  663. if constraint_name := self.evaluate_input("Name"):
  664. c.name = constraint_name
  665. self.bObject = c
  666. # get number of targets
  667. num_targets = len( list(self.inputs.values())[6:] )//2
  668. props_sockets = self.gen_property_socket_map()
  669. targets_weights = {}
  670. for i in range(num_targets):
  671. target = c.targets.new()
  672. target_input_name = list(self.inputs.keys())[i*2+6 ]
  673. weight_input_name = list(self.inputs.keys())[i*2+6+1]
  674. self.get_target_and_subtarget(target, target_input_name)
  675. weight_value=self.evaluate_input(weight_input_name)
  676. if not isinstance(weight_value, float):
  677. weight_value=0
  678. targets_weights[i]=weight_value
  679. props_sockets["targets[%d].weight" % i] = (weight_input_name, 0)
  680. # targets_weights.append({"weight":(weight_input_name, 0)})
  681. evaluate_sockets(self, c, props_sockets)
  682. for target, value in targets_weights.items():
  683. c.targets[target].weight=value
  684. self.executed = True
  685. class LinkSplineIK(MantisLinkNode):
  686. '''A node representing an armature object'''
  687. def __init__(self, signature, base_tree):
  688. super().__init__(signature, base_tree, LinkSplineIKSockets)
  689. self.init_parameters(additional_parameters={"Name":None })
  690. self.set_traverse([("Input Relationship", "Output Relationship")])
  691. def GetxForm(self):
  692. return GetxForm(self)
  693. def bExecute(self, bContext = None,):
  694. prepare_parameters(self)
  695. prGreen("Creating Spline-IK Constraint for bone: \""+ self.GetxForm().bGetObject().name + "\"")
  696. c = self.GetxForm().bGetObject().constraints.new('SPLINE_IK')
  697. self.get_target_and_subtarget(c)
  698. if constraint_name := self.evaluate_input("Name"):
  699. c.name = constraint_name
  700. self.bObject = c
  701. props_sockets = self.gen_property_socket_map()
  702. evaluate_sockets(self, c, props_sockets)
  703. self.executed = True