misc_nodes.py 65 KB

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