ops_generate_tree.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  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. parent_node = node_tree.nodes.new("linkInherit")
  15. parent_bone_node = node_tree.nodes.get(parent_name)
  16. if not parent_bone_node:
  17. raise RuntimeError("Can't Find parent node!!")
  18. parent_node.location = parent_bone_node.location; parent_node.location.x+=200
  19. node_tree.links.new(parent_bone_node.outputs["xForm Out"], parent_node.inputs['Parent'])
  20. parent_node.inputs["Connected"].default_value = pb.bone.use_connect
  21. parent_node.inputs["Inherit Scale"].default_value = pb.bone.inherit_scale
  22. parent_node.inputs["Inherit Rotation"].default_value = pb.bone.use_inherit_rotation
  23. if (bone_inherit_node.get(parent_bone_node.name)):
  24. bone_inherit_node[parent_bone_node.name].append(parent_node)
  25. else:
  26. bone_inherit_node[parent_bone_node.name] = [parent_node]
  27. return parent_node
  28. def get_pretty_name(name):
  29. pretty = name.replace("_", " ")
  30. words = pretty.split(" "); pretty = ''
  31. for word in words:
  32. pretty+=(word.capitalize()); pretty+=' '
  33. return pretty [:-1] #omit the last trailing space
  34. constraint_link_map={
  35. 'COPY_LOCATION' : "LinkCopyLocation",
  36. 'COPY_ROTATION' : "LinkCopyRotation",
  37. 'COPY_SCALE' : "LinkCopyScale",
  38. 'COPY_TRANSFORMS' : "LinkCopyTransforms",
  39. 'LIMIT_DISTANCE' : "LinkLimitDistance",
  40. 'LIMIT_LOCATION' : "LinkLimitLocation",
  41. 'LIMIT_ROTATION' : "LinkLimitRotation",
  42. 'LIMIT_SCALE' : "LinkLimitScale",
  43. 'DAMPED_TRACK' : "LinkDampedTrack",
  44. 'LOCKED_TRACK' : "LinkLockedTrack",
  45. 'STRETCH_TO' : "LinkStretchTo",
  46. 'TRACK_TO' : "LinkTrackTo",
  47. 'CHILD_OF' : "LinkInheritConstraint",
  48. 'IK' : "LinkInverseKinematics",
  49. 'ARMATURE' : "LinkArmature",
  50. 'SPLINE_IK' : "LinkSplineIK",
  51. 'TRANSFORM' : "LinkTransformation",
  52. }
  53. def create_relationship_node_for_constraint(node_tree, c):
  54. if cls_name := constraint_link_map.get(c.type):
  55. return node_tree.nodes.new(cls_name)
  56. else:
  57. prRed ("Not yet implemented: %s" % c.type)
  58. return None
  59. def fill_parameters(node, c):
  60. # just try the basic parameters...
  61. node.mute = not c.enabled
  62. if c.mute == True and c.enabled == True:
  63. node.mute = c.mute
  64. # this is obviously stupid, but it's the new API as of, IIRC, 2.80
  65. try:
  66. owner_space = c.owner_space
  67. if c.owner_space == 'CUSTOM':
  68. raise NotImplementedError("Custom Space is a TODO")
  69. if ( input := node.inputs.get("Owner Space") ):
  70. input.default_value = owner_space
  71. except AttributeError:
  72. pass
  73. try:
  74. target_space = c.target_space
  75. if c.target_space == 'CUSTOM':
  76. raise NotImplementedError("Custom Space is a TODO")
  77. if ( input := node.inputs.get("Target Space") ):
  78. input.default_value = target_space
  79. except AttributeError:
  80. pass
  81. try:
  82. use_x, use_y, use_z = c.use_x, c.use_y, c.use_z
  83. if ( input := node.inputs.get("Axes") ):
  84. input.default_value[0] = use_x
  85. input.default_value[1] = use_y
  86. input.default_value[2] = use_z
  87. except AttributeError:
  88. pass
  89. try:
  90. invert_x, invert_y, invert_z = c.invert_x, c.invert_y, c.invert_z
  91. if ( input := node.inputs.get("Invert") ):
  92. input.default_value[0] = invert_x
  93. input.default_value[1] = invert_y
  94. input.default_value[2] = invert_z
  95. except AttributeError:
  96. pass
  97. try:
  98. influence = c.influence
  99. if ( input := node.inputs.get("Influence") ):
  100. input.default_value = influence
  101. except AttributeError:
  102. pass
  103. # gonna dispense with the try/except from here on
  104. if (c.type == 'COPY_LOCATION'):
  105. node.inputs["Head/Tail"].default_value = c.head_tail
  106. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  107. elif (c.type == 'COPY_ROTATION'):
  108. node.inputs["RotationOrder"].default_value = c.euler_order
  109. # ofset (legacy) is not supported TODO BUG
  110. if (mix_mode := c.mix_mode) == 'OFFSET':
  111. mix_mode = 'AFTER'
  112. node.inputs["Rotation Mix"].default_value = mix_mode
  113. elif (c.type == 'COPY_SCALE'):
  114. #node.inputs["Additive"].default_value = c.use_make_uniform # not yet implemented
  115. #node.inputs["Power"].default_value = c.head_tail
  116. node.inputs["Average"].default_value = c.use_make_uniform
  117. node.inputs["Offset"].default_value = c.use_offset
  118. elif (c.type == 'COPY_TRANSFORMS'):
  119. node.inputs["Head/Tail"].default_value = c.head_tail
  120. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  121. node.inputs["Mix"].default_value = c.mix_mode
  122. elif (c.type == 'LIMIT_DISTANCE'):
  123. print ("Not yet handled: ", c.type)
  124. elif (c.type in ['LIMIT_LOCATION', 'LIMIT_ROTATION', 'LIMIT_SCALE']):
  125. # print (c.type)
  126. try:
  127. node.inputs["Use Max X"].default_value = c.use_max_x
  128. node.inputs["Use Max Y"].default_value = c.use_max_y
  129. node.inputs["Use Max Z"].default_value = c.use_max_z
  130. #
  131. node.inputs["Use Min X"].default_value = c.use_min_x
  132. node.inputs["Use Min Y"].default_value = c.use_min_y
  133. node.inputs["Use Min Z"].default_value = c.use_min_z
  134. except AttributeError: # rotation
  135. node.inputs["Use X"].default_value = c.use_limit_x
  136. node.inputs["Use Y"].default_value = c.use_limit_y
  137. node.inputs["Use Z"].default_value = c.use_limit_z
  138. node.inputs["Max X"].default_value = c.max_x
  139. node.inputs["Max Y"].default_value = c.max_y
  140. node.inputs["Max Z"].default_value = c.max_z
  141. #
  142. node.inputs["Min X"].default_value = c.min_x
  143. node.inputs["Min Y"].default_value = c.min_y
  144. node.inputs["Min Z"].default_value = c.min_z
  145. elif (c.type == 'DAMPED_TRACK'):
  146. node.inputs["Head/Tail"].default_value = c.head_tail
  147. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  148. node.inputs["Track Axis"].default_value = c.track_axis
  149. elif (c.type == 'LOCKED_TRACK'):
  150. node.inputs["Head/Tail"].default_value = c.head_tail
  151. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  152. node.inputs["Track Axis"].default_value = c.track_axis
  153. node.inputs["Lock Axis"].default_value = c.lock_axis
  154. elif (c.type == 'STRETCH_TO'):
  155. node.inputs["Head/Tail"].default_value = c.head_tail
  156. node.inputs["UseBBone"].default_value = c.use_bbone_shape
  157. node.inputs["Volume Variation"].default_value = c.bulge
  158. node.inputs["Use Volume Min"].default_value = c.use_bulge_min
  159. node.inputs["Volume Min"].default_value = c.bulge_min
  160. node.inputs["Use Volume Max"].default_value = c.use_bulge_max
  161. node.inputs["Volume Max"].default_value = c.bulge_max
  162. node.inputs["Smooth"].default_value = c.bulge_smooth
  163. node.inputs["Maintain Volume"].default_value = c.volume
  164. node.inputs["Rotation"].default_value = c.keep_axis
  165. elif (c.type == 'TRACK_TO'):
  166. print ("Not yet handled: ", c.type)
  167. elif (c.type == 'CHILD_OF'):
  168. print ("Not yet handled: ", c.type)
  169. elif (c.type == 'IK'):
  170. node.inputs["Chain Length"].default_value = c.chain_count
  171. node.inputs["Use Tail"].default_value = c.use_tail
  172. node.inputs["Stretch"].default_value = c.use_stretch
  173. # this isn't quite right lol
  174. node.inputs["Position"].default_value = c.weight
  175. node.inputs["Rotation"].default_value = c.orient_weight
  176. if not (c.use_location):
  177. node.inputs["Position"].default_value = 0
  178. if not (c.use_rotation):
  179. node.inputs["Rotation"].default_value = 0
  180. elif (c.type == 'ARMATURE'):
  181. node.inputs["Preserve Volume"].default_value = c.use_deform_preserve_volume
  182. node.inputs["Use Envelopes"].default_value = c.use_bone_envelopes
  183. node.inputs["Use Current Location"].default_value = c.use_current_location
  184. for i in range(len(c.targets)):
  185. bpy.ops.mantis.link_armature_node_add_target({'node':node})
  186. elif (c.type == 'SPLINE_IK'):
  187. node.inputs["Chain Length"].default_value = c.chain_count
  188. node.inputs["Even Divisions"].default_value = c.use_even_divisions
  189. node.inputs["Chain Offset"].default_value = c.use_chain_offset
  190. node.inputs["Use Curve Radius"].default_value = c.use_curve_radius
  191. node.inputs["Y Scale Mode"].default_value = c.y_scale_mode
  192. node.inputs["XZ Scale Mode"].default_value = c.xz_scale_mode
  193. elif (c.type == 'TRANSFORM'):
  194. # I can't be arsed to do all this work..
  195. from .link_containers import transformation_props_sockets as props
  196. for prop, (sock_name, _unused) in props.items():
  197. if "from" in prop:
  198. if prop in ["map_from"] or "to" in prop:
  199. pass
  200. elif c.map_from == 'LOCATION':
  201. if "scale" in prop:
  202. continue
  203. if "rot" in prop:
  204. continue
  205. elif c.map_from == 'ROTATION':
  206. if "rot" not in prop:
  207. continue
  208. elif c.map_from == 'SCALE':
  209. if "scale" not in prop:
  210. continue
  211. if "to" in prop:
  212. if prop in ["map_to"] or "from" in prop:
  213. pass
  214. elif c.map_from == 'LOCATION':
  215. if "scale" in prop:
  216. continue
  217. if "rot" in prop:
  218. continue
  219. elif c.map_from == 'ROTATION':
  220. if "rot" not in prop:
  221. continue
  222. elif c.map_from == 'SCALE':
  223. if "scale" not in prop:
  224. continue
  225. node.inputs[sock_name].default_value = getattr(c, prop)
  226. if prop in "mute":
  227. node.inputs[sock_name].default_value = not getattr(c, prop)
  228. # should probably do it this way all over actually.
  229. else:
  230. raise NotImplementedError("Not handled yet: %s" % c.type)
  231. return None
  232. def walk_edit_bone(armOb, bone):
  233. # this is a simplified version of the node-tree walking code
  234. bonePath, bones, lines, seek = [0,], set(), [], bone
  235. while (True):
  236. curheight = len(bonePath)-1; ind = bonePath[-1]
  237. if (curheight == 0) and (ind > len(bone.children)-1):
  238. break
  239. if (curheight > 0):
  240. parent = seek.parent
  241. if (ind > len(seek.children)-1 ):
  242. bonePath[curheight-1]+=1
  243. del bonePath[curheight]
  244. seek = parent
  245. continue
  246. # should work...
  247. seek = get_bone_from_path(bone, bonePath)
  248. if (seek.name not in bones):
  249. lines.append(bonePath.copy())
  250. bones.add(seek.name)
  251. if (seek.children):
  252. bonePath.append(0)
  253. else:
  254. bonePath[curheight] = bonePath[curheight] + 1
  255. seek = seek.parent
  256. return lines
  257. def get_bone_from_path(root_bone, path):
  258. # this function assumes the path is valid
  259. path = path.copy(); bone = root_bone
  260. while(path):
  261. bone = bone.children[path.pop(0)]
  262. return bone
  263. def setup_custom_properties(bone_node, pb):
  264. for k, v in pb.items(): # Custom Properties
  265. socktype, prop_type = '', type(v)
  266. # print (prop_type)
  267. if prop_type == bool:
  268. socktype = 'ParameterBoolSocket'
  269. elif prop_type == int:
  270. socktype = 'ParameterIntSocket'
  271. elif prop_type == float:
  272. socktype = 'ParameterFloatSocket'
  273. elif prop_type == bpy.props.FloatVectorProperty:
  274. socktype = 'ParameterVectorSocket'
  275. elif prop_type == str:
  276. socktype = 'ParameterStringSocket'
  277. else:
  278. continue # it's a PointerProp or something
  279. #if self.prop_type == 'ENUM':
  280. # sock_type = 'ParameterStringSocket'
  281. new_prop = bone_node.inputs.new( socktype, k)
  282. bone_node.outputs.new( socktype, k)
  283. # set its value and limits and such
  284. # from rna_prop_ui import rna_idprop_ui_create
  285. # I have no idea how to get the data in a sane way, I guess I will use this...
  286. ui_data = pb.id_properties_ui(k).as_dict()
  287. new_prop.default_value = ui_data['default']
  288. try:
  289. new_prop.min = ui_data['min']
  290. new_prop.max = ui_data['max']
  291. new_prop.soft_min = ui_data['soft_min']
  292. new_prop.soft_max = ui_data['soft_max']
  293. except AttributeError:
  294. pass # it's not a number
  295. except KeyError:
  296. pass # same, or not defined maybe
  297. try:
  298. new_prop.description = ui_data['description']
  299. except KeyError:
  300. prOrange("Figure out why this happens?")
  301. def setup_ik_settings(bone_node, pb):
  302. # Set Up IK settings:
  303. stiffness = [pb.ik_stiffness_x, pb.ik_stiffness_y, pb.ik_stiffness_z]
  304. lock = [pb.lock_ik_x, pb.lock_ik_y, pb.lock_ik_z]
  305. limit = [pb.use_ik_limit_x, pb.use_ik_limit_y, pb.use_ik_limit_z]
  306. bone_node.inputs["IK Stretch"].default_value = pb.ik_stretch
  307. bone_node.inputs["Lock IK"].default_value = lock
  308. bone_node.inputs["IK Stiffness"].default_value = stiffness
  309. bone_node.inputs["Limit IK"].default_value = limit
  310. bone_node.inputs["X Min"].default_value = pb.ik_min_x
  311. bone_node.inputs["X Max"].default_value = pb.ik_max_x
  312. bone_node.inputs["Y Min"].default_value = pb.ik_min_y
  313. bone_node.inputs["Y Max"].default_value = pb.ik_max_y
  314. bone_node.inputs["Z Min"].default_value = pb.ik_min_z
  315. bone_node.inputs["Z Max"].default_value = pb.ik_max_z
  316. def setup_vp_settings(bone_node, pb, do_after, node_tree):
  317. # bone_node.inputs["Hide"].default_value = pb.bone.hide
  318. bone_node.inputs["Custom Object Scale"].default_value = pb.custom_shape_scale_xyz
  319. bone_node.inputs["Custom Object Translation"].default_value = pb.custom_shape_translation
  320. bone_node.inputs["Custom Object Rotation"].default_value = pb.custom_shape_rotation_euler
  321. bone_node.inputs["Custom Object Scale to Bone Length"].default_value = pb.use_custom_shape_bone_size
  322. bone_node.inputs["Custom Object Wireframe"].default_value = pb.bone.show_wire
  323. bone_node.inputs["Layer Mask"].default_value = pb.bone.layers
  324. if (shape_ob := pb.custom_shape):
  325. shape_n = None
  326. for n in node_tree.nodes:
  327. if n.name == shape_ob.name:
  328. shape_n = n
  329. break
  330. else: # we make it now
  331. shape_n = node_tree.nodes.new("InputExistingGeometryObject")
  332. shape_n.name = shape_ob.name
  333. shape_n.label = shape_ob.name
  334. shape_n.inputs["Name"].default_value = shape_ob.name
  335. node_tree.links.new(shape_n.outputs["Object"], bone_node.inputs['Custom Object'])
  336. if (shape_xform_ob := pb.custom_shape_transform): # not implemented just yet
  337. shape_xform_n = None
  338. for n in node_tree.nodes:
  339. if n.name == shape_xform_ob.name:
  340. shape_xform_n = n
  341. node_tree.links.new(shape_xform_n.outputs["xForm"], bone_node.inputs['Custom Object xForm Override'])
  342. break
  343. else: # make it a task
  344. do_after.append( ("Custom Object xForm Override", bone_node.name , shape_xform_ob.name ) )
  345. # all the above should be in a function.
  346. def setup_df_settings(bone_node, pb):
  347. bone_node.inputs["Deform"] = pb.bone.use_deform
  348. # TODO: get the rest of these working
  349. # eb.envelope_distance = self.evaluate_input("Envelope Distance")
  350. # eb.envelope_weight = self.evaluate_input("Envelope Weight")
  351. # eb.use_envelope_multiply = self.evaluate_input("Envelope Multiply")
  352. # eb.head_radius = self.evaluate_input("Envelope Head Radius")
  353. # eb.tail_radius = self.evaluate_input("Envelope Tail Radius")
  354. def create_driver(in_node_name, out_node_name, armOb, finished_drivers, switches, driver_vars, fcurves, drivers, node_tree):
  355. # TODO: CLEAN this ABOMINATION
  356. print ("DRIVER: ", in_node_name, out_node_name)
  357. in_node = node_tree.nodes[ in_node_name]
  358. out_node = node_tree.nodes[out_node_name]
  359. for fc in armOb.animation_data.drivers:
  360. if (in_node.label not in fc.data_path) or ( "[\""+out_node.label+"\"]" not in fc.data_path):
  361. # print ("node not in name?: %s" % fc.data_path)
  362. continue
  363. if fc.data_path in finished_drivers:
  364. continue
  365. finished_drivers.add(fc.data_path)
  366. print ("Creating driver.... %s" % fc.data_path)
  367. keys = []
  368. for k in fc.keyframe_points:
  369. key = {}
  370. for prop in dir(k):
  371. if ("__" in prop) or ("bl_" in prop): continue
  372. #it's __name__ or bl_rna or something
  373. key[prop] = getattr(k, prop)
  374. keys.append(key)
  375. switch, inverted = False, False
  376. if (fc.evaluate(0) == 0) and (fc.evaluate(1) == 1):
  377. switch = True
  378. elif (fc.evaluate(0) == 1) and (fc.evaluate(1) == 0):
  379. switch = True; inverted = True
  380. if (fc.driver.type == 'SCRIPTED'):
  381. #print (fc.driver.expression)
  382. if not (len(fc.driver.variables) == 1 and fc.driver.expression == fc.driver.variables[0].name):
  383. switch = False
  384. if (switch):
  385. # OK, let's prepare before making the node
  386. # we want to reuse existing nodes if possible.
  387. target_string = fc.driver.variables[0].targets[0].data_path
  388. bone = target_string.split("pose.bones[\"")[1]
  389. bone = bone.split("\"]")[0]
  390. bone_node = node_tree.nodes.get(bone)
  391. if not (bone_node):
  392. raise RuntimeError("excpected to find....", bone)
  393. p_string = fc.driver.variables[0].targets[0].data_path
  394. p_string = p_string.split("[\"")[-1]; p_string = p_string.split("\"]")[0]
  395. #switch_node.inputs["Parameter"].default_value = p_string
  396. #switch_node.inputs["Parameter Index"].default_value = fc.array_index
  397. #switch_node.inputs["Invert Switch"].default_value = inverted
  398. parameter = fc.data_path
  399. # Try to find an existing node.
  400. fail = False
  401. switch_node = None
  402. for n in switches:
  403. if n.inputs[0].is_linked:
  404. if n.inputs[0].links[0].from_node != bone_node:
  405. fail = True
  406. if n.inputs[1].is_linked:
  407. if n.inputs[1].links[0].from_node != bone_node:
  408. fail = True
  409. if n.inputs[1].links[0].from_socket != bone_node.outputs.get(p_string):
  410. fail = True
  411. else:
  412. if n.inputs[1].default_value != p_string:
  413. fail = True
  414. if n.inputs[2].default_value != fc.array_index:
  415. fail = True
  416. if n.inputs[3].default_value != inverted:
  417. fail = True
  418. if not fail:
  419. switch_node = n
  420. break # found it!
  421. else:
  422. # make and connect the switch node
  423. switch_node = node_tree.nodes.new("UtilitySwitch"); switches.append(switch_node)
  424. node_tree.links.new(bone_node.outputs["xForm Out"], switch_node.inputs[0])
  425. node_tree.links.new(bone_node.outputs[p_string], switch_node.inputs[1])
  426. switch_node.inputs[2].default_value = fc.array_index
  427. switch_node.inputs[3].default_value = inverted
  428. #print (" Inverted? ", inverted, (fc.evaluate(0) == 1) and (fc.evaluate(1) == 0), switch_node.inputs[3].default_value)
  429. if not inverted:
  430. print (" --> Check this node: %s" % switch_node.name)
  431. # this may be a custom property or a normal property...
  432. # this should lead to a constraint
  433. if len(parameter.split("[\"") ) == 3:
  434. property = parameter.split(".")[-1]
  435. if (property == 'mute'): # this is mapped to the 'Enable' socket...
  436. prop_in = out_node.inputs.get('Enable')
  437. else:
  438. prop_in = out_node.inputs.get(get_pretty_name(property))
  439. if prop_in:
  440. node_tree.links.new(switch_node.outputs["Driver"], prop_in)
  441. else:
  442. print (" couldn't find: ", property, out_node.label, out_node.name)
  443. # this won't always work tho
  444. #Finally, it should be noted that we are assuming it uses the same object ...
  445. # drivers from Rigify always should use the same object, but I want to support
  446. # detecting drivers across objects.
  447. else: # we'll have to set this one up manually
  448. # Let's make the variable nodes, the Driver node, and the fCurve node.
  449. # Get the variable information
  450. if (True):
  451. var_nodes = []; num_vars = 0
  452. for num_vars, var in enumerate(fc.driver.variables):
  453. target1, target2, bone_target, bone_target2 = [None]*4
  454. var_data = {}
  455. var_data["Variable Type"] = var.type
  456. if len(var.targets) >= 1:
  457. target1 = var.targets[0]
  458. if (var_data["Variable Type"] != 'SINGLE_PROP'):
  459. bone_target = var.targets[0].bone_target
  460. else: # figure it out by the data path string.
  461. target_string = var.targets[0].data_path
  462. bone_target = target_string.split("pose.bones[\"")[1]; bone_target = bone_target.split("\"]")[0]
  463. # we also need to get the property.
  464. p_string = fc.driver.variables[0].targets[0].data_path
  465. p_string = p_string.split("[\"")[-1]; p_string = p_string.split("\"]")[0]
  466. var_data["Property"] = p_string
  467. if (var_data["Variable Type"] == 'TRANSFORMS'):
  468. transform_channel_map = {
  469. "LOC_X" : ('location', 0),
  470. "LOC_Y" : ('location', 1),
  471. "LOC_Z" : ('location', 2),
  472. "ROT_X" : ('rotation', 0),
  473. "ROT_Y" : ('rotation', 1),
  474. "ROT_Z" : ('rotation', 2),
  475. "ROT_W" : ('rotation', 3),
  476. "SCALE_X" : ('scale', 0),
  477. "SCALE_Y" : ('scale', 1),
  478. "SCALE_Z" : ('scale', 2),
  479. "SCALE_AVG" : ('scale', 3), }
  480. if (var.transform_type in transform_channel_map.keys()):
  481. var_data["Property"], var_data["Property Index"] = transform_channel_map[var.transform_type]
  482. var_data["Evaluation Space"] = var.targets[0].transform_space
  483. var_data["Rotation Mode"] = var.targets[0].rotation_mode
  484. if len(var.targets) == 2:
  485. target2 = var.targets[1]
  486. bone_target2 = var.targets[1].bone_target
  487. # check if the variable already exists in the tree.
  488. target_node1, target_node2 = None, None
  489. if (target1 and bone_target):
  490. target_node1 = node_tree.nodes[bone_target]
  491. elif (target1 and not bone_target):
  492. target_node1 = node_tree.nodes[target1]
  493. if (target2 and bone_target2):
  494. target_node2 = node_tree.nodes[bone_target2]
  495. elif (target2 and not bone_target2):
  496. target_node2 = node_tree.nodes[target2]
  497. var_node = None
  498. for n in driver_vars:
  499. fail = False
  500. if (inp := n.inputs['xForm 1']).is_linked:
  501. if inp.links[0].from_node != target_node1:
  502. fail = True
  503. if (inp := n.inputs['xForm 2']).is_linked:
  504. if inp.links[0].from_node != target_node2:
  505. fail = True
  506. #
  507. if n.inputs[0].default_value != var_data["Variable Type"]:
  508. fail = True
  509. if n.inputs[1].default_value != var_data["Property"]:
  510. fail = True
  511. try:
  512. if n.inputs[2].default_value != var_data["Property Index"]:
  513. fail = True
  514. if n.inputs[3].default_value != var_data["Evaluation Space"]:
  515. fail = True
  516. if n.inputs[4].default_value != var_data["Rotation Mode"]:
  517. fail = True
  518. except KeyError:
  519. pass # this is a SCRIPTED node it seems
  520. if not fail:
  521. var_node = n
  522. prWhite("Variable Node Found %s!" % var_node )
  523. break # found it!
  524. else:
  525. var_node = node_tree.nodes.new("UtilityDriverVariable"); driver_vars.append(var_node)
  526. prRed("Creating Node: %s" % var_node.name)
  527. for key, value in var_data.items():
  528. var_node.inputs[key].default_value = value
  529. if (target1 and bone_target):
  530. node_tree.links.new(node_tree.nodes[bone_target].outputs['xForm Out'], var_node.inputs['xForm 1'])
  531. elif (target1 and not bone_target):
  532. node_tree.links.new(node_tree.nodes[target1].outputs['xForm Out'], var_node.inputs['xForm 1'])
  533. if (target2 and bone_target2):
  534. node_tree.links.new(node_tree.nodes[bone_target2].outputs['xForm Out'], var_node.inputs['xForm 2'])
  535. elif (target2 and not bone_target2):
  536. node_tree.links.new(node_tree.nodes[target2].outputs['xForm Out'], var_node.inputs['xForm 2'])
  537. var_nodes.append(var_node)
  538. num_vars+=1 # so the len(num_vars) will be correct
  539. # get the keyframes from the driver fCurve
  540. keys = {}
  541. from mathutils import Vector
  542. if len(fc.keyframe_points) > 0:
  543. # TODO: make this do more than co_ui
  544. for i, k in enumerate(fc.keyframe_points):
  545. keys[i] = {'co_ui':k.co_ui}
  546. # print (fc.data_path)
  547. # print (len(fc.keyframe_points))
  548. # raise NotImplementedError("Not needed for first milestone")
  549. else:
  550. # fc_ob = fCurve_node.fake_fcurve_ob
  551. # node_fc = fc_ob.animation_data.action.fcurves[0]
  552. # fc.keyframe_points.add(2)
  553. if ((len(fc.modifiers) == 0) or ((fc.evaluate(0) == 0) and (fc.evaluate(1) == 1))):
  554. keys[0] = {'co_ui':Vector((0, 0))}
  555. keys[1] = {'co_ui':Vector((1, 1))}
  556. elif (fc.evaluate(0) == 1) and (fc.evaluate(1) == 0):
  557. keys[0] = {'co_ui':Vector((0, 1))}
  558. keys[1] = {'co_ui':Vector((1, 0))}
  559. else:
  560. print ("Could not get keys!")
  561. # TODO find out why this happens
  562. # I HAVE NO IDEA
  563. pass
  564. # elif (fc.evaluate(0) == 1) and (fc.evaluate(1) == 0):
  565. # kf0 = fc.keyframe_points[0]; kf0.co_ui = (0, 1)
  566. # kf1 = fc.keyframe_points[1]; kf1.co_ui = (1, 0)
  567. # now get the fCurve
  568. fCurve_node = None
  569. for n in fcurves:
  570. fc_ob = n.fake_fcurve_ob; node_fc = fc_ob.animation_data.action.fcurves[0]
  571. node_keys = {}
  572. for i, k in enumerate(node_fc.keyframe_points):
  573. node_keys[i] = {'co_ui':k.co_ui}
  574. # now let's see if they are the same:
  575. if (keys != node_keys):
  576. continue
  577. fCurve_node = n
  578. break
  579. else:
  580. fCurve_node = node_tree.nodes.new("UtilityFCurve")
  581. fc_ob = fCurve_node.fake_fcurve_ob
  582. node_fc = fc_ob.animation_data.action.fcurves[0]
  583. fcurves.append(fCurve_node)
  584. while(node_fc.keyframe_points): # clear it, it has a default FC
  585. node_fc.keyframe_points.remove(node_fc.keyframe_points[0], fast=True)
  586. node_fc.update()
  587. node_fc.keyframe_points.add(len(keys))
  588. for k, v in keys.items():
  589. node_fc.keyframe_points[k].co_ui = v['co_ui']
  590. # todo eventually the other dict elements ofc
  591. # NOW the driver itself
  592. driver_node = None
  593. # checc for it...
  594. driver_node = node_tree.nodes.new("UtilityDriver")
  595. driver_node.inputs["Driver Type"].default_value = fc.driver.type
  596. driver_node.inputs["Expression"].default_value = fc.driver.expression.replace ('var', 'a')
  597. # HACK, fix the above with a more robust solution
  598. node_tree.links.new(fCurve_node.outputs[0], driver_node.inputs['fCurve'])
  599. for i, var_node in zip(range(num_vars), var_nodes):
  600. # TODO TODO
  601. bpy.ops.mantis.driver_node_add_variable({'node':driver_node})
  602. # This causes an error when you run it from the console! DO NOT leave this
  603. node_tree.links.new(var_node.outputs[0], driver_node.inputs[-1])
  604. # HACK duplicated code from earlier...
  605. parameter = fc.data_path
  606. prWhite( "parameter: %s" % parameter)
  607. if len(parameter.split("[\"") ) == 3:
  608. property = parameter.split(".")[-1]
  609. if (property == 'mute'): # this is mapped to the 'Enable' socket...
  610. prop_in = out_node.inputs.get('Enable')
  611. else:
  612. prop_in = out_node.inputs.get(get_pretty_name(property))
  613. if not prop_in:
  614. # try one last thing:
  615. property = parameter.split("targets[")[-1]
  616. target_index = int(property[0])
  617. property = "targets[" + property # HACK lol
  618. # get the property by index...
  619. prop_in = out_node.inputs[target_index*2+6+1] # this is the weight, not the target
  620. if prop_in:
  621. prRed (" found: %s, %s, %s" % (property, out_node.label, out_node.name))
  622. node_tree.links.new(driver_node.outputs["Driver"], prop_in)
  623. else:
  624. prRed (" couldn't find: %s, %s, %s" % (property, out_node.label, out_node.name))
  625. else:
  626. prWhite( "parameter: %s" % parameter)
  627. prRed (" couldn't find: ", property, out_node.label, out_node.name)
  628. def do_generate_armature(context, node_tree):
  629. from time import time
  630. start = time()
  631. node_tree.do_live_update = False
  632. armOb = bpy.context.active_object
  633. #This will generate it in the current node tree and OVERWRITE!
  634. node_tree.nodes.clear()
  635. world_in = node_tree.nodes.new("xFormRootNode")
  636. armature = node_tree.nodes.new("xFormArmatureNode")
  637. world_in.location = (-200, 0)
  638. armature.location = ( 0, 0)
  639. do_after = []
  640. for root in armOb.data.bones:
  641. if root.parent is None:
  642. iter_start= time()
  643. lines = []
  644. lines = walk_edit_bone(armOb, root)
  645. lines.append([]) # add the root itself HACK ugly
  646. milestone=time()
  647. prPurple("got the bone paths", time() - milestone); milestone=time()
  648. # create links:
  649. node_tree.links.new(world_in.outputs["World Out"], armature.inputs['Relationship'])
  650. # set up some properties:
  651. armature.inputs["Name"].default_value = armOb.name
  652. armature.name = armOb.name; armature.label = armOb.name
  653. # for getting parent nodes
  654. bone_inherit_node = {}
  655. # do short lines first bc longer lines rely on their results
  656. sort_by_len = lambda elem : len(elem)
  657. lines.sort(key=sort_by_len)
  658. for bone_path in lines:
  659. prGreen("for bone_path in lines", time() - milestone); milestone=time()
  660. # first go through the bone path and find relevant information
  661. bone = get_bone_from_path(root, bone_path)
  662. bone_node = node_tree.nodes.new("xFormBoneNode")
  663. bone_node.inputs["Name"].default_value = bone.name
  664. bone_node.name, bone_node.label = bone.name, bone.name
  665. matrix = bone.matrix_local.copy()
  666. bone_node.inputs["Matrix"].default_value = [
  667. matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3],
  668. matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3],
  669. matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3], # last element is bone length, for mantis
  670. matrix[3][0], matrix[3][1], matrix[3][2], bone.length ] #matrix[3][3], ]
  671. x_distance, y_distance = 0, 0
  672. pb = armOb.pose.bones[bone.name]
  673. possible_parent_nodes = []
  674. if bone_path: # not a root
  675. x_distance, y_distance = len(bone_path), bone_path[-1]
  676. possible_parent_nodes = bone_inherit_node.get(bone.parent.name)
  677. # Set the parent
  678. parent_node = None
  679. if not (possible_parent_nodes):
  680. parent_node = create_inheritance_node(pb, bone.parent.name, bone_inherit_node, node_tree)
  681. else:
  682. for ppn in possible_parent_nodes:
  683. # check if it has the right connected, inherit scale, inherit rotation
  684. if ppn.inputs["Connected"].default_value != pb.bone.use_connect:
  685. continue
  686. if ppn.inputs["Inherit Scale"].default_value != pb.bone.inherit_scale:
  687. continue
  688. if ppn.inputs["Inherit Rotation"].default_value != pb.bone.use_inherit_rotation:
  689. continue
  690. parent_node = ppn; break
  691. else:
  692. parent_node = create_inheritance_node(pb, bone.parent.name, bone_inherit_node, node_tree)
  693. print("Got parent node", time() - milestone); milestone=time()
  694. if parent_node is None:
  695. raise RuntimeError("No parent node?")
  696. else: # This is a root
  697. prOrange("else this is a root",time() - milestone); milestone=time()
  698. parent_node = node_tree.nodes.new("linkInherit")
  699. # root_child = node_tree.nodes.new("linkInherit")
  700. node_tree.links.new(parent_node.outputs["Inheritance"], bone_node.inputs['Relationship'])
  701. # node_tree.links.new(bone_node.outputs["xForm Out"], root_child.inputs['Parent'])
  702. node_tree.links.new(armature.outputs["xForm Out"], parent_node.inputs['Parent'])
  703. parent_node.inputs["Inherit Rotation"].default_value = True
  704. parent_node.location = (200, 0)
  705. bone_node.location = (400, 0)
  706. # root_child.location = (600, 0)
  707. # bone_inherit_node[bone_node.name]=[root_child]
  708. setup_custom_properties(bone_node, pb)
  709. setup_ik_settings(bone_node, pb)
  710. setup_vp_settings(bone_node, pb, do_after, node_tree)
  711. setup_df_settings(bone_node, pb)
  712. #
  713. for c in pb.constraints:
  714. prWhite("constraint %s for %s" % (c.name, pb.name), time() - milestone); milestone=time()
  715. # make relationship nodes and set up links...
  716. if ( c_node := create_relationship_node_for_constraint(node_tree, c)):
  717. c_node.label = c.name
  718. # this node definitely has a parent inherit node.
  719. c_node.location = parent_node.location; c_node.location.x += 200
  720. try:
  721. node_tree.links.new(parent_node.outputs["Inheritance"], c_node.inputs['Input Relationship'])
  722. except KeyError: # not a inherit node anymore
  723. node_tree.links.new(parent_node.outputs["Output Relationship"], c_node.inputs['Input Relationship'])
  724. parent_node = c_node
  725. #Target Tasks:
  726. if (hasattr(c, "target") and not hasattr(c, "subtarget")):
  727. do_after.append( ("Object Target", c_node.name , c.target.name ) )
  728. if (hasattr(c, "subtarget")):
  729. if c.target and c.subtarget: # this node has a target, find the node associated with it...
  730. do_after.append( ("Target", c_node.name , c.subtarget ) )
  731. else:
  732. do_after.append( ("Object Target", c_node.name , c.target.name ) )
  733. if (hasattr(c, "pole_subtarget")):
  734. if c.pole_target and c.pole_subtarget: # this node has a pole target, find the node associated with it...
  735. do_after.append( ("Pole Target", c_node.name , c.pole_subtarget ) )
  736. fill_parameters(c_node, c)
  737. if (hasattr(c, "targets")): # Armature Modifier, annoying.
  738. for i in range(len(c.targets)):
  739. if (c.targets[i].subtarget):
  740. do_after.append( ("Target."+str(i).zfill(3), c_node.name , c.targets[i].subtarget ) )
  741. # Driver Tasks
  742. if armOb.animation_data:
  743. for fc in armOb.animation_data.drivers:
  744. pb_string = fc.data_path.split("[\"")[1]; pb_string = pb_string.split("\"]")[0]
  745. try:
  746. c_string = fc.data_path.split("[\"")[2]; c_string = c_string.split("\"]")[0]
  747. except IndexError:
  748. print ("Find out what causes this: %s" % c_string)
  749. if pb.name == pb_string and c.name == c_string:
  750. do_after.append ( ("driver", bone_node.name, c_node.name) )
  751. try:
  752. node_tree.links.new(parent_node.outputs["Inheritance"], bone_node.inputs['Relationship'])
  753. except KeyError: # may have changed, see above
  754. node_tree.links.new(parent_node.outputs["Output Relationship"], bone_node.inputs['Relationship'])
  755. bone_node.location = (400 + parent_node.location.x, -200*y_distance + parent_node.location.y)
  756. prPurple("iteration: ", time() - iter_start)
  757. finished_drivers = set()
  758. switches, driver_vars, fcurves, drivers = [],[],[],[]
  759. # Now do the tasks.
  760. for (task, in_node_name, out_node_name) in do_after:
  761. prOrange(task, in_node_name, out_node_name)
  762. prPurple(len(node_tree.nodes))
  763. if task in ['Object Target']:
  764. in_node = node_tree.nodes[ in_node_name ]
  765. out_node= node_tree.nodes.new("InputExistingGeometryObject")
  766. out_node.inputs["Name"].default_value=out_node_name
  767. node_tree.links.new(out_node.outputs["Object"], in_node.inputs["Target"])
  768. if task in ['Target', 'Pole Target']:
  769. in_node = node_tree.nodes[ in_node_name ]
  770. out_node = node_tree.nodes[ out_node_name ]
  771. #
  772. node_tree.links.new(out_node.outputs["xForm Out"], in_node.inputs[task])
  773. elif (task[:6] == 'Target'):
  774. in_node = node_tree.nodes[ in_node_name ]
  775. out_node = node_tree.nodes[ out_node_name ]
  776. #
  777. node_tree.links.new(out_node.outputs["xForm Out"], in_node.inputs[task])
  778. elif task in ["Custom Object xForm Override"]:
  779. shape_xform_n = None
  780. for n in node_tree.nodes:
  781. if n.name == out_node_name:
  782. shape_xform_n = n
  783. node_tree.links.new(shape_xform_n.outputs["xForm"], node_tree.nodes[in_node_name].inputs['Custom Object xForm Override'])
  784. break
  785. else: # make it a task
  786. prRed("Cannot set custom object transform override for %s to %s" % (in_node_name, out_node_name))
  787. elif task in ["driver"]:
  788. create_driver(in_node_name, out_node_name, armOb, finished_drivers, switches, driver_vars, fcurves, drivers, node_tree)
  789. # annoyingly, Rigify uses f-modifiers to setup its fcurves
  790. # I do not intend to support fcurve modifiers in Mantis at this time
  791. for node in node_tree.nodes:
  792. if (node == world_in):
  793. continue
  794. node.select = False
  795. node_tree.nodes.active = world_in
  796. prGreen("Finished generating %d nodes in %f seconds." % (len(node_tree.nodes), time() - start))
  797. #bpy.ops.node.cleanup()
  798. node_tree.do_live_update = True
  799. class CreateMantisTree(Operator):
  800. """Create Mantis Tree From Selected"""
  801. bl_idname = "mantis.create_tree"
  802. bl_label = "Create Mantis Tree"
  803. @classmethod
  804. def poll(cls, context):
  805. return (mantis_poll_op(context))
  806. def execute(self, context):
  807. space = context.space_data
  808. path = space.path
  809. node_tree = space.path[len(path)-1].node_tree
  810. do_profile=False
  811. import cProfile
  812. from os import environ
  813. print (environ.get("DOPROFILE"))
  814. if environ.get("DOPROFILE"):
  815. do_profile=True
  816. if do_profile:
  817. cProfile.runctx("do_generate_armature(context, node_tree)", None, locals())
  818. else:
  819. do_generate_armature(context, node_tree)
  820. return {"FINISHED"}
  821. return {"FINISHED"}