misc_nodes.py 76 KB

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