ops_generate_tree.py 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  1. from bpy.types import Operator
  2. import bpy
  3. from .utilities import (prRed, prGreen, prPurple, prWhite,
  4. prOrange,
  5. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  6. wrapOrange,)
  7. def mantis_poll_op(context):
  8. space = context.space_data
  9. if hasattr(space, "node_tree"):
  10. if (space.node_tree):
  11. return (space.tree_type == "MantisTree")
  12. return False
  13. def create_inheritance_node(pb, parent_name, bone_inherit_node, node_tree):
  14. from bpy.types import PoseBone
  15. parent_node = node_tree.nodes.new("linkInherit")
  16. parent_node.select = True # for sorting
  17. parent_bone_node = node_tree.nodes.get(parent_name)
  18. if not parent_bone_node:
  19. raise RuntimeError("Can't Find parent node!!")
  20. parent_node.location = parent_bone_node.location; parent_node.location.x+=200
  21. node_tree.links.new(parent_bone_node.outputs["xForm Out"], parent_node.inputs['Parent'])
  22. if isinstance(pb, PoseBone):
  23. parent_node.inputs["Connected"].default_value = pb.bone.use_connect
  24. parent_node.inputs["Inherit Scale"].default_value = pb.bone.inherit_scale
  25. parent_node.inputs["Inherit Rotation"].default_value = pb.bone.use_inherit_rotation
  26. else:
  27. parent_node.inputs["Connected"].default_value = False
  28. parent_node.inputs["Inherit Scale"].default_value = "FULL"
  29. parent_node.inputs["Inherit Rotation"].default_value = True
  30. if (bone_inherit_node.get(parent_bone_node.name)):
  31. bone_inherit_node[parent_bone_node.name].append(parent_node)
  32. else:
  33. bone_inherit_node[parent_bone_node.name] = [parent_node]
  34. return parent_node
  35. def get_pretty_name(name):
  36. if name == "bbone_curveinx": return "BBone X Curve-In"
  37. elif name == "bbone_curveinz": return "BBone Z Curve-In"
  38. elif name == "bbone_curveoutx": return "BBone X Curve-Out"
  39. elif name == "bbone_curveoutz": return "BBone Z Curve-Out"
  40. elif name == "BBone HQ Deformation":
  41. raise NotImplementedError(wrapRed("I wasn't expecting this property to be driven lol why would you even want to do that"))
  42. elif name == "bbone_handle_type_start": return "BBone Start Handle Type"
  43. elif name == "bbone_handle_type_end": return "BBone End Handle Type"
  44. elif name == "bbone_x": return "BBone X Size"
  45. elif name == "bbone_z": return "BBone Z Size"
  46. elif name == "bbone_rollin": return "BBone Roll-In"
  47. elif name == "bbone_rollout": return "BBone Roll-Out"
  48. elif name == "bbone_scalein": return "BBone Scale-In"
  49. elif name == "bbone_scaleout": return "BBone Scale-Out"
  50. pretty = name.replace("_", " ")
  51. words = pretty.split(" "); pretty = ''
  52. for word in words:
  53. pretty+=(word.capitalize()); pretty+=' '
  54. return pretty [:-1] #omit the last trailing space
  55. constraint_link_map={
  56. 'COPY_LOCATION' : "LinkCopyLocation",
  57. 'COPY_ROTATION' : "LinkCopyRotation",
  58. 'COPY_SCALE' : "LinkCopyScale",
  59. 'COPY_TRANSFORMS' : "LinkCopyTransforms",
  60. 'LIMIT_DISTANCE' : "LinkLimitDistance",
  61. 'LIMIT_LOCATION' : "LinkLimitLocation",
  62. 'LIMIT_ROTATION' : "LinkLimitRotation",
  63. 'LIMIT_SCALE' : "LinkLimitScale",
  64. 'DAMPED_TRACK' : "LinkDampedTrack",
  65. 'LOCKED_TRACK' : "LinkLockedTrack",
  66. 'STRETCH_TO' : "LinkStretchTo",
  67. 'TRACK_TO' : "LinkTrackTo",
  68. 'CHILD_OF' : "LinkInheritConstraint",
  69. 'IK' : "LinkInverseKinematics",
  70. 'ARMATURE' : "LinkArmature",
  71. 'SPLINE_IK' : "LinkSplineIK",
  72. 'TRANSFORM' : "LinkTransformation",
  73. 'FLOOR' : "LinkFloor",
  74. 'SHRINKWRAP' : "LinkShrinkWrap",
  75. 'GEOMETRY_ATTRIBUTE': "LinkGeometryAttribute"
  76. }
  77. def create_relationship_node_for_constraint(node_tree, c):
  78. if cls_name := constraint_link_map.get(c.type):
  79. n = node_tree.nodes.new(cls_name)
  80. n.select = True # for sorting
  81. return n
  82. else:
  83. prRed ("Not yet implemented: %s" % c.type)
  84. return None
  85. def fill_parameters(node, c, context):
  86. # just try the basic parameters...
  87. node.mute = not c.enabled
  88. if c.mute == True and c.enabled == True:
  89. node.mute = c.mute
  90. # this is obviously stupid, but it's the new API as of, IIRC, 2.80
  91. try:
  92. owner_space = c.owner_space
  93. if c.owner_space == 'CUSTOM':
  94. pass
  95. #raise NotImplementedError("Custom Space is a TODO")
  96. if ( input := node.inputs.get("Owner Space") ):
  97. input.default_value = owner_space
  98. except AttributeError:
  99. pass
  100. try:
  101. target_space = c.target_space
  102. if c.target_space == 'CUSTOM':
  103. pass
  104. #raise NotImplementedError("Custom Space is a TODO")
  105. if ( input := node.inputs.get("Target Space") ):
  106. input.default_value = target_space
  107. except AttributeError:
  108. pass
  109. try:
  110. use_x, use_y, use_z = c.use_x, c.use_y, c.use_z
  111. if ( input := node.inputs.get("Axes") ):
  112. input.default_value[0] = use_x
  113. input.default_value[1] = use_y
  114. input.default_value[2] = use_z
  115. except AttributeError:
  116. pass
  117. try:
  118. invert_x, invert_y, invert_z = c.invert_x, c.invert_y, c.invert_z
  119. if ( input := node.inputs.get("Invert") ):
  120. input.default_value[0] = invert_x
  121. input.default_value[1] = invert_y
  122. input.default_value[2] = invert_z
  123. except AttributeError:
  124. pass
  125. try:
  126. influence = c.influence
  127. if ( input := node.inputs.get("Influence") ):
  128. input.default_value = influence
  129. except AttributeError:
  130. pass
  131. # gonna dispense with the try/except from here on
  132. match c.type:
  133. case 'COPY_LOCATION':
  134. node.inputs["Head/Tail"].default_value = c.head_tail
  135. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  136. case 'COPY_ROTATION':
  137. node.inputs["RotationOrder"].default_value = c.euler_order
  138. # ofset (legacy) is not supported TODO BUG
  139. if (mix_mode := c.mix_mode) == 'OFFSET':
  140. mix_mode = 'AFTER' # TODO there should be a message here. IIRC rigify rigs use this
  141. node.inputs["Rotation Mix"].default_value = mix_mode
  142. case'COPY_SCALE':
  143. node.inputs["Additive"].default_value = c.use_make_uniform
  144. node.inputs["Power"].default_value = c.power
  145. node.inputs["Average"].default_value = c.use_make_uniform
  146. node.inputs["Offset"].default_value = c.use_offset
  147. case'COPY_TRANSFORMS':
  148. node.inputs["Head/Tail"].default_value = c.head_tail
  149. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  150. node.inputs["Mix"].default_value = c.mix_mode
  151. case 'LIMIT_LOCATION' | 'LIMIT_ROTATION' | 'LIMIT_SCALE':
  152. try:
  153. node.inputs["Use Max X"].default_value = c.use_max_x
  154. node.inputs["Use Max Y"].default_value = c.use_max_y
  155. node.inputs["Use Max Z"].default_value = c.use_max_z
  156. #
  157. node.inputs["Use Min X"].default_value = c.use_min_x
  158. node.inputs["Use Min Y"].default_value = c.use_min_y
  159. node.inputs["Use Min Z"].default_value = c.use_min_z
  160. except AttributeError: # rotation
  161. node.inputs["Use X"].default_value = c.use_limit_x
  162. node.inputs["Use Y"].default_value = c.use_limit_y
  163. node.inputs["Use Z"].default_value = c.use_limit_z
  164. node.inputs["Max X"].default_value = c.max_x
  165. node.inputs["Max Y"].default_value = c.max_y
  166. node.inputs["Max Z"].default_value = c.max_z
  167. #
  168. node.inputs["Min X"].default_value = c.min_x
  169. node.inputs["Min Y"].default_value = c.min_y
  170. node.inputs["Min Z"].default_value = c.min_z
  171. case 'DAMPED_TRACK':
  172. node.inputs["Head/Tail"].default_value = c.head_tail
  173. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  174. node.inputs["Track Axis"].default_value = c.track_axis
  175. case 'LOCKED_TRACK':
  176. node.inputs["Head/Tail"].default_value = c.head_tail
  177. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  178. node.inputs["Track Axis"].default_value = c.track_axis
  179. node.inputs["Lock Axis"].default_value = c.lock_axis
  180. case 'STRETCH_TO':
  181. node.inputs["Head/Tail"].default_value = c.head_tail
  182. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  183. node.inputs["Volume Variation"].default_value = c.bulge
  184. node.inputs["Use Volume Min"].default_value = c.use_bulge_min
  185. node.inputs["Volume Min"].default_value = c.bulge_min
  186. node.inputs["Use Volume Max"].default_value = c.use_bulge_max
  187. node.inputs["Volume Max"].default_value = c.bulge_max
  188. node.inputs["Smooth"].default_value = c.bulge_smooth
  189. node.inputs["Maintain Volume"].default_value = c.volume
  190. node.inputs["Rotation"].default_value = c.keep_axis
  191. case 'IK':
  192. node.inputs["Chain Length"].default_value = c.chain_count
  193. node.inputs["Use Tail"].default_value = c.use_tail
  194. node.inputs["Stretch"].default_value = c.use_stretch
  195. # this isn't quite right lol
  196. node.inputs["Position"].default_value = c.weight
  197. node.inputs["Rotation"].default_value = c.orient_weight
  198. if not (c.use_location):
  199. node.inputs["Position"].default_value = 0
  200. if not (c.use_rotation):
  201. node.inputs["Rotation"].default_value = 0
  202. case 'ARMATURE':
  203. node.inputs["Preserve Volume"].default_value = c.use_deform_preserve_volume
  204. node.inputs["Use Envelopes"].default_value = c.use_bone_envelopes
  205. node.inputs["Use Current Location"].default_value = c.use_current_location
  206. for i in range(len(c.targets)):
  207. with context.temp_override(node=node):
  208. bpy.ops.mantis.link_armature_node_add_target()
  209. node.inputs["Weight."+str(i).zfill(3)].default_value = c.targets[i].weight
  210. case 'SPLINE_IK':
  211. node.inputs["Chain Length"].default_value = c.chain_count
  212. node.inputs["Even Divisions"].default_value = c.use_even_divisions
  213. node.inputs["Chain Offset"].default_value = c.use_chain_offset
  214. node.inputs["Use Curve Radius"].default_value = c.use_curve_radius
  215. node.inputs["Y Scale Mode"].default_value = c.y_scale_mode
  216. node.inputs["XZ Scale Mode"].default_value = c.xz_scale_mode
  217. case 'TRANSFORM':
  218. # I can't be arsed to do all this work..
  219. # from .link_nodes import transformation_props_sockets as props
  220. from .link_socket_templates import LinkTransformationSockets
  221. for template in LinkTransformationSockets:
  222. prop = template.blender_property; socket_name = template.name
  223. if "from" in prop:
  224. if prop in ["map_from"] or "to" in prop:
  225. pass
  226. elif c.map_from == 'LOCATION':
  227. if "scale" in prop:
  228. continue
  229. if "rot" in prop:
  230. continue
  231. elif c.map_from == 'ROTATION':
  232. if "rot" not in prop:
  233. continue
  234. elif c.map_from == 'SCALE':
  235. if "scale" not in prop:
  236. continue
  237. if "to" in prop:
  238. if prop in ["map_to"] or "from" in prop:
  239. pass
  240. elif c.map_from == 'LOCATION':
  241. if "scale" in prop:
  242. continue
  243. if "rot" in prop:
  244. continue
  245. elif c.map_from == 'ROTATION':
  246. if "rot" not in prop:
  247. continue
  248. elif c.map_from == 'SCALE':
  249. if "scale" not in prop:
  250. continue
  251. node.inputs[socket_name].default_value = getattr(c, prop)
  252. if prop in "mute":
  253. node.inputs[socket_name].default_value = not getattr(c, prop)
  254. case _:
  255. print (f"Not yet implemented: {c.type}")
  256. def walk_edit_bone(armOb, bone):
  257. # this is a simplified version of the node-tree walking code
  258. bonePath, bones, lines, seek = [0,], set(), [], bone
  259. while (True):
  260. curheight = len(bonePath)-1; ind = bonePath[-1]
  261. if (curheight == 0) and (ind > len(bone.children)-1):
  262. break
  263. if (curheight > 0):
  264. parent = seek.parent
  265. if (ind > len(seek.children)-1 ):
  266. bonePath[curheight-1]+=1
  267. del bonePath[curheight]
  268. seek = parent
  269. continue
  270. # should work...
  271. seek = get_bone_from_path(bone, bonePath)
  272. if (seek.name not in bones):
  273. lines.append(bonePath.copy())
  274. bones.add(seek.name)
  275. if (seek.children):
  276. bonePath.append(0)
  277. else:
  278. bonePath[curheight] = bonePath[curheight] + 1
  279. seek = seek.parent
  280. return lines
  281. def get_bone_from_path(root_bone, path):
  282. # this function assumes the path is valid
  283. path = path.copy(); bone = root_bone
  284. while(path):
  285. bone = bone.children[path.pop(0)]
  286. return bone
  287. # THIS IS BAD AND DUMB
  288. def setup_custom_properties(bone_node, pb):
  289. for k, v in pb.items():
  290. socktype, prop_type = '', type(v)
  291. if prop_type == bool:
  292. socktype = 'ParameterBoolSocket'
  293. elif prop_type == int:
  294. socktype = 'ParameterIntSocket'
  295. elif prop_type == float:
  296. socktype = 'ParameterFloatSocket'
  297. elif prop_type == bpy.props.FloatVectorProperty:
  298. socktype = 'ParameterVectorSocket'
  299. elif prop_type == str:
  300. socktype = 'ParameterStringSocket'
  301. else:
  302. prRed(f"Cannot create property {k} of type {prop_type} in {bone_node}")
  303. continue # it's a PointerProp or something
  304. new_prop = bone_node.inputs.new( socktype, k)
  305. bone_node.outputs.new( socktype, k)
  306. # set its value and limits and such
  307. # the ui_data is where this is stored. Feels hacky.
  308. ui_data = pb.id_properties_ui(k).as_dict()
  309. new_prop.default_value = ui_data['default']
  310. for attr_name in ['min', 'max', 'soft_min', 'soft_max', 'description']:
  311. if prop_type == str and attr_name != "description":
  312. continue # the first four are not available for string prop.
  313. try:
  314. attr_val = ui_data[attr_name]
  315. # there is a weird conversion error for unset min/max
  316. # because it defaults to exactly the value of long or something?
  317. if not isinstance(attr_val, str): # this doesn't work??
  318. if attr_val >= 2147483647.0: attr_val = 2147483646.0
  319. if attr_val <= -2147483648.0: attr_val = -2147483647.0
  320. setattr(new_prop, attr_name, attr_val)
  321. except KeyError:
  322. # TODO: find out why this happens and quit using exceptions
  323. prRed(f"prop {k} has no attribute {attr_name} (in {bone_node})")
  324. def setup_ik_settings(bone_node, pb):
  325. # Set Up IK settings:
  326. stiffness = [pb.ik_stiffness_x, pb.ik_stiffness_y, pb.ik_stiffness_z]
  327. lock = [pb.lock_ik_x, pb.lock_ik_y, pb.lock_ik_z]
  328. limit = [pb.use_ik_limit_x, pb.use_ik_limit_y, pb.use_ik_limit_z]
  329. bone_node.inputs["IK Stretch"].default_value = pb.ik_stretch
  330. bone_node.inputs["Lock IK"].default_value = lock
  331. bone_node.inputs["IK Stiffness"].default_value = stiffness
  332. bone_node.inputs["Limit IK"].default_value = limit
  333. bone_node.inputs["X Min"].default_value = pb.ik_min_x
  334. bone_node.inputs["X Max"].default_value = pb.ik_max_x
  335. bone_node.inputs["Y Min"].default_value = pb.ik_min_y
  336. bone_node.inputs["Y Max"].default_value = pb.ik_max_y
  337. bone_node.inputs["Z Min"].default_value = pb.ik_min_z
  338. bone_node.inputs["Z Max"].default_value = pb.ik_max_z
  339. def setup_vp_settings(bone_node, pb, do_after, node_tree):
  340. # bone_node.inputs["Hide"].default_value = pb.bone.hide
  341. bone_node.inputs["Custom Object Scale"].default_value = pb.custom_shape_scale_xyz
  342. bone_node.inputs["Custom Object Translation"].default_value = pb.custom_shape_translation
  343. bone_node.inputs["Custom Object Rotation"].default_value = pb.custom_shape_rotation_euler
  344. bone_node.inputs["Custom Object Scale to Bone Length"].default_value = pb.use_custom_shape_bone_size
  345. bone_node.inputs["Custom Object Wireframe"].default_value = pb.bone.show_wire
  346. # bone_node.inputs["Layer Mask"].default_value = pb.bone.layers
  347. collection_membership = ''
  348. for col in pb.bone.collections:
  349. # TODO: implement this!
  350. pass
  351. bone_node.inputs["Bone Collection"].default_value = collection_membership
  352. if (shape_ob := pb.custom_shape):
  353. shape_n = None
  354. for n in node_tree.nodes:
  355. if n.name == shape_ob.name:
  356. shape_n = n
  357. break
  358. else: # we make it now
  359. shape_n = node_tree.nodes.new("InputExistingGeometryObject")
  360. shape_n.select = True # for sorting
  361. shape_n.name = shape_ob.name
  362. shape_n.label = shape_ob.name
  363. shape_n.inputs["Name"].default_value = shape_ob.name
  364. node_tree.links.new(shape_n.outputs["Object"], bone_node.inputs['Custom Object'])
  365. if (shape_xform_ob := pb.custom_shape_transform): # not implemented just yet
  366. shape_xform_n = None
  367. for n in node_tree.nodes:
  368. if n.name == shape_xform_ob.name:
  369. shape_xform_n = n
  370. node_tree.links.new(shape_xform_n.outputs["xForm"], bone_node.inputs['Custom Object xForm Override'])
  371. break
  372. else: # make it a task
  373. do_after.add( ("Custom Object xForm Override", bone_node.name , shape_xform_ob.name ) )
  374. # all the above should be in a function.
  375. def setup_df_settings(bone_node, pb):
  376. bone_node.inputs["Deform"].default_value = pb.bone.use_deform
  377. # TODO: get the rest of these working
  378. # eb.envelope_distance = self.evaluate_input("Envelope Distance")
  379. # eb.envelope_weight = self.evaluate_input("Envelope Weight")
  380. # eb.use_envelope_multiply = self.evaluate_input("Envelope Multiply")
  381. # eb.head_radius = self.evaluate_input("Envelope Head Radius")
  382. # eb.tail_radius = self.evaluate_input("Envelope Tail Radius")
  383. def create_driver(in_node_name, out_node_name, armOb, finished_drivers, switches, driver_vars, fcurves, drivers, node_tree, context):
  384. # TODO: CLEAN this ABOMINATION
  385. # print ("DRIVER: ", in_node_name, out_node_name)
  386. in_node = node_tree.nodes[ in_node_name]
  387. out_node = node_tree.nodes[out_node_name]
  388. for fc in armOb.animation_data.drivers:
  389. if (in_node.label not in fc.data_path) or ( "[\""+out_node.label+"\"]" not in fc.data_path):
  390. # print ("node not in name?: %s" % fc.data_path)
  391. continue
  392. if fc.data_path in finished_drivers:
  393. continue
  394. finished_drivers.add(fc.data_path)
  395. # print ("Creating driver.... %s" % fc.data_path)
  396. keys = []
  397. for k in fc.keyframe_points:
  398. key = {}
  399. for prop in dir(k):
  400. if ("__" in prop) or ("bl_" in prop): continue
  401. #it's __name__ or bl_rna or something
  402. key[prop] = getattr(k, prop)
  403. keys.append(key)
  404. switch, inverted = False, False
  405. if (fc.evaluate(0) == 0) and (fc.evaluate(1) == 1):
  406. switch = True
  407. elif (fc.evaluate(0) == 1) and (fc.evaluate(1) == 0):
  408. switch = True; inverted = True
  409. if (fc.driver.type == 'SCRIPTED'):
  410. #print (fc.driver.expression)
  411. if not (len(fc.driver.variables) == 1 and fc.driver.expression == fc.driver.variables[0].name):
  412. switch = False
  413. if (switch):
  414. # OK, let's prepare before making the node
  415. # we want to reuse existing nodes if possible.
  416. target_string = fc.driver.variables[0].targets[0].data_path
  417. if target_string == "":
  418. for var in fc.driver.variables:
  419. print (var)
  420. print (var.name)
  421. print (var.targets)
  422. bone = target_string.split("pose.bones[\"")[1]
  423. bone = bone.split("\"]")[0]
  424. bone_node = node_tree.nodes.get(bone)
  425. if not (bone_node):
  426. raise RuntimeError("excpected to find....", bone)
  427. p_string = fc.driver.variables[0].targets[0].data_path
  428. p_string = p_string.split("[\"")[-1]; p_string = p_string.split("\"]")[0]
  429. #switch_node.inputs["Parameter"].default_value = p_string
  430. #switch_node.inputs["Parameter Index"].default_value = fc.array_index
  431. #switch_node.inputs["Invert Switch"].default_value = inverted
  432. parameter = fc.data_path
  433. # Try to find an existing node.
  434. fail = False
  435. switch_node = None
  436. for n in switches:
  437. # if n.inputs[0].is_linked:
  438. # if n.inputs[0].links[0].from_node != bone_node:
  439. # fail = True
  440. if n.inputs[0].is_linked:
  441. if n.inputs[0].links[0].from_node != bone_node:
  442. fail = True
  443. if n.inputs[0].links[0].from_socket != bone_node.outputs.get(p_string):
  444. fail = True
  445. else:
  446. if n.inputs[0].default_value != p_string:
  447. fail = True
  448. if n.inputs[1].default_value != fc.array_index:
  449. fail = True
  450. if n.inputs[2].default_value != inverted:
  451. fail = True
  452. if not fail:
  453. switch_node = n
  454. break # found it!
  455. else:
  456. # make and connect the switch node
  457. switch_node = node_tree.nodes.new("UtilitySwitch"); switches.append(switch_node)
  458. switch_node.select = True # for sorting
  459. # node_tree.links.new(bone_node.outputs["xForm Out"], switch_node.inputs[0])
  460. try:
  461. node_tree.links.new(bone_node.outputs[p_string], switch_node.inputs[0])
  462. except KeyError:
  463. prRed("this is such bad code lol fix this", p_string)
  464. switch_node.inputs[1].default_value = fc.array_index
  465. switch_node.inputs[2].default_value = inverted
  466. #print (" Inverted? ", inverted, (fc.evaluate(0) == 1) and (fc.evaluate(1) == 0), switch_node.inputs[3].default_value)
  467. if not inverted:
  468. pass # TODO find out why there is a warning here?
  469. # print (" --> Check this node: %s" % switch_node.name)
  470. # this may be a custom property or a normal property...
  471. # this should lead to a constraint
  472. if len(parameter.split("[\"") ) == 3:
  473. property = parameter.split(".")[-1]
  474. if (property == 'mute'): # this is mapped to the 'Enable' socket...
  475. prop_in = out_node.inputs.get('Enable')
  476. else:
  477. prop_in = out_node.inputs.get(get_pretty_name(property))
  478. if prop_in:
  479. node_tree.links.new(switch_node.outputs["Driver"], prop_in)
  480. else:
  481. print (" couldn't find: ", property, out_node.label, out_node.name)
  482. # this won't always work tho
  483. #Finally, it should be noted that we are assuming it uses the same object ...
  484. # drivers from Rigify always should use the same object, but I want to support
  485. # detecting drivers across objects.
  486. else: # we'll have to set this one up manually
  487. # Let's make the variable nodes, the Driver node, and the fCurve node.
  488. # Get the variable information
  489. if (True):
  490. var_nodes = []; num_vars = 0
  491. for num_vars, var in enumerate(fc.driver.variables):
  492. target1, target2, bone_target, bone_target2 = [None]*4
  493. var_data = {}
  494. var_data["Variable Type"] = var.type
  495. var_data["Property"] = ""
  496. if len(var.targets) >= 1:
  497. target1 = var.targets[0]
  498. if (var_data["Variable Type"] != 'SINGLE_PROP'):
  499. bone_target = var.targets[0].bone_target
  500. else: # figure it out by the data path string.
  501. target_string = var.targets[0].data_path
  502. bone_target = target_string.split("pose.bones[\"")[1]; bone_target = bone_target.split("\"]")[0]
  503. # we also need to get the property.
  504. p_string = fc.driver.variables[0].targets[0].data_path
  505. p_string = p_string.split("[\"")[-1]; p_string = p_string.split("\"]")[0]
  506. var_data["Property"] = p_string
  507. if (var_data["Variable Type"] == 'TRANSFORMS'):
  508. transform_channel_map = {
  509. "LOC_X" : ('location', 0),
  510. "LOC_Y" : ('location', 1),
  511. "LOC_Z" : ('location', 2),
  512. "ROT_X" : ('rotation', 0),
  513. "ROT_Y" : ('rotation', 1),
  514. "ROT_Z" : ('rotation', 2),
  515. "ROT_W" : ('rotation', 3),
  516. "SCALE_X" : ('scale', 0),
  517. "SCALE_Y" : ('scale', 1),
  518. "SCALE_Z" : ('scale', 2),
  519. "SCALE_AVG" : ('scale', 3), }
  520. # if (var.transform_type in transform_channel_map.keys()):
  521. # var_data["Property"], var_data["Property Index"] = transform_channel_map[var.transform_type]
  522. prRed("I am pretty sure this thing does not friggin work with whatever it is I commented above...")
  523. var_data["Evaluation Space"] = var.targets[0].transform_space
  524. var_data["Rotation Mode"] = var.targets[0].rotation_mode
  525. if len(var.targets) == 2:
  526. target2 = var.targets[1]
  527. bone_target2 = var.targets[1].bone_target
  528. # check if the variable already exists in the tree.
  529. target_node1, target_node2 = None, None
  530. if (target1 and bone_target):
  531. target_node1 = node_tree.nodes[bone_target]
  532. elif (target1 and not bone_target):
  533. target_node1 = node_tree.nodes[target1]
  534. if (target2 and bone_target2):
  535. target_node2 = node_tree.nodes[bone_target2]
  536. elif (target2 and not bone_target2):
  537. target_node2 = node_tree.nodes[target2]
  538. var_node = None
  539. for n in driver_vars:
  540. fail = False
  541. if (inp := n.inputs['xForm 1']).is_linked:
  542. if inp.links[0].from_node != target_node1:
  543. fail = True
  544. if (inp := n.inputs['xForm 2']).is_linked:
  545. if inp.links[0].from_node != target_node2:
  546. fail = True
  547. #
  548. if n.inputs[0].default_value != var_data["Variable Type"]:
  549. fail = True
  550. if n.inputs[1].default_value != var_data["Property"]:
  551. fail = True
  552. try:
  553. if n.inputs[2].default_value != var_data["Property Index"]:
  554. fail = True
  555. if n.inputs[3].default_value != var_data["Evaluation Space"]:
  556. fail = True
  557. if n.inputs[4].default_value != var_data["Rotation Mode"]:
  558. fail = True
  559. except KeyError:
  560. pass # this is a SCRIPTED node it seems
  561. if not fail:
  562. var_node = n
  563. prWhite("Variable Node Found %s!" % var_node )
  564. break # found it!
  565. else:
  566. var_node = node_tree.nodes.new("UtilityDriverVariable"); driver_vars.append(var_node)
  567. var_node.select = True # for sorting
  568. prRed("Creating Node: %s" % var_node.name)
  569. for key, value in var_data.items():
  570. try:
  571. var_node.inputs[key].default_value = value
  572. except TypeError as e: # maybe it is a variable\
  573. if key == "Variable Type":
  574. var_node.inputs[key].default_value = "SINGLE_PROP"
  575. else: raise e
  576. if (target1 and bone_target):
  577. node_tree.links.new(node_tree.nodes[bone_target].outputs['xForm Out'], var_node.inputs['xForm 1'])
  578. elif (target1 and not bone_target):
  579. node_tree.links.new(node_tree.nodes[target1].outputs['xForm Out'], var_node.inputs['xForm 1'])
  580. if (target2 and bone_target2):
  581. node_tree.links.new(node_tree.nodes[bone_target2].outputs['xForm Out'], var_node.inputs['xForm 2'])
  582. elif (target2 and not bone_target2):
  583. node_tree.links.new(node_tree.nodes[target2].outputs['xForm Out'], var_node.inputs['xForm 2'])
  584. var_nodes.append(var_node)
  585. num_vars+=1 # so the len(num_vars) will be correct
  586. # get the keyframes from the driver fCurve
  587. keys = {}
  588. from mathutils import Vector
  589. if len(fc.keyframe_points) > 0:
  590. # TODO: make this do more than co_ui
  591. for i, k in enumerate(fc.keyframe_points):
  592. keys[i] = {'co_ui':k.co_ui}
  593. else:
  594. if ((len(fc.modifiers) == 0) or ((fc.evaluate(0) == 0) and (fc.evaluate(1) == 1))):
  595. keys[0] = {'co_ui':Vector((0, 0))}
  596. keys[1] = {'co_ui':Vector((1, 1))}
  597. elif (fc.evaluate(0) == 1) and (fc.evaluate(1) == 0):
  598. keys[0] = {'co_ui':Vector((0, 1))}
  599. keys[1] = {'co_ui':Vector((1, 0))}
  600. else:
  601. prRed ("Could not get keys!")
  602. # TODO find out why this happens
  603. pass
  604. # elif (fc.evaluate(0) == 1) and (fc.evaluate(1) == 0):
  605. # kf0 = fc.keyframe_points[0]; kf0.co_ui = (0, 1)
  606. # kf1 = fc.keyframe_points[1]; kf1.co_ui = (1, 0)
  607. # now get the fCurve
  608. fCurve_node = None
  609. for n in fcurves:
  610. fc_ob = n.fake_fcurve_ob; node_fc = fc_ob.animation_data.action.fcurves[0]
  611. node_keys = {}
  612. for i, k in enumerate(node_fc.keyframe_points):
  613. node_keys[i] = {'co_ui':k.co_ui}
  614. # now let's see if they are the same:
  615. if (keys != node_keys):
  616. continue
  617. fCurve_node = n
  618. break
  619. else:
  620. fCurve_node = node_tree.nodes.new("UtilityFCurve")
  621. fCurve_node.select = True # for sorting
  622. # fc_ob = fCurve_node.fake_fcurve_ob
  623. # node_fc = fc_ob.animation_data.action.fcurves[0]
  624. # fcurves.append(fCurve_node)
  625. # while(node_fc.keyframe_points): # clear it, it has a default FC
  626. # node_fc.keyframe_points.remove(node_fc.keyframe_points[0], fast=True)
  627. # node_fc.update()
  628. # node_fc.keyframe_points.add(len(keys))
  629. # for k, v in keys.items():
  630. # node_fc.keyframe_points[k].co_ui = v['co_ui']
  631. # # todo eventually the other dict elements ofc
  632. for num_keys, (k, v) in enumerate(keys.items()):
  633. fCurve_node.inputs.new("KeyframeSocket", "Keyframe."+str(num_keys).zfill(3))
  634. kf_node = node_tree.nodes.new("UtilityKeyframe")
  635. kf_node.select = True # for sorting
  636. kf_node.inputs[0].default_value = v['co_ui'][0]
  637. kf_node.inputs[1].default_value = v['co_ui'][1]
  638. node_tree.links.new(kf_node.outputs[0], fCurve_node.inputs[num_keys])
  639. # NOW the driver itself
  640. driver_node = None
  641. # checc for it...
  642. driver_node = node_tree.nodes.new("UtilityDriver")
  643. driver_node.select = True # for sorting
  644. driver_node.inputs["Driver Type"].default_value = fc.driver.type
  645. driver_node.inputs["Expression"].default_value = fc.driver.expression.replace ('var', 'a')
  646. # HACK, fix the above with a more robust solution
  647. node_tree.links.new(fCurve_node.outputs[0], driver_node.inputs['fCurve'])
  648. for i, var_node in zip(range(num_vars), var_nodes):
  649. # TODO TODO BUG HACK
  650. with context.temp_override(node=driver_node):
  651. bpy.ops.mantis.driver_node_add_variable()
  652. # This causes an error when you run it from the console! DO NOT leave this
  653. node_tree.links.new(var_node.outputs[0], driver_node.inputs[-1])
  654. # HACK duplicated code from earlier...
  655. parameter = fc.data_path
  656. prWhite( "parameter: %s" % parameter)
  657. property = ''
  658. if len(parameter.split("[\"") ) == 3:
  659. property = parameter.split(".")[-1]
  660. if (property == 'mute'): # this is mapped to the 'Enable' socket...
  661. prop_in = out_node.inputs.get('Enable')
  662. else:
  663. prop_in = out_node.inputs.get(get_pretty_name(property))
  664. if not prop_in: # this is a HACK because my solution is terrible and also bad
  665. if property == "head_tail":
  666. prop_in = out_node.inputs.get("Head/Tail")
  667. # the socket should probably know what Blender thing is being mapped to it as a custom prop
  668. if not prop_in:
  669. # try one last thing:
  670. property = parameter.split("targets[")[-1]
  671. target_index = int(property[0])
  672. property = "targets[" + property # HACK lol
  673. # get the property by index...
  674. prop_in = out_node.inputs[target_index*2+6+1] # this is the weight, not the target
  675. if prop_in:
  676. prRed (" found: %s, %s, %s" % (property, out_node.label, out_node.name))
  677. node_tree.links.new(driver_node.outputs["Driver"], prop_in)
  678. else:
  679. prRed (" couldn't find: %s, %s, %s" % (property, out_node.label, out_node.name))
  680. elif len(parameter.split("[\"") ) == 2:
  681. property = parameter.split(".")[-1]
  682. else:
  683. prWhite( "parameter: %s" % parameter)
  684. prRed (" couldn't find: ", property, out_node.label, out_node.name)
  685. def set_parent_from_node(pb, bone_inherit_node, node_tree):
  686. bone = pb.bone
  687. possible_parent_nodes = bone_inherit_node.get(bone.parent.name)
  688. # Set the parent
  689. parent = None
  690. if not (possible_parent_nodes):
  691. parent = create_inheritance_node(pb, bone.parent.name, bone_inherit_node, node_tree)
  692. else:
  693. for ppn in possible_parent_nodes:
  694. # check if it has the right connected, inherit scale, inherit rotation
  695. if ppn.inputs["Connected"].default_value != pb.bone.use_connect:
  696. continue
  697. if ppn.inputs["Inherit Scale"].default_value != pb.bone.inherit_scale:
  698. continue
  699. if ppn.inputs["Inherit Rotation"].default_value != pb.bone.use_inherit_rotation:
  700. continue
  701. parent = ppn; break
  702. else:
  703. parent = create_inheritance_node(pb, bone.parent.name, bone_inherit_node, node_tree)
  704. return parent
  705. def do_generate_graph( context, node_tree, include_links_and_deforms=True, generate_children=False):
  706. active_object = context.active_object
  707. for n in node_tree.nodes: n.select=False
  708. # clear selection so that the sorting code works, it operates on selection
  709. # the other functions are responsible for setting selection properly.
  710. if active_object.select_get() == False:
  711. return
  712. elif active_object.type in ["MESH", "CURVE", "EMPTY"]:
  713. do_generate_geom(active_object, node_tree, do_deformers = include_links_and_deforms, generate_children=generate_children)
  714. elif active_object.type == 'ARMATURE':
  715. do_generate_armature(active_object, context, node_tree, bones_only= not include_links_and_deforms, generate_children=generate_children)
  716. def do_generate_geom(ob, node_tree, parent_node=None, do_deformers=False, generate_children= False):
  717. ob_node = node_tree.nodes.new("xFormGeometryObject")
  718. ob_node.select = True # for sorting
  719. ob_node.name = ob.name; ob_node.label = ob.name
  720. ob_node.inputs["Name"].default_value=ob.name+"_MANTIS"
  721. if ob.data:
  722. geometry_node = node_tree.nodes.new("InputExistingGeometryData")
  723. geometry_node.select = True # for sorting
  724. geometry_node.inputs[0].default_value=ob.data.name
  725. node_tree.links.new(input=geometry_node.outputs[0], output=ob_node.inputs["Geometry"])
  726. matrix_of = node_tree.nodes.new("UtilityMatrixFromXForm")
  727. existing_ob = node_tree.nodes.new("InputExistingGeometryObject")
  728. existing_ob.inputs["Name"].default_value = ob.name
  729. node_tree.links.new(input=existing_ob.outputs[0], output=matrix_of.inputs[0])
  730. node_tree.links.new(input=matrix_of.outputs[0], output=ob_node.inputs["Matrix"])
  731. # Generate Deformers
  732. prev_def_node = None
  733. if do_deformers:
  734. for m in ob.modifiers:
  735. if m.type == "ARMATURE":
  736. def_node = node_tree.nodes.new("DeformerArmature")
  737. def_node.select = True # for sorting
  738. def_node.inputs["Blend Vertex Group"].default_value = m.vertex_group
  739. def_node.inputs["Invert Vertex Group"].default_value = m.invert_vertex_group
  740. def_node.inputs["Preserve Volume"].default_value = m.use_deform_preserve_volume
  741. def_node.inputs["Use Multi Modifier"].default_value = m.use_multi_modifier
  742. def_node.inputs["Use Envelopes"].default_value = m.use_bone_envelopes
  743. def_node.inputs["Use Vertex Groups"].default_value = m.use_vertex_groups
  744. # def_node.inputs["Copy Skin Weights From"]
  745. def_node.inputs["Skinning Method"].default_value="EXISTING_GROUPS"
  746. def_ob = node_tree.nodes.get(m.object.name)
  747. # get the deformer's target object...
  748. if def_ob:
  749. node_tree.links.new(input=def_ob.outputs["xForm Out"], output=def_node.inputs["Armature Object"])
  750. if prev_def_node:
  751. node_tree.links.new(input=prev_def_node.outputs["Deformer"], inputs=def_node.inputs["Deformer"])
  752. prev_def_node = def_node
  753. if prev_def_node:
  754. node_tree.links.new(input=prev_def_node.outputs["Deformer"], output=ob_node.inputs["Deformer"])
  755. if parent_node:
  756. node_tree.links.new(input=parent_node.outputs["Inheritance"], output=ob_node.inputs["Relationship"])
  757. # NOTE: there should be constraints here, too!
  758. # copied from below with minor modification # TODO de-dupe me
  759. if generate_children:
  760. for child in ob.children:
  761. its_parent = create_inheritance_node(None, ob.name, {}, node_tree)
  762. if child.type in ["MESH", "CURVE", "EMPTY"]:
  763. do_generate_geom(child, node_tree, parent_node=its_parent, do_deformers=do_deformers, generate_children=True)
  764. if child.type in ["ARMATURE"]:
  765. do_generate_armature(armOb, context, node_tree, parent_node=its_parent, bones_only=not do_deformers, generate_children=True)
  766. def do_generate_armature(armOb, context, node_tree, parent_node=None,
  767. bones_only=False, generate_children=False):
  768. from time import time
  769. start = time()
  770. meta_rig_nodes = {}
  771. bone_inherit_node = {}
  772. do_after = set()
  773. armature = node_tree.nodes.new("xFormArmatureNode")
  774. armature.select = True # for sorting
  775. mr_node_name = armOb.name
  776. if not (mr_node:= meta_rig_nodes.get(mr_node_name)):
  777. mr_node = node_tree.nodes.new("UtilityMetaRig")
  778. mr_node.select = True # for sorting
  779. meta_rig_nodes[mr_node_name] = mr_node
  780. mr_node.inputs[0].search_prop=armOb
  781. node_tree.links.new(input=mr_node.outputs[0], output=armature.inputs["Matrix"])
  782. if parent_node:
  783. node_tree.links.new()
  784. bones = []
  785. for root in armOb.data.bones:
  786. if root.parent is None:
  787. iter_start= time()
  788. milestone=time()
  789. prPurple("got the bone paths", time() - milestone); milestone=time()
  790. armature.inputs["Name"].default_value = armOb.name + "_MANTIS"
  791. armature.name = armOb.name; armature.label = armOb.name
  792. bones.extend([root])
  793. if parent_node:
  794. node_tree.links.new(input=parent_node.outputs["Inheritance"], output=armature.inputs["Relationship"])
  795. # for bone_path in lines:
  796. for bone in bones:
  797. prGreen(time() - milestone); milestone=time()
  798. # first go through the bone path and find relevant information
  799. bone_node = node_tree.nodes.new("xFormBoneNode")
  800. bone_node.select = True # for sorting
  801. bone_node.inputs["Name"].default_value = bone.name
  802. bone_node.name, bone_node.label = bone.name, bone.name
  803. matrix = bone.matrix_local.copy()
  804. bone_node.inputs["Matrix"].default_value = [
  805. matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3],
  806. matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3],
  807. matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3], # last element is bone length, for mantis
  808. matrix[3][0], matrix[3][1], matrix[3][2], bone.length ] #matrix[3][3], ]
  809. mr_node_name = armOb.name+":"+bone.name
  810. if not (mr_node:= meta_rig_nodes.get(mr_node_name)):
  811. mr_node = node_tree.nodes.new("UtilityMetaRig")
  812. meta_rig_nodes[mr_node_name] = mr_node
  813. mr_node.inputs[0].search_prop=armOb
  814. mr_node.inputs[1].armature=armOb
  815. mr_node.inputs[1].bone=bone.name
  816. mr_node.inputs[1].default_value=bone.name
  817. node_tree.links.new(input=mr_node.outputs[0], output=bone_node.inputs["Matrix"])
  818. pb = armOb.pose.bones[bone.name]
  819. if bone.parent: # not a root
  820. parent = set_parent_from_node(pb, bone_inherit_node, node_tree)
  821. # prWhite("Got parent node", time() - milestone); milestone=time()
  822. if parent is None:
  823. raise RuntimeError("No parent node?")
  824. else: # This is a root
  825. if (parent_list := bone_inherit_node.get(armOb.name)) is None:
  826. parent = node_tree.nodes.new("linkInherit")
  827. parent.select = True # for sorting
  828. bone_inherit_node[armOb.name] = [parent]
  829. node_tree.links.new(armature.outputs["xForm Out"], parent.inputs['Parent'])
  830. parent.inputs["Inherit Rotation"].default_value = True
  831. else:
  832. parent = parent_list[0]
  833. node_tree.links.new(parent.outputs["Inheritance"], bone_node.inputs['Relationship'])
  834. bone_node.inputs["Lock Location"].default_value = pb.lock_location
  835. bone_node.inputs["Lock Rotation"].default_value = pb.lock_rotation
  836. bone_node.inputs["Lock Scale"].default_value = pb.lock_scale
  837. bone_node.inputs["Rotation Order"].default_value = pb.rotation_mode
  838. setup_custom_properties(bone_node, pb)
  839. setup_ik_settings(bone_node, pb)
  840. setup_vp_settings(bone_node, pb, do_after, node_tree)
  841. setup_df_settings(bone_node, pb)
  842. # BBONES
  843. bone_node.inputs["BBone X Size"].default_value = pb.bone.bbone_x
  844. bone_node.inputs["BBone Z Size"].default_value = pb.bone.bbone_z
  845. bone_node.inputs["BBone Segments"].default_value = pb.bone.bbone_segments
  846. if pb.bone.bbone_mapping_mode == "CURVED":
  847. bone_node.inputs["BBone HQ Deformation"].default_value = True
  848. bone_node.inputs["BBone Start Handle Type"].default_value = pb.bone.bbone_handle_type_start
  849. bone_node.inputs["BBone End Handle Type"].default_value = pb.bone.bbone_handle_type_end
  850. bone_node.inputs["BBone Custom Start Handle"].default_value = pb.bone.bbone_handle_type_start
  851. bone_node.inputs["BBone Custom End Handle"].default_value = pb.bone.bbone_handle_type_end
  852. bone_node.inputs["BBone X Curve-In"].default_value = pb.bone.bbone_curveinx
  853. bone_node.inputs["BBone Z Curve-In"].default_value = pb.bone.bbone_curveinz
  854. bone_node.inputs["BBone X Curve-Out"].default_value = pb.bone.bbone_curveoutx
  855. bone_node.inputs["BBone Z Curve-Out"].default_value = pb.bone.bbone_curveoutz
  856. # prRed("BBone Implementation is not complete, expect errors and missing features for now")
  857. for c in pb.constraints:
  858. # prWhite("constraint %s for %s" % (c.name, pb.name), time() - milestone); milestone=time()
  859. # make relationship nodes and set up links...
  860. if ( c_node := create_relationship_node_for_constraint(node_tree, c)):
  861. # HACK but this code is all ugly hacky crap anyway so this is good enough
  862. if bones_only == True:
  863. continue
  864. c_node.label = c.name
  865. # this node definitely has a parent inherit node.
  866. c_node.location = parent.location; c_node.location.x += 200
  867. try:
  868. node_tree.links.new(parent.outputs["Inheritance"], c_node.inputs['Input Relationship'])
  869. except KeyError: # not a inherit node anymore
  870. node_tree.links.new(parent.outputs["Output Relationship"], c_node.inputs['Input Relationship'])
  871. parent = c_node
  872. #Target Tasks:
  873. if (hasattr(c, "target") and not hasattr(c, "subtarget")):
  874. do_after.add( ("Object Target", c_node.name , c.target.name ) )
  875. if (hasattr(c, "subtarget")):
  876. if c.target and c.subtarget: # this node has a target, find the node associated with it...
  877. do_after.add( ("Target", c_node.name , c.subtarget ) )
  878. else:
  879. do_after.add( ("Object Target", c_node.name , c.target.name ) )
  880. if (hasattr(c, "pole_subtarget")):
  881. if c.pole_target and c.pole_subtarget: # this node has a pole target, find the node associated with it...
  882. do_after.add( ("Pole Target", c_node.name , c.pole_subtarget ) )
  883. fill_parameters(c_node, c, context)
  884. if (hasattr(c, "targets")): # Armature Modifier, annoying.
  885. for i in range(len(c.targets)):
  886. if (c.targets[i].subtarget):
  887. do_after.add( ("Target."+str(i).zfill(3), c_node.name , c.targets[i].subtarget ) )
  888. # Driver Tasks
  889. if armOb.animation_data:
  890. for fc in armOb.animation_data.drivers:
  891. pb_string = fc.data_path.split("[\"")[1]; pb_string = pb_string.split("\"]")[0]
  892. try:
  893. c_string = fc.data_path.split("[\"")[2]; c_string = c_string.split("\"]")[0]
  894. do_after.add ( ("driver", bone_node.name, c_node.name) )
  895. except IndexError: # the above expects .pose.bones["some name"].constraints["some constraint"]
  896. do_after.add ( ("driver", bone_node.name, bone_node.name) ) # it's a property I guess
  897. try:
  898. node_tree.links.new(parent.outputs["Inheritance"], bone_node.inputs['Relationship'])
  899. except KeyError: # may have changed, see above
  900. node_tree.links.new(parent.outputs["Output Relationship"], bone_node.inputs['Relationship'])
  901. prPurple("iteration: ", time() - iter_start)
  902. bones.extend(bone.children)
  903. finished_drivers = set()
  904. switches, driver_vars, fcurves, drivers = [],[],[],[]
  905. # Now do the tasks.
  906. for (task, in_node_name, out_node_name) in do_after:
  907. # prOrange(task, in_node_name, out_node_name)f
  908. if task in ['Object Target']:
  909. in_node = node_tree.nodes[ in_node_name ]
  910. out_node= node_tree.nodes.new("InputExistingGeometryObject")
  911. out_node.select = True # for sorting
  912. out_node.inputs["Name"].default_value=out_node_name
  913. node_tree.links.new(out_node.outputs["Object"], in_node.inputs["Target"])
  914. if task in ['Target', 'Pole Target']:
  915. in_node = node_tree.nodes[ in_node_name ]
  916. try:
  917. out_node = node_tree.nodes[ out_node_name ]
  918. except KeyError:
  919. prRed (f"Failed to find node: {out_node_name} as pole target for node: {in_node_name} and input {task}")
  920. #
  921. node_tree.links.new(out_node.outputs["xForm Out"], in_node.inputs[task])
  922. elif (task[:6] == 'Target'):
  923. in_node = node_tree.nodes[ in_node_name ]
  924. out_node = node_tree.nodes[ out_node_name ]
  925. #
  926. node_tree.links.new(out_node.outputs["xForm Out"], in_node.inputs[task])
  927. elif task in ["Custom Object xForm Override"]:
  928. shape_xform_n = None
  929. for n in node_tree.nodes:
  930. if n.name == out_node_name:
  931. shape_xform_n = n
  932. node_tree.links.new(shape_xform_n.outputs["xForm Out"], node_tree.nodes[in_node_name].inputs['Custom Object xForm Override'])
  933. break
  934. else: # make it a task
  935. prRed("Cannot set custom object transform override for %s to %s" % (in_node_name, out_node_name))
  936. elif task in ["driver"]:
  937. create_driver(in_node_name, out_node_name, armOb, finished_drivers, switches, driver_vars, fcurves, drivers, node_tree, context)
  938. # annoyingly, Rigify uses f-modifiers to setup its fcurves
  939. # I do not intend to support fcurve modifiers in Mantis at this time
  940. if generate_children:
  941. for child in armOb.children:
  942. its_parent = None
  943. parent_name = armOb.name
  944. if child.parent_type == "BONE":
  945. parent_name = child.parent_bone
  946. if not (possible_parent_nodes := bone_inherit_node.get(parent_name)):
  947. its_parent = create_inheritance_node(child, parent_name, bone_inherit_node, node_tree)
  948. else:
  949. for ppn in possible_parent_nodes: # check if it has the right connected, inherit scale, inherit rotation
  950. if ppn.inputs["Connected"].default_value != False: continue
  951. if ppn.inputs["Inherit Scale"].default_value != "FULL": continue
  952. if ppn.inputs["Inherit Rotation"].default_value != True: continue
  953. its_parent = ppn; break
  954. else:
  955. its_parent = create_inheritance_node(pb, parent_name, bone_inherit_node, node_tree)
  956. if child.type in ["MESH", "CURVE", "EMPTY"]:
  957. do_generate_geom(child, node_tree, its_parent)
  958. if child.type in ["ARMATURE"]:
  959. do_generate_armature(armOb, context, node_tree, parent_node=its_parent)
  960. prGreen("Finished generating %d nodes in %f seconds." % (len(node_tree.nodes), time() - start))
  961. return armature
  962. class GenerateMantisTree(Operator):
  963. """Generate Mantis Tree From Selected"""
  964. bl_idname = "mantis.generate_tree"
  965. bl_label = "Generate Mantis Tree from Selected"
  966. bl_options = {'REGISTER', 'UNDO'}
  967. clear_tree : bpy.props.BoolProperty(default=False, name="Clear Tree?")
  968. include_links_and_deforms : bpy.props.BoolProperty(default=False, name="Include Links, Deformers, and Drivers?")
  969. generate_children : bpy.props.BoolProperty(default=False, name="Generate Object's Children, too? Warning: This may be slow.")
  970. @classmethod
  971. def poll(cls, context):
  972. return (mantis_poll_op(context))
  973. # show the props dialog so the user can get the info they want
  974. def invoke(self, context, event):
  975. wm = context.window_manager
  976. return wm.invoke_props_dialog(self)
  977. def execute(self, context):
  978. space = context.space_data
  979. path = space.path
  980. node_tree = space.path[len(path)-1].node_tree
  981. do_profile=False
  982. if self.clear_tree:
  983. node_tree.nodes.clear() # is this wise?
  984. import cProfile
  985. from os import environ
  986. if environ.get("DOPROFILE"):
  987. do_profile=True
  988. node_tree.do_live_update = False
  989. node_tree.is_exporting = True
  990. try:
  991. if do_profile:
  992. import pstats, io
  993. from pstats import SortKey
  994. with cProfile.Profile() as pr:
  995. do_generate_graph(context, node_tree, include_links_and_deforms = self.include_links_and_deforms, generate_children=self.generate_children)
  996. s = io.StringIO()
  997. sortby = SortKey.TIME
  998. # sortby = SortKey.CUMULATIVE
  999. ps = pstats.Stats(pr, stream=s).strip_dirs().sort_stats(sortby)
  1000. ps.print_stats(20) # print the top 20
  1001. print(s.getvalue())
  1002. else:
  1003. do_generate_graph(context, node_tree, include_links_and_deforms = self.include_links_and_deforms, generate_children=self.generate_children)
  1004. from .utilities import SugiyamaGraph
  1005. try: # the graph gen code has selected the nodes to sort.
  1006. SugiyamaGraph(node_tree, 16)
  1007. except ImportError: # if for some reason Sugiyama isn't available
  1008. pass
  1009. finally:
  1010. node_tree.do_live_update = True
  1011. node_tree.is_exporting = False
  1012. node_tree.prevent_next_exec = True
  1013. return {"FINISHED"}