misc_nodes.py 79 KB

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