xForm_containers.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. from .node_container_common import *
  2. from bpy.types import Node
  3. from .base_definitions import MantisNode
  4. def TellClasses():
  5. return [
  6. # xForm
  7. xFormArmature,
  8. xFormBone,
  9. xFormGeometryObject,
  10. ]
  11. #*#-------------------------------#++#-------------------------------#*#
  12. # X - F O R M N O D E S
  13. #*#-------------------------------#++#-------------------------------#*#
  14. class xFormArmature:
  15. '''A node representing an armature object'''
  16. bObject = None
  17. def __init__(self, signature, base_tree):
  18. self.base_tree=base_tree
  19. self.signature = signature
  20. self.inputs = {
  21. "Name" : NodeSocket(is_input = True, name = "Name", node = self),
  22. "Rotation Order" : NodeSocket(is_input = True, name = "Rotation Order", node = self),
  23. "Matrix" : NodeSocket(is_input = True, name = "Matrix", node = self),
  24. "Relationship" : NodeSocket(is_input = True, name = "Relationship", node = self),
  25. }
  26. self.outputs = {
  27. "xForm Out" : NodeSocket(name="xForm Out", node = self),
  28. }
  29. self.parameters = {
  30. "Name":None,
  31. "Rotation Order":None,
  32. "Matrix":None,
  33. "Relationship":None,
  34. }
  35. self.links = {} # leave this empty for now!
  36. # now set up the traverse target...
  37. self.inputs["Relationship"].set_traverse_target(self.outputs["xForm Out"])
  38. self.outputs["xForm Out"].set_traverse_target(self.inputs["Relationship"])
  39. self.node_type = 'XFORM'
  40. self.hierarchy_connections = []
  41. self.connections = []
  42. self.hierarchy_dependencies = []
  43. self.dependencies = []
  44. self.prepared = True
  45. self.executed = False
  46. def bExecute(self, bContext = None,):
  47. # from .utilities import get_node_prototype
  48. import bpy
  49. if (not isinstance(bContext, bpy.types.Context)):
  50. raise RuntimeError("Incorrect context")
  51. name = self.evaluate_input("Name")
  52. if not ( matrix := self.evaluate_input('Matrix')):
  53. raise RuntimeError(wrapRed(f"No matrix found for Armature {self}"))
  54. self.parameters['Matrix'] = matrix
  55. reset_transforms = False
  56. #check if an object by the name exists
  57. if (name) and (ob := bpy.data.objects.get(name)):
  58. if (ob.animation_data):
  59. while (ob.animation_data.drivers):
  60. ob.animation_data.drivers.remove(ob.animation_data.drivers[-1])
  61. for pb in ob.pose.bones:
  62. # clear it, even after deleting the edit bones,
  63. # if we create them again the pose bones will be reused
  64. while (pb.constraints):
  65. pb.constraints.remove(pb.constraints[-1])
  66. if reset_transforms:
  67. pb.location = (0,0,0)
  68. pb.rotation_euler = (0,0,0)
  69. pb.rotation_quaternion = (1.0,0,0,0)
  70. pb.rotation_axis_angle = (0,0,1.0,0)
  71. pb.scale = (1.0,1.0,1.0)
  72. # feels ugly and bad, whatever
  73. collections = []
  74. for bc in ob.data.collections:
  75. collections.append(bc)
  76. for bc in collections:
  77. ob.data.collections.remove(bc)
  78. del collections
  79. # end ugly/bad
  80. else:
  81. # Create the Object
  82. ob = bpy.data.objects.new(name, bpy.data.armatures.new(name)) #create ob
  83. if (ob.name != name):
  84. raise RuntimeError("Could not create xForm object", name)
  85. self.bObject = ob.name
  86. ob.matrix_world = matrix.copy()
  87. ob.data.pose_position = 'REST'
  88. if True:
  89. from bpy.types import EditBone
  90. parent_nc = get_parent(self, type='LINK')
  91. if parent_nc:
  92. parent = parent_nc.inputs['Parent'].links[0].from_node.bGetObject(mode = 'OBJECT')
  93. ob.parent = parent
  94. # Link to Scene:
  95. if (ob.name not in bContext.view_layer.active_layer_collection.collection.objects):
  96. bContext.view_layer.active_layer_collection.collection.objects.link(ob)
  97. #self.bParent(bContext)
  98. print( wrapGreen("Created Armature object: ")+ wrapWhite(ob.name))
  99. # Finalize the action
  100. # oddly, overriding context doesn't seem to work
  101. try:
  102. bpy.ops.object.select_all(action='DESELECT')
  103. except RuntimeError:
  104. pass # we're already in edit mode, should be OK to do this.
  105. bContext.view_layer.objects.active = ob
  106. selected=[]
  107. for other_ob in bpy.data.objects:
  108. if other_ob.mode == "EDIT":
  109. selected.append(other_ob)
  110. selected.append(ob)
  111. context_override = {"active_object":ob, "selected_objects":selected}
  112. print("Changing Armature Mode to " +wrapPurple("EDIT"))
  113. with bContext.temp_override(**context_override):
  114. bpy.ops.object.mode_set(mode='EDIT')
  115. if ob.mode != "EDIT":
  116. prRed("eh?")
  117. # clear it
  118. while (len(ob.data.edit_bones) > 0):
  119. ob.data.edit_bones.remove(ob.data.edit_bones[0])
  120. # bContext.view_layer.objects.active = prevAct
  121. self.executed = True
  122. def bGetObject(self, mode = ''):
  123. import bpy; return bpy.data.objects[self.bObject]
  124. bone_inputs= [
  125. "Name",
  126. "Rotation Order",
  127. "Matrix",
  128. "Relationship",
  129. # IK settings
  130. "IK Stretch",
  131. "Lock IK",
  132. "IK Stiffness",
  133. "Limit IK",
  134. "X Min",
  135. "X Max",
  136. "Y Min",
  137. "Y Max",
  138. "Z Min",
  139. "Z Max",
  140. # Visual stuff
  141. "Bone Collection",
  142. "Hide",
  143. "Custom Object",
  144. "Custom Object xForm Override",
  145. "Custom Object Scale to Bone Length",
  146. "Custom Object Wireframe",
  147. "Custom Object Scale",
  148. "Custom Object Translation",
  149. "Custom Object Rotation",
  150. # Deform Stuff
  151. "Deform",
  152. "Envelope Distance",
  153. "Envelope Weight",
  154. "Envelope Multiply",
  155. "Envelope Head Radius",
  156. "Envelope Tail Radius",
  157. # BBone stuff:
  158. "BBone Segments",
  159. "BBone X Size",
  160. "BBone Z Size",
  161. "BBone HQ Deformation",
  162. "BBone X Curve-In",
  163. "BBone Z Curve-In",
  164. "BBone X Curve-Out",
  165. "BBone Z Curve-Out",
  166. "BBone Roll-In",
  167. "BBone Roll-Out",
  168. "BBone Inherit End Roll",
  169. "BBone Scale-In",
  170. "BBone Scale-Out",
  171. "BBone Ease-In",
  172. "BBone Ease-Out",
  173. "BBone Easing",
  174. "BBone Start Handle Type",
  175. "BBone Custom Start Handle",
  176. "BBone Start Handle Scale",
  177. "BBone Start Handle Ease",
  178. "BBone End Handle Type",
  179. "BBone Custom End Handle",
  180. "BBone End Handle Scale",
  181. "BBone End Handle Ease",
  182. # locks
  183. "Lock Location",
  184. "Lock Rotation",
  185. "Lock Scale",
  186. ]
  187. class xFormBone:
  188. '''A node representing a bone in an armature'''
  189. # DO: make a way to identify which armature this belongs to
  190. def __init__(self, signature, base_tree):
  191. self.base_tree=base_tree
  192. self.signature = signature
  193. self.inputs = {
  194. "Name" : NodeSocket(is_input = True, name = "Name", node = self,),
  195. "Rotation Order" : NodeSocket(is_input = True, name = "Rotation Order", node = self,),
  196. "Matrix" : NodeSocket(is_input = True, name = "Matrix", node = self,),
  197. "Relationship" : NodeSocket(is_input = True, name = "Relationship", node = self,),
  198. # IK settings
  199. "IK Stretch" : NodeSocket(is_input = True, name = "IK Stretch", node = self,),
  200. "Lock IK" : NodeSocket(is_input = True, name = "Lock IK", node = self,),
  201. "IK Stiffness" : NodeSocket(is_input = True, name = "IK Stiffness", node = self,),
  202. "Limit IK" : NodeSocket(is_input = True, name = "Limit IK", node = self,),
  203. "X Min" : NodeSocket(is_input = True, name = "X Min", node = self,),
  204. "X Max" : NodeSocket(is_input = True, name = "X Max", node = self,),
  205. "Y Min" : NodeSocket(is_input = True, name = "Y Min", node = self,),
  206. "Y Max" : NodeSocket(is_input = True, name = "Y Max", node = self,),
  207. "Z Min" : NodeSocket(is_input = True, name = "Z Min", node = self,),
  208. "Z Max" : NodeSocket(is_input = True, name = "Z Max", node = self,),
  209. # Visual stuff
  210. "Bone Collection" : NodeSocket(is_input = True, name = "Bone Collection", node = self,),
  211. "Hide" : NodeSocket(is_input = True, name = "Hide", node = self,),
  212. "Custom Object" : NodeSocket(is_input = True, name = "Custom Object", node = self,),
  213. "Custom Object xForm Override" : NodeSocket(is_input = True, name = "Custom Object xForm Override", node = self,),
  214. "Custom Object Scale to Bone Length" : NodeSocket(is_input = True, name = "Custom Object Scale to Bone Length", node = self,),
  215. "Custom Object Wireframe" : NodeSocket(is_input = True, name = "Custom Object Wireframe", node = self,),
  216. "Custom Object Scale" : NodeSocket(is_input = True, name = "Custom Object Scale", node = self,),
  217. "Custom Object Translation" : NodeSocket(is_input = True, name = "Custom Object Translation", node = self,),
  218. "Custom Object Rotation" : NodeSocket(is_input = True, name = "Custom Object Rotation", node = self,),
  219. # Deform Stuff
  220. "Deform" : NodeSocket(is_input = True, name = "Deform", node = self,),
  221. "Envelope Distance" : NodeSocket(is_input = True, name = "Envelope Distance", node = self,),
  222. "Envelope Weight" : NodeSocket(is_input = True, name = "Envelope Weight", node = self,),
  223. "Envelope Multiply" : NodeSocket(is_input = True, name = "Envelope Multiply", node = self,),
  224. "Envelope Head Radius" : NodeSocket(is_input = True, name = "Envelope Head Radius", node = self,),
  225. "Envelope Tail Radius" : NodeSocket(is_input = True, name = "Envelope Tail Radius", node = self,),
  226. # BBone stuff:
  227. "BBone Segments" : NodeSocket(is_input = True, name = "BBone Segments", node=self,),
  228. "BBone X Size" : NodeSocket(is_input = True, name = "BBone X Size", node=self,),
  229. "BBone Z Size" : NodeSocket(is_input = True, name = "BBone Z Size", node=self,),
  230. "BBone HQ Deformation" : NodeSocket(is_input = True, name = "BBone HQ Deformation", node=self,),
  231. "BBone X Curve-In" : NodeSocket(is_input = True, name = "BBone X Curve-In", node=self,),
  232. "BBone Z Curve-In" : NodeSocket(is_input = True, name = "BBone Z Curve-In", node=self,),
  233. "BBone X Curve-Out" : NodeSocket(is_input = True, name = "BBone X Curve-Out", node=self,),
  234. "BBone Z Curve-Out" : NodeSocket(is_input = True, name = "BBone Z Curve-Out", node=self,),
  235. "BBone Roll-In" : NodeSocket(is_input = True, name = "BBone Roll-In", node=self,),
  236. "BBone Roll-Out" : NodeSocket(is_input = True, name = "BBone Roll-Out", node=self,),
  237. "BBone Inherit End Roll" : NodeSocket(is_input = True, name = "BBone Inherit End Roll", node=self,),
  238. "BBone Scale-In" : NodeSocket(is_input = True, name = "BBone Scale-In", node=self,),
  239. "BBone Scale-Out" : NodeSocket(is_input = True, name = "BBone Scale-Out", node=self,),
  240. "BBone Ease-In" : NodeSocket(is_input = True, name = "BBone Ease-In", node=self,),
  241. "BBone Ease-Out" : NodeSocket(is_input = True, name = "BBone Ease-Out", node=self,),
  242. "BBone Easing" : NodeSocket(is_input = True, name = "BBone Easing", node=self,),
  243. "BBone Start Handle Type" : NodeSocket(is_input = True, name = "BBone Start Handle Type", node=self,),
  244. "BBone Custom Start Handle" : NodeSocket(is_input = True, name = "BBone Custom Start Handle", node=self,),
  245. "BBone Start Handle Scale" : NodeSocket(is_input = True, name = "BBone Start Handle Scale", node=self,),
  246. "BBone Start Handle Ease" : NodeSocket(is_input = True, name = "BBone Start Handle Ease", node=self,),
  247. "BBone End Handle Type" : NodeSocket(is_input = True, name = "BBone End Handle Type", node=self,),
  248. "BBone Custom End Handle" : NodeSocket(is_input = True, name = "BBone Custom End Handle", node=self,),
  249. "BBone End Handle Scale" : NodeSocket(is_input = True, name = "BBone End Handle Scale", node=self,),
  250. "BBone End Handle Ease" : NodeSocket(is_input = True, name = "BBone End Handle Ease", node=self,),
  251. # locks
  252. "Lock Location" : NodeSocket(is_input = True, name = "Lock Location", node = self,),
  253. "Lock Rotation" : NodeSocket(is_input = True, name = "Lock Rotation", node = self,),
  254. "Lock Scale" : NodeSocket(is_input = True, name = "Lock Scale", node = self,),
  255. }
  256. self.outputs = {
  257. "xForm Out" : NodeSocket(name = "xForm Out", node = self),
  258. }
  259. self.parameters = {
  260. "Name":None,
  261. "Rotation Order":None,
  262. "Matrix":None,
  263. "Relationship":None,
  264. # IK settings
  265. "IK Stretch":None,
  266. "Lock IK":None,
  267. "IK Stiffness":None,
  268. "Limit IK":None,
  269. "X Min":None,
  270. "X Max":None,
  271. "Y Min":None,
  272. "Y Max":None,
  273. "Z Min":None,
  274. "Z Max":None,
  275. "Hide":None,
  276. "Bone Collection":None,
  277. "Hide":None,
  278. "Custom Object":None,
  279. "Custom Object xForm Override":None,
  280. "Custom Object Scale to Bone Length":None,
  281. "Custom Object Wireframe":None,
  282. "Custom Object Scale":None,
  283. "Custom Object Translation":None,
  284. "Custom Object Rotation":None,
  285. "Deform" : None,
  286. "Envelope Distance" : None,
  287. "Envelope Weight" : None,
  288. "Envelope Multiply" : None,
  289. "Envelope Head Radius" : None,
  290. "Envelope Tail Radius" : None,
  291. #
  292. "BBone Segments" : None,
  293. "BBone X Size" : None,
  294. "BBone Z Size" : None,
  295. "BBone HQ Deformation" : None,
  296. "BBone X Curve-In" : None,
  297. "BBone Z Curve-In" : None,
  298. "BBone X Curve-Out" : None,
  299. "BBone Z Curve-Out" : None,
  300. "BBone Roll-In" : None,
  301. "BBone Roll-Out" : None,
  302. "BBone Inherit End Roll" : None,
  303. "BBone Scale-In" : None,
  304. "BBone Scale-Out" : None,
  305. "BBone Ease-In" : None,
  306. "BBone Ease-Out" : None,
  307. "BBone Easing" : None,
  308. "BBone Start Handle Type" : None,
  309. "BBone Custom Start Handle" : None,
  310. "BBone Start Handle Scale" : None,
  311. "BBone Start Handle Ease" : None,
  312. "BBone End Handle Type" : None,
  313. "BBone Custom End Handle" : None,
  314. "BBone End Handle Scale" : None,
  315. "BBone End Handle Ease" : None,
  316. #
  317. "Lock Location" : None,
  318. "Lock Rotation" : None,
  319. "Lock Scale" : None,
  320. }
  321. self.links = {} # leave this empty for now!
  322. # now set up the traverse target...
  323. self.inputs["Relationship"].set_traverse_target(self.outputs["xForm Out"])
  324. self.outputs["xForm Out"].set_traverse_target(self.inputs["Relationship"])
  325. self.node_type = 'XFORM'
  326. self.hierarchy_connections = []
  327. self.connections = []
  328. self.hierarchy_dependencies = []
  329. self.dependencies = []
  330. self.prepared = True
  331. self.executed = False
  332. self.input_length = len(self.inputs) # HACK HACK HACK
  333. def bGetParentArmature(self):
  334. finished = False
  335. if (trace := trace_single_line(self, "Relationship")[0] ) :
  336. for i in range(len(trace)):
  337. # have to look in reverse, actually TODO
  338. if ( isinstance(trace[ i ], xFormArmature ) ):
  339. return trace[ i ].bGetObject()
  340. return None
  341. #should do the trick...
  342. def bSetParent(self, eb):
  343. # print (self.bObject)
  344. from bpy.types import EditBone
  345. parent_nc = get_parent(self, type='LINK')
  346. # print (self, parent_nc.inputs['Parent'].from_node)
  347. parent=None
  348. if parent_nc.inputs['Parent'].links[0].from_node.node_type == 'XFORM':
  349. parent = parent_nc.inputs['Parent'].links[0].from_node.bGetObject(mode = 'EDIT')
  350. else:
  351. raise RuntimeError(wrapRed(f"Cannot set parent for node {self}"))
  352. if isinstance(parent, EditBone):
  353. eb.parent = parent
  354. #DUMMY
  355. # I NEED TO GET THE LINK NC
  356. # IDIOT
  357. eb.use_connect = parent_nc.evaluate_input("Connected")
  358. eb.use_inherit_rotation = parent_nc.evaluate_input("Inherit Rotation")
  359. eb.inherit_scale = parent_nc.evaluate_input("Inherit Scale")
  360. # otherwise, no need to do anything.
  361. def bExecute(self, bContext = None,): #possibly will need to pass context?
  362. import bpy
  363. from mathutils import Vector
  364. if not (name := self.evaluate_input("Name")):
  365. raise RuntimeError(wrapRed(f"Could not set name for bone in {self}"))
  366. if (not isinstance(bContext, bpy.types.Context)):
  367. raise RuntimeError("Incorrect context")
  368. if not (xF := self.bGetParentArmature()):
  369. raise RuntimeError("Could not create edit bone: ", name, " from node:", self.signature, " Reason: No armature object to add bone to.")
  370. if not ( matrix := self.evaluate_input('Matrix')):
  371. # print(self.inputs['Matrix'].links[0].from_node.parameters)
  372. raise RuntimeError(wrapRed(f"No matrix found for Bone {self}"))
  373. self.parameters['Matrix'] = matrix
  374. length = matrix[3][3]
  375. if (xF):
  376. if (xF.mode != "EDIT"):
  377. raise RuntimeError("Armature Object Not in Edit Mode, exiting...")
  378. #
  379. # Create the Object
  380. d = xF.data
  381. eb = d.edit_bones.new(name)
  382. # Bone Collections:
  383. # We treat each separate string as a Bone Collection that this object belongs to
  384. # Bone Collections are fully qualified by their hierarchy.
  385. # Separate Strings with "|" and indicate hierarchy with ">". These are special characters.
  386. # NOTE: if the user names the collections differently at different times, this will take the FIRST definition and go with it
  387. sCols = self.evaluate_input("Bone Collection")
  388. bone_collections = sCols.split("|")
  389. for collection_list in bone_collections:
  390. hierarchy = collection_list.split(">")
  391. col_parent = None
  392. for sCol in hierarchy:
  393. if ( col := d.collections.get(sCol) ) is None:
  394. col = d.collections.new(sCol)
  395. col.parent = col_parent
  396. col_parent = col
  397. col.assign(eb)
  398. if (eb.name != name):
  399. prRed(f"Expected bone of name: {name}, got {eb.name} instead.")
  400. raise RuntimeError("Could not create bone ", name, "; Perhaps there is a duplicate bone name in the node tree?")
  401. eb.matrix = matrix.copy()
  402. tailoffset = Vector((0,length,0)) #Vector((0,self.tailoffset, 0))
  403. tailoffset = matrix.copy().to_3x3() @ tailoffset
  404. eb.tail = eb.head + tailoffset
  405. if (eb.name != name):
  406. raise RuntimeError("Could not create edit bone: ", name)
  407. assert (eb.name), "Bone must have a name."
  408. self.bObject = eb.name
  409. # The bone should have relationships going in at this point.
  410. self.bSetParent(eb)
  411. if eb.head == eb.tail:
  412. raise RuntimeError(wrapRed(f"Could not create edit bone: {name} because bone head was located in the same place as bone tail."))
  413. # Setup Deform attributes...
  414. eb.use_deform = self.evaluate_input("Deform")
  415. eb.envelope_distance = self.evaluate_input("Envelope Distance")
  416. eb.envelope_weight = self.evaluate_input("Envelope Weight")
  417. eb.use_envelope_multiply = self.evaluate_input("Envelope Multiply")
  418. eb.head_radius = self.evaluate_input("Envelope Head Radius")
  419. eb.tail_radius = self.evaluate_input("Envelope Tail Radius")
  420. print( wrapGreen("Created Bone: ") + wrapOrange(eb.name) + wrapGreen(" in ") + wrapWhite(self.bGetParentArmature().name))
  421. self.executed = True
  422. def bFinalize(self, bContext = None):
  423. do_bb=False
  424. b = self.bGetParentArmature().data.bones[self.bObject]
  425. b.bbone_x = self.evaluate_input("BBone X Size"); b.bbone_x = max(b.bbone_x, 0.0002)
  426. b.bbone_z = self.evaluate_input("BBone Z Size"); b.bbone_z = max(b.bbone_z, 0.0002)
  427. if (segs := self.evaluate_input("BBone Segments")) > 1:
  428. do_bb=True
  429. b.bbone_segments = segs
  430. b.bbone_x = self.evaluate_input("BBone X Size")
  431. b.bbone_z = self.evaluate_input("BBone Z Size")
  432. if self.evaluate_input("BBone HQ Deformation"):
  433. b.bbone_mapping_mode = "CURVED"
  434. # 'bbone_handle_type_start' : ("BBone Start Handle Type", "AUTO"),
  435. # 'bbone_handle_type_end' : ("BBone End Handle Type", "AUTO"),
  436. # 'bbone_custom_handle_start' : ("BBone Custom Start Handle", "AUTO"),
  437. # 'bbone_custom_handle_end' : ("BBone Custom End Handle", "AUTO"),
  438. if handle_type := self.evaluate_input("BBone Start Handle Type"):
  439. b.bbone_handle_type_start = handle_type
  440. if handle_type := self.evaluate_input("BBone End Handle Type"):
  441. b.bbone_handle_type_end = handle_type
  442. try:
  443. if (custom_handle := self.evaluate_input("BBone Custom Start Handle")):
  444. b.bbone_custom_handle_start = self.bGetParentArmature().data.bones[custom_handle]
  445. # hypothetically we should support xForm inputs.... but we won't do that for now
  446. # elif custom_handle is None:
  447. # b.bbone_custom_handle_start = self.inputs["BBone Custom Start Handle"].links[0].from_node.bGetObject().name
  448. if (custom_handle := self.evaluate_input("BBone Custom End Handle")):
  449. b.bbone_custom_handle_end = self.bGetParentArmature().data.bones[custom_handle]
  450. except KeyError:
  451. prRed("Warning: BBone start or end handle not set because of missing bone in armature.")
  452. b.bbone_curveinx = self.evaluate_input("BBone X Curve-In")
  453. b.bbone_curveinz = self.evaluate_input("BBone Z Curve-In")
  454. b.bbone_curveoutx = self.evaluate_input("BBone X Curve-Out")
  455. b.bbone_curveoutz = self.evaluate_input("BBone Z Curve-Out")
  456. # 'bbone_curveinx' : ("BBone X Curve-In", pb.bone.bbone_curveinx),
  457. # 'bbone_curveinz' : ("BBone Z Curve-In", pb.bone.bbone_curveinz),
  458. # 'bbone_curveoutx' : ("BBone X Curve-Out", pb.bone.bbone_curveoutx),
  459. # 'bbone_curveoutz' : ("BBone Z Curve-Out", pb.bone.bbone_curveoutz),
  460. # TODO this section should be done with props-socket thing
  461. b.bbone_handle_use_scale_start = self.evaluate_input("BBone Start Handle Scale")
  462. b.bbone_handle_use_scale_end = self.evaluate_input("BBone End Handle Scale")
  463. import bpy
  464. from .drivers import MantisDriver
  465. # prevAct = bContext.view_layer.objects.active
  466. # bContext.view_layer.objects.active = ob
  467. # bpy.ops.object.mode_set(mode='OBJECT')
  468. # bContext.view_layer.objects.active = prevAct
  469. #
  470. #get relationship
  471. # ensure we have a pose bone...
  472. # set the ik parameters
  473. #
  474. #
  475. # Don't need to bother about whatever that was
  476. pb = self.bGetParentArmature().pose.bones[self.bObject]
  477. rotation_mode = self.evaluate_input("Rotation Order")
  478. if rotation_mode == "AUTO": rotation_mode = "XYZ"
  479. pb.rotation_mode = rotation_mode
  480. pb.id_properties_clear()
  481. # these are kept around unless explicitly deleted.
  482. # from .utilities import get_node_prototype
  483. # np = get_node_prototype(self.signature, self.base_tree)
  484. driver = None
  485. do_prints=False
  486. # print (self.input_length)
  487. # even worse hack coming
  488. for i, inp in enumerate(self.inputs.values()):
  489. if inp.name in bone_inputs:
  490. continue
  491. name = inp.name
  492. try:
  493. value = self.evaluate_input(inp.name)
  494. except KeyError as e:
  495. trace = trace_single_line(self, inp.name)
  496. if do_prints: print(trace[0][-1], trace[1])
  497. if do_prints: print (trace[0][-1].parameters)
  498. raise e
  499. # This may be driven, so let's do this:
  500. if do_prints: print (value)
  501. if (isinstance(value, tuple)):
  502. # it's either a CombineThreeBool or a CombineVector.
  503. prRed("COMITTING SUICIDE NOW!!")
  504. bpy.ops.wm.quit_blender()
  505. if (isinstance(value, MantisDriver)):
  506. # the value should be the default for its socket...
  507. if do_prints: print (type(self.parameters[inp.name]))
  508. type_val_map = {
  509. str:"",
  510. bool:False,
  511. int:0,
  512. float:0.0,
  513. bpy.types.bpy_prop_array:(0,0,0),
  514. }
  515. driver = value
  516. value = type_val_map[type(self.parameters[inp.name])]
  517. if (value is None):
  518. prRed("This is probably not supposed to happen")
  519. value = 0
  520. raise RuntimeError("Could not set value of custom parameter")
  521. # it creates a more confusing error later sometimes, better to catch it here.
  522. # IMPORTANT: Is it possible for more than one driver to
  523. # come through here, and for the variable to be
  524. # overwritten?
  525. #TODO important
  526. #from rna_prop_ui import rna_idprop_ui_create
  527. # use this ^
  528. # add the custom properties to the **Pose Bone**
  529. pb[name] = value
  530. # This is much simpler now.
  531. ui_data = pb.id_properties_ui(name)
  532. description=''
  533. ui_data.update(
  534. description=description,#inp.description,
  535. default=value,)
  536. #if a number
  537. if type(value) == float:
  538. ui_data.update(
  539. min = inp.min,
  540. max = inp.max,
  541. soft_min = inp.soft_min,
  542. soft_max = inp.soft_max,)
  543. elif type(value) == int:
  544. ui_data.update(
  545. min = int(inp.min),
  546. max = int(inp.max),
  547. soft_min = int(inp.soft_min),
  548. soft_max = int(inp.soft_max),)
  549. elif type(value) == bool:
  550. ui_data.update() # TODO I can't figure out what the update function expects because it isn't documented
  551. if (pb.is_in_ik_chain):
  552. # this props_socket thing wasn't really meant to work here but it does, neat
  553. props_sockets = {
  554. 'ik_stretch' : ("IK Stretch", 0),
  555. 'lock_ik_x' : (("Lock IK", 0), False),
  556. 'lock_ik_y' : (("Lock IK", 1), False),
  557. 'lock_ik_z' : (("Lock IK", 2), False),
  558. 'ik_stiffness_x' : (("IK Stiffness", 0), 0.0),
  559. 'ik_stiffness_y' : (("IK Stiffness", 1), 0.0),
  560. 'ik_stiffness_z' : (("IK Stiffness", 2), 0.0),
  561. 'use_ik_limit_x' : (("Limit IK", 0), False),
  562. 'use_ik_limit_y' : (("Limit IK", 1), False),
  563. 'use_ik_limit_z' : (("Limit IK", 2), False),
  564. 'ik_min_x' : ("X Min", 0),
  565. 'ik_max_x' : ("X Max", 0),
  566. 'ik_min_y' : ("Y Min", 0),
  567. 'ik_max_y' : ("Y Max", 0),
  568. 'ik_min_z' : ("Z Min", 0),
  569. 'ik_max_z' : ("Z Max", 0),
  570. }
  571. evaluate_sockets(self, pb, props_sockets)
  572. if do_bb:
  573. props_sockets = {
  574. 'bbone_curveinx' : ("BBone X Curve-In", pb.bone.bbone_curveinx),
  575. 'bbone_curveinz' : ("BBone Z Curve-In", pb.bone.bbone_curveinz),
  576. 'bbone_curveoutx' : ("BBone X Curve-Out", pb.bone.bbone_curveoutx),
  577. 'bbone_curveoutz' : ("BBone Z Curve-Out", pb.bone.bbone_curveoutz),
  578. 'bbone_easein' : ("BBone Ease-In", 0),
  579. 'bbone_easeout' : ("BBone Ease-Out", 0),
  580. 'bbone_rollin' : ("BBone Roll-In", 0),
  581. 'bbone_rollout' : ("BBone Roll-Out", 0),
  582. 'bbone_scalein' : ("BBone Scale-In", (1,1,1)),
  583. 'bbone_scaleout' : ("BBone Scale-Out", (1,1,1)),
  584. }
  585. prRed("BBone Implementation is not complete, expect errors and missing features for now")
  586. evaluate_sockets(self, pb, props_sockets)
  587. # we need to clear this stuff since our only real goal was to get some drivers from the above
  588. for attr_name in props_sockets.keys():
  589. try:
  590. setattr(pb, attr_name, 0) # just clear it
  591. except ValueError:
  592. setattr(pb, attr_name, (1.0,1.0,1.0)) # scale needs to be set to 1
  593. # important TODO... all of the drivers and stuff should be handled this way, right?
  594. # time to set up drivers!
  595. # just gonna add this to the end and build off it I guess
  596. props_sockets = {
  597. "lock_location" : ("Lock Location", [False, False, False]),
  598. "lock_rotation" : ("Lock Rotation", [False, False, False]),
  599. "lock_scale" : ("Lock Scale", [False, False, False]),
  600. 'custom_shape_scale_xyz' : ("Custom Object Scale", (0.0,0.0,0.0) ),
  601. 'custom_shape_translation' : ("Custom Object Translation", (0.0,0.0,0.0) ),
  602. 'custom_shape_rotation_euler' : ("Custom Object Rotation", (0.0,0.0,0.0) ),
  603. 'use_custom_shape_bone_size' : ("Custom Object Scale to Bone Length", True,)
  604. }
  605. evaluate_sockets(self, pb, props_sockets)
  606. # this could probably be moved to bExecute
  607. props_sockets = {
  608. 'hide' : ("Hide", False),
  609. 'show_wire' : ("Custom Object Wireframe", False),
  610. }
  611. evaluate_sockets(self, pb.bone, props_sockets)
  612. if (driver):
  613. pass
  614. # whatever I was doing there.... was stupid. CLEAN UP TODO
  615. # this is the right thing to do.
  616. finish_drivers(self)
  617. #
  618. # OK, visual settings
  619. #
  620. # Get the override xform's bone:
  621. if len(self.inputs["Custom Object xForm Override"].links) > 0:
  622. trace = trace_single_line(self, "Custom Object xForm Override")
  623. try:
  624. pb.custom_shape_transform = trace[0][1].bGetObject()
  625. except AttributeError:
  626. pass
  627. if len(self.inputs["Custom Object"].links) > 0:
  628. trace = trace_single_line(self, "Custom Object")
  629. try:
  630. ob = trace[0][1].bGetObject()
  631. except AttributeError:
  632. ob=None
  633. if type(ob) in [bpy.types.Object]:
  634. pb.custom_shape = ob
  635. def bGetObject(self, mode = 'POSE'):
  636. if mode in ["POSE", "OBJECT"] and self.bGetParentArmature().mode == "EDIT":
  637. raise RuntimeError("Cannot get Bone or PoseBone in Edit mode.")
  638. elif mode == "EDIT" and self.bGetParentArmature().mode != "EDIT":
  639. raise RuntimeError("Cannot get EditBone except in Edit mode.")
  640. try:
  641. if (mode == 'EDIT'):
  642. return self.bGetParentArmature().data.edit_bones[self.bObject]
  643. elif (mode == 'OBJECT'):
  644. return self.bGetParentArmature().data.bones[self.bObject]
  645. elif (mode == 'POSE'):
  646. return self.bGetParentArmature().pose.bones[self.bObject]
  647. except Exception as e:
  648. prRed ("Cannot get bone for %s" % self)
  649. raise e
  650. def fill_parameters(self):
  651. # this is the fill_parameters that is run if it isn't a schema
  652. setup_custom_props(self)
  653. fill_parameters(self)
  654. # otherwise we will do this from the schema
  655. class xFormGeometryObject:
  656. '''A node representing an armature object'''
  657. bObject = None
  658. def __init__(self, signature, base_tree):
  659. self.base_tree=base_tree
  660. self.signature = signature
  661. self.inputs = {
  662. "Name" : NodeSocket(is_input = True, name = "Name", node = self),
  663. "Geometry" : NodeSocket(is_input = True, name = "Geometry", node = self),
  664. "Matrix" : NodeSocket(is_input = True, name = "Matrix", node = self),
  665. "Relationship" : NodeSocket(is_input = True, name = "Relationship", node = self),
  666. "Deformer" : NodeSocket(is_input = True, name = "Relationship", node = self),
  667. "Hide in Viewport" : NodeSocket(is_input = True, name = "Hide in Viewport", node = self),
  668. "Hide in Render" : NodeSocket(is_input = True, name = "Hide in Render", node = self),
  669. }
  670. self.outputs = {
  671. "xForm Out" : NodeSocket(is_input = False, name="xForm Out", node = self), }
  672. self.parameters = {
  673. "Name":None,
  674. "Geometry":None,
  675. "Matrix":None,
  676. "Relationship":None,
  677. "Deformer":None,
  678. "Hide in Viewport":None,
  679. "Hide in Render":None,
  680. }
  681. self.links = {} # leave this empty for now!
  682. # now set up the traverse target...
  683. self.inputs["Relationship"].set_traverse_target(self.outputs["xForm Out"])
  684. self.outputs["xForm Out"].set_traverse_target(self.inputs["Relationship"])
  685. self.node_type = "XFORM"
  686. self.bObject = None
  687. self.prepared = False
  688. self.executed = False
  689. self.has_shape_keys = False
  690. self.drivers = {}
  691. def bSetParent(self):
  692. from bpy.types import Object
  693. parent_nc = get_parent(self, type='LINK')
  694. if (parent_nc):
  695. parent = None
  696. if self.inputs["Relationship"].is_linked:
  697. trace = trace_single_line(self, "Relationship")
  698. for node in trace[0]:
  699. if node is self: continue # lol
  700. if (node.node_type == 'XFORM'):
  701. parent = node; break
  702. if parent is None:
  703. prWhite(f"INFO: no parent set for {self}.")
  704. return
  705. if (parent_object := parent.bGetObject()) is None:
  706. raise GraphError(f"Could not get parent object from node {parent} for {self}")
  707. if isinstance(parent, xFormBone):
  708. armOb= parent.bGetParentArmature()
  709. self.bObject.parent = armOb
  710. self.bObject.parent_type = 'BONE'
  711. self.bObject.parent_bone = parent.bObject
  712. # self.bObject.matrix_parent_inverse = parent.parameters["Matrix"].inverted()
  713. elif isinstance(parent_object, Object):
  714. self.bObject.parent = parent.bGetObject()
  715. def bPrepare(self, bContext = None,):
  716. import bpy
  717. if not self.evaluate_input("Name"):
  718. self.prepared = True
  719. self.executed = True
  720. # and return an error if there are any dependencies:
  721. if self.hierarchy_connections:
  722. raise GraphError(wrapRed(f"Cannot Generate object {self} because the chosen name is empty or invalid."))
  723. return
  724. self.bObject = bpy.data.objects.get(self.evaluate_input("Name"))
  725. trace = trace_single_line(self, "Geometry")
  726. if (not self.bObject):
  727. if trace[-1]:
  728. self.bObject = bpy.data.objects.new(self.evaluate_input("Name"), trace[-1].node.bGetObject())
  729. # handle mismatched data.
  730. data_wrong = False; data = None
  731. if (self.inputs["Geometry"].is_linked and self.bObject.type == "EMPTY"):
  732. data_wrong = True; data = trace[-1].node.bGetObject()
  733. elif (not self.inputs["Geometry"].is_linked and not self.bObject.type == "EMPTY"):
  734. data_wrong = True
  735. # clumsy but functional
  736. if data_wrong:
  737. unlink_me = self.bObject
  738. unlink_me.name = "MANTIS_TRASH.000"
  739. for col in unlink_me.users_collection:
  740. col.objects.unlink(unlink_me)
  741. self.bObject = bpy.data.objects.new(self.evaluate_input("Name"), data)
  742. if self.bObject and (self.inputs["Geometry"].is_linked and self.bObject.type in ["MESH", "CURVE"]):
  743. self.bObject.data = trace[-1].node.bGetObject()
  744. # clear it
  745. self.bObject.constraints.clear()
  746. self.bObject.animation_data_clear() # this is a little dangerous. TODO find a better solution since this can wipe animation the user wants to keep
  747. self.bObject.modifiers.clear() # I would also like a way to copy modifiers and their settings, or bake them down. oh well
  748. try:
  749. bpy.context.collection.objects.link(self.bObject)
  750. except RuntimeError: #already in; but a dangerous thing to pass.
  751. pass
  752. self.prepared = True
  753. def bExecute(self, bContext = None,):
  754. self.has_shape_keys = False
  755. # putting this in bExecute simply prevents it from being run more than once.
  756. # maybe I should do that with the rest of bPrepare, too.
  757. props_sockets = {
  758. 'hide_viewport' : ("Hide in Viewport", False),
  759. 'hide_render' : ("Hide in Render", False),
  760. }
  761. evaluate_sockets(self, self.bObject, props_sockets)
  762. self.executed = True
  763. def bFinalize(self, bContext = None):
  764. self.bSetParent()
  765. matrix = self.evaluate_input("Matrix")
  766. self.parameters['Matrix'] = matrix
  767. self.bObject.matrix_world = matrix
  768. for i, (driver_key, driver_item) in enumerate(self.drivers.items()):
  769. print (wrapGreen(i), wrapWhite(self), wrapPurple(driver_key))
  770. prOrange(driver_item)
  771. finish_drivers(self)
  772. def bGetObject(self, mode = 'POSE'):
  773. return self.bObject
  774. for c in TellClasses():
  775. setup_container(c)