xForm_containers.py 42 KB

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