misc_nodes.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692
  1. from .node_container_common import *
  2. from .base_definitions import MantisNode, NodeSocket
  3. from .xForm_containers import xFormArmature, xFormBone
  4. from math import pi, tau
  5. def TellClasses():
  6. return [
  7. # utility
  8. InputFloat,
  9. InputIntNode,
  10. InputVector,
  11. InputBoolean,
  12. InputBooleanThreeTuple,
  13. InputRotationOrder,
  14. InputTransformSpace,
  15. InputString,
  16. InputMatrix,
  17. InputExistingGeometryObject,
  18. InputExistingGeometryData,
  19. UtilityGeometryOfXForm,
  20. UtilityNameOfXForm,
  21. UtilityPointFromCurve,
  22. UtilityMatrixFromCurve,
  23. UtilityMatricesFromCurve,
  24. UtilityNumberOfCurveSegments,
  25. UtilityMatrixFromCurveSegment,
  26. UtilityKDChoosePoint,
  27. UtilityKDChooseXForm,
  28. UtilityMetaRig,
  29. UtilityBoneProperties,
  30. UtilityDriverVariable,
  31. UtilityDriver,
  32. UtilityFCurve,
  33. UtilityKeyframe,
  34. UtilitySwitch,
  35. UtilityCombineThreeBool,
  36. UtilityCombineVector,
  37. UtilitySeparateVector,
  38. UtilityCatStrings,
  39. UtilityGetBoneLength,
  40. UtilityPointFromBoneMatrix,
  41. UtilitySetBoneLength,
  42. UtilityMatrixSetLocation,
  43. UtilityMatrixGetLocation,
  44. UtilityMatrixFromXForm,
  45. UtilityAxesFromMatrix,
  46. UtilityBoneMatrixHeadTailFlip,
  47. UtilityMatrixTransform,
  48. UtilityTransformationMatrix,
  49. UtilityIntToString,
  50. UtilityArrayGet,
  51. UtilityArrayLength,
  52. UtilitySetBoneMatrixTail,
  53. # Control flow switches
  54. UtilityCompare,
  55. UtilityChoose,
  56. # useful NoOp:
  57. UtilityPrint,
  58. ]
  59. def matrix_from_head_tail(head, tail, normal=None):
  60. from mathutils import Vector, Quaternion, Matrix
  61. if normal is None:
  62. rotation = Vector((0,1,0)).rotation_difference((tail-head).normalized()).to_matrix()
  63. m= Matrix.LocRotScale(head, rotation, None)
  64. m[3][3] = (tail-head).length
  65. else: # construct a basis matrix
  66. m = Matrix.Identity(3)
  67. axis = (tail-head).normalized()
  68. conormal = axis.cross(normal)
  69. m[0]=conormal
  70. m[1]=axis
  71. m[2]=normal
  72. m = m.transposed().to_4x4()
  73. return m
  74. def get_ribbon_mesh_from_curve(curve_name : str, execution_id : str, bContext):
  75. from bpy import data
  76. curve = data.objects.get(curve_name)
  77. assert curve.type == 'CURVE', f"ERROR: object is not a curve: {curve_name}"
  78. from .utilities import mesh_from_curve
  79. m_name = curve_name+'.'+str(hash(curve_name+'.'+execution_id))
  80. if not (m := data.meshes.get(m_name)):
  81. m = mesh_from_curve(curve, bContext)
  82. m.name = m_name
  83. return m
  84. def cleanup_curve(curve_name : str, execution_id : str) -> None:
  85. import bpy
  86. curve = bpy.data.objects.get(curve_name)
  87. m_name = curve_name+'.'+str(hash(curve.name+'.'+ execution_id))
  88. if (mesh := bpy.data.meshes.get(m_name)):
  89. bpy.data.meshes.remove(mesh)
  90. def kd_find(node, points, ref_pt, num_points):
  91. if num_points == 0:
  92. raise RuntimeError(f"Cannot find 0 points for {node}")
  93. from mathutils import kdtree
  94. kd = kdtree.KDTree(len(points))
  95. for i, pt in enumerate(points):
  96. try:
  97. kd.insert(pt, i)
  98. except (TypeError, ValueError) as e:
  99. prRed(f"Cannot get point from for {node}")
  100. raise e
  101. kd.balance()
  102. try:
  103. if num_points == 1: # make it a list to keep it consistent with
  104. result = [kd.find(ref_pt)] # find_n which returns a list
  105. else:
  106. result = kd.find_n(ref_pt, num_points)
  107. # the result of kd.find has some other stuff we don't care about
  108. except (TypeError, ValueError) as e:
  109. prRed(f"Reference Point {ref_pt} invalid for {node}")
  110. raise e
  111. return result
  112. def array_choose_relink(node, indices, array_input, output, ):
  113. """
  114. Used to choose the correct link to send out of an array-choose node.
  115. """
  116. from .utilities import init_dependencies
  117. keep_links = []
  118. init_my_connections=[]
  119. for index in indices:
  120. l = node.inputs[array_input].links[index]
  121. keep_links.append(l)
  122. init_my_connections.append(l.from_node)
  123. for link in node.outputs[output].links:
  124. to_node = link.to_node
  125. for l in keep_links:
  126. l.from_node.outputs[l.from_socket].connect(to_node, link.to_socket)
  127. link.die()
  128. def array_choose_data(node, data, output):
  129. """
  130. Used to choose the correct data to send out of an array-choose node.
  131. """
  132. from .utilities import init_dependencies
  133. # We need to make new outputs and link from each one based on the data in the array...
  134. node.outputs.init_sockets([output+"."+str(i).zfill(4) for i in range(len(data)) ])
  135. for i, data_item in enumerate(data):
  136. node.parameters[output+"."+str(i).zfill(4)] = data_item
  137. for link in node.outputs[output].links:
  138. to_node = link.to_node
  139. for i in range(len(data)):
  140. # Make a link from the new output.
  141. node.outputs[output+"."+str(i).zfill(4)].connect(to_node, link.to_socket)
  142. link.die()
  143. #*#-------------------------------#++#-------------------------------#*#
  144. # U T I L I T Y N O D E S
  145. #*#-------------------------------#++#-------------------------------#*#
  146. class InputFloat(MantisNode):
  147. '''A node representing float input'''
  148. def __init__(self, signature, base_tree):
  149. super().__init__(signature, base_tree)
  150. outputs = ["Float Input"]
  151. self.outputs.init_sockets(outputs)
  152. self.init_parameters()
  153. self.node_type = 'UTILITY'
  154. self.prepared = True
  155. self.executed = True
  156. class InputIntNode(MantisNode):
  157. '''A node representing integer input'''
  158. def __init__(self, signature, base_tree):
  159. super().__init__(signature, base_tree)
  160. outputs = ["Integer"]
  161. self.outputs.init_sockets(outputs)
  162. self.init_parameters()
  163. self.node_type = 'UTILITY'
  164. self.prepared = True
  165. self.executed = True
  166. class InputVector(MantisNode):
  167. '''A node representing vector input'''
  168. def __init__(self, signature, base_tree):
  169. super().__init__(signature, base_tree)
  170. outputs = [""]
  171. self.outputs.init_sockets(outputs)
  172. self.init_parameters()
  173. self.node_type = 'UTILITY'
  174. self.prepared = True
  175. self.executed = True
  176. class InputBoolean(MantisNode):
  177. '''A node representing boolean input'''
  178. def __init__(self, signature, base_tree):
  179. super().__init__(signature, base_tree)
  180. outputs = [""]
  181. self.outputs.init_sockets(outputs)
  182. self.init_parameters()
  183. self.node_type = 'UTILITY'
  184. self.prepared = True
  185. self.executed = True
  186. class InputBooleanThreeTuple(MantisNode):
  187. '''A node representing a tuple of three booleans'''
  188. def __init__(self, signature, base_tree):
  189. super().__init__(signature, base_tree)
  190. outputs = [""]
  191. self.outputs.init_sockets(outputs)
  192. self.init_parameters()
  193. self.node_type = 'UTILITY'
  194. self.prepared = True
  195. self.executed = True
  196. class InputRotationOrder(MantisNode):
  197. '''A node representing string input for rotation order'''
  198. def __init__(self, signature, base_tree):
  199. super().__init__(signature, base_tree)
  200. outputs = [""]
  201. self.outputs.init_sockets(outputs)
  202. self.init_parameters()
  203. self.node_type = 'UTILITY'
  204. self.prepared = True
  205. self.executed = True
  206. class InputTransformSpace(MantisNode):
  207. '''A node representing string input for transform space'''
  208. def __init__(self, signature, base_tree):
  209. super().__init__(signature, base_tree)
  210. outputs = [""]
  211. self.outputs.init_sockets(outputs)
  212. self.init_parameters()
  213. self.node_type = 'UTILITY'
  214. self.prepared = True
  215. self.executed = True
  216. def evaluate_input(self, input_name):
  217. return self.parameters[""]
  218. class InputString(MantisNode):
  219. '''A node representing string input'''
  220. def __init__(self, signature, base_tree):
  221. super().__init__(signature, base_tree)
  222. outputs = [""]
  223. self.outputs.init_sockets(outputs)
  224. self.init_parameters()
  225. self.node_type = 'UTILITY'
  226. self.prepared = True
  227. self.executed = True
  228. class InputMatrix(MantisNode):
  229. '''A node representing axis-angle quaternion input'''
  230. def __init__(self, signature, base_tree):
  231. super().__init__(signature, base_tree)
  232. outputs = ["Matrix",]
  233. self.outputs.init_sockets(outputs)
  234. self.init_parameters()
  235. self.node_type = 'UTILITY'
  236. self.prepared = True
  237. self.executed = True
  238. class UtilityMatrixFromCurve(MantisNode):
  239. '''Get a matrix from a curve'''
  240. def __init__(self, signature, base_tree):
  241. super().__init__(signature, base_tree)
  242. inputs = [
  243. "Curve" ,
  244. "Total Divisions" ,
  245. "Matrix Index" ,
  246. ]
  247. outputs = [
  248. "Matrix" ,
  249. ]
  250. self.inputs.init_sockets(inputs)
  251. self.outputs.init_sockets(outputs)
  252. self.init_parameters()
  253. self.node_type = "UTILITY"
  254. def bPrepare(self, bContext = None,):
  255. from mathutils import Matrix
  256. import bpy
  257. mat = Matrix.Identity(4)
  258. curve_name = self.evaluate_input("Curve")
  259. curve = bpy.data.objects.get(curve_name)
  260. if not curve:
  261. prRed(f"WARN: No curve found for {self}. Using an identity matrix instead.")
  262. mat[3][3] = 1.0
  263. elif curve.type != "CURVE":
  264. prRed(f"WARN: Object {curve.name} is not a curve. Using an identity matrix instead.")
  265. mat[3][3] = 1.0
  266. else:
  267. if bContext is None: bContext = bpy.context # is this wise?
  268. m = get_ribbon_mesh_from_curve(curve.name, self.base_tree.execution_id, bContext)
  269. from .utilities import data_from_ribbon_mesh
  270. #
  271. num_divisions = self.evaluate_input("Total Divisions")
  272. m_index = self.evaluate_input("Matrix Index")
  273. factors = [1/num_divisions*m_index, 1/num_divisions*(m_index+1)]
  274. data = data_from_ribbon_mesh(m, [factors], curve.matrix_world)
  275. head=data[0][0][0]
  276. tail= data[0][0][1]
  277. axis = (tail-head).normalized()
  278. normal=data[0][2][0]
  279. # make sure the normal is perpendicular to the tail
  280. from .utilities import make_perpendicular
  281. normal = make_perpendicular(axis, normal)
  282. mat = matrix_from_head_tail(head, tail, normal)
  283. # this is in world space... let's just convert it back
  284. mat.translation = head - curve.location
  285. mat[3][3]=(tail-head).length
  286. # TODO HACK TODO
  287. # all the nodes should work in world-space, and it should be the responsibility
  288. # of the xForm node to convert!
  289. self.parameters["Matrix"] = mat
  290. self.prepared = True
  291. self.executed = True
  292. def bFinalize(self, bContext=None):
  293. cleanup_curve(self.evaluate_input("Curve"), self.base_tree.execution_id)
  294. class UtilityPointFromCurve(MantisNode):
  295. '''Get a point from a curve'''
  296. def __init__(self, signature, base_tree):
  297. super().__init__(signature, base_tree)
  298. inputs = [
  299. "Curve" ,
  300. "Factor" ,
  301. ]
  302. outputs = [
  303. "Point" ,
  304. ]
  305. self.inputs.init_sockets(inputs)
  306. self.outputs.init_sockets(outputs)
  307. self.init_parameters()
  308. self.node_type = "UTILITY"
  309. def bPrepare(self, bContext = None,):
  310. import bpy
  311. curve = bpy.data.objects.get(self.evaluate_input("Curve"))
  312. if not curve:
  313. raise RuntimeError(f"No curve found for {self}.")
  314. elif curve.type != "CURVE":
  315. raise GraphError(f"ERROR: Object {curve.name} is not a curve.")
  316. else:
  317. if bContext is None: bContext = bpy.context # is this wise?
  318. m = get_ribbon_mesh_from_curve(curve.name, self.base_tree.execution_id, bContext)
  319. from .utilities import data_from_ribbon_mesh
  320. #
  321. num_divisions = 1
  322. factors = [self.evaluate_input("Factor")]
  323. data = data_from_ribbon_mesh(m, [factors], curve.matrix_world)
  324. p = data[0][0][0] - curve.location
  325. self.parameters["Point"] = p
  326. self.prepared, self.executed = True, True
  327. def bFinalize(self, bContext=None):
  328. cleanup_curve(self.evaluate_input("Curve"), self.base_tree.execution_id)
  329. class UtilityMatricesFromCurve(MantisNode):
  330. '''Get matrices from a curve'''
  331. def __init__(self, signature, base_tree):
  332. super().__init__(signature, base_tree)
  333. inputs = [
  334. "Curve" ,
  335. "Total Divisions" ,
  336. ]
  337. outputs = [
  338. "Matrices" ,
  339. ]
  340. self.inputs.init_sockets(inputs)
  341. self.outputs.init_sockets(outputs)
  342. self.init_parameters()
  343. self.node_type = "UTILITY"
  344. def bPrepare(self, bContext = None,):
  345. import time
  346. # start_time = time.time()
  347. #
  348. from mathutils import Matrix
  349. import bpy
  350. m = Matrix.Identity(4)
  351. curve_name = self.evaluate_input("Curve")
  352. curve = bpy.data.objects.get(curve_name)
  353. if not curve:
  354. prRed(f"WARN: No curve found for {self}. Using an identity matrix instead.")
  355. m[3][3] = 1.0
  356. elif curve.type != "CURVE":
  357. prRed(f"WARN: Object {curve.name} is not a curve. Using an identity matrix instead.")
  358. m[3][3] = 1.0
  359. else:
  360. if bContext is None: bContext = bpy.context # is this wise?
  361. mesh = get_ribbon_mesh_from_curve(curve.name, self.base_tree.execution_id, bContext)
  362. from .utilities import data_from_ribbon_mesh
  363. num_divisions = self.evaluate_input("Total Divisions")
  364. factors = [0.0] + [(1/num_divisions*(i+1)) for i in range(num_divisions)]
  365. data = data_from_ribbon_mesh(mesh, [factors], curve.matrix_world)
  366. # 0 is the spline index. 0 selects points as opposed to normals or whatever.
  367. from .utilities import make_perpendicular
  368. matrices = [matrix_from_head_tail(
  369. data[0][0][i],
  370. data[0][0][i+1],
  371. make_perpendicular((data[0][0][i+1]-data[0][0][i]).normalized(), data[0][2][i]),) \
  372. for i in range(num_divisions)]
  373. for link in self.outputs["Matrices"].links:
  374. for i, m in enumerate(matrices):
  375. name = "Matrix"+str(i).zfill(4)
  376. if not (out := self.outputs.get(name)): # reuse them if there are multiple links.
  377. out = self.outputs[name] = NodeSocket(name = name, node=self)
  378. c = out.connect(link.to_node, link.to_socket)
  379. # prOrange(c)
  380. self.parameters[name] = m
  381. # print (mesh)
  382. link.die()
  383. self.prepared = True
  384. self.executed = True
  385. # prGreen(f"Matrices from curves took {time.time() - start_time} seconds.")
  386. def bFinalize(self, bContext=None):
  387. import bpy
  388. curve_name = self.evaluate_input("Curve")
  389. curve = bpy.data.objects.get(curve_name)
  390. m_name = curve.name+'.'+self.base_tree.execution_id
  391. if (mesh := bpy.data.meshes.get(m_name)):
  392. prGreen(f"Freeing mesh data {m_name}...")
  393. bpy.data.meshes.remove(mesh)
  394. class UtilityNumberOfCurveSegments(MantisNode):
  395. def __init__(self, signature, base_tree):
  396. super().__init__(signature, base_tree)
  397. inputs = [
  398. "Curve" ,
  399. "Spline Index" ,
  400. ]
  401. outputs = [
  402. "Number of Segments" ,
  403. ]
  404. self.inputs.init_sockets(inputs)
  405. self.outputs.init_sockets(outputs)
  406. self.init_parameters()
  407. self.node_type = "UTILITY"
  408. def bPrepare(self, bContext = None,):
  409. import bpy
  410. curve_name = self.evaluate_input("Curve")
  411. curve = bpy.data.objects.get(curve_name)
  412. spline = curve.data.splines[self.evaluate_input("Spline Index")]
  413. if spline.type == "BEZIER":
  414. self.parameters["Number of Segments"] = len(spline.bezier_points)-1
  415. else:
  416. self.parameters["Number of Segments"] = len(spline.points)-1
  417. self.prepared = True
  418. self.executed = True
  419. class UtilityMatrixFromCurveSegment(MantisNode):
  420. def __init__(self, signature, base_tree):
  421. super().__init__(signature, base_tree)
  422. inputs = [
  423. "Curve" ,
  424. "Spline Index" ,
  425. "Segment Index" ,
  426. ]
  427. outputs = [
  428. "Matrix" ,
  429. ]
  430. self.inputs.init_sockets(inputs)
  431. self.outputs.init_sockets(outputs)
  432. self.init_parameters()
  433. self.node_type = "UTILITY"
  434. def bPrepare(self, bContext = None,):
  435. import bpy
  436. curve = bpy.data.objects.get(self.evaluate_input("Curve"))
  437. if not curve:
  438. raise RuntimeError(f"No curve found for {self}.")
  439. elif curve.type != "CURVE":
  440. raise GraphError(f"ERROR: Object {curve.name} is not a curve.")
  441. else:
  442. if bContext is None: bContext = bpy.context # is this wise?
  443. m = get_ribbon_mesh_from_curve(curve.name, self.base_tree.execution_id, bContext)
  444. from .utilities import data_from_ribbon_mesh
  445. # this section is dumb, but it is because the data_from_ribbon_mesh
  446. # function is designed to pull data from many splines at once (for optimization)
  447. # so we have to give it empty splines for each one we skip.
  448. # TODO: Refactor this to make it so I can select spline index
  449. spline_index = self.evaluate_input("Spline Index")
  450. spline = curve.data.splines[spline_index]
  451. splines_factors = [ [] for i in range (spline_index)]
  452. factors = [0.0]
  453. points = spline.bezier_points if spline.type == 'BEZIER' else spline.points
  454. total_length=0.0
  455. for i in range(len(points)-1):
  456. total_length+= (seg_length := (points[i+1].co - points[i].co).length)
  457. factors.append(seg_length)
  458. prev_length = 0.0
  459. for i in range(len(factors)):
  460. factors[i] = prev_length+factors[i]/total_length
  461. prev_length=factors[i]
  462. # Why does this happen? Floating point error?
  463. if factors[i]>1.0: factors[i] = 1.0
  464. splines_factors.append(factors)
  465. #
  466. data = data_from_ribbon_mesh(m, splines_factors, curve.matrix_world)
  467. segment_index = self.evaluate_input("Segment Index")
  468. head=data[spline_index][0][segment_index]
  469. tail= data[spline_index][0][segment_index+1]
  470. axis = (tail-head).normalized()
  471. normal=data[spline_index][2][segment_index]
  472. # make sure the normal is perpendicular to the tail
  473. from .utilities import make_perpendicular
  474. normal = make_perpendicular(axis, normal)
  475. m = matrix_from_head_tail(head, tail, normal)
  476. m.translation = head - curve.location
  477. m[3][3]=(tail-head).length
  478. self.parameters["Matrix"] = m
  479. self.prepared, self.executed = True, True
  480. def bFinalize(self, bContext=None):
  481. cleanup_curve(self.evaluate_input("Curve"), self.base_tree.execution_id)
  482. class UtilityKDChoosePoint(MantisNode):
  483. def __init__(self, signature, base_tree):
  484. super().__init__(signature, base_tree)
  485. inputs = [
  486. "Reference Point" ,
  487. "Points" ,
  488. "Number to Find" ,
  489. ]
  490. outputs = [
  491. "Result Point" ,
  492. "Result Index" ,
  493. "Result Distance" ,
  494. ]
  495. self.inputs.init_sockets(inputs)
  496. self.outputs.init_sockets(outputs)
  497. self.init_parameters()
  498. self.node_type = "UTILITY"
  499. def bPrepare(self, bContext = None,):
  500. from mathutils import Vector
  501. points= []
  502. ref_point = self.evaluate_input('Reference Point')
  503. num_points = self.evaluate_input('Number to Find')
  504. for i, l in enumerate(self.inputs['Points'].links):
  505. pt = self.evaluate_input('Points', i)
  506. points.append(pt)
  507. if not isinstance(pt, Vector):
  508. prRed(f"Cannot get point from {l.from_node} for {self}")
  509. assert ref_point is not None, wrapRed(f"Reference Point {ref_point} is invalid in node {self}")
  510. result = kd_find(self, points, ref_point, num_points)
  511. indices = [ found_point[1] for found_point in result ]
  512. distances = [ found_point[2] for found_point in result ]
  513. array_choose_relink(self, indices, "Points", "Result Point")
  514. array_choose_data(self, indices, "Result Index")
  515. array_choose_data(self, distances, "Result Distance")
  516. self.prepared, self.executed = True, True
  517. class UtilityKDChooseXForm(MantisNode):
  518. def __init__(self, signature, base_tree):
  519. super().__init__(signature, base_tree)
  520. inputs = [
  521. "Reference Point" ,
  522. "xForm Nodes" ,
  523. "Get Point Head/Tail" ,
  524. "Number to Find" ,
  525. ]
  526. outputs = [
  527. "Result xForm" ,
  528. "Result Index" ,
  529. "Result Distance" ,
  530. ]
  531. self.inputs.init_sockets(inputs)
  532. self.outputs.init_sockets(outputs)
  533. self.init_parameters()
  534. self.node_type = "UTILITY"
  535. def bPrepare(self, bContext = None,):
  536. if len(self.hierarchy_dependencies)==0 and len(self.hierarchy_connections)==0 and \
  537. len(self.connections)==0 and len(self.dependencies)==0:
  538. self.prepared, self.executed = True, True
  539. return #Either it is already done or it doesn't matter.
  540. from mathutils import Vector
  541. points= []
  542. ref_point = self.evaluate_input('Reference Point')
  543. num_points = self.evaluate_input('Number to Find')
  544. for i, l in enumerate(self.inputs['xForm Nodes'].links):
  545. matrix = l.from_node.evaluate_input('Matrix')
  546. if matrix is None:
  547. raise GraphError(f"Cannot get point from {l.from_node} for {self}. Does it have a matrix?")
  548. pt = matrix.translation
  549. if head_tail := self.evaluate_input("Get Point Head/Tail"):
  550. # get the Y-axis of the basis, assume it is normalized
  551. y_axis = Vector((matrix[0][1],matrix[1][1], matrix[2][1]))
  552. pt = pt.lerp(pt+y_axis*matrix[3][3], head_tail)
  553. points.append(pt)
  554. if not isinstance(pt, Vector):
  555. prRed(f"Cannot get point from {l.from_node} for {self}")
  556. assert ref_point is not None, wrapRed(f"Reference Point {ref_point} is invalid in node {self}")
  557. result = kd_find(self, points, ref_point, num_points)
  558. indices = [ found_point[1] for found_point in result ]
  559. distances = [ found_point[2] for found_point in result ]
  560. array_choose_relink(self, indices, "xForm Nodes", "Result xForm")
  561. array_choose_data(self, indices, "Result Index")
  562. array_choose_data(self, distances, "Result Distance")
  563. self.prepared, self.executed = True, True
  564. class UtilityMetaRig(MantisNode):
  565. '''A node representing an armature object'''
  566. def __init__(self, signature, base_tree):
  567. super().__init__(signature, base_tree)
  568. inputs = [
  569. "Meta-Armature" ,
  570. "Meta-Bone" ,
  571. ]
  572. outputs = [
  573. "Matrix" ,
  574. ]
  575. self.inputs.init_sockets(inputs)
  576. self.outputs.init_sockets(outputs)
  577. self.init_parameters()
  578. self.node_type = "UTILITY"
  579. def bPrepare(self, bContext = None,):
  580. #kinda clumsy, whatever
  581. import bpy
  582. from mathutils import Matrix
  583. m = Matrix.Identity(4)
  584. meta_rig = self.evaluate_input("Meta-Armature")
  585. meta_bone = self.evaluate_input("Meta-Bone")
  586. if meta_rig:
  587. if ( armOb := bpy.data.objects.get(meta_rig) ):
  588. m = armOb.matrix_world
  589. if ( b := armOb.data.bones.get(meta_bone)):
  590. # calculate the correct object-space matrix
  591. m = Matrix.Identity(3)
  592. bones = [] # from the last ancestor, mult the matrices until we get to b
  593. while (b): bones.append(b); b = b.parent
  594. while (bones): b = bones.pop(); m = m @ b.matrix
  595. m = Matrix.Translation(b.head_local) @ m.to_4x4()
  596. #
  597. m[3][3] = b.length # this is where I arbitrarily decided to store length
  598. # else:
  599. # prRed("no bone for MetaRig node ", self)
  600. else:
  601. raise RuntimeError(wrapRed(f"No meta-rig input for MetaRig node {self}"))
  602. self.parameters["Matrix"] = m
  603. self.prepared = True
  604. self.executed = True
  605. class UtilityBoneProperties(MantisNode):
  606. '''A node representing a bone's gettable properties'''
  607. def __init__(self, signature, base_tree):
  608. super().__init__(signature, base_tree)
  609. outputs = [
  610. "matrix" ,
  611. "matrix_local" ,
  612. "matrix_basis" ,
  613. "head" ,
  614. "tail" ,
  615. "length" ,
  616. "rotation" ,
  617. "location" ,
  618. "scale" ,
  619. ]
  620. self.outputs.init_sockets(outputs)
  621. self.init_parameters()
  622. self.node_type = "UTILITY"
  623. self.prepared = True
  624. self.executed = True
  625. def fill_parameters(self, prototype=None):
  626. return
  627. # TODO this should probably be moved to Links
  628. class UtilityDriverVariable(MantisNode):
  629. '''A node representing an armature object'''
  630. def __init__(self, signature, base_tree):
  631. super().__init__(signature, base_tree)
  632. inputs = [
  633. "Variable Type" ,
  634. "Property" ,
  635. "Property Index" ,
  636. "Evaluation Space",
  637. "Rotation Mode" ,
  638. "xForm 1" ,
  639. "xForm 2" ,
  640. ]
  641. outputs = [
  642. "Driver Variable",
  643. ]
  644. self.inputs.init_sockets(inputs)
  645. self.outputs.init_sockets(outputs)
  646. self.init_parameters()
  647. self.node_type = "DRIVER" # MUST be run in Pose mode
  648. self.prepared = True
  649. def evaluate_input(self, input_name):
  650. if input_name == 'Property':
  651. if self.inputs.get('Property'):
  652. if self.inputs['Property'].is_linked:
  653. # get the name instead...
  654. trace = trace_single_line(self, input_name)
  655. return trace[1].name # the name of the socket
  656. return self.parameters["Property"]
  657. return super().evaluate_input(input_name)
  658. def GetxForm(self, index=1):
  659. trace = trace_single_line(self, "xForm 1" if index == 1 else "xForm 2")
  660. for node in trace[0]:
  661. if (node.__class__ in [xFormArmature, xFormBone]):
  662. return node #this will fetch the first one, that's good!
  663. return None
  664. def bExecute(self, bContext = None,):
  665. prepare_parameters(self)
  666. #prPurple ("Executing Driver Variable Node")
  667. xForm1 = self.GetxForm()
  668. xForm2 = self.GetxForm(index=2)
  669. # kinda clumsy
  670. if xForm1 : xForm1 = xForm1.bGetObject()
  671. if xForm2 : xForm2 = xForm2.bGetObject()
  672. v_type = self.evaluate_input("Variable Type")
  673. i = self.evaluate_input("Property Index"); dVarChannel = ""
  674. if (i >= 0): #negative values will use the vector property.
  675. if self.evaluate_input("Property") == 'location':
  676. if i == 0: dVarChannel = "LOC_X"
  677. elif i == 1: dVarChannel = "LOC_Y"
  678. elif i == 2: dVarChannel = "LOC_Z"
  679. else: raise RuntimeError("Invalid property index for %s" % self)
  680. if self.evaluate_input("Property") == 'rotation':
  681. if i == 0: dVarChannel = "ROT_X"
  682. elif i == 1: dVarChannel = "ROT_Y"
  683. elif i == 2: dVarChannel = "ROT_Z"
  684. elif i == 3: dVarChannel = "ROT_W"
  685. else: raise RuntimeError("Invalid property index for %s" % self)
  686. if self.evaluate_input("Property") == 'scale':
  687. if i == 0: dVarChannel = "SCALE_X"
  688. elif i == 1: dVarChannel = "SCALE_Y"
  689. elif i == 2: dVarChannel = "SCALE_Z"
  690. elif i == 3: dVarChannel = "SCALE_AVG"
  691. else: raise RuntimeError("Invalid property index for %s" % self)
  692. if self.evaluate_input("Property") == 'scale_average':
  693. dVarChannel = "SCALE_AVG"
  694. if dVarChannel: v_type = "TRANSFORMS"
  695. my_var = {
  696. "owner" : xForm1, # will be filled in by Driver
  697. "prop" : self.evaluate_input("Property"), # will be filled in by Driver
  698. "type" : v_type,
  699. "space" : self.evaluate_input("Evaluation Space"),
  700. "rotation_mode" : self.evaluate_input("Rotation Mode"),
  701. "xForm 1" : xForm1,#self.GetxForm(index = 1),
  702. "xForm 2" : xForm2,#self.GetxForm(index = 2),
  703. "channel" : dVarChannel,}
  704. # Push parameter to downstream connected node.connected:
  705. if (out := self.outputs["Driver Variable"]).is_linked:
  706. self.parameters[out.name] = my_var
  707. for link in out.links:
  708. link.to_node.parameters[link.to_socket] = my_var
  709. self.executed = True
  710. class UtilityKeyframe(MantisNode):
  711. '''A node representing a keyframe for a F-Curve'''
  712. def __init__(self, signature, base_tree):
  713. super().__init__(signature, base_tree)
  714. inputs = [
  715. "Frame" ,
  716. "Value" ,
  717. ]
  718. outputs = [
  719. "Keyframe" ,
  720. ]
  721. additional_parameters = {"Keyframe":{}}
  722. self.inputs.init_sockets(inputs)
  723. self.outputs.init_sockets(outputs)
  724. self.init_parameters( additional_parameters=additional_parameters)
  725. self.node_type = "DRIVER" # MUST be run in Pose mode
  726. setup_custom_props(self)
  727. def bPrepare(self, bContext = None,):
  728. key = self.parameters["Keyframe"]
  729. from mathutils import Vector
  730. key["co"]= Vector( (self.evaluate_input("Frame"), self.evaluate_input("Value"),))
  731. key["type"]="GENERATED"
  732. key["interpolation"] = "LINEAR"
  733. # eventually this will have the right data, TODO
  734. # self.parameters["Keyframe"] = key
  735. self.prepared = True
  736. self.executed = True
  737. class UtilityFCurve(MantisNode):
  738. '''A node representing an armature object'''
  739. def __init__(self, signature, base_tree):
  740. super().__init__(signature, base_tree)
  741. inputs = [
  742. "Extrapolation Mode",
  743. ]
  744. outputs = [
  745. "fCurve",
  746. ]
  747. self.inputs.init_sockets(inputs)
  748. self.outputs.init_sockets(outputs)
  749. self.init_parameters()
  750. self.node_type = "UTILITY"
  751. setup_custom_props(self)
  752. self.prepared = True
  753. def evaluate_input(self, input_name):
  754. return super().evaluate_input(input_name)
  755. def bExecute(self, bContext = None,):
  756. prepare_parameters(self)
  757. from .utilities import get_node_prototype
  758. np = get_node_prototype(self.signature, self.base_tree)
  759. extrap_mode = self.evaluate_input("Extrapolation Mode")
  760. keys = [] # ugly but whatever
  761. #['amplitude', 'back', 'bl_rna', 'co', 'co_ui', 'easing', 'handle_left', 'handle_left_type', 'handle_right', 'handle_right_type',
  762. # 'interpolation', 'period', 'rna_type', 'select_control_point', 'select_left_handle', 'select_right_handle', 'type']
  763. for k in self.inputs.keys():
  764. if k == 'Extrapolation Mode' : continue
  765. # print (self.inputs[k])
  766. if (key := self.evaluate_input(k)) is None:
  767. prOrange(f"WARN: No keyframe connected to {self}:{k}. Skipping Link.")
  768. else:
  769. keys.append(key)
  770. if len(keys) <1:
  771. prOrange(f"WARN: no keys in fCurve {self}.")
  772. keys.append(extrap_mode)
  773. self.parameters["fCurve"] = keys
  774. self.executed = True
  775. #TODO make the fCurve data a data class instead of a dict
  776. class UtilityDriver(MantisNode):
  777. '''A node representing an armature object'''
  778. def __init__(self, signature, base_tree):
  779. super().__init__(signature, base_tree)
  780. inputs = [
  781. "Driver Type" ,
  782. "Expression" ,
  783. "fCurve" ,
  784. ]
  785. outputs = [
  786. "Driver",
  787. ]
  788. from .drivers import MantisDriver
  789. additional_parameters = {
  790. "Driver":MantisDriver(),
  791. }
  792. self.inputs.init_sockets(inputs)
  793. self.outputs.init_sockets(outputs)
  794. self.init_parameters(additional_parameters=additional_parameters)
  795. self.node_type = "DRIVER" # MUST be run in Pose mode
  796. setup_custom_props(self)
  797. self.prepared = True
  798. def bExecute(self, bContext = None,):
  799. prepare_parameters(self)
  800. from .drivers import MantisDriver
  801. #prPurple("Executing Driver Node")
  802. my_vars = []
  803. keys = self.evaluate_input("fCurve")
  804. if keys is None or len(keys) <2:
  805. prWhite(f"INFO: no fCurve connected to {self}; using default fCurve.")
  806. from mathutils import Vector
  807. keys = [
  808. {"co":Vector( (0, 0,)), "type":"GENERATED", "interpolation":"LINEAR" },
  809. {"co":Vector( (1, 1,)), "type":"GENERATED", "interpolation":"LINEAR" },
  810. "CONSTANT",]
  811. for inp in list(self.inputs.keys() )[3:]:
  812. if (new_var := self.evaluate_input(inp)):
  813. new_var["name"] = inp
  814. my_vars.append(new_var)
  815. else:
  816. raise RuntimeError(f"Failed to initialize Driver variable for {self}")
  817. my_driver ={ "owner" : None,
  818. "prop" : None, # will be filled out in the node that uses the driver
  819. "expression" : self.evaluate_input("Expression"),
  820. "ind" : -1, # same here
  821. "type" : self.evaluate_input("Driver Type"),
  822. "vars" : my_vars,
  823. "keys" : keys[:-1],
  824. "extrapolation" : keys[-1] }
  825. my_driver = MantisDriver(my_driver)
  826. self.parameters["Driver"].update(my_driver)
  827. print("Initializing driver %s " % (wrapPurple(self.__repr__())) )
  828. self.executed = True
  829. class UtilitySwitch(MantisNode):
  830. '''A node representing an armature object'''
  831. def __init__(self, signature, base_tree):
  832. super().__init__(signature, base_tree)
  833. inputs = {
  834. "Parameter" ,
  835. "Parameter Index" ,
  836. "Invert Switch" ,
  837. }
  838. outputs = [
  839. "Driver",
  840. ]
  841. from .drivers import MantisDriver
  842. additional_parameters = {
  843. "Driver":MantisDriver(),
  844. }
  845. self.inputs.init_sockets(inputs)
  846. self.outputs.init_sockets(outputs)
  847. self.init_parameters(additional_parameters=additional_parameters)
  848. self.node_type = "DRIVER" # MUST be run in Pose mode
  849. self.prepared = True
  850. def evaluate_input(self, input_name):
  851. if input_name == 'Parameter':
  852. if self.inputs['Parameter'].is_connected:
  853. trace = trace_single_line(self, input_name)
  854. return trace[1].name # the name of the socket
  855. return self.parameters["Parameter"]
  856. return super().evaluate_input(input_name)
  857. def GetxForm(self,):
  858. trace = trace_single_line(self, "Parameter" )
  859. for node in trace[0]:
  860. if (node.__class__ in [xFormArmature, xFormBone]):
  861. return node #this will fetch the first one, that's good!
  862. return None
  863. def bExecute(self, bContext = None,):
  864. #prepare_parameters(self)
  865. #prPurple ("Executing Switch Node")
  866. xForm = self.GetxForm()
  867. if xForm : xForm = xForm.bGetObject()
  868. if not xForm:
  869. raise RuntimeError("Could not evaluate xForm for %s" % self)
  870. from .drivers import MantisDriver
  871. my_driver ={ "owner" : None,
  872. "prop" : None, # will be filled out in the node that uses the driver
  873. "ind" : -1, # same here
  874. "type" : "SCRIPTED",
  875. "vars" : [ { "owner" : xForm,
  876. "prop" : self.evaluate_input("Parameter"),
  877. "name" : "a",
  878. "type" : "SINGLE_PROP", } ],
  879. "keys" : [ { "co":(0,0),
  880. "interpolation": "LINEAR",
  881. "type":"KEYFRAME",}, #display type
  882. { "co":(1,1),
  883. "interpolation": "LINEAR",
  884. "type":"KEYFRAME",},],
  885. "extrapolation": 'CONSTANT', }
  886. my_driver ["expression"] = "a"
  887. my_driver = MantisDriver(my_driver)
  888. # this makes it so I can check for type later!
  889. if self.evaluate_input("Invert Switch") == True:
  890. my_driver ["expression"] = "1 - a"
  891. # this way, regardless of what order things are handled, the
  892. # driver is sent to the next node.
  893. # In the case of some drivers, the parameter may be sent out
  894. # before it's filled in (because there is a circular dependency)
  895. # I want to support this behaviour because Blender supports it.
  896. # We do not make a copy. We update the driver, so that
  897. # the same instance is filled out.
  898. self.parameters["Driver"].update(my_driver)
  899. print("Initializing driver %s " % (wrapPurple(self.__repr__())) )
  900. self.executed = True
  901. class UtilityCombineThreeBool(MantisNode):
  902. '''A node for combining three booleans into a boolean three-tuple'''
  903. def __init__(self, signature, base_tree):
  904. super().__init__(signature, base_tree)
  905. inputs = [
  906. "X" ,
  907. "Y" ,
  908. "Z" ,
  909. ]
  910. outputs = [
  911. "Three-Bool",
  912. ]
  913. self.inputs.init_sockets(inputs)
  914. self.outputs.init_sockets(outputs)
  915. self.init_parameters()
  916. self.node_type = "UTILITY"
  917. def bPrepare(self, bContext = None,):
  918. self.parameters["Three-Bool"] = (
  919. self.evaluate_input("X"),
  920. self.evaluate_input("Y"),
  921. self.evaluate_input("Z"), )
  922. self.prepared = True
  923. self.executed = True
  924. # Note this is a copy of the above. This needs to be de-duplicated.
  925. class UtilityCombineVector(MantisNode):
  926. '''A node for combining three floats into a vector'''
  927. def __init__(self, signature, base_tree):
  928. super().__init__(signature, base_tree)
  929. super().__init__(signature, base_tree)
  930. inputs = [
  931. "X" ,
  932. "Y" ,
  933. "Z" ,
  934. ]
  935. outputs = [
  936. "Vector",
  937. ]
  938. self.inputs.init_sockets(inputs)
  939. self.outputs.init_sockets(outputs)
  940. self.init_parameters()
  941. self.node_type = "UTILITY"
  942. def bPrepare(self, bContext = None,):
  943. #prPurple("Executing CombineVector Node")
  944. prepare_parameters(self)
  945. self.parameters["Vector"] = (
  946. self.evaluate_input("X"),
  947. self.evaluate_input("Y"),
  948. self.evaluate_input("Z"), )
  949. self.prepared = True
  950. self.executed = True
  951. class UtilitySeparateVector(MantisNode):
  952. '''A node for separating a vector into three floats'''
  953. def __init__(self, signature, base_tree):
  954. super().__init__(signature, base_tree)
  955. inputs = [
  956. "Vector"
  957. ]
  958. outputs = [
  959. "X" ,
  960. "Y" ,
  961. "Z" ,
  962. ]
  963. self.inputs.init_sockets(inputs)
  964. self.outputs.init_sockets(outputs)
  965. self.init_parameters()
  966. self.node_type = "UTILITY"
  967. def bPrepare(self, bContext = None,):
  968. self.parameters["X"] = self.evaluate_input("Vector")[0]
  969. self.parameters["Y"] = self.evaluate_input("Vector")[1]
  970. self.parameters["Z"] = self.evaluate_input("Vector")[2]
  971. self.prepared = True
  972. self.executed = True
  973. class UtilityCatStrings(MantisNode):
  974. '''A node representing an armature object'''
  975. def __init__(self, signature, base_tree):
  976. super().__init__(signature, base_tree)
  977. inputs = [
  978. "String_1" ,
  979. "String_2" ,
  980. ]
  981. outputs = [
  982. "OutputString" ,
  983. ]
  984. self.inputs.init_sockets(inputs)
  985. self.outputs.init_sockets(outputs)
  986. self.init_parameters()
  987. self.node_type = "UTILITY"
  988. def bPrepare(self, bContext = None,):
  989. self.parameters["OutputString"] = self.evaluate_input("String_1")+self.evaluate_input("String_2")
  990. self.prepared = True
  991. self.executed = True
  992. class InputExistingGeometryObject(MantisNode):
  993. '''A node representing an existing object'''
  994. def __init__(self, signature, base_tree):
  995. super().__init__(signature, base_tree)
  996. inputs = [
  997. "Name" ,
  998. ]
  999. outputs = [
  1000. "Object" ,
  1001. ]
  1002. self.inputs.init_sockets(inputs)
  1003. self.outputs.init_sockets(outputs)
  1004. self.init_parameters()
  1005. self.node_type = "XFORM"
  1006. def bPrepare(self, bContext=None):
  1007. from bpy import data
  1008. name = self.evaluate_input("Name")
  1009. if name:
  1010. self.bObject = data.objects.get( name )
  1011. else:
  1012. self.bObject = None
  1013. if self is None and (name := self.evaluate_input("Name")):
  1014. prRed(f"No object found with name {name} in {self}")
  1015. self.prepared = True; self.executed = True
  1016. def bGetObject(self, mode=''):
  1017. return self.bObject
  1018. class InputExistingGeometryData(MantisNode):
  1019. '''A node representing existing object data'''
  1020. def __init__(self, signature, base_tree):
  1021. super().__init__(signature, base_tree)
  1022. inputs = [
  1023. "Name" ,
  1024. ]
  1025. outputs = [
  1026. "Geometry" ,
  1027. ]
  1028. self.inputs.init_sockets(inputs)
  1029. self.outputs.init_sockets(outputs)
  1030. self.init_parameters()
  1031. self.node_type = "UTILITY"
  1032. self.prepared = True
  1033. self.executed = True
  1034. # the mode argument is only for interface consistency
  1035. def bGetObject(self, mode=''):
  1036. from bpy import data
  1037. # first try Curve, then try Mesh
  1038. bObject = data.curves.get(self.evaluate_input("Name"))
  1039. if not bObject:
  1040. bObject = data.meshes.get(self.evaluate_input("Name"))
  1041. if bObject is None:
  1042. raise RuntimeError(f"Could not find a mesh or curve datablock named \"{self.evaluate_input('Name')}\" for node {self}")
  1043. return bObject
  1044. class UtilityGeometryOfXForm(MantisNode):
  1045. '''A node representing existing object data'''
  1046. def __init__(self, signature, base_tree):
  1047. super().__init__(signature, base_tree)
  1048. inputs = [
  1049. "xForm" ,
  1050. ]
  1051. outputs = [
  1052. "Geometry" ,
  1053. ]
  1054. self.inputs.init_sockets(inputs)
  1055. self.outputs.init_sockets(outputs)
  1056. self.init_parameters()
  1057. self.node_type = "UTILITY"
  1058. self.prepared = True
  1059. self.executed = True
  1060. # mode for interface consistency
  1061. def bGetObject(self, mode=''):
  1062. if not (self.inputs.get('xForm') and self.inputs['xForm'].links):
  1063. prOrange(f"WARN: Cannot retrieve data from {self}, there is no xForm node connected.")
  1064. return None
  1065. xf = self.inputs["xForm"].links[0].from_node
  1066. if xf.node_type == 'XFORM':
  1067. xf_ob = xf.bGetObject()
  1068. if xf_ob.type in ['MESH', 'CURVE']:
  1069. return xf_ob.data
  1070. prOrange(f"WARN: Cannot retrieve data from {self}, the connected xForm is not a mesh or curve.")
  1071. return None
  1072. class UtilityNameOfXForm(MantisNode):
  1073. '''A node representing existing object data'''
  1074. def __init__(self, signature, base_tree):
  1075. super().__init__(signature, base_tree)
  1076. inputs = [
  1077. "xForm" ,
  1078. ]
  1079. outputs = [
  1080. "Name" ,
  1081. ]
  1082. self.inputs.init_sockets(inputs)
  1083. self.outputs.init_sockets(outputs)
  1084. self.init_parameters()
  1085. self.node_type = "UTILITY"
  1086. # mode for interface consistency
  1087. def bPrepare(self, bContext = None,):
  1088. if not (self.inputs.get('xForm') and self.inputs['xForm'].links):
  1089. prOrange(f"WARN: Cannot retrieve data from {self}, there is no xForm node connected.")
  1090. return ''
  1091. xf = self.inputs["xForm"].links[0].from_node
  1092. self.parameters["Name"] = xf.evaluate_input('Name')
  1093. self.prepared, self.executed = True, True
  1094. class UtilityGetBoneLength(MantisNode):
  1095. '''A node to get the length of a bone matrix'''
  1096. def __init__(self, signature, base_tree):
  1097. super().__init__(signature, base_tree)
  1098. inputs = [
  1099. "Bone Matrix" ,
  1100. ]
  1101. outputs = [
  1102. "Bone Length" ,
  1103. ]
  1104. self.inputs.init_sockets(inputs)
  1105. self.outputs.init_sockets(outputs)
  1106. self.init_parameters()
  1107. self.node_type = "UTILITY"
  1108. def bPrepare(self, bContext = None,):
  1109. if (l := self.evaluate_input("Bone Matrix")) is not None:
  1110. self.parameters["Bone Length"] = l[3][3]
  1111. else:
  1112. other = self.inputs["Bone Matrix"].links[0].from_node
  1113. raise RuntimeError(f"Cannot get matrix for {self} from {other}")
  1114. self.prepared = True
  1115. self.executed = True
  1116. class UtilityPointFromBoneMatrix(MantisNode):
  1117. '''A node representing an armature object'''
  1118. def __init__(self, signature, base_tree):
  1119. super().__init__(signature, base_tree)
  1120. inputs = [
  1121. "Bone Matrix" ,
  1122. "Head/Tail" ,
  1123. ]
  1124. outputs = [
  1125. "Point" ,
  1126. ]
  1127. self.inputs.init_sockets(inputs)
  1128. self.outputs.init_sockets(outputs)
  1129. self.init_parameters()
  1130. self.node_type = "UTILITY"
  1131. # TODO: find out why this is sometimes not ready at bPrepare phase
  1132. def bPrepare(self, bContext = None,):
  1133. from mathutils import Vector
  1134. matrix = self.evaluate_input("Bone Matrix")
  1135. head, rotation, _scale = matrix.copy().decompose()
  1136. tail = head.copy() + (rotation @ Vector((0,1,0)))*matrix[3][3]
  1137. self.parameters["Point"] = head.lerp(tail, self.evaluate_input("Head/Tail"))
  1138. self.prepared = True
  1139. self.executed = True
  1140. class UtilitySetBoneLength(MantisNode):
  1141. '''Sets the length of a Bone's matrix'''
  1142. def __init__(self, signature, base_tree):
  1143. super().__init__(signature, base_tree)
  1144. inputs = [
  1145. "Bone Matrix" ,
  1146. "Length" ,
  1147. ]
  1148. outputs = [
  1149. "Bone Matrix" ,
  1150. ]
  1151. self.inputs.init_sockets(inputs)
  1152. self.outputs.init_sockets(outputs)
  1153. self.init_parameters()
  1154. self.node_type = "UTILITY"
  1155. def bPrepare(self, bContext = None,):
  1156. from mathutils import Vector
  1157. if matrix := self.evaluate_input("Bone Matrix"):
  1158. matrix = matrix.copy()
  1159. # print (self.inputs["Length"].links)
  1160. matrix[3][3] = self.evaluate_input("Length")
  1161. self.parameters["Length"] = self.evaluate_input("Length")
  1162. self.parameters["Bone Matrix"] = matrix
  1163. else:
  1164. raise RuntimeError(f"Cannot get matrix for {self}")
  1165. self.prepared = True
  1166. self.executed = True
  1167. class UtilityMatrixSetLocation(MantisNode):
  1168. '''Sets the location of a matrix'''
  1169. def __init__(self, signature, base_tree):
  1170. super().__init__(signature, base_tree)
  1171. inputs = [
  1172. "Matrix" ,
  1173. "Location" ,
  1174. ]
  1175. outputs = [
  1176. "Matrix" ,
  1177. ]
  1178. self.inputs.init_sockets(inputs)
  1179. self.outputs.init_sockets(outputs)
  1180. self.init_parameters()
  1181. self.node_type = "UTILITY"
  1182. def bPrepare(self, bContext = None,):
  1183. from mathutils import Vector
  1184. if matrix := self.evaluate_input("Matrix"):
  1185. matrix = matrix.copy()
  1186. # print (self.inputs["Length"].links)
  1187. loc = self.evaluate_input("Location")
  1188. matrix[0][3] = loc[0]; matrix[1][3] = loc[1]; matrix[2][3] = loc[2]
  1189. self.parameters["Matrix"] = matrix
  1190. self.prepared = True
  1191. self.executed = True
  1192. class UtilityMatrixGetLocation(MantisNode):
  1193. '''Gets the location of a matrix'''
  1194. def __init__(self, signature, base_tree):
  1195. super().__init__(signature, base_tree)
  1196. inputs = [
  1197. "Matrix" ,
  1198. ]
  1199. outputs = [
  1200. "Location" ,
  1201. ]
  1202. self.inputs.init_sockets(inputs)
  1203. self.outputs.init_sockets(outputs)
  1204. self.init_parameters()
  1205. self.node_type = "UTILITY"
  1206. def bPrepare(self, bContext = None,):
  1207. from mathutils import Vector
  1208. if matrix := self.evaluate_input("Matrix"):
  1209. self.parameters["Location"] = matrix.to_translation()
  1210. self.prepared = True; self.executed = True
  1211. class UtilityMatrixFromXForm(MantisNode):
  1212. """Returns the matrix of the given xForm node."""
  1213. def __init__(self, signature, base_tree):
  1214. super().__init__(signature, base_tree)
  1215. inputs = [
  1216. "xForm" ,
  1217. ]
  1218. outputs = [
  1219. "Matrix" ,
  1220. ]
  1221. self.node_type = "UTILITY"
  1222. self.inputs.init_sockets(inputs)
  1223. self.outputs.init_sockets(outputs)
  1224. self.init_parameters()
  1225. def GetxForm(self):
  1226. trace = trace_single_line(self, "xForm")
  1227. for node in trace[0]:
  1228. if (node.node_type == 'XFORM'):
  1229. return node
  1230. raise GraphError("%s is not connected to an xForm" % self)
  1231. def bPrepare(self, bContext = None,):
  1232. from mathutils import Vector, Matrix
  1233. self.parameters["Matrix"] = Matrix.Identity(4)
  1234. if matrix := self.GetxForm().parameters.get("Matrix"):
  1235. self.parameters["Matrix"] = matrix.copy()
  1236. elif hasattr(self.GetxForm().bObject, "matrix"):
  1237. self.parameters["Matrix"] = self.GetxForm().bObject.matrix.copy()
  1238. elif hasattr(self.GetxForm().bObject, "matrix_world"):
  1239. self.parameters["Matrix"] = self.GetxForm().bObject.matrix_world.copy()
  1240. else:
  1241. prRed(f"Could not find matrix for {self} - check if the referenced object exists.")
  1242. self.prepared = True; self.executed = True
  1243. class UtilityAxesFromMatrix(MantisNode):
  1244. """Returns the axes of the given matrix."""
  1245. def __init__(self, signature, base_tree):
  1246. super().__init__(signature, base_tree)
  1247. inputs = [
  1248. "Matrix" ,
  1249. ]
  1250. outputs = [
  1251. "X Axis" ,
  1252. "Y Axis" ,
  1253. "Z Axis" ,
  1254. ]
  1255. self.inputs.init_sockets(inputs)
  1256. self.outputs.init_sockets(outputs)
  1257. self.init_parameters()
  1258. self.node_type = "UTILITY"
  1259. def bPrepare(self, bContext = None,):
  1260. from mathutils import Vector
  1261. if matrix := self.evaluate_input("Matrix"):
  1262. matrix= matrix.copy().to_3x3()
  1263. self.parameters['X Axis'] = matrix @ Vector((1,0,0))
  1264. self.parameters['Y Axis'] = matrix @ Vector((0,1,0))
  1265. self.parameters['Z Axis'] = matrix @ Vector((0,0,1))
  1266. self.prepared = True; self.executed = True
  1267. class UtilityBoneMatrixHeadTailFlip(MantisNode):
  1268. def __init__(self, signature, base_tree):
  1269. super().__init__(signature, base_tree)
  1270. inputs = [
  1271. "Bone Matrix" ,
  1272. ]
  1273. outputs = [
  1274. "Bone Matrix" ,
  1275. ]
  1276. self.inputs.init_sockets(inputs)
  1277. self.outputs.init_sockets(outputs)
  1278. self.init_parameters()
  1279. self.node_type = "UTILITY"
  1280. def bPrepare(self, bContext = None,):
  1281. from mathutils import Vector, Matrix, Quaternion
  1282. from bpy.types import Bone
  1283. if matrix := self.evaluate_input("Bone Matrix"):
  1284. axis, roll = Bone.AxisRollFromMatrix(matrix.to_3x3())
  1285. new_mat = Bone.MatrixFromAxisRoll(-1*axis, roll)
  1286. length = matrix[3][3]
  1287. new_mat.resize_4x4() # last column contains
  1288. new_mat[0][3] = matrix[0][3] + axis[0]*length # x location
  1289. new_mat[1][3] = matrix[1][3] + axis[1]*length # y location
  1290. new_mat[2][3] = matrix[2][3] + axis[2]*length # z location
  1291. new_mat[3][3] = length # length
  1292. self.parameters["Bone Matrix"] = new_mat
  1293. self.prepared, self.executed = True, True
  1294. class UtilityMatrixTransform(MantisNode):
  1295. def __init__(self, signature, base_tree):
  1296. super().__init__(signature, base_tree)
  1297. inputs = [
  1298. "Matrix 1" ,
  1299. "Matrix 2" ,
  1300. ]
  1301. outputs = [
  1302. "Out Matrix" ,
  1303. ]
  1304. self.inputs.init_sockets(inputs)
  1305. self.outputs.init_sockets(outputs)
  1306. self.init_parameters()
  1307. self.node_type = "UTILITY"
  1308. def bPrepare(self, bContext = None,):
  1309. from mathutils import Vector
  1310. mat1 = self.evaluate_input("Matrix 1"); mat2 = self.evaluate_input("Matrix 2")
  1311. if mat1 and mat2:
  1312. mat1copy = mat1.copy()
  1313. self.parameters["Out Matrix"] = mat2 @ mat1copy
  1314. self.parameters["Out Matrix"].translation = mat1copy.to_translation()+ mat2.to_translation()
  1315. else:
  1316. raise RuntimeError(wrapRed(f"Node {self} did not receive all matrix inputs... found input 1? {mat1 is not None}, 2? {mat2 is not None}"))
  1317. self.prepared = True
  1318. self.executed = True
  1319. class UtilityTransformationMatrix(MantisNode):
  1320. def __init__(self, signature, base_tree):
  1321. super().__init__(signature, base_tree)
  1322. inputs = [
  1323. "Operation" ,
  1324. "Vector" ,
  1325. "W" ,
  1326. ]
  1327. outputs = [
  1328. "Matrix" ,
  1329. ]
  1330. self.inputs.init_sockets(inputs)
  1331. self.outputs.init_sockets(outputs)
  1332. self.init_parameters()
  1333. self.node_type = "UTILITY"
  1334. def bPrepare(self, bContext = None,):
  1335. from mathutils import Matrix, Vector
  1336. if (operation := self.evaluate_input("Operation")) == 'ROTATE_AXIS_ANGLE':
  1337. # this can, will, and should fail if the axis is 0,0,0
  1338. self.parameters["Matrix"] = rotMat = Matrix.Rotation(self.evaluate_input("W"), 4, Vector(self.evaluate_input("Vector")).normalized())
  1339. elif (operation := self.evaluate_input("Operation")) == 'TRANSLATE':
  1340. m = Matrix.Identity(4)
  1341. if axis := self.evaluate_input("Vector"):
  1342. m[0][3]=axis[0];m[1][3]=axis[1];m[2][3]=axis[2]
  1343. self.parameters['Matrix'] = m
  1344. elif (operation := self.evaluate_input("Operation")) == 'SCALE':
  1345. self.parameters["Matrix"] = Matrix.Scale(self.evaluate_input("W"), 4, Vector(self.evaluate_input("Vector")).normalized())
  1346. else:
  1347. raise NotImplementedError(self.evaluate_input("Operation").__repr__()+ " Operation not yet implemented.")
  1348. self.prepared = True
  1349. self.executed = True
  1350. class UtilityIntToString(MantisNode):
  1351. def __init__(self, signature, base_tree):
  1352. super().__init__(signature, base_tree)
  1353. inputs = [
  1354. "Number" ,
  1355. "Zero Padding" ,
  1356. ]
  1357. outputs = [
  1358. "String" ,
  1359. ]
  1360. self.inputs.init_sockets(inputs)
  1361. self.outputs.init_sockets(outputs)
  1362. self.init_parameters()
  1363. self.node_type = "UTILITY"
  1364. def bPrepare(self, bContext = None,):
  1365. number = self.evaluate_input("Number")
  1366. zeroes = self.evaluate_input("Zero Padding")
  1367. # I'm casting to int because I want to support any number, even though the node asks for int.
  1368. self.parameters["String"] = str(int(number)).zfill(int(zeroes))
  1369. self.prepared = True
  1370. self.executed = True
  1371. class UtilityArrayGet(MantisNode):
  1372. def __init__(self, signature, base_tree):
  1373. super().__init__(signature, base_tree)
  1374. inputs = [
  1375. "Index" ,
  1376. "OoB Behaviour" ,
  1377. "Array" ,
  1378. ]
  1379. outputs = [
  1380. "Output" ,
  1381. ]
  1382. self.inputs.init_sockets(inputs)
  1383. self.outputs.init_sockets(outputs)
  1384. self.init_parameters()
  1385. self.node_type = "UTILITY"
  1386. def bPrepare(self, bContext = None,):
  1387. if len(self.hierarchy_dependencies)==0 and len(self.hierarchy_connections)==0 and \
  1388. len(self.connections)==0 and len(self.dependencies)==0:
  1389. self.prepared, self.executed = True, True
  1390. return #Either it is already done or it doesn't matter.
  1391. elif self.prepared == False:
  1392. # sort the array entries
  1393. for inp in self.inputs.values():
  1394. inp.links.sort(key=lambda a : -a.multi_input_sort_id)
  1395. oob = self.evaluate_input("OoB Behaviour")
  1396. index = self.evaluate_input("Index")
  1397. from .utilities import cap, wrap
  1398. # we must assume that the array has sent the correct number of links
  1399. if oob == 'WRAP':
  1400. index = index % len(self.inputs['Array'].links)
  1401. if oob == 'HOLD':
  1402. index = cap(index, len(self.inputs['Array'].links)-1)
  1403. array_choose_relink(self, [index], "Array", "Output")
  1404. self.prepared, self.executed = True, True
  1405. class UtilityArrayLength(MantisNode):
  1406. def __init__(self, signature, base_tree):
  1407. super().__init__(signature, base_tree)
  1408. inputs = [
  1409. "Array" ,
  1410. ]
  1411. outputs = [
  1412. "Length" ,
  1413. ]
  1414. self.inputs.init_sockets(inputs)
  1415. self.outputs.init_sockets(outputs)
  1416. self.init_parameters()
  1417. self.node_type = "UTILITY"
  1418. def bPrepare(self, bContext = None,):
  1419. self.parameters["Length"] = len(self.inputs["Array"].links)
  1420. self.prepared, self.executed = True, True
  1421. class UtilitySetBoneMatrixTail(MantisNode):
  1422. def __init__(self, signature, base_tree):
  1423. super().__init__(signature, base_tree)
  1424. inputs = {
  1425. "Matrix" ,
  1426. "Tail Location" ,
  1427. }
  1428. outputs = [
  1429. "Result" ,
  1430. ]
  1431. self.inputs.init_sockets(inputs)
  1432. self.outputs.init_sockets(outputs)
  1433. self.init_parameters()
  1434. self.node_type = "UTILITY"
  1435. def bPrepare(self, bContext = None,):
  1436. from mathutils import Matrix
  1437. matrix = self.evaluate_input("Matrix")
  1438. if matrix is None: matrix = Matrix.Identity(4)
  1439. #just do this for now lol
  1440. self.parameters["Result"] = matrix_from_head_tail(matrix.translation, self.evaluate_input("Tail Location"))
  1441. self.prepared = True
  1442. self.executed = True
  1443. class UtilityPrint(MantisNode):
  1444. def __init__(self, signature, base_tree):
  1445. super().__init__(signature, base_tree)
  1446. inputs = [
  1447. "Input" ,
  1448. ]
  1449. self.inputs.init_sockets(inputs)
  1450. self.init_parameters()
  1451. self.node_type = "UTILITY"
  1452. def bPrepare(self, bContext = None,):
  1453. if my_input := self.evaluate_input("Input"):
  1454. print("Preparation phase: ", wrapWhite(self), wrapGreen(my_input))
  1455. # else:
  1456. # prRed("No input to print.")
  1457. self.prepared = True
  1458. def bExecute(self, bContext = None,):
  1459. if my_input := self.evaluate_input("Input"):
  1460. print("Execution phase: ", wrapWhite(self), wrapGreen(my_input))
  1461. # else:
  1462. # prRed("No input to print.")
  1463. self.executed = True
  1464. class UtilityCompare(MantisNode):
  1465. def __init__(self, signature, base_tree):
  1466. super().__init__(signature, base_tree)
  1467. inputs = [
  1468. "A" ,
  1469. "B" ,
  1470. ]
  1471. outputs = [
  1472. "Result" ,
  1473. ]
  1474. self.inputs.init_sockets(inputs)
  1475. self.outputs.init_sockets(outputs)
  1476. self.init_parameters()
  1477. self.node_type = "UTILITY"
  1478. def bPrepare(self, bContext = None,):
  1479. self.parameters["Result"] = self.evaluate_input("A") == self.evaluate_input("B")
  1480. self.prepared = True; self.executed = True
  1481. class UtilityChoose(MantisNode):
  1482. def __init__(self, signature, base_tree):
  1483. super().__init__(signature, base_tree)
  1484. inputs = [
  1485. "Condition" ,
  1486. "A" ,
  1487. "B" ,
  1488. ]
  1489. outputs = [
  1490. "Result" ,
  1491. ]
  1492. self.inputs.init_sockets(inputs)
  1493. self.outputs.init_sockets(outputs)
  1494. self.init_parameters()
  1495. self.node_type = "UTILITY"
  1496. def bPrepare(self, bContext = None,):
  1497. condition = self.evaluate_input("Condition")
  1498. if condition:
  1499. self.parameters["Result"] = self.evaluate_input("B")
  1500. else:
  1501. self.parameters["Result"] = self.evaluate_input("A")
  1502. self.prepared = True
  1503. self.executed = True