link_nodes.py 43 KB

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