misc_nodes.py 77 KB

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