misc_nodes.py 78 KB

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