xForm_nodes.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. from .node_container_common import *
  2. from .base_definitions import MantisNode, NodeSocket
  3. from .xForm_socket_templates import *
  4. def TellClasses():
  5. return [
  6. # xForm
  7. xFormArmature,
  8. xFormBone,
  9. xFormGeometryObject,
  10. xFormObjectInstance,
  11. xFormCurvePin,
  12. ]
  13. #*#-------------------------------#++#-------------------------------#*#
  14. # X - F O R M N O D E S
  15. #*#-------------------------------#++#-------------------------------#*#
  16. def reset_object_data(ob):
  17. # moving this to a common function so I can figure out the details later
  18. ob.constraints.clear()
  19. ob.animation_data_clear() # this is a little dangerous. TODO find a better solution since this can wipe animation the user wants to keep
  20. ob.modifiers.clear() # I would also like a way to copy modifiers and their settings, or bake them down. oh well
  21. def get_parent_node(node_container, type = 'XFORM'):
  22. # type variable for selecting whether to get either
  23. # the parent xForm or the inheritance node
  24. node_line, _last_socket = trace_single_line(node_container, "Relationship")
  25. for i in range(len(node_line)):
  26. # check each of the possible parent types.
  27. if ( (node_line[ i ].__class__.__name__ == 'LinkInherit') ):
  28. try: # it's the next one
  29. if (type == 'XFORM'):
  30. return node_line[ i + 1 ]
  31. else: # type = 'LINK'
  32. return node_line[ i ]
  33. except IndexError: # if there is no next one...
  34. return None # then there's no parent!
  35. return None
  36. def get_matrix(node):
  37. matrix = node.evaluate_input('Matrix')
  38. if matrix is None:
  39. node_line, socket = trace_single_line(node, "Matrix")
  40. raise RuntimeError(wrapRed(f"No matrix found for Armature {node}"))
  41. return matrix
  42. def set_object_parent(node):
  43. parent_nc = get_parent_node(node, type='LINK')
  44. if (parent_nc):
  45. parent = None
  46. if node.inputs["Relationship"].is_linked:
  47. trace = trace_single_line(node, "Relationship")
  48. for other_node in trace[0]:
  49. if other_node is node: continue # lol
  50. if (other_node.node_type == 'XFORM'):
  51. parent = other_node; break
  52. if parent is None:
  53. prWhite(f"INFO: no parent set for {node}.")
  54. return
  55. prWhite(f"INFO: setting parent of {node} to {other_node}.")
  56. if (parent.bObject) is None:
  57. raise GraphError(f"Could not get parent object from node {parent} for {node}")
  58. if isinstance(parent, xFormBone):
  59. armOb= parent.bGetParentArmature()
  60. node.bObject.parent = armOb
  61. node.bObject.parent_type = 'BONE'
  62. node.bObject.parent_bone = parent.bObject
  63. else:
  64. node.bObject.parent = parent.bGetObject()
  65. class xFormNode(MantisNode):
  66. def __init__(self, signature, base_tree, socket_templates=[]):
  67. super().__init__(signature, base_tree, socket_templates)
  68. self.node_type = 'XFORM'
  69. self.bObject=None
  70. # because new objects are created during prep phase
  71. def reset_execution(self):
  72. super().reset_execution()
  73. self.prepared=False
  74. class xFormArmature(xFormNode):
  75. '''A node representing an armature object'''
  76. def __init__(self, signature, base_tree):
  77. super().__init__(signature, base_tree, xFormArmatureSockets)
  78. self.init_parameters()
  79. self.set_traverse([("Relationship", "xForm Out")])
  80. def bPrepare(self, bContext=None):
  81. self.parameters['Matrix'] = get_matrix(self)
  82. self.prepared = True
  83. def bTransformPass(self, bContext = None,):
  84. # from .utilities import get_node_prototype
  85. import bpy
  86. if (not isinstance(bContext, bpy.types.Context)):
  87. raise RuntimeError("Incorrect context")
  88. name = self.evaluate_input("Name")
  89. matrix = self.parameters['Matrix']
  90. reset_transforms = False
  91. #check if an object by the name exists
  92. if (name) and (ob := bpy.data.objects.get(name)):
  93. if (ob.animation_data):
  94. while (ob.animation_data.drivers):
  95. ob.animation_data.drivers.remove(ob.animation_data.drivers[-1])
  96. for pb in ob.pose.bones:
  97. # clear it, even after deleting the edit bones,
  98. # if we create them again the pose bones will be reused
  99. while (pb.constraints):
  100. pb.constraints.remove(pb.constraints[-1])
  101. if reset_transforms:
  102. pb.location = (0,0,0)
  103. pb.rotation_euler = (0,0,0)
  104. pb.rotation_quaternion = (1.0,0,0,0)
  105. pb.rotation_axis_angle = (0,0,1.0,0)
  106. pb.scale = (1.0,1.0,1.0)
  107. # feels ugly and bad, whatever
  108. collections = []
  109. for bc in ob.data.collections:
  110. collections.append(bc)
  111. for bc in collections:
  112. ob.data.collections.remove(bc)
  113. del collections
  114. # end ugly/bad
  115. else:
  116. # Create the Object
  117. ob = bpy.data.objects.new(name, bpy.data.armatures.new(name)) #create ob
  118. if (ob.name != name):
  119. raise RuntimeError("Could not create xForm object", name)
  120. self.bObject = ob.name
  121. ob.matrix_world = matrix.copy()
  122. ob.data.pose_position = 'REST'
  123. set_object_parent(self)
  124. # Link to Scene:
  125. if (ob.name not in bContext.view_layer.active_layer_collection.collection.objects):
  126. bContext.view_layer.active_layer_collection.collection.objects.link(ob)
  127. print( wrapGreen("Created Armature object: ")+ wrapWhite(ob.name))
  128. # Finalize the action
  129. # oddly, overriding context doesn't seem to work
  130. try:
  131. bpy.ops.object.select_all(action='DESELECT')
  132. except RuntimeError:
  133. pass # we're already in edit mode, should be OK to do this.
  134. bContext.view_layer.objects.active = ob
  135. selected=[]
  136. for other_ob in bpy.data.objects:
  137. if other_ob.mode == "EDIT":
  138. selected.append(other_ob)
  139. selected.append(ob)
  140. context_override = {"active_object":ob, "selected_objects":selected}
  141. print("Changing Armature Mode to " +wrapPurple("EDIT"))
  142. with bContext.temp_override(**context_override):
  143. bpy.ops.object.mode_set(mode='EDIT')
  144. if ob.mode != "EDIT":
  145. prRed("eh?")
  146. # clear it
  147. while (len(ob.data.edit_bones) > 0):
  148. ob.data.edit_bones.remove(ob.data.edit_bones[0])
  149. # bContext.view_layer.objects.active = prevAct
  150. self.executed = True
  151. def bGetObject(self, mode = ''):
  152. import bpy; return bpy.data.objects[self.bObject]
  153. bone_inputs= [
  154. "Name",
  155. "Rotation Order",
  156. "Matrix",
  157. "Relationship",
  158. # IK settings
  159. "IK Stretch",
  160. "Lock IK",
  161. "IK Stiffness",
  162. "Limit IK",
  163. "X Min",
  164. "X Max",
  165. "Y Min",
  166. "Y Max",
  167. "Z Min",
  168. "Z Max",
  169. # Visual stuff
  170. "Bone Collection",
  171. "Hide",
  172. "Custom Object",
  173. "Custom Object xForm Override",
  174. "Custom Object Scale to Bone Length",
  175. "Custom Object Wireframe",
  176. "Custom Object Scale",
  177. "Custom Object Translation",
  178. "Custom Object Rotation",
  179. "Color",
  180. "Inherit Color",
  181. # Deform Stuff
  182. "Deform",
  183. "Envelope Distance",
  184. "Envelope Weight",
  185. "Envelope Multiply",
  186. "Envelope Head Radius",
  187. "Envelope Tail Radius",
  188. # BBone stuff:
  189. "BBone Segments",
  190. "BBone X Size",
  191. "BBone Z Size",
  192. "BBone HQ Deformation",
  193. "BBone X Curve-In",
  194. "BBone Z Curve-In",
  195. "BBone X Curve-Out",
  196. "BBone Z Curve-Out",
  197. "BBone Roll-In",
  198. "BBone Roll-Out",
  199. "BBone Inherit End Roll",
  200. "BBone Scale-In",
  201. "BBone Scale-Out",
  202. "BBone Ease-In",
  203. "BBone Ease-Out",
  204. "BBone Easing",
  205. "BBone Start Handle Type",
  206. "BBone Custom Start Handle",
  207. "BBone Start Handle Scale",
  208. "BBone Start Handle Ease",
  209. "BBone End Handle Type",
  210. "BBone Custom End Handle",
  211. "BBone End Handle Scale",
  212. "BBone End Handle Ease",
  213. # locks
  214. "Lock Location",
  215. "Lock Rotation",
  216. "Lock Scale",
  217. ]
  218. class xFormBone(xFormNode):
  219. '''A node representing a bone in an armature'''
  220. # DO: make a way to identify which armature this belongs to
  221. def __init__(self, signature, base_tree):
  222. super().__init__(signature, base_tree)
  223. outputs = [
  224. "xForm Out",
  225. ]
  226. self.inputs.init_sockets(bone_inputs)
  227. self.outputs.init_sockets(outputs)
  228. self.socket_templates=xFormBoneSockets
  229. # TODO: implement socket templates completely for Bone
  230. # currently it is waiting on BBone and refactoring/cleanup.
  231. self.init_parameters()
  232. self.set_traverse([("Relationship", "xForm Out")])
  233. def bGetParentArmature(self):
  234. if (trace := trace_single_line(self, "Relationship")[0] ) :
  235. for i in range(len(trace)):
  236. # have to look in reverse, actually TODO
  237. if ( isinstance(trace[ i ], xFormArmature ) ):
  238. return trace[ i ].bGetObject()
  239. return None
  240. #should do the trick...
  241. def bSetParent(self, eb):
  242. from bpy.types import EditBone
  243. parent_nc = get_parent_node(self, type='LINK')
  244. if parent_nc is None:
  245. raise RuntimeError(wrapRed(f"Cannot set parent for node {self}"))
  246. node_lines, _last_socket = trace_single_line(parent_nc, 'Parent')
  247. for other_node in node_lines:
  248. if isinstance(other_node, (xFormArmature, xFormBone)):
  249. parent = other_node.bGetObject(mode = 'EDIT'); break
  250. else:
  251. raise RuntimeError(wrapRed(f"Cannot set parent for node {self}"))
  252. if isinstance(parent, EditBone): # otherwise, no need to do anything.
  253. eb.parent = parent
  254. eb.use_connect = parent_nc.evaluate_input("Connected")
  255. eb.use_inherit_rotation = parent_nc.evaluate_input("Inherit Rotation")
  256. eb.inherit_scale = parent_nc.evaluate_input("Inherit Scale")
  257. def bPrepare(self, bContext=None):
  258. self.parameters['Matrix'] = get_matrix(self)
  259. self.prepared = True
  260. def bTransformPass(self, bContext = None,): #possibly will need to pass context?
  261. import bpy
  262. from mathutils import Vector
  263. if not (name := self.evaluate_input("Name")):
  264. raise RuntimeError(wrapRed(f"Could not set name for bone in {self}"))
  265. if (not isinstance(bContext, bpy.types.Context)):
  266. raise RuntimeError("Incorrect context")
  267. if not (xF := self.bGetParentArmature()):
  268. raise RuntimeError("Could not create edit bone: ", name, " from node:", self, " Reason: No armature object to add bone to.")
  269. matrix = self.parameters['Matrix']
  270. length = matrix[3][3]
  271. if (xF):
  272. if (xF.mode != "EDIT"):
  273. raise RuntimeError("Armature Object Not in Edit Mode, exiting...")
  274. #
  275. # Create the Object
  276. d = xF.data
  277. eb = d.edit_bones.new(name)
  278. # Bone Collections:
  279. # We treat each separate string as a Bone Collection that this object belongs to
  280. # Bone Collections are fully qualified by their hierarchy.
  281. # Separate Strings with "|" and indicate hierarchy with ">". These are special characters.
  282. # NOTE: if the user names the collections differently at different times, this will take the FIRST definition and go with it
  283. if self.inputs['Bone Collection'].links:
  284. bCol_groups = []
  285. for i, l in enumerate(self.inputs['Bone Collection'].links):
  286. bCol_group = self.evaluate_input("Bone Collection", index=i)
  287. bCol_groups.append(bCol_group)
  288. bCols = '|'.join(bCol_groups)
  289. else:
  290. bCols = self.evaluate_input("Bone Collection")
  291. if bCols: # it is actually possible to add a bone to no collections. odd.
  292. bone_collections = bCols.split("|")
  293. for collection_list in bone_collections:
  294. hierarchy = collection_list.split(">")
  295. col_parent = None
  296. for bCol in hierarchy:
  297. if ( col := d.collections_all.get(bCol) ) is None:
  298. col = d.collections.new(bCol)
  299. col.parent = col_parent
  300. col_parent = col
  301. d.collections_all.get(hierarchy[-1]).assign(eb)
  302. if (eb.name != name):
  303. prRed(f"Expected bone of name: {name}, got {eb.name} instead.")
  304. raise RuntimeError("Could not create bone ", name, "; Perhaps there is a duplicate bone name in the node tree?")
  305. eb.matrix = matrix.copy()
  306. tailoffset = Vector((0,length,0)) #Vector((0,self.tailoffset, 0))
  307. tailoffset = matrix.copy().to_3x3() @ tailoffset
  308. eb.tail = eb.head + tailoffset
  309. if (eb.name != name):
  310. raise RuntimeError("Could not create edit bone: ", name)
  311. assert (eb.name), "Bone must have a name."
  312. self.bObject = eb.name
  313. # The bone should have relationships going in at this point.
  314. self.bSetParent(eb)
  315. if eb.head == eb.tail:
  316. raise RuntimeError(wrapRed(f"Could not create edit bone: {name} because bone head was located in the same place as bone tail."))
  317. # Setup Deform attributes...
  318. eb.use_deform = self.evaluate_input("Deform")
  319. eb.envelope_distance = self.evaluate_input("Envelope Distance")
  320. eb.envelope_weight = self.evaluate_input("Envelope Weight")
  321. eb.use_envelope_multiply = self.evaluate_input("Envelope Multiply")
  322. eb.head_radius = self.evaluate_input("Envelope Head Radius")
  323. eb.tail_radius = self.evaluate_input("Envelope Tail Radius")
  324. print( wrapGreen("Created Bone: ") + wrapOrange(eb.name) + wrapGreen(" in ") + wrapWhite(self.bGetParentArmature().name))
  325. self.executed = True
  326. def set_bone_color(self, b, inherit_color, bContext):
  327. color_values = self.evaluate_input('Color')
  328. if color_values is None:
  329. prOrange(f"Warning: No color information found for {b.name}. This should not happen.")
  330. return
  331. if inherit_color and b.parent:
  332. b.color.palette=b.parent.color.palette
  333. if b.color.palette == 'CUSTOM':
  334. b.color.custom.active=b.parent.color.custom.active
  335. b.color.custom.normal=b.parent.color.custom.normal
  336. b.color.custom.select=b.parent.color.custom.select
  337. return
  338. from mathutils import Color
  339. color_active = Color(color_values[:3])
  340. color_normal = Color(color_values[3:6])
  341. color_select = Color(color_values[6:])
  342. is_theme_colors = False
  343. theme = bContext.preferences.themes[0]
  344. for i, color_set in enumerate(theme.bone_color_sets):
  345. if ((color_active == color_set.active) and
  346. (color_normal == color_set.normal) and
  347. (color_select == color_set.select) ):
  348. is_theme_colors=True; break
  349. if is_theme_colors: # add 1, not 0-indexed
  350. b.color.palette = 'THEME'+str(i+1).zfill(2)
  351. elif ((color_active == theme.view_3d.bone_pose_active) and
  352. (color_normal == theme.view_3d.bone_solid) and
  353. (color_select == theme.view_3d.bone_pose) ):
  354. b.color.palette = 'DEFAULT'
  355. else:
  356. b.color.palette = 'CUSTOM'
  357. b.color.custom.active=color_active
  358. b.color.custom.normal=color_normal
  359. b.color.custom.select=color_select
  360. def bFinalize(self, bContext = None):
  361. b = self.bGetParentArmature().data.bones[self.bObject]
  362. # let's do bone colors first
  363. inherit_color = self.evaluate_input("Inherit Color")
  364. if len(self.inputs['Color'].links) > 0:
  365. inherit_color = False # use the link instead
  366. # try: # just in case, this shouldn't cause a failure
  367. self.set_bone_color(b, inherit_color, bContext)
  368. # except Exception as e:
  369. # prRed("WARNING: failed to set color because of error, see report below:")
  370. # prOrange(e)
  371. #
  372. do_bb=False
  373. b.bbone_x = self.evaluate_input("BBone X Size"); b.bbone_x = max(b.bbone_x, 0.0002)
  374. b.bbone_z = self.evaluate_input("BBone Z Size"); b.bbone_z = max(b.bbone_z, 0.0002)
  375. if (segs := self.evaluate_input("BBone Segments")) > 1:
  376. do_bb=True
  377. b.bbone_segments = segs
  378. b.bbone_x = self.evaluate_input("BBone X Size")
  379. b.bbone_z = self.evaluate_input("BBone Z Size")
  380. if self.evaluate_input("BBone HQ Deformation"):
  381. b.bbone_mapping_mode = "CURVED"
  382. # 'bbone_handle_type_start' : ("BBone Start Handle Type", "AUTO"),
  383. # 'bbone_handle_type_end' : ("BBone End Handle Type", "AUTO"),
  384. # 'bbone_custom_handle_start' : ("BBone Custom Start Handle", "AUTO"),
  385. # 'bbone_custom_handle_end' : ("BBone Custom End Handle", "AUTO"),
  386. if handle_type := self.evaluate_input("BBone Start Handle Type"):
  387. b.bbone_handle_type_start = handle_type
  388. if handle_type := self.evaluate_input("BBone End Handle Type"):
  389. b.bbone_handle_type_end = handle_type
  390. try:
  391. if (custom_handle := self.evaluate_input("BBone Custom Start Handle")):
  392. b.bbone_custom_handle_start = self.bGetParentArmature().data.bones[custom_handle]
  393. if (custom_handle := self.evaluate_input("BBone Custom End Handle")):
  394. b.bbone_custom_handle_end = self.bGetParentArmature().data.bones[custom_handle]
  395. except KeyError:
  396. prRed("Warning: BBone start or end handle not set because of missing bone in armature.")
  397. bone_props_socket= {
  398. 'bbone_curveinx' : ("BBone X Curve-In", 0.0),
  399. 'bbone_curveinz' : ("BBone Z Curve-In", 0.0),
  400. 'bbone_curveoutx' : ("BBone X Curve-Out", 0.0),
  401. 'bbone_curveoutz' : ("BBone Z Curve-Out", 0.0),
  402. }
  403. evaluate_sockets(self, b, bone_props_socket)
  404. # TODO this section should be done with props-socket thing
  405. b.bbone_handle_use_scale_start = self.evaluate_input("BBone Start Handle Scale")
  406. b.bbone_handle_use_scale_end = self.evaluate_input("BBone End Handle Scale")
  407. import bpy
  408. from .drivers import MantisDriver
  409. # prevAct = bContext.view_layer.objects.active
  410. # bContext.view_layer.objects.active = ob
  411. # bpy.ops.object.mode_set(mode='OBJECT')
  412. # bContext.view_layer.objects.active = prevAct
  413. #
  414. #get relationship
  415. # ensure we have a pose bone...
  416. # set the ik parameters
  417. #
  418. #
  419. # Don't need to bother about whatever that was
  420. pb = self.bGetParentArmature().pose.bones[self.bObject]
  421. rotation_mode = self.evaluate_input("Rotation Order")
  422. if rotation_mode == "AUTO": rotation_mode = "XYZ"
  423. pb.rotation_mode = rotation_mode
  424. pb.id_properties_clear()
  425. # these are kept around unless explicitly deleted.
  426. # from .utilities import get_node_prototype
  427. # np = get_node_prototype(self.signature, self.base_tree)
  428. driver = None
  429. do_prints=False
  430. # detect custom inputs
  431. for i, inp in enumerate(self.inputs.values()):
  432. custom_prop=False
  433. for s_template in self.socket_templates:
  434. if s_template.name == inp.name:
  435. break
  436. else:
  437. custom_prop=True
  438. if custom_prop == False: continue
  439. name = inp.name
  440. value = self.evaluate_input(inp.name)
  441. # This may be driven, so let's do this:
  442. if (isinstance(value, tuple)):
  443. raise RuntimeError(f"The custom property type is not supported: {self}")
  444. if (isinstance(value, MantisDriver)):
  445. # the value should be the default for its socket...
  446. type_val_map = {
  447. str:"",
  448. bool:False,
  449. int:0,
  450. float:0.0,
  451. bpy.types.bpy_prop_array:(0,0,0),
  452. }
  453. driver = value
  454. value = type_val_map[type(self.parameters[inp.name])]
  455. if (value is None):
  456. raise RuntimeError("Could not set value of custom parameter")
  457. # it creates a more confusing error later sometimes, better to catch it here.
  458. pb[name] = value
  459. ui_data = pb.id_properties_ui(name)
  460. description = ''
  461. if hasattr(inp, 'description'):
  462. description = inp.description
  463. # i am assuming there was a reason I was not already taking inp.description
  464. # So guard it a little here just to be safe and not change things too much.
  465. ui_data.update(
  466. default=value,
  467. description=description)
  468. #if a number, set the min/max values. it may overflow on the C side
  469. if type(value) in [float, int]:
  470. for prop_name in ['min', 'max', 'soft_min', 'soft_max', ]:
  471. prop_value = getattr(inp, prop_name)
  472. if type(value) == int: prop_value = int(prop_value)
  473. # DO: figure out the right way to prevent an oveflow
  474. try: # we have to do this as a keyword argument like this
  475. ui_data.update( **{prop_name:prop_value} )
  476. except OverflowError: #this occurs when the value is inf
  477. prRed(f"invalid value {prop_value} for custom prop {prop_name}"
  478. f" of type {type(value)} in {self}. It will remain unset.")
  479. pb.property_overridable_library_set(f"[\"{name}\"]", True)
  480. if (pb.is_in_ik_chain):
  481. # this props_socket thing wasn't really meant to work here but it does, neat
  482. props_sockets = {
  483. 'ik_stretch' : ("IK Stretch", 0),
  484. 'lock_ik_x' : (("Lock IK", 0), False),
  485. 'lock_ik_y' : (("Lock IK", 1), False),
  486. 'lock_ik_z' : (("Lock IK", 2), False),
  487. 'ik_stiffness_x' : (("IK Stiffness", 0), 0.0),
  488. 'ik_stiffness_y' : (("IK Stiffness", 1), 0.0),
  489. 'ik_stiffness_z' : (("IK Stiffness", 2), 0.0),
  490. 'use_ik_limit_x' : (("Limit IK", 0), False),
  491. 'use_ik_limit_y' : (("Limit IK", 1), False),
  492. 'use_ik_limit_z' : (("Limit IK", 2), False),
  493. 'ik_min_x' : ("X Min", 0),
  494. 'ik_max_x' : ("X Max", 0),
  495. 'ik_min_y' : ("Y Min", 0),
  496. 'ik_max_y' : ("Y Max", 0),
  497. 'ik_min_z' : ("Z Min", 0),
  498. 'ik_max_z' : ("Z Max", 0),
  499. }
  500. evaluate_sockets(self, pb, props_sockets)
  501. if do_bb:
  502. props_sockets = {
  503. 'bbone_curveinx' : ("BBone X Curve-In", pb.bone.bbone_curveinx),
  504. 'bbone_curveinz' : ("BBone Z Curve-In", pb.bone.bbone_curveinz),
  505. 'bbone_curveoutx' : ("BBone X Curve-Out", pb.bone.bbone_curveoutx),
  506. 'bbone_curveoutz' : ("BBone Z Curve-Out", pb.bone.bbone_curveoutz),
  507. 'bbone_easein' : ("BBone Ease-In", 0),
  508. 'bbone_easeout' : ("BBone Ease-Out", 0),
  509. 'bbone_rollin' : ("BBone Roll-In", 0),
  510. 'bbone_rollout' : ("BBone Roll-Out", 0),
  511. 'bbone_scalein' : ("BBone Scale-In", (1,1,1)),
  512. 'bbone_scaleout' : ("BBone Scale-Out", (1,1,1)),
  513. }
  514. evaluate_sockets(self, pb, props_sockets)
  515. # we need to clear this stuff since our only real goal was to get some drivers from the above
  516. for attr_name in props_sockets.keys():
  517. try:
  518. setattr(pb, attr_name, 0) # just clear it
  519. except ValueError:
  520. setattr(pb, attr_name, (1.0,1.0,1.0)) # scale needs to be set to 1
  521. # important TODO... all of the drivers and stuff should be handled this way, right?
  522. # time to set up drivers!
  523. # just gonna add this to the end and build off it I guess
  524. props_sockets = {
  525. "lock_location" : ("Lock Location", [False, False, False]),
  526. "lock_rotation" : ("Lock Rotation", [False, False, False]),
  527. "lock_scale" : ("Lock Scale", [False, False, False]),
  528. 'custom_shape_scale_xyz' : ("Custom Object Scale", (0.0,0.0,0.0) ),
  529. 'custom_shape_translation' : ("Custom Object Translation", (0.0,0.0,0.0) ),
  530. 'custom_shape_rotation_euler' : ("Custom Object Rotation", (0.0,0.0,0.0) ),
  531. 'use_custom_shape_bone_size' : ("Custom Object Scale to Bone Length", True,)
  532. }
  533. evaluate_sockets(self, pb, props_sockets)
  534. # this could probably be moved to bTransformPass
  535. props_sockets = {
  536. 'hide' : ("Hide", False),
  537. 'show_wire' : ("Custom Object Wireframe", False),
  538. }
  539. evaluate_sockets(self, pb.bone, props_sockets)
  540. if (driver):
  541. pass
  542. # whatever I was doing there.... was stupid. CLEAN UP TODO
  543. # this is the right thing to do.
  544. finish_drivers(self)
  545. #
  546. # OK, visual settings
  547. #
  548. # Get the override xform's bone:
  549. pb.custom_shape_transform = None
  550. pb.custom_shape = None
  551. if len(self.inputs["Custom Object xForm Override"].links) > 0:
  552. trace = trace_single_line(self, "Custom Object xForm Override")
  553. try:
  554. pb.custom_shape_transform = trace[0][1].bGetObject()
  555. except AttributeError:
  556. pass
  557. if len(self.inputs["Custom Object"].links) > 0:
  558. trace = trace_single_line(self, "Custom Object")
  559. try:
  560. ob = trace[0][1].bGetObject()
  561. except AttributeError:
  562. ob=None
  563. if type(ob) in [bpy.types.Object]:
  564. pb.custom_shape = ob
  565. def bGetObject(self, mode = 'POSE'):
  566. if self.bObject is None: return None
  567. if mode in ["POSE", "OBJECT"] and self.bGetParentArmature().mode == "EDIT":
  568. raise RuntimeError("Cannot get Bone or PoseBone in Edit mode.")
  569. elif mode == "EDIT" and self.bGetParentArmature().mode != "EDIT":
  570. raise RuntimeError("Cannot get EditBone except in Edit mode.")
  571. try:
  572. if (mode == 'EDIT'):
  573. return self.bGetParentArmature().data.edit_bones[self.bObject]
  574. elif (mode == 'OBJECT'):
  575. return self.bGetParentArmature().data.bones[self.bObject]
  576. elif (mode == 'POSE'):
  577. return self.bGetParentArmature().pose.bones[self.bObject]
  578. except Exception as e:
  579. prRed ("Cannot get bone for %s" % self)
  580. raise e
  581. def fill_parameters(self, prototype=None):
  582. # this is the fill_parameters that is run if it isn't a schema
  583. setup_custom_props(self)
  584. super().fill_parameters(prototype)
  585. # otherwise we will do this from the schema
  586. # LEGIBILITY TODO - why? explain this?
  587. class xFormGeometryObject(xFormNode):
  588. '''A node representing an armature object'''
  589. def __init__(self, signature, base_tree):
  590. super().__init__(signature, base_tree, xFormGeometryObjectSockets)
  591. self.init_parameters()
  592. self.set_traverse([("Relationship", "xForm Out")])
  593. self.has_shape_keys = False
  594. def bPrepare(self, bContext = None,):
  595. import bpy
  596. if not self.evaluate_input("Name"):
  597. self.prepared = True
  598. self.executed = True
  599. # and return an error if there are any dependencies:
  600. if self.hierarchy_connections:
  601. raise GraphError(wrapRed(f"Cannot Generate object {self} because the chosen name is empty or invalid."))
  602. return
  603. self.bObject = bpy.data.objects.get(self.evaluate_input("Name"))
  604. trace = trace_single_line(self, "Geometry")
  605. if (not self.bObject):
  606. if trace[-1]:
  607. self.bObject = bpy.data.objects.new(self.evaluate_input("Name"), trace[-1].node.bGetObject())
  608. # handle mismatched data.
  609. data_wrong = False; data = None
  610. if (self.inputs["Geometry"].is_linked and self.bObject.type == "EMPTY"):
  611. data_wrong = True; data = trace[-1].node.bGetObject()
  612. elif (not self.inputs["Geometry"].is_linked and not self.bObject.type == "EMPTY"):
  613. data_wrong = True
  614. # clumsy but functional
  615. if data_wrong:
  616. unlink_me = self.bObject
  617. unlink_me.name = "MANTIS_TRASH.000"
  618. for col in unlink_me.users_collection:
  619. col.objects.unlink(unlink_me)
  620. self.bObject = bpy.data.objects.new(self.evaluate_input("Name"), data)
  621. if self.bObject and (self.inputs["Geometry"].is_linked and self.bObject.type in ["MESH", "CURVE"]):
  622. self.bObject.data = trace[-1].node.bGetObject()
  623. # NOW: find out if we need to duplicate the object data.
  624. dupe_data=False
  625. node_line = trace_single_line(self, "Deformer")[0]
  626. from .deformer_nodes import DeformerHook
  627. for deformer in node_line:
  628. if isinstance(deformer, DeformerHook) and \
  629. deformer.evaluate_input("Affect Curve Radius") == True and \
  630. self.bObject.type == 'CURVE':
  631. print(f"INFO: Duplicating data {self.bObject.data.name} in {self} so it can be used for drivers.")
  632. dupe_data=True; break
  633. if dupe_data:
  634. name = self.bObject.data.name
  635. # it has to be a curve
  636. data = bpy.data.curves.get(self.bObject.data.name+"_MANTIS")
  637. if data: # Delete it and regenerate it if it exists.
  638. data.name+="_TRASH.000" # but we can't actually delete it here
  639. # since previous executions of the graph may be using it.
  640. # instead, we'll rename it and use a new copy. This will probably
  641. # be deleted on its own by Blender's garbage collector.
  642. # if it isn't, then it is still in use and I may NOT touch it.
  643. data=self.bObject.data.copy(); data.animation_data_clear()
  644. data.name = name+"_MANTIS"
  645. self.bObject.data = data
  646. reset_object_data(self.bObject)
  647. matrix= get_matrix(self)
  648. self.parameters['Matrix'] = matrix
  649. try:
  650. set_object_parent(self)
  651. except: # I guess it isn't ready yet. we'll do it later
  652. pass # (This can happen when solving schema.)
  653. self.bObject.matrix_world = matrix
  654. self.prepared = True
  655. def bTransformPass(self, bContext = None,):
  656. try:
  657. bContext.collection.objects.link(self.bObject)
  658. except RuntimeError: #already in; but a dangerous thing to pass.
  659. pass
  660. self.has_shape_keys = False
  661. # putting this in bTransformPass simply prevents it from being run more than once.
  662. # maybe I should do that with the rest of bPrepare, too.
  663. props_sockets = {
  664. 'hide_viewport' : ("Hide in Viewport", False),
  665. 'hide_render' : ("Hide in Render", False),
  666. }
  667. evaluate_sockets(self, self.bObject, props_sockets)
  668. self.executed = True
  669. def bFinalize(self, bContext = None):
  670. matrix= get_matrix(self)
  671. set_object_parent(self)
  672. self.bObject.matrix_world = matrix
  673. for i, (driver_key, driver_item) in enumerate(self.drivers.items()):
  674. print (wrapGreen(i), wrapWhite(self), wrapPurple(driver_key))
  675. prOrange(driver_item)
  676. finish_drivers(self)
  677. def bGetObject(self, mode = 'POSE'):
  678. return self.bObject
  679. class xFormObjectInstance(xFormNode):
  680. """Represents an instance of an existing geometry object."""
  681. def __init__(self, signature, base_tree):
  682. super().__init__(signature, base_tree, xFormGeometryObjectInstanceSockets)
  683. self.init_parameters()
  684. # TODO: I think this field is a leftover from a test or something. see if it can be removed.
  685. self.links = {} # leave this empty for now!
  686. self.set_traverse([("Relationship", "xForm Out")])
  687. self.has_shape_keys = False # Shape Keys will make a dupe so this is OK
  688. def ui_modify_socket(self, ui_socket, socket_name=None):
  689. if ui_socket.name == 'As Instance':
  690. change_handled = True
  691. try:
  692. self.bObject.modifiers[0]['Socket_1'] = ui_socket.default_value
  693. except Exception as e:
  694. print("Failed to update mantis socket because of %s" % e,
  695. "Updating tree instead.")
  696. return change_handled
  697. else:
  698. return super().ui_modify_socket(ui_socket, socket_name)
  699. def bPrepare(self, bContext = None,):
  700. from bpy import data
  701. empty_mesh = data.meshes.get("MANTIS_EMPTY_MESH")
  702. if not empty_mesh:
  703. empty_mesh = data.meshes.new("MANTIS_EMPTY_MESH")
  704. if not self.evaluate_input("Name"):
  705. self.prepared = True
  706. self.executed = True
  707. # and return an error if there are any dependencies:
  708. if self.hierarchy_connections:
  709. raise GraphError(wrapRed(f"Cannot Generate object {self} because the chosen name is empty or invalid."))
  710. return
  711. self.bObject = data.objects.get(self.evaluate_input("Name"))
  712. if (not self.bObject):
  713. self.bObject = data.objects.new(self.evaluate_input("Name"), empty_mesh)
  714. reset_object_data(self.bObject)
  715. matrix= get_matrix(self)
  716. self.parameters['Matrix'] = matrix
  717. set_object_parent(self)
  718. self.bObject.matrix_world = matrix
  719. self.prepared = True
  720. def bTransformPass(self, bContext = None,):
  721. try:
  722. bContext.collection.objects.link(self.bObject)
  723. except RuntimeError: #already in; but a dangerous thing to pass.
  724. pass
  725. self.has_shape_keys = False
  726. # putting this in bTransformPass simply prevents it from being run more than once.
  727. # maybe I should do that with the rest of bPrepare, too.
  728. props_sockets = {
  729. 'hide_viewport' : ("Hide in Viewport", False),
  730. 'hide_render' : ("Hide in Render", False),
  731. }
  732. evaluate_sockets(self, self.bObject, props_sockets)
  733. self.executed = True
  734. def bFinalize(self, bContext = None):
  735. # now we need to set the object instance up.
  736. from bpy import data
  737. trace = trace_single_line(self, "Source Object")
  738. for node in trace[0]:
  739. if node is self: continue # lol
  740. if (node.node_type == 'XFORM'):
  741. source_ob = node.bGetObject(); break
  742. modifier = self.bObject.modifiers.new("Object Instance", type='NODES')
  743. ng = data.node_groups.get("Object Instance")
  744. if ng is None:
  745. from .geometry_node_graphgen import gen_object_instance_node_group
  746. ng = gen_object_instance_node_group()
  747. modifier.node_group = ng
  748. modifier["Socket_0"] = source_ob
  749. modifier["Socket_1"] = self.evaluate_input("As Instance")
  750. for i, (driver_key, driver_item) in enumerate(self.drivers.items()):
  751. print (wrapGreen(i), wrapWhite(self), wrapPurple(driver_key))
  752. prOrange(driver_item)
  753. finish_drivers(self)
  754. def bGetObject(self, mode = 'POSE'):
  755. return self.bObject
  756. class xFormCurvePin(xFormNode):
  757. """An xForm pinned to a specific location on a curve."""
  758. def __init__(self, signature, base_tree):
  759. super().__init__(signature, base_tree,xFormCurvePinSockets)
  760. self.init_parameters(additional_parameters={"Matrix":None})
  761. def prep_driver_values(self, constraint):
  762. from .misc_nodes import UtilityDriver, UtilitySwitch
  763. for socket_name in ["Curve Pin Factor", "Forward Axis","Up Axis",]:
  764. if self.inputs.get(socket_name) is None: continue # in case it has been bypassed
  765. if self.inputs[socket_name].is_linked:
  766. node_line, _last_socket = trace_single_line(self, socket_name)
  767. driver = None
  768. for other_node in node_line:
  769. if other_node.node_type == 'DRIVER':
  770. driver = other_node; break
  771. if isinstance(driver, UtilityDriver):
  772. prop_amount = driver.evaluate_input("Property")
  773. elif isinstance(driver, UtilitySwitch):
  774. xf=driver.GetxForm()
  775. prop_amount = xf.evaluate_input(driver.evaluate_input('Parameter'))
  776. else:
  777. return
  778. for template in self.socket_templates:
  779. if template.name == socket_name: break
  780. setattr(constraint, template.blender_property, prop_amount )
  781. def bPrepare(self, bContext = None,):
  782. from bpy import data
  783. if not bContext: # lol
  784. import bpy
  785. bContext = bpy.context
  786. ob = data.objects.get(self.evaluate_input("Name"))
  787. if not ob:
  788. ob = data.objects.new(self.evaluate_input("Name"), None)
  789. ob.lock_location = [True, True, True]
  790. ob.lock_rotation = [True, True, True]
  791. ob.lock_scale = [True, True, True]
  792. ob.lock_rotation_w = True
  793. ob.empty_display_type = 'CONE'
  794. ob.empty_display_size = 0.10
  795. self.bObject = ob
  796. reset_object_data(ob)
  797. node_line = trace_single_line(self, "Parent Curve")[0][1:] # slice excludes self
  798. for other_node in node_line:
  799. if other_node.node_type == 'XFORM':
  800. break
  801. else:
  802. raise GraphError(f"ERROR: {self} is not connected to a parent curve")
  803. if isinstance(other_node, (xFormArmature, xFormBone, xFormObjectInstance,)):
  804. raise GraphError(f"ERROR: {self} must be connected to curve,"
  805. " not {other_node.__class__.__name__}")
  806. curve=other_node.bGetObject()
  807. if curve.type != 'CURVE':
  808. raise GraphError(f"ERROR: {self} must be connected to curve,"
  809. " not {curve.type}")
  810. # we'll limit all the transforms so we can parent it
  811. # because it is annoying to have a cluttered outliner.
  812. #
  813. # always do this so that everything stays consistent.
  814. spline_index = self.evaluate_input("Spline Index")
  815. from .utilities import get_extracted_spline_object
  816. curve = get_extracted_spline_object(curve, spline_index, self.mContext)
  817. # Link to Scene:
  818. for link_me in [ob, curve]:
  819. if (link_me.name not in bContext.view_layer.active_layer_collection.collection.objects):
  820. bContext.view_layer.active_layer_collection.collection.objects.link(link_me)
  821. c = ob.constraints.new("LIMIT_LOCATION")
  822. for max_min in ['max','min']:
  823. for axis in "xyz":
  824. setattr(c, "use_"+max_min+"_"+axis, True)
  825. setattr(c, max_min+"_"+axis, 0.0)
  826. c = ob.constraints.new("LIMIT_ROTATION")
  827. for axis in "xyz":
  828. setattr(c, "use_limit_"+axis, True)
  829. setattr(c, max_min+"_"+axis, 0.0)
  830. c = ob.constraints.new("LIMIT_SCALE")
  831. for max_min in ['max','min']:
  832. for axis in "xyz":
  833. setattr(c, "use_"+max_min+"_"+axis, True)
  834. setattr(c, max_min+"_"+axis, 1.0)
  835. c = ob.constraints.new("FOLLOW_PATH")
  836. c.target = curve
  837. c.use_fixed_location = True
  838. c.use_curve_radius = True
  839. c.use_curve_follow = True
  840. c.name = "Curve Pin"
  841. props_sockets = self.gen_property_socket_map()
  842. constraint_props_sockets = props_sockets.copy()
  843. del constraint_props_sockets['name']; del constraint_props_sockets['empty_display_size']
  844. del props_sockets['offset_factor']; del props_sockets['forward_axis']
  845. del props_sockets['up_axis']
  846. evaluate_sockets(self, c, constraint_props_sockets)
  847. evaluate_sockets(self, self.bObject, props_sockets)
  848. # this isn't usually run on xForm nodes so for now I need to set the
  849. # driver's default values manually if I want a matrix now.
  850. # because the drivers may not have initialized yet.
  851. self.prep_driver_values(c)
  852. # now if all goes well... the matrix will be correct.
  853. dg = bContext.view_layer.depsgraph
  854. dg.update()
  855. # and the matrix should be correct now - copy because it may be modified
  856. self.parameters['Matrix'] = ob.matrix_world.copy()
  857. ob.parent=curve
  858. print( wrapGreen("Created Curve Pin: ") + wrapOrange(self.bObject.name) )
  859. self.prepared = True; self.executed = True
  860. def bFinalize(self, bContext = None):
  861. finish_drivers(self)
  862. def bGetObject(self, mode = 'POSE'):
  863. return self.bObject