misc_nodes.py 73 KB

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