misc_nodes.py 79 KB

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