misc_nodes.py 78 KB

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