xForm_containers.py 35 KB

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