xForm_containers.py 40 KB

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