misc_nodes.py 72 KB

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