link_nodes.py 39 KB

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