xForm_containers.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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. # TODO this section should be done with props-socket thing
  518. b.bbone_handle_use_scale_start = self.evaluate_input("BBone Start Handle Scale")
  519. b.bbone_handle_use_scale_start = self.evaluate_input("BBone End Handle Scale")
  520. import bpy
  521. from .drivers import MantisDriver
  522. # prevAct = bContext.view_layer.objects.active
  523. # bContext.view_layer.objects.active = ob
  524. # bpy.ops.object.mode_set(mode='OBJECT')
  525. # bContext.view_layer.objects.active = prevAct
  526. #
  527. #get relationship
  528. # ensure we have a pose bone...
  529. # set the ik parameters
  530. #
  531. #
  532. # Don't need to bother about whatever that was
  533. pb = self.bGetParentArmature().pose.bones[self.bObject]
  534. rotation_mode = self.evaluate_input("Rotation Order")
  535. if rotation_mode == "AUTO": rotation_mode = "XYZ"
  536. pb.rotation_mode = rotation_mode
  537. pb.id_properties_clear()
  538. # these are kept around unless explicitly deleted.
  539. # from .utilities import get_node_prototype
  540. # np = get_node_prototype(self.signature, self.base_tree)
  541. driver = None
  542. do_prints=False
  543. # print (self.input_length)
  544. # even worse hack coming
  545. for i, inp in enumerate(self.inputs.values()):
  546. if inp.name in bone_inputs:
  547. continue
  548. name = inp.name
  549. try:
  550. value = self.evaluate_input(inp.name)
  551. except KeyError as e:
  552. trace = trace_single_line(self, inp.name)
  553. if do_prints: print(trace[0][-1], trace[1])
  554. if do_prints: print (trace[0][-1].parameters)
  555. raise e
  556. # This may be driven, so let's do this:
  557. if do_prints: print (value)
  558. if (isinstance(value, tuple)):
  559. # it's either a CombineThreeBool or a CombineVector.
  560. prRed("COMITTING SUICIDE NOW!!")
  561. bpy.ops.wm.quit_blender()
  562. if (isinstance(value, MantisDriver)):
  563. # the value should be the default for its socket...
  564. if do_prints: print (type(self.parameters[inp.name]))
  565. type_val_map = {
  566. str:"",
  567. bool:False,
  568. int:0,
  569. float:0.0,
  570. bpy.types.bpy_prop_array:(0,0,0),
  571. }
  572. driver = value
  573. value = type_val_map[type(self.parameters[inp.name])]
  574. if (value is None):
  575. prRed("This is probably not supposed to happen")
  576. value = 0
  577. raise RuntimeError("Could not set value of custom parameter")
  578. # it creates a more confusing error later sometimes, better to catch it here.
  579. # IMPORTANT: Is it possible for more than one driver to
  580. # come through here, and for the variable to be
  581. # overwritten?
  582. #TODO important
  583. #from rna_prop_ui import rna_idprop_ui_create
  584. # use this ^
  585. # add the custom properties to the **Pose Bone**
  586. pb[name] = value
  587. # This is much simpler now.
  588. ui_data = pb.id_properties_ui(name)
  589. description=''
  590. ui_data.update(
  591. description=description,#inp.description,
  592. default=value,)
  593. #if a number
  594. if type(value) == float:
  595. ui_data.update(
  596. min = inp.min,
  597. max = inp.max,
  598. soft_min = inp.soft_min,
  599. soft_max = inp.soft_max,)
  600. elif type(value) == int:
  601. ui_data.update(
  602. min = int(inp.min),
  603. max = int(inp.max),
  604. soft_min = int(inp.soft_min),
  605. soft_max = int(inp.soft_max),)
  606. elif type(value) == bool:
  607. ui_data.update() # TODO I can't figure out what the update function expects because it isn't documented
  608. if (pb.is_in_ik_chain):
  609. # this props_socket thing wasn't really meant to work here but it does, neat
  610. props_sockets = {
  611. 'ik_stretch' : ("IK Stretch", 0),
  612. 'lock_ik_x' : (("Lock IK", 0), False),
  613. 'lock_ik_y' : (("Lock IK", 1), False),
  614. 'lock_ik_z' : (("Lock IK", 2), False),
  615. 'ik_stiffness_x' : (("IK Stiffness", 0), 0.0),
  616. 'ik_stiffness_y' : (("IK Stiffness", 1), 0.0),
  617. 'ik_stiffness_z' : (("IK Stiffness", 2), 0.0),
  618. 'use_ik_limit_x' : (("Limit IK", 0), False),
  619. 'use_ik_limit_y' : (("Limit IK", 1), False),
  620. 'use_ik_limit_z' : (("Limit IK", 2), False),
  621. 'ik_min_x' : ("X Min", 0),
  622. 'ik_max_x' : ("X Max", 0),
  623. 'ik_min_y' : ("Y Min", 0),
  624. 'ik_max_y' : ("Y Max", 0),
  625. 'ik_min_z' : ("Z Min", 0),
  626. 'ik_max_z' : ("Z Max", 0),
  627. }
  628. evaluate_sockets(self, pb, props_sockets)
  629. if do_bb:
  630. props_sockets = {
  631. 'bbone_curveinx' : ("BBone X Curve-In", pb.bone.bbone_curveinx),
  632. 'bbone_curveinz' : ("BBone Z Curve-In", pb.bone.bbone_curveinz),
  633. 'bbone_curveoutx' : ("BBone X Curve-Out", pb.bone.bbone_curveoutx),
  634. 'bbone_curveoutz' : ("BBone Z Curve-Out", pb.bone.bbone_curveoutz),
  635. 'bbone_easein' : ("BBone Ease-In", 0),
  636. 'bbone_easeout' : ("BBone Ease-Out", 0),
  637. 'bbone_rollin' : ("BBone Roll-In", 0),
  638. 'bbone_rollout' : ("BBone Roll-Out", 0),
  639. 'bbone_scalein' : ("BBone Scale-In", (1,1,1)),
  640. 'bbone_scaleout' : ("BBone Scale-Out", (1,1,1)),
  641. }
  642. prRed("BBone Implementation is not complete, expect errors and missing features for now")
  643. evaluate_sockets(self, pb, props_sockets)
  644. # we need to clear this stuff since our only real goal was to get some drivers from the above
  645. for attr_name in props_sockets.keys():
  646. try:
  647. setattr(pb, attr_name, 0) # just clear it
  648. except ValueError:
  649. setattr(pb, attr_name, (1.0,1.0,1.0)) # scale needs to be set to 1
  650. # important TODO... all of the drivers and stuff should be handled this way, right?
  651. # time to set up drivers!
  652. # just gonna add this to the end and build off it I guess
  653. props_sockets = {
  654. "lock_location" : ("Lock Location", [False, False, False]),
  655. "lock_rotation" : ("Lock Rotation", [False, False, False]),
  656. "lock_scale" : ("Lock Scale", [False, False, False]),
  657. 'custom_shape_scale_xyz' : ("Custom Object Scale", (0.0,0.0,0.0) ),
  658. 'custom_shape_translation' : ("Custom Object Translation", (0.0,0.0,0.0) ),
  659. 'custom_shape_rotation_euler' : ("Custom Object Rotation", (0.0,0.0,0.0) ),
  660. 'use_custom_shape_bone_size' : ("Custom Object Scale to Bone Length", True,)
  661. }
  662. evaluate_sockets(self, pb, props_sockets)
  663. # this could probably be moved to bExecute
  664. props_sockets = {
  665. 'hide' : ("Hide", False),
  666. 'show_wire' : ("Custom Object Wireframe", False),
  667. }
  668. evaluate_sockets(self, pb.bone, props_sockets)
  669. if (driver):
  670. pass
  671. # whatever I was doing there.... was stupid. CLEAN UP TODO
  672. # this is the right thing to do.
  673. finish_drivers(self)
  674. #
  675. # OK, visual settings
  676. #
  677. # Get the override xform's bone:
  678. if len(self.inputs["Custom Object xForm Override"].links) > 0:
  679. trace = trace_single_line(self, "Custom Object xForm Override")
  680. try:
  681. pb.custom_shape_transform = trace[0][1].bGetObject()
  682. except AttributeError:
  683. pass
  684. if len(self.inputs["Custom Object"].links) > 0:
  685. trace = trace_single_line(self, "Custom Object")
  686. try:
  687. ob = trace[0][1].bGetObject()
  688. except AttributeError:
  689. ob=None
  690. if type(ob) in [bpy.types.Object]:
  691. pb.custom_shape = ob
  692. #
  693. # pb.bone.hide = self.evaluate_input("Hide")
  694. # pb.custom_shape_scale_xyz = self.evaluate_input("Custom Object Scale")
  695. # pb.custom_shape_translation = self.evaluate_input("Custom Object Translation")
  696. # pb.custom_shape_rotation_euler = self.evaluate_input("Custom Object Rotation")
  697. # pb.use_custom_shape_bone_size = self.evaluate_input("Custom Object Scale to Bone Length")
  698. # pb.bone.show_wire = self.evaluate_input("Custom Object Wireframe")
  699. # #
  700. # # D E P R E C A T E D
  701. # #
  702. # # Bone Groups
  703. # if bg_name := self.evaluate_input("Bone Group"): # this is a string
  704. # obArm = self.bGetParentArmature()
  705. # # Temporary! Temporary! HACK
  706. # color_set_items= [
  707. # "DEFAULT",
  708. # "THEME01",
  709. # "THEME02",
  710. # "THEME03",
  711. # "THEME04",
  712. # "THEME05",
  713. # "THEME06",
  714. # "THEME07",
  715. # "THEME08",
  716. # "THEME09",
  717. # "THEME10",
  718. # "THEME11",
  719. # "THEME12",
  720. # "THEME13",
  721. # "THEME14",
  722. # "THEME15",
  723. # "THEME16",
  724. # "THEME17",
  725. # "THEME18",
  726. # "THEME19",
  727. # "THEME20",
  728. # # "CUSTOM",
  729. # ]
  730. # try:
  731. # bg = obArm.pose.bone_groups.get(bg_name)
  732. # except SystemError:
  733. # bg = None
  734. # pass # no clue why this happens. uninitialzied?
  735. # if not bg:
  736. # bg = obArm.pose.bone_groups.new(name=bg_name)
  737. # #HACK lol
  738. # from random import randint
  739. # bg.color_set = color_set_items[randint(0,14)]
  740. # #15-20 are black by default, gross
  741. # # this is good enough for now!
  742. # pb.bone_group = bg
  743. def bGetObject(self, mode = 'POSE'):
  744. if mode in ["POSE", "OBJECT"] and self.bGetParentArmature().mode == "EDIT":
  745. raise RuntimeError("Cannot get Bone or PoseBone in Edit mode.")
  746. elif mode == "EDIT" and self.bGetParentArmature().mode != "EDIT":
  747. raise RuntimeError("Cannot get EditBone except in Edit mode.")
  748. try:
  749. if (mode == 'EDIT'):
  750. return self.bGetParentArmature().data.edit_bones[self.bObject]
  751. elif (mode == 'OBJECT'):
  752. return self.bGetParentArmature().data.bones[self.bObject]
  753. elif (mode == 'POSE'):
  754. return self.bGetParentArmature().pose.bones[self.bObject]
  755. except Exception as e:
  756. prRed ("Cannot get bone for %s" % self)
  757. raise e
  758. def fill_parameters(self):
  759. # this is the fill_parameters that is run if it isn't a schema
  760. setup_custom_props(self)
  761. fill_parameters(self)
  762. # otherwise we will do this from the schema
  763. class xFormGeometryObject:
  764. '''A node representing an armature object'''
  765. bObject = None
  766. def __init__(self, signature, base_tree):
  767. self.base_tree=base_tree
  768. self.signature = signature
  769. self.inputs = {
  770. "Name" : NodeSocket(is_input = True, name = "Name", node = self),
  771. "Geometry" : NodeSocket(is_input = True, name = "Geometry", node = self),
  772. "Matrix" : NodeSocket(is_input = True, name = "Matrix", node = self),
  773. "Relationship" : NodeSocket(is_input = True, name = "Relationship", node = self),
  774. "Deformer" : NodeSocket(is_input = True, name = "Relationship", node = self),
  775. "Hide in Viewport" : NodeSocket(is_input = True, name = "Hide in Viewport", node = self),
  776. "Hide in Render" : NodeSocket(is_input = True, name = "Hide in Render", node = self),
  777. }
  778. self.outputs = {
  779. "xForm Out" : NodeSocket(is_input = False, name="xForm Out", node = self), }
  780. self.parameters = {
  781. "Name":None,
  782. "Geometry":None,
  783. "Matrix":None,
  784. "Relationship":None,
  785. "Deformer":None,
  786. "Hide in Viewport":None,
  787. "Hide in Render":None,
  788. }
  789. self.links = {} # leave this empty for now!
  790. # now set up the traverse target...
  791. self.inputs["Relationship"].set_traverse_target(self.outputs["xForm Out"])
  792. self.outputs["xForm Out"].set_traverse_target(self.inputs["Relationship"])
  793. self.node_type = "XFORM"
  794. self.bObject = None
  795. self.prepared = False
  796. self.executed = False
  797. self.drivers = {}
  798. def bSetParent(self):
  799. from bpy.types import Object, Bone
  800. parent_nc = get_parent(self, type='LINK')
  801. if (parent_nc):
  802. parent = None
  803. if self.inputs["Relationship"].is_linked:
  804. trace = trace_single_line(self, "Relationship")
  805. for node in trace[0]:
  806. if node is self: continue # lol
  807. if (node.node_type == 'XFORM'):
  808. parent = node; break
  809. if parent is None:
  810. raise GraphError(f"Could not get parent node for {self}")
  811. if parent.bObject is None:
  812. raise GraphError(f"Could not get parent object from node {parent} for {self}")
  813. if isinstance(parent, xFormBone):
  814. armOb= parent.bGetParentArmature()
  815. self.bObject.parent = armOb
  816. self.bObject.parent_type = 'BONE'
  817. self.bObject.parent_bone = parent.bObject
  818. # self.bObject.matrix_parent_inverse = parent.parameters["Matrix"].inverted()
  819. elif isinstance(parent, xFormArmature):
  820. self.bObject.parent = parent.bGetObject()
  821. def bPrepare(self, bContext = None,):
  822. import bpy
  823. if not self.evaluate_input("Name"):
  824. self.prepared = True
  825. self.executed = True
  826. # and return an error if there are any dependencies:
  827. if self.hierarchy_connections:
  828. raise GraphError(wrapRed(f"Cannot Generate object {self} because the chosen name is empty or invalid."))
  829. return
  830. self.bObject = bpy.data.objects.get(self.evaluate_input("Name"))
  831. trace = trace_single_line(self, "Geometry")
  832. if (not self.bObject):
  833. if trace[-1]:
  834. self.bObject = bpy.data.objects.new(self.evaluate_input("Name"), trace[-1].node.bGetObject())
  835. # handle mismatched data.
  836. data_wrong = False; data = None
  837. if (self.inputs["Geometry"].is_linked and self.bObject.type == "EMPTY"):
  838. data_wrong = True; data = trace[-1].node.bGetObject()
  839. elif (not self.inputs["Geometry"].is_linked and not self.bObject.type == "EMPTY"):
  840. data_wrong = True
  841. # clumsy but functional
  842. if data_wrong:
  843. unlink_me = self.bObject
  844. unlink_me.name = "MANTIS_TRASH.000"
  845. for col in unlink_me.users_collection:
  846. col.objects.unlink(unlink_me)
  847. self.bObject = bpy.data.objects.new(self.evaluate_input("Name"), data)
  848. if self.bObject and (self.inputs["Geometry"].is_linked and self.bObject.type in ["MESH", "CURVE"]):
  849. self.bObject.data = trace[-1].node.bGetObject()
  850. # clear it
  851. self.bObject.constraints.clear()
  852. 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
  853. self.bObject.modifiers.clear() # I would also like a way to copy modifiers and their settings, or bake them down. oh well
  854. try:
  855. bpy.context.collection.objects.link(self.bObject)
  856. except RuntimeError: #already in; but a dangerous thing to pass.
  857. pass
  858. self.prepared = True
  859. def bExecute(self, bContext = None,):
  860. # putting this in bExecute simply prevents it from being run more than once.
  861. # maybe I should do that with the rest of bPrepare, too.
  862. props_sockets = {
  863. 'hide_viewport' : ("Hide in Viewport", False),
  864. 'hide_render' : ("Hide in Render", False),
  865. }
  866. evaluate_sockets(self, self.bObject, props_sockets)
  867. self.executed = True
  868. def bFinalize(self, bContext = None):
  869. self.bSetParent()
  870. matrix = self.evaluate_input("Matrix")
  871. self.parameters['Matrix'] = matrix
  872. self.bObject.matrix_world = matrix
  873. for i, (driver_key, driver_item) in enumerate(self.drivers.items()):
  874. print (wrapGreen(i), wrapWhite(self), wrapPurple(driver_key))
  875. prOrange(driver_item)
  876. finish_drivers(self)
  877. def bGetObject(self, mode = 'POSE'):
  878. return self.bObject
  879. for c in TellClasses():
  880. setup_container(c)