link_nodes.py 41 KB

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