xForm_containers.py 39 KB

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