xForm_containers.py 39 KB

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