misc_nodes.py 79 KB

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