misc_nodes.py 64 KB

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