misc_nodes.py 73 KB

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