misc_nodes.py 73 KB

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