__init__.py 14 KB

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