xForm_containers.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. from .node_container_common import *
  2. from .base_definitions import MantisNode, NodeSocket
  3. from .xForm_socket_templates import *
  4. def TellClasses():
  5. return [
  6. # xForm
  7. xFormArmature,
  8. xFormBone,
  9. xFormGeometryObject,
  10. xFormObjectInstance,
  11. xFormCurvePin,
  12. ]
  13. #*#-------------------------------#++#-------------------------------#*#
  14. # X - F O R M N O D E S
  15. #*#-------------------------------#++#-------------------------------#*#
  16. def reset_object_data(ob):
  17. # moving this to a common function so I can figure out the details later
  18. ob.constraints.clear()
  19. ob.animation_data_clear() # this is a little dangerous. TODO find a better solution since this can wipe animation the user wants to keep
  20. ob.modifiers.clear() # I would also like a way to copy modifiers and their settings, or bake them down. oh well
  21. def get_parent_node(node_container, type = 'XFORM'):
  22. # type variable for selecting whether to get either
  23. # the parent xForm or the inheritance node
  24. node_line, socket = trace_single_line(node_container, "Relationship")
  25. parent_nc = None
  26. for i in range(len(node_line)):
  27. # check each of the possible parent types.
  28. if ( (node_line[ i ].__class__.__name__ == 'LinkInherit') ):
  29. try: # it's the next one
  30. if (type == 'XFORM'):
  31. return node_line[ i + 1 ]
  32. else: # type = 'LINK'
  33. return node_line[ i ]
  34. except IndexError: # if there is no next one...
  35. return None # then there's no parent!
  36. return None
  37. def get_matrix(node):
  38. matrix = node.evaluate_input('Matrix')
  39. if matrix is None:
  40. node_line, socket = trace_single_line(node, "Matrix")
  41. raise RuntimeError(wrapRed(f"No matrix found for Armature {node}"))
  42. return matrix
  43. def set_object_parent(node):
  44. parent_nc = get_parent_node(node, type='LINK')
  45. if (parent_nc):
  46. parent = None
  47. if node.inputs["Relationship"].is_linked:
  48. trace = trace_single_line(node, "Relationship")
  49. for other_node in trace[0]:
  50. if other_node is node: continue # lol
  51. if (other_node.node_type == 'XFORM'):
  52. parent = other_node; break
  53. if parent is None:
  54. prWhite(f"INFO: no parent set for {node}.")
  55. return
  56. prWhite(f"INFO: setting parent of {node} to {other_node}.")
  57. if (parent.bObject) is None:
  58. raise GraphError(f"Could not get parent object from node {parent} for {node}")
  59. if isinstance(parent, xFormBone):
  60. armOb= parent.bGetParentArmature()
  61. node.bObject.parent = armOb
  62. node.bObject.parent_type = 'BONE'
  63. node.bObject.parent_bone = parent.bObject
  64. else:
  65. node.bObject.parent = parent.bGetObject()
  66. class xFormNode(MantisNode):
  67. def __init__(self, signature, base_tree, socket_templates=[]):
  68. super().__init__(signature, base_tree, socket_templates)
  69. self.node_type = 'XFORM'
  70. self.bObject=None
  71. # because new objects are created during prep phase
  72. def reset_execution(self):
  73. super().reset_execution()
  74. self.prepared=False
  75. class xFormArmature(xFormNode):
  76. '''A node representing an armature object'''
  77. def __init__(self, signature, base_tree):
  78. super().__init__(signature, base_tree, xFormArmatureSockets)
  79. self.init_parameters()
  80. self.set_traverse([("Relationship", "xForm Out")])
  81. def bPrepare(self, bContext=None):
  82. self.parameters['Matrix'] = get_matrix(self)
  83. self.prepared = True
  84. def bExecute(self, bContext = None,):
  85. # from .utilities import get_node_prototype
  86. import bpy
  87. if (not isinstance(bContext, bpy.types.Context)):
  88. raise RuntimeError("Incorrect context")
  89. name = self.evaluate_input("Name")
  90. matrix = self.parameters['Matrix']
  91. reset_transforms = False
  92. #check if an object by the name exists
  93. if (name) and (ob := bpy.data.objects.get(name)):
  94. if (ob.animation_data):
  95. while (ob.animation_data.drivers):
  96. ob.animation_data.drivers.remove(ob.animation_data.drivers[-1])
  97. for pb in ob.pose.bones:
  98. # clear it, even after deleting the edit bones,
  99. # if we create them again the pose bones will be reused
  100. while (pb.constraints):
  101. pb.constraints.remove(pb.constraints[-1])
  102. if reset_transforms:
  103. pb.location = (0,0,0)
  104. pb.rotation_euler = (0,0,0)
  105. pb.rotation_quaternion = (1.0,0,0,0)
  106. pb.rotation_axis_angle = (0,0,1.0,0)
  107. pb.scale = (1.0,1.0,1.0)
  108. # feels ugly and bad, whatever
  109. collections = []
  110. for bc in ob.data.collections:
  111. collections.append(bc)
  112. for bc in collections:
  113. ob.data.collections.remove(bc)
  114. del collections
  115. # end ugly/bad
  116. else:
  117. # Create the Object
  118. ob = bpy.data.objects.new(name, bpy.data.armatures.new(name)) #create ob
  119. if (ob.name != name):
  120. raise RuntimeError("Could not create xForm object", name)
  121. self.bObject = ob.name
  122. ob.matrix_world = matrix.copy()
  123. ob.data.pose_position = 'REST'
  124. set_object_parent(self)
  125. # Link to Scene:
  126. if (ob.name not in bContext.view_layer.active_layer_collection.collection.objects):
  127. bContext.view_layer.active_layer_collection.collection.objects.link(ob)
  128. print( wrapGreen("Created Armature object: ")+ wrapWhite(ob.name))
  129. # Finalize the action
  130. # oddly, overriding context doesn't seem to work
  131. try:
  132. bpy.ops.object.select_all(action='DESELECT')
  133. except RuntimeError:
  134. pass # we're already in edit mode, should be OK to do this.
  135. bContext.view_layer.objects.active = ob
  136. selected=[]
  137. for other_ob in bpy.data.objects:
  138. if other_ob.mode == "EDIT":
  139. selected.append(other_ob)
  140. selected.append(ob)
  141. context_override = {"active_object":ob, "selected_objects":selected}
  142. print("Changing Armature Mode to " +wrapPurple("EDIT"))
  143. with bContext.temp_override(**context_override):
  144. bpy.ops.object.mode_set(mode='EDIT')
  145. if ob.mode != "EDIT":
  146. prRed("eh?")
  147. # clear it
  148. while (len(ob.data.edit_bones) > 0):
  149. ob.data.edit_bones.remove(ob.data.edit_bones[0])
  150. # bContext.view_layer.objects.active = prevAct
  151. self.executed = True
  152. def bGetObject(self, mode = ''):
  153. import bpy; return bpy.data.objects[self.bObject]
  154. bone_inputs= [
  155. "Name",
  156. "Rotation Order",
  157. "Matrix",
  158. "Relationship",
  159. # IK settings
  160. "IK Stretch",
  161. "Lock IK",
  162. "IK Stiffness",
  163. "Limit IK",
  164. "X Min",
  165. "X Max",
  166. "Y Min",
  167. "Y Max",
  168. "Z Min",
  169. "Z Max",
  170. # Visual stuff
  171. "Bone Collection",
  172. "Hide",
  173. "Custom Object",
  174. "Custom Object xForm Override",
  175. "Custom Object Scale to Bone Length",
  176. "Custom Object Wireframe",
  177. "Custom Object Scale",
  178. "Custom Object Translation",
  179. "Custom Object Rotation",
  180. # Deform Stuff
  181. "Deform",
  182. "Envelope Distance",
  183. "Envelope Weight",
  184. "Envelope Multiply",
  185. "Envelope Head Radius",
  186. "Envelope Tail Radius",
  187. # BBone stuff:
  188. "BBone Segments",
  189. "BBone X Size",
  190. "BBone Z Size",
  191. "BBone HQ Deformation",
  192. "BBone X Curve-In",
  193. "BBone Z Curve-In",
  194. "BBone X Curve-Out",
  195. "BBone Z Curve-Out",
  196. "BBone Roll-In",
  197. "BBone Roll-Out",
  198. "BBone Inherit End Roll",
  199. "BBone Scale-In",
  200. "BBone Scale-Out",
  201. "BBone Ease-In",
  202. "BBone Ease-Out",
  203. "BBone Easing",
  204. "BBone Start Handle Type",
  205. "BBone Custom Start Handle",
  206. "BBone Start Handle Scale",
  207. "BBone Start Handle Ease",
  208. "BBone End Handle Type",
  209. "BBone Custom End Handle",
  210. "BBone End Handle Scale",
  211. "BBone End Handle Ease",
  212. # locks
  213. "Lock Location",
  214. "Lock Rotation",
  215. "Lock Scale",
  216. ]
  217. class xFormBone(xFormNode):
  218. '''A node representing a bone in an armature'''
  219. # DO: make a way to identify which armature this belongs to
  220. def __init__(self, signature, base_tree):
  221. super().__init__(signature, base_tree)
  222. outputs = [
  223. "xForm Out",
  224. ]
  225. self.inputs.init_sockets(bone_inputs)
  226. self.outputs.init_sockets(outputs)
  227. self.socket_templates=xFormBoneSockets
  228. # TODO: implement socket templates completely for Bone
  229. # currently it is waiting on BBone and refactoring/cleanup.
  230. self.init_parameters()
  231. self.set_traverse([("Relationship", "xForm Out")])
  232. def bGetParentArmature(self):
  233. if (trace := trace_single_line(self, "Relationship")[0] ) :
  234. for i in range(len(trace)):
  235. # have to look in reverse, actually TODO
  236. if ( isinstance(trace[ i ], xFormArmature ) ):
  237. return trace[ i ].bGetObject()
  238. return None
  239. #should do the trick...
  240. def bSetParent(self, eb):
  241. # print (self.bObject)
  242. from bpy.types import EditBone
  243. parent_nc = get_parent_node(self, type='LINK')
  244. # print (self, parent_nc.inputs['Parent'].from_node)
  245. parent=None
  246. if parent_nc.inputs['Parent'].links[0].from_node.node_type == 'XFORM':
  247. parent = parent_nc.inputs['Parent'].links[0].from_node.bGetObject(mode = 'EDIT')
  248. else:
  249. raise RuntimeError(wrapRed(f"Cannot set parent for node {self}"))
  250. if isinstance(parent, EditBone):
  251. eb.parent = parent
  252. eb.use_connect = parent_nc.evaluate_input("Connected")
  253. eb.use_inherit_rotation = parent_nc.evaluate_input("Inherit Rotation")
  254. eb.inherit_scale = parent_nc.evaluate_input("Inherit Scale")
  255. # otherwise, no need to do anything.
  256. def bPrepare(self, bContext=None):
  257. self.parameters['Matrix'] = get_matrix(self)
  258. self.prepared = True
  259. def bExecute(self, bContext = None,): #possibly will need to pass context?
  260. import bpy
  261. from mathutils import Vector
  262. if not (name := self.evaluate_input("Name")):
  263. raise RuntimeError(wrapRed(f"Could not set name for bone in {self}"))
  264. if (not isinstance(bContext, bpy.types.Context)):
  265. raise RuntimeError("Incorrect context")
  266. if not (xF := self.bGetParentArmature()):
  267. raise RuntimeError("Could not create edit bone: ", name, " from node:", self, " Reason: No armature object to add bone to.")
  268. matrix = self.parameters['Matrix']
  269. length = matrix[3][3]
  270. if (xF):
  271. if (xF.mode != "EDIT"):
  272. raise RuntimeError("Armature Object Not in Edit Mode, exiting...")
  273. #
  274. # Create the Object
  275. d = xF.data
  276. eb = d.edit_bones.new(name)
  277. # Bone Collections:
  278. # We treat each separate string as a Bone Collection that this object belongs to
  279. # Bone Collections are fully qualified by their hierarchy.
  280. # Separate Strings with "|" and indicate hierarchy with ">". These are special characters.
  281. # NOTE: if the user names the collections differently at different times, this will take the FIRST definition and go with it
  282. sCols = self.evaluate_input("Bone Collection")
  283. bone_collections = sCols.split("|")
  284. for collection_list in bone_collections:
  285. hierarchy = collection_list.split(">")
  286. col_parent = None
  287. for sCol in hierarchy:
  288. if ( col := d.collections.get(sCol) ) is None:
  289. col = d.collections.new(sCol)
  290. col.parent = col_parent
  291. col_parent = col
  292. col.assign(eb)
  293. if (eb.name != name):
  294. prRed(f"Expected bone of name: {name}, got {eb.name} instead.")
  295. raise RuntimeError("Could not create bone ", name, "; Perhaps there is a duplicate bone name in the node tree?")
  296. eb.matrix = matrix.copy()
  297. tailoffset = Vector((0,length,0)) #Vector((0,self.tailoffset, 0))
  298. tailoffset = matrix.copy().to_3x3() @ tailoffset
  299. eb.tail = eb.head + tailoffset
  300. if (eb.name != name):
  301. raise RuntimeError("Could not create edit bone: ", name)
  302. assert (eb.name), "Bone must have a name."
  303. self.bObject = eb.name
  304. # The bone should have relationships going in at this point.
  305. self.bSetParent(eb)
  306. if eb.head == eb.tail:
  307. raise RuntimeError(wrapRed(f"Could not create edit bone: {name} because bone head was located in the same place as bone tail."))
  308. # Setup Deform attributes...
  309. eb.use_deform = self.evaluate_input("Deform")
  310. eb.envelope_distance = self.evaluate_input("Envelope Distance")
  311. eb.envelope_weight = self.evaluate_input("Envelope Weight")
  312. eb.use_envelope_multiply = self.evaluate_input("Envelope Multiply")
  313. eb.head_radius = self.evaluate_input("Envelope Head Radius")
  314. eb.tail_radius = self.evaluate_input("Envelope Tail Radius")
  315. print( wrapGreen("Created Bone: ") + wrapOrange(eb.name) + wrapGreen(" in ") + wrapWhite(self.bGetParentArmature().name))
  316. self.executed = True
  317. def bFinalize(self, bContext = None):
  318. do_bb=False
  319. b = self.bGetParentArmature().data.bones[self.bObject]
  320. b.bbone_x = self.evaluate_input("BBone X Size"); b.bbone_x = max(b.bbone_x, 0.0002)
  321. b.bbone_z = self.evaluate_input("BBone Z Size"); b.bbone_z = max(b.bbone_z, 0.0002)
  322. if (segs := self.evaluate_input("BBone Segments")) > 1:
  323. do_bb=True
  324. b.bbone_segments = segs
  325. b.bbone_x = self.evaluate_input("BBone X Size")
  326. b.bbone_z = self.evaluate_input("BBone Z Size")
  327. if self.evaluate_input("BBone HQ Deformation"):
  328. b.bbone_mapping_mode = "CURVED"
  329. # 'bbone_handle_type_start' : ("BBone Start Handle Type", "AUTO"),
  330. # 'bbone_handle_type_end' : ("BBone End Handle Type", "AUTO"),
  331. # 'bbone_custom_handle_start' : ("BBone Custom Start Handle", "AUTO"),
  332. # 'bbone_custom_handle_end' : ("BBone Custom End Handle", "AUTO"),
  333. if handle_type := self.evaluate_input("BBone Start Handle Type"):
  334. b.bbone_handle_type_start = handle_type
  335. if handle_type := self.evaluate_input("BBone End Handle Type"):
  336. b.bbone_handle_type_end = handle_type
  337. try:
  338. if (custom_handle := self.evaluate_input("BBone Custom Start Handle")):
  339. b.bbone_custom_handle_start = self.bGetParentArmature().data.bones[custom_handle]
  340. # hypothetically we should support xForm inputs.... but we won't do that for now
  341. # elif custom_handle is None:
  342. # b.bbone_custom_handle_start = self.inputs["BBone Custom Start Handle"].links[0].from_node.bGetObject().name
  343. if (custom_handle := self.evaluate_input("BBone Custom End Handle")):
  344. b.bbone_custom_handle_end = self.bGetParentArmature().data.bones[custom_handle]
  345. except KeyError:
  346. prRed("Warning: BBone start or end handle not set because of missing bone in armature.")
  347. bone_props_socket= {
  348. 'bbone_curveinx' : ("BBone X Curve-In", 0.0),
  349. 'bbone_curveinz' : ("BBone Z Curve-In", 0.0),
  350. 'bbone_curveoutx' : ("BBone X Curve-Out", 0.0),
  351. 'bbone_curveoutz' : ("BBone Z Curve-Out", 0.0),
  352. }
  353. evaluate_sockets(self, b, bone_props_socket)
  354. # TODO this section should be done with props-socket thing
  355. b.bbone_handle_use_scale_start = self.evaluate_input("BBone Start Handle Scale")
  356. b.bbone_handle_use_scale_end = self.evaluate_input("BBone End Handle Scale")
  357. import bpy
  358. from .drivers import MantisDriver
  359. # prevAct = bContext.view_layer.objects.active
  360. # bContext.view_layer.objects.active = ob
  361. # bpy.ops.object.mode_set(mode='OBJECT')
  362. # bContext.view_layer.objects.active = prevAct
  363. #
  364. #get relationship
  365. # ensure we have a pose bone...
  366. # set the ik parameters
  367. #
  368. #
  369. # Don't need to bother about whatever that was
  370. pb = self.bGetParentArmature().pose.bones[self.bObject]
  371. rotation_mode = self.evaluate_input("Rotation Order")
  372. if rotation_mode == "AUTO": rotation_mode = "XYZ"
  373. pb.rotation_mode = rotation_mode
  374. pb.id_properties_clear()
  375. # these are kept around unless explicitly deleted.
  376. # from .utilities import get_node_prototype
  377. # np = get_node_prototype(self.signature, self.base_tree)
  378. driver = None
  379. do_prints=False
  380. # detect custom inputs
  381. for i, inp in enumerate(self.inputs.values()):
  382. custom_prop=False
  383. for s_template in self.socket_templates:
  384. if s_template.name == inp.name:
  385. break
  386. else:
  387. custom_prop=True
  388. if custom_prop == False: continue
  389. prPurple (inp.name)
  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, xFormGeometryObjectSockets)
  557. self.init_parameters()
  558. self.set_traverse([("Relationship", "xForm Out")])
  559. self.has_shape_keys = False
  560. def bPrepare(self, bContext = None,):
  561. import bpy
  562. if not self.evaluate_input("Name"):
  563. self.prepared = True
  564. self.executed = True
  565. # and return an error if there are any dependencies:
  566. if self.hierarchy_connections:
  567. raise GraphError(wrapRed(f"Cannot Generate object {self} because the chosen name is empty or invalid."))
  568. return
  569. self.bObject = bpy.data.objects.get(self.evaluate_input("Name"))
  570. trace = trace_single_line(self, "Geometry")
  571. if (not self.bObject):
  572. if trace[-1]:
  573. self.bObject = bpy.data.objects.new(self.evaluate_input("Name"), trace[-1].node.bGetObject())
  574. # handle mismatched data.
  575. data_wrong = False; data = None
  576. if (self.inputs["Geometry"].is_linked and self.bObject.type == "EMPTY"):
  577. data_wrong = True; data = trace[-1].node.bGetObject()
  578. elif (not self.inputs["Geometry"].is_linked and not self.bObject.type == "EMPTY"):
  579. data_wrong = True
  580. # clumsy but functional
  581. if data_wrong:
  582. unlink_me = self.bObject
  583. unlink_me.name = "MANTIS_TRASH.000"
  584. for col in unlink_me.users_collection:
  585. col.objects.unlink(unlink_me)
  586. self.bObject = bpy.data.objects.new(self.evaluate_input("Name"), data)
  587. if self.bObject and (self.inputs["Geometry"].is_linked and self.bObject.type in ["MESH", "CURVE"]):
  588. self.bObject.data = trace[-1].node.bGetObject()
  589. # NOW: find out if we need to duplicate the object data.
  590. dupe_data=False
  591. node_line = trace_single_line(self, "Deformer")[0]
  592. from .deformer_containers import DeformerHook
  593. for deformer in node_line:
  594. if isinstance(deformer, DeformerHook) and \
  595. deformer.evaluate_input("Affect Curve Radius") == True and \
  596. self.bObject.type == 'CURVE':
  597. print(f"INFO: Duplicating data {self.bObject.data.name} in {self} so it can be used for drivers.")
  598. dupe_data=True; break
  599. if dupe_data:
  600. name = self.bObject.data.name
  601. # it has to be a curve
  602. data = bpy.data.curves.get(self.bObject.data.name+"_MANTIS")
  603. if data: # Delete it and regenerate it if it exists.
  604. data.name+="_TRASH.000" # but we can't actually delete it here
  605. # since previous executions of the graph may be using it.
  606. # instead, we'll rename it and use a new copy. This will probably
  607. # be deleted on its own by Blender's garbage collector.
  608. # if it isn't, then it is still in use and I may NOT touch it.
  609. data=self.bObject.data.copy(); data.animation_data_clear()
  610. data.name = name+"_MANTIS"
  611. self.bObject.data = data
  612. reset_object_data(self.bObject)
  613. matrix= get_matrix(self)
  614. self.parameters['Matrix'] = matrix
  615. try:
  616. set_object_parent(self)
  617. except: # I guess it isn't ready yet. we'll do it later
  618. pass # (This can happen when solving schema.)
  619. self.bObject.matrix_world = matrix
  620. self.prepared = True
  621. def bExecute(self, bContext = None,):
  622. try:
  623. bContext.collection.objects.link(self.bObject)
  624. except RuntimeError: #already in; but a dangerous thing to pass.
  625. pass
  626. self.has_shape_keys = False
  627. # putting this in bExecute simply prevents it from being run more than once.
  628. # maybe I should do that with the rest of bPrepare, too.
  629. props_sockets = {
  630. 'hide_viewport' : ("Hide in Viewport", False),
  631. 'hide_render' : ("Hide in Render", False),
  632. }
  633. evaluate_sockets(self, self.bObject, props_sockets)
  634. self.executed = True
  635. def bFinalize(self, bContext = None):
  636. matrix= get_matrix(self)
  637. set_object_parent(self)
  638. self.bObject.matrix_world = matrix
  639. for i, (driver_key, driver_item) in enumerate(self.drivers.items()):
  640. print (wrapGreen(i), wrapWhite(self), wrapPurple(driver_key))
  641. prOrange(driver_item)
  642. finish_drivers(self)
  643. def bGetObject(self, mode = 'POSE'):
  644. return self.bObject
  645. class xFormObjectInstance(xFormNode):
  646. """Represents an instance of an existing geometry object."""
  647. def __init__(self, signature, base_tree):
  648. super().__init__(signature, base_tree, xFormGeometryObjectInstanceSockets)
  649. self.init_parameters()
  650. # TODO: I think this field is a leftover from a test or something. see if it can be removed.
  651. self.links = {} # leave this empty for now!
  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 ui_modify_socket(self, ui_socket, socket_name=None):
  655. if ui_socket.name == 'As Instance':
  656. change_handled = True
  657. try:
  658. self.bObject.modifiers[0]['Socket_1'] = ui_socket.default_value
  659. except Exception as e:
  660. print("Failed to update mantis socket because of %s" % e,
  661. "Updating tree instead.")
  662. return change_handled
  663. else:
  664. return super().ui_modify_socket(ui_socket, socket_name)
  665. def bPrepare(self, bContext = None,):
  666. from bpy import data
  667. empty_mesh = data.meshes.get("MANTIS_EMPTY_MESH")
  668. if not empty_mesh:
  669. empty_mesh = data.meshes.new("MANTIS_EMPTY_MESH")
  670. if not self.evaluate_input("Name"):
  671. self.prepared = True
  672. self.executed = True
  673. # and return an error if there are any dependencies:
  674. if self.hierarchy_connections:
  675. raise GraphError(wrapRed(f"Cannot Generate object {self} because the chosen name is empty or invalid."))
  676. return
  677. self.bObject = data.objects.get(self.evaluate_input("Name"))
  678. if (not self.bObject):
  679. self.bObject = data.objects.new(self.evaluate_input("Name"), empty_mesh)
  680. reset_object_data(self.bObject)
  681. matrix= get_matrix(self)
  682. self.parameters['Matrix'] = matrix
  683. set_object_parent(self)
  684. self.bObject.matrix_world = matrix
  685. self.prepared = True
  686. def bExecute(self, bContext = None,):
  687. try:
  688. bContext.collection.objects.link(self.bObject)
  689. except RuntimeError: #already in; but a dangerous thing to pass.
  690. pass
  691. self.has_shape_keys = False
  692. # putting this in bExecute simply prevents it from being run more than once.
  693. # maybe I should do that with the rest of bPrepare, too.
  694. props_sockets = {
  695. 'hide_viewport' : ("Hide in Viewport", False),
  696. 'hide_render' : ("Hide in Render", False),
  697. }
  698. evaluate_sockets(self, self.bObject, props_sockets)
  699. self.executed = True
  700. def bFinalize(self, bContext = None):
  701. # now we need to set the object instance up.
  702. from bpy import data
  703. trace = trace_single_line(self, "Source Object")
  704. for node in trace[0]:
  705. if node is self: continue # lol
  706. if (node.node_type == 'XFORM'):
  707. source_ob = node.bGetObject(); break
  708. modifier = self.bObject.modifiers.new("Object Instance", type='NODES')
  709. ng = data.node_groups.get("Object Instance")
  710. if ng is None:
  711. from .geometry_node_graphgen import gen_object_instance_node_group
  712. ng = gen_object_instance_node_group()
  713. modifier.node_group = ng
  714. modifier["Socket_0"] = source_ob
  715. modifier["Socket_1"] = self.evaluate_input("As Instance")
  716. for i, (driver_key, driver_item) in enumerate(self.drivers.items()):
  717. print (wrapGreen(i), wrapWhite(self), wrapPurple(driver_key))
  718. prOrange(driver_item)
  719. finish_drivers(self)
  720. def bGetObject(self, mode = 'POSE'):
  721. return self.bObject
  722. class xFormCurvePin(xFormNode):
  723. """An xForm pinned to a specific location on a curve."""
  724. def __init__(self, signature, base_tree):
  725. super().__init__(signature, base_tree,xFormCurvePinSockets)
  726. self.init_parameters(additional_parameters={"Matrix":None})
  727. def prep_driver_values(self, constraint):
  728. from .misc_nodes import UtilityDriver, UtilitySwitch
  729. for socket_name in ["Curve Pin Factor", "Forward Axis","Up Axis",]:
  730. if self.inputs.get(socket_name) is None: continue # in case it has been bypassed
  731. if self.inputs[socket_name].is_linked:
  732. link = self.inputs[socket_name].links[0]
  733. driver = link.from_node
  734. if isinstance(driver, UtilityDriver):
  735. prop_amount = driver.evaluate_input("Property")
  736. elif isinstance(driver, UtilitySwitch):
  737. xf=driver.GetxForm()
  738. prop_amount = xf.evaluate_input(driver.evaluate_input('Parameter'))
  739. else:
  740. return
  741. for template in self.socket_templates:
  742. if template.name == socket_name: break
  743. setattr(constraint, template.blender_property, prop_amount )
  744. def bPrepare(self, bContext = None,):
  745. from bpy import data
  746. if not bContext: # lol
  747. import bpy
  748. bContext = bpy.context
  749. ob = data.objects.get(self.evaluate_input("Name"))
  750. if not ob:
  751. ob = data.objects.new(self.evaluate_input("Name"), None)
  752. ob.lock_location = [True, True, True]
  753. ob.lock_rotation = [True, True, True]
  754. ob.lock_scale = [True, True, True]
  755. ob.lock_rotation_w = True
  756. ob.empty_display_type = 'CONE'
  757. ob.empty_display_size = 0.10
  758. self.bObject = ob
  759. reset_object_data(ob)
  760. node_line = trace_single_line(self, "Parent Curve")[0][1:] # slice excludes self
  761. for other_node in node_line:
  762. if other_node.node_type == 'XFORM':
  763. break
  764. else:
  765. raise GraphError(f"ERROR: {self} is not connected to a parent curve")
  766. if isinstance(other_node, (xFormArmature, xFormBone, xFormObjectInstance,)):
  767. raise GraphError(f"ERROR: {self} must be connected to curve,"
  768. " not {other_node.__class__.__name__}")
  769. curve=other_node.bGetObject()
  770. if curve.type != 'CURVE':
  771. raise GraphError(f"ERROR: {self} must be connected to curve,"
  772. " not {curve.type}")
  773. # we'll limit all the transforms so we can parent it
  774. # because it is annoying to have a cluttered outliner.
  775. #
  776. # always do this so that everything stays consistent.
  777. spline_index = self.evaluate_input("Spline Index")
  778. from .utilities import get_extracted_spline_object
  779. curve = get_extracted_spline_object(curve, spline_index, self.mContext)
  780. # Link to Scene:
  781. for link_me in [ob, curve]:
  782. if (link_me.name not in bContext.view_layer.active_layer_collection.collection.objects):
  783. bContext.view_layer.active_layer_collection.collection.objects.link(link_me)
  784. c = ob.constraints.new("LIMIT_LOCATION")
  785. for max_min in ['max','min']:
  786. for axis in "xyz":
  787. setattr(c, "use_"+max_min+"_"+axis, True)
  788. setattr(c, max_min+"_"+axis, 0.0)
  789. c = ob.constraints.new("LIMIT_ROTATION")
  790. for axis in "xyz":
  791. setattr(c, "use_limit_"+axis, True)
  792. setattr(c, max_min+"_"+axis, 0.0)
  793. c = ob.constraints.new("LIMIT_SCALE")
  794. for max_min in ['max','min']:
  795. for axis in "xyz":
  796. setattr(c, "use_"+max_min+"_"+axis, True)
  797. setattr(c, max_min+"_"+axis, 1.0)
  798. c = ob.constraints.new("FOLLOW_PATH")
  799. c.target = curve
  800. c.use_fixed_location = True
  801. c.use_curve_radius = True
  802. c.use_curve_follow = True
  803. c.name = "Curve Pin"
  804. props_sockets = self.gen_property_socket_map()
  805. constraint_props_sockets = props_sockets.copy()
  806. del constraint_props_sockets['name']; del constraint_props_sockets['empty_display_size']
  807. del props_sockets['offset_factor']; del props_sockets['forward_axis']
  808. del props_sockets['up_axis']
  809. evaluate_sockets(self, c, constraint_props_sockets)
  810. evaluate_sockets(self, self.bObject, props_sockets)
  811. # this isn't usually run on xForm nodes so for now I need to set the
  812. # driver's default values manually if I want a matrix now.
  813. # because the drivers may not have initialized yet.
  814. self.prep_driver_values(c)
  815. # now if all goes well... the matrix will be correct.
  816. dg = bContext.view_layer.depsgraph
  817. dg.update()
  818. # and the matrix should be correct now - copy because it may be modified
  819. self.parameters['Matrix'] = ob.matrix_world.copy()
  820. ob.parent=curve
  821. print( wrapGreen("Created Curve Pin: ") + wrapOrange(self.bObject.name) )
  822. self.prepared = True; self.executed = True
  823. def bFinalize(self, bContext = None):
  824. finish_drivers(self)
  825. def bGetObject(self, mode = 'POSE'):
  826. return self.bObject