misc_nodes.py 68 KB

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