__init__.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. from . import ( ops_nodegroup,
  2. base_definitions,
  3. socket_definitions,
  4. link_definitions,
  5. xForm_definitions,
  6. misc_nodes_ui,
  7. primitives_definitions,
  8. deformer_definitions,
  9. math_definitions,
  10. i_o,
  11. schema_definitions,
  12. )
  13. from .ops_generate_tree import GenerateMantisTree
  14. from .utilities import prRed
  15. MANTIS_VERSION_MAJOR=0
  16. MANTIS_VERSION_MINOR=11
  17. MANTIS_VERSION_SUB=1
  18. classLists = [module.TellClasses() for module in [
  19. link_definitions,
  20. xForm_definitions,
  21. misc_nodes_ui,
  22. socket_definitions,
  23. ops_nodegroup,
  24. primitives_definitions,
  25. deformer_definitions,
  26. math_definitions,
  27. i_o,
  28. schema_definitions,
  29. base_definitions,
  30. ]]
  31. classLists.append( [GenerateMantisTree] )
  32. #
  33. classes = []
  34. while (classLists):
  35. classes.extend(classLists.pop())
  36. interface_classes = []
  37. from os import environ
  38. if environ.get("ENABLEVIS"):
  39. from .visualize import MantisVisualizeNode, MantisVisualizeOutput, MantisVisualizeTree
  40. classes.extend([MantisVisualizeTree, MantisVisualizeNode, MantisVisualizeOutput, ])
  41. import nodeitems_utils
  42. from nodeitems_utils import NodeCategory, NodeItem
  43. class MantisNodeCategory(NodeCategory):
  44. @classmethod
  45. def poll(cls, context):
  46. return (context.space_data.tree_type in ['MantisTree', 'SchemaTree'])
  47. class SchemaNodeCategory(NodeCategory):
  48. @classmethod
  49. def poll(cls, context):
  50. return (context.space_data.path[len(context.space_data.path)-1].node_tree.bl_idname == 'SchemaTree')
  51. class MantisGroupCategory(NodeCategory):
  52. @classmethod
  53. def poll(cls, context):
  54. return (context.space_data.path[len(context.space_data.path)-1].node_tree.bl_idname in ['MantisTree'] and len(context.space_data.path)>1)
  55. input_category=[
  56. NodeItem("InputFloatNode"),
  57. NodeItem("InputVectorNode"),
  58. NodeItem("InputBooleanNode"),
  59. NodeItem("InputStringNode"),
  60. NodeItem("InputIntNode"),
  61. NodeItem("InputMatrixNode"),
  62. NodeItem("InputExistingGeometryObject"),
  63. NodeItem("InputExistingGeometryData"),
  64. ]
  65. link_transform_category = [
  66. NodeItem("LinkCopyLocation"),
  67. NodeItem("LinkCopyRotation"),
  68. NodeItem("LinkCopyScale"),
  69. NodeItem("LinkCopyTransforms"),
  70. NodeItem("LinkLimitLocation"),
  71. NodeItem("LinkLimitScale"),
  72. NodeItem("LinkLimitRotation"),
  73. NodeItem("LinkLimitDistance"),
  74. NodeItem("LinkTransformation"),
  75. ]
  76. link_tracking_category = [
  77. NodeItem("LinkInverseKinematics"),
  78. NodeItem("LinkSplineIK"),
  79. NodeItem("LinkStretchTo"),
  80. NodeItem("LinkDampedTrack"),
  81. NodeItem("LinkLockedTrack"),
  82. NodeItem("LinkTrackTo"),
  83. ]
  84. link_relationship_category = [
  85. NodeItem("linkInherit"),
  86. NodeItem("LinkInheritConstraint"),
  87. NodeItem("LinkArmature"),
  88. ]
  89. deformer_category=[NodeItem(cls.bl_idname) for cls in deformer_definitions.TellClasses()]
  90. xForm_category = [
  91. NodeItem("xFormGeometryObject"),
  92. NodeItem("xFormBoneNode"),
  93. NodeItem("xFormArmatureNode"),
  94. NodeItem("xFormObjectInstance"),
  95. NodeItem("xFormCurvePin"),
  96. ]
  97. driver_category = [
  98. NodeItem("LinkDrivenParameter"),
  99. NodeItem("UtilityFCurve"),
  100. NodeItem("UtilityBoneProperties"),
  101. NodeItem("UtilityDriverVariable"),
  102. NodeItem("UtilitySwitch"),
  103. NodeItem("UtilityDriver"),
  104. NodeItem("UtilityKeyframe"),
  105. ]
  106. geometry_category = [
  107. NodeItem("GeometryCirclePrimitive"),
  108. ]
  109. utility_category = [
  110. NodeItem("MathStaticInt"),
  111. NodeItem("MathStaticFloat"),
  112. NodeItem("MathStaticVector"),
  113. NodeItem("UtilityCatStrings"),
  114. NodeItem("UtilityGeometryOfXForm"),
  115. NodeItem("UtilityNameOfXForm"),
  116. NodeItem("UtilityCombineThreeBool"),
  117. NodeItem("UtilityCombineVector"),
  118. NodeItem("UtilityIntToString"),
  119. NodeItem("UtilityArrayGet"),
  120. NodeItem("UtilityArrayLength"),
  121. NodeItem("UtilityChoose"),
  122. NodeItem("UtilityCompare"),
  123. NodeItem("UtilityPrint"),
  124. NodeItem("UtilitySeparateVector"),
  125. NodeItem("UtilityGetNearestFactorOnCurve"),
  126. NodeItem("UtilityKDChoosePoint"),
  127. NodeItem("UtilityKDChooseXForm"),
  128. ]
  129. matrix_category = [
  130. NodeItem("UtilityMetaRig"),
  131. NodeItem("UtilityMatrixFromCurve"),
  132. NodeItem("UtilityMatricesFromCurve"),
  133. NodeItem("UtilityNumberOfCurveSegments"),
  134. NodeItem("UtilityMatrixFromCurveSegment"),
  135. NodeItem("UtilityPointFromCurve"),
  136. NodeItem("UtilityGetCurvePoint"),
  137. NodeItem("UtilityPointFromBoneMatrix"),
  138. NodeItem("UtilitySetBoneLength"),
  139. NodeItem("UtilityGetBoneLength"),
  140. NodeItem("UtilityBoneMatrixHeadTailFlip"),
  141. NodeItem("UtilityMatrixSetLocation"),
  142. NodeItem("UtilityMatrixFromXForm"),
  143. NodeItem("UtilityAxesFromMatrix"),
  144. NodeItem("UtilityMatrixTransform"),
  145. NodeItem("UtilityMatrixInvert"),
  146. NodeItem("UtilityMatrixCompose"),
  147. NodeItem("UtilityMatrixAlignRoll"),
  148. NodeItem("UtilityTransformationMatrix"),
  149. NodeItem("UtilitySetBoneMatrixTail"),
  150. ]
  151. groups_category = [
  152. NodeItem("MantisNodeGroup"),
  153. NodeItem("MantisSchemaGroup"),
  154. ]
  155. group_interface_category = [
  156. NodeItem("NodeGroupInput"),
  157. NodeItem("NodeGroupOutput"),
  158. ]
  159. node_categories = [
  160. # identifier, label, items list
  161. MantisNodeCategory('INPUT', "Input", items=input_category),
  162. MantisNodeCategory('LINK_TRANSFORM', "Link (Transform)", items=link_transform_category),
  163. MantisNodeCategory('LINK_TRACKING', "Link (Tracking)", items=link_tracking_category),
  164. MantisNodeCategory('LINK_RELATIONSHIP', "Link (Inheritance)", items=link_relationship_category),
  165. MantisNodeCategory('DEFORMER', "Deformer", items=deformer_category),
  166. MantisNodeCategory('XFORM', "Transform", items=xForm_category),
  167. MantisNodeCategory('DRIVER', "Driver", items=driver_category),
  168. MantisNodeCategory('GEOMETRY', "Geometry", items =geometry_category),
  169. MantisNodeCategory('UTILITIES', "Utility", items=utility_category),
  170. MantisNodeCategory('MATRIX', "Matrix", items=matrix_category),
  171. MantisNodeCategory('GROUPS', "Groups", items=groups_category),
  172. MantisGroupCategory('GROUP_INTERFACE', "Group In/Out", items=group_interface_category),
  173. ]
  174. schema_category=[NodeItem(cls.bl_idname) for cls in schema_definitions.TellClasses()]
  175. # DEPRECATION:
  176. schema_category.pop() # remove the last item, SchemaArrayInputGet
  177. # TODO: make a nicer, cleaner way of doing this. will refactor node categories eventually.
  178. schema_categories = [
  179. SchemaNodeCategory('SCHEMA_SCHEMA', "Schema", items=schema_category),
  180. ]
  181. import bpy
  182. def init_keymaps():
  183. kc = bpy.context.window_manager.keyconfigs.addon
  184. km = kc.keymaps.new(name="Node Generic", space_type='NODE_EDITOR')
  185. kmi = [
  186. # Normal operation
  187. km.keymap_items.new("mantis.group_nodes", 'G', 'PRESS', ctrl=True),
  188. km.keymap_items.new("mantis.edit_group", 'TAB', 'PRESS'),
  189. km.keymap_items.new("mantis.execute_node_tree", 'E', 'PRESS'),
  190. km.keymap_items.new("mantis.mute_node", 'M', 'PRESS'),
  191. km.keymap_items.new("mantis.nodes_cleanup", "C", 'PRESS', shift=True,),
  192. # Testing
  193. km.keymap_items.new("mantis.query_sockets", 'Q', 'PRESS'),
  194. km.keymap_items.new("mantis.test_operator", 'T', 'PRESS'),
  195. km.keymap_items.new("mantis.visualize_output", 'V', 'PRESS'),
  196. # Saving, Loading, Reloading, etc.
  197. km.keymap_items.new("mantis.export_save_choose", "S", 'PRESS', alt=True,),
  198. km.keymap_items.new("mantis.export_save_as", "S", 'PRESS', alt=True, shift=True),
  199. km.keymap_items.new("mantis.reload_tree", "R", 'PRESS', alt=True,),
  200. km.keymap_items.new("mantis.import_tree", "O", 'PRESS', ctrl=True,),
  201. ]
  202. return km, kmi
  203. addon_keymaps = []
  204. # handlers! these have to be persistent
  205. from bpy.app.handlers import persistent
  206. from .base_definitions import hash_tree
  207. @persistent
  208. def update_handler(scene):
  209. # return
  210. context=bpy.context
  211. if context.space_data:
  212. if not hasattr(context.space_data, "path"):
  213. return
  214. trees = [p.node_tree for p in context.space_data.path]
  215. if not trees: return
  216. if (node_tree := trees[0]).bl_idname in ['MantisTree']:
  217. if node_tree.is_exporting:
  218. return
  219. if node_tree.prevent_next_exec : pass
  220. elif node_tree.do_live_update and not (node_tree.is_executing):
  221. node_tree.update_tree(context)
  222. @persistent
  223. def execute_handler(scene):
  224. context = bpy.context
  225. if context.space_data:
  226. if not hasattr(context.space_data, "path"):
  227. return
  228. trees = [p.node_tree for p in context.space_data.path]
  229. if not trees: return
  230. if (node_tree := trees[0]).bl_idname in ['MantisTree']:
  231. # check here instead of in execute_tree because these values can be
  232. # modified at weird times and checking from the handler is more consistent
  233. if ( node_tree.tree_valid) and ( node_tree.do_live_update ):
  234. node_tree.execute_tree(context)
  235. node_tree.tree_valid=False
  236. versioning_node_tasks = [
  237. #relevant bl_idnames # task
  238. #(['LinkTransformation'], transformation_constraint_radians_to_degrees)
  239. ]
  240. def do_version_update(node_tree):
  241. from .base_definitions import NODES_REMOVED, SOCKETS_REMOVED, SOCKETS_RENAMED, SOCKETS_ADDED
  242. for n in node_tree.nodes:
  243. rename_jobs = []
  244. if n.bl_idname in NODES_REMOVED:
  245. print(f"INFO: removing node {n.name} of type {n.bl_idname} because it has been deprecated.")
  246. n.inputs.remove(socket)
  247. continue
  248. for i, socket in enumerate(n.inputs.values()):
  249. if (n.bl_idname, socket.identifier) in SOCKETS_REMOVED:
  250. print(f"INFO: removing socket {socket.identifier} of node {n.name} of type {n.bl_idname} because it has been deprecated.")
  251. n.inputs.remove(socket)
  252. for old_class, old_bl_idname, old_name, new_bl_idname, new_name, multi in SOCKETS_RENAMED:
  253. if (n.bl_idname == old_class and socket.bl_idname == old_bl_idname and socket.name == old_name):
  254. rename_jobs.append((socket, i, new_bl_idname, new_name, multi))
  255. for i, socket in enumerate(n.outputs.values()):
  256. if (n.bl_idname, socket.identifier) in SOCKETS_REMOVED:
  257. print(f"INFO: removing socket {socket.identifier} of node {n.name} of type {n.bl_idname} because it has been deprecated.")
  258. n.outputs.remove(socket)
  259. for old_class, old_bl_idname, old_name, new_bl_idname, new_name, multi in SOCKETS_RENAMED:
  260. if (n.bl_idname == old_class and socket.bl_idname == old_bl_idname and socket.name == old_name):
  261. rename_jobs.append((socket, i, new_bl_idname, new_name, multi))
  262. for bl_idname, in_out, socket_type, socket_name, index, use_multi_input, default_val in SOCKETS_ADDED:
  263. if n.bl_idname != bl_idname:
  264. continue
  265. if in_out == 'INPUT' and n.inputs.get(socket_name) is None:
  266. print(f"INFO: adding socket \"{socket_name}\" of type {socket_type} to node {n.name} of type {n.bl_idname}.")
  267. s = n.inputs.new(socket_type, socket_name, use_multi_input=use_multi_input)
  268. s.default_value = default_val
  269. n.inputs.move(len(n.inputs)-1, index)
  270. socket_map = None
  271. if rename_jobs:
  272. from .utilities import get_socket_maps
  273. socket_maps = get_socket_maps(n)
  274. for socket, socket_index, new_bl_idname, new_name, multi in rename_jobs:
  275. old_id = socket.identifier
  276. print (f"Renaming socket {socket.identifier} to {new_name} in node {n.name}")
  277. from .utilities import do_relink
  278. if socket.is_output:
  279. index = 1
  280. in_out = "OUTPUT"
  281. n.outputs.remove(socket)
  282. s = n.outputs.new(new_bl_idname, new_name, identifier=new_name, use_multi_input=multi)
  283. n.outputs.move(len(n.outputs)-1, socket_index)
  284. socket_map = socket_maps[1]
  285. else:
  286. index = 0
  287. in_out = "INPUT"
  288. n.inputs.remove(socket)
  289. s = n.inputs.new(new_bl_idname, new_name, identifier=new_name, use_multi_input=multi)
  290. n.inputs.move(len(n.inputs)-1, socket_index)
  291. socket_map = socket_maps[0]
  292. socket_map[new_name] = socket_map[old_id]; del socket_map[old_id]
  293. do_relink(n, s, socket_map)
  294. for bl_idname, task in versioning_node_tasks:
  295. if n.bl_idname in bl_idname: task(n)
  296. # increment the version at the end
  297. node_tree.mantis_version[0] = MANTIS_VERSION_MAJOR
  298. node_tree.mantis_version[1] = MANTIS_VERSION_MINOR
  299. node_tree.mantis_version[2] = MANTIS_VERSION_SUB
  300. @persistent
  301. def version_update_handler(filename):
  302. for node_tree in bpy.data.node_groups: # ensure it can update again after file load.
  303. if node_tree.bl_idname in ["MantisTree", "SchemaTree"]:
  304. node_tree.is_exporting=False; node_tree.is_executing=False
  305. for node_tree in bpy.data.node_groups:
  306. if node_tree.bl_idname in ["MantisTree", "SchemaTree"]:
  307. if (node_tree.mantis_version[0] < MANTIS_VERSION_MAJOR) or \
  308. (node_tree.mantis_version[1] < MANTIS_VERSION_MINOR) or \
  309. (node_tree.mantis_version[2] < MANTIS_VERSION_SUB):
  310. print (f"Updating tree {node_tree.name} to {MANTIS_VERSION_MAJOR}.{MANTIS_VERSION_MINOR}.{MANTIS_VERSION_SUB}")
  311. do_version_update(node_tree)
  312. # I'll need to do some fiddling here when it comes time to try
  313. # and make rig definitions animatable.
  314. @persistent
  315. def on_animation_playback_pre_handler(scene,depsgraph):
  316. for t in bpy.data.node_groups:
  317. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  318. t.is_executing = True
  319. @persistent
  320. def on_animation_playback_post_handler(scene,depsgraph):
  321. for t in bpy.data.node_groups:
  322. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  323. t.is_executing = False
  324. @persistent
  325. def on_undo_post_handler(scene): # the undo will trigger a depsgraph update
  326. for t in bpy.data.node_groups: # so we enable prevent_next_exec.
  327. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  328. t.prevent_next_exec = True
  329. t.hash=""
  330. # set the tree to invalid to trigger a tree update
  331. # since the context data is wiped by an undo.
  332. def register():
  333. from bpy.utils import register_class
  334. for cls in classes:
  335. try:
  336. register_class(cls)
  337. except RuntimeError as e:
  338. prRed(f"Registration error for class: {cls.__name__}")
  339. raise e
  340. nodeitems_utils.register_node_categories('MantisNodeCategories', node_categories)
  341. nodeitems_utils.register_node_categories('SchemaNodeCategories', schema_categories)
  342. km, kmi = init_keymaps()
  343. for k in kmi:
  344. k.active = True
  345. addon_keymaps.append((km, k))
  346. # add the handlers
  347. bpy.app.handlers.depsgraph_update_pre.insert(0, update_handler)
  348. bpy.app.handlers.depsgraph_update_post.insert(0, execute_handler)
  349. bpy.app.handlers.load_post.insert(0, version_update_handler)
  350. bpy.app.handlers.animation_playback_pre.insert(0, on_animation_playback_pre_handler)
  351. bpy.app.handlers.animation_playback_post.insert(0, on_animation_playback_post_handler)
  352. bpy.app.handlers.undo_post.insert(0, on_undo_post_handler)
  353. # I'm adding mine in first to ensure other addons don't mess up mine
  354. # but I am a good citizen! so my addon won't mess up yours! probably...
  355. def unregister():
  356. for tree in bpy.data.node_groups: # ensure it doesn't try to update while quitting.
  357. if tree.bl_idname in ['MantisTree, SchemaTree']:
  358. tree.is_exporting=True; tree.is_executing=True
  359. nodeitems_utils.unregister_node_categories('MantisNodeCategories')
  360. nodeitems_utils.unregister_node_categories('SchemaNodeCategories')
  361. from bpy.utils import unregister_class
  362. for cls in reversed(classes):
  363. unregister_class(cls)
  364. for km, kmi in addon_keymaps:
  365. km.keymap_items.remove(kmi)
  366. addon_keymaps.clear()