__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. schema_nodes_ui,
  12. menu_classes,
  13. )
  14. from .ops_generate_tree import GenerateMantisTree
  15. from .utilities import i_o
  16. from .utilities.utilities import prRed
  17. from .base_definitions import (MANTIS_VERSION_MAJOR,
  18. MANTIS_VERSION_MINOR,
  19. MANTIS_VERSION_SUB)
  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 .preferences import MantisPreferences
  42. classes.append(MantisPreferences)
  43. from os import environ
  44. if environ.get("ENABLEVIS"):
  45. from .dev_helpers.visualize import MantisVisualizeNode, MantisVisualizeOutput, MantisVisualizeTree
  46. classes.extend([MantisVisualizeTree, MantisVisualizeNode, MantisVisualizeOutput, ])
  47. DOERROR = False
  48. if environ.get("DOERROR"):
  49. DOERROR = True
  50. import nodeitems_utils
  51. from nodeitems_utils import NodeCategory, NodeItem
  52. class MantisNodeCategory(NodeCategory):
  53. @classmethod
  54. def poll(cls, context):
  55. return (context.space_data.tree_type in ['MantisTree', 'SchemaTree'])
  56. class SchemaNodeCategory(NodeCategory):
  57. @classmethod
  58. def poll(cls, context):
  59. return (context.space_data.path[len(context.space_data.path)-1].node_tree.bl_idname == 'SchemaTree')
  60. class MantisGroupCategory(NodeCategory):
  61. @classmethod
  62. def poll(cls, context):
  63. return (context.space_data.path[len(context.space_data.path)-1].node_tree.bl_idname in ['MantisTree'] and len(context.space_data.path)>1)
  64. input_category=[
  65. NodeItem("InputFloatNode"),
  66. NodeItem("InputVectorNode"),
  67. NodeItem("InputBooleanNode"),
  68. NodeItem("InputBooleanThreeTupleNode"),
  69. NodeItem("InputStringNode"),
  70. NodeItem("InputIntNode"),
  71. NodeItem("InputMatrixNode"),
  72. NodeItem("InputWidget"),
  73. NodeItem("InputExistingGeometryObject"),
  74. NodeItem("xFormGetBone"),
  75. NodeItem("InputExistingGeometryData"),
  76. NodeItem("UtilityDeclareCollections"),
  77. NodeItem("InputThemeBoneColorSets"),
  78. NodeItem("InputColorSetPallete"),
  79. ]
  80. link_transform_category = [
  81. NodeItem("LinkCopyLocation"),
  82. NodeItem("LinkCopyRotation"),
  83. NodeItem("LinkCopyScale"),
  84. NodeItem("LinkCopyTransforms"),
  85. NodeItem("LinkLimitLocation"),
  86. NodeItem("LinkLimitScale"),
  87. NodeItem("LinkLimitRotation"),
  88. NodeItem("LinkLimitDistance"),
  89. NodeItem("LinkTransformation"),
  90. NodeItem("LinkGeometryAttribute"),
  91. NodeItem("LinkFloor"),
  92. ]
  93. link_tracking_category = [
  94. NodeItem("LinkInverseKinematics"),
  95. NodeItem("LinkSplineIK"),
  96. NodeItem("LinkStretchTo"),
  97. NodeItem("LinkDampedTrack"),
  98. NodeItem("LinkLockedTrack"),
  99. NodeItem("LinkTrackTo"),
  100. NodeItem("LinkShrinkWrap"),
  101. ]
  102. link_relationship_category = [
  103. NodeItem("linkInherit"),
  104. NodeItem("LinkInheritConstraint"),
  105. NodeItem("LinkArmature"),
  106. ]
  107. deformer_category=[NodeItem(cls.bl_idname) for cls in deformer_nodes_ui.TellClasses()]
  108. xForm_category = [
  109. NodeItem("xFormGeometryObject"),
  110. NodeItem("xFormBoneNode"),
  111. NodeItem("xFormArmatureNode"),
  112. NodeItem("xFormObjectInstance"),
  113. NodeItem("xFormCurvePin"),
  114. ]
  115. driver_category = [
  116. NodeItem("UtilityCustomProperty"),
  117. NodeItem("LinkDrivenParameter"),
  118. NodeItem("UtilityFCurve"),
  119. NodeItem("UtilityBoneProperties"),
  120. NodeItem("UtilityDriverVariable"),
  121. NodeItem("UtilitySwitch"),
  122. NodeItem("UtilityDriver"),
  123. NodeItem("UtilityKeyframe"),
  124. ]
  125. geometry_category = [
  126. NodeItem("GeometryCirclePrimitive"),
  127. NodeItem("GeometryLattice"),
  128. ]
  129. utility_category = [
  130. NodeItem("MathStaticInt"),
  131. NodeItem("MathStaticFloat"),
  132. NodeItem("MathStaticVector"),
  133. NodeItem("UtilityCatStrings"),
  134. NodeItem("UtilityCollectionJoin"),
  135. NodeItem("UtilityCollectionHierarchy"),
  136. NodeItem("UtilityGeometryOfXForm"),
  137. NodeItem("UtilityNameOfXForm"),
  138. NodeItem("UtilityCombineThreeBool"),
  139. NodeItem("UtilityCombineVector"),
  140. NodeItem("UtilityIntToString"),
  141. NodeItem("UtilityArrayGet"),
  142. NodeItem("UtilityArrayLength"),
  143. NodeItem("UtilityChoose"),
  144. NodeItem("UtilityCompare"),
  145. NodeItem("UtilityPrint"),
  146. NodeItem("UtilitySeparateVector"),
  147. NodeItem("UtilityGetNearestFactorOnCurve"),
  148. NodeItem("UtilityKDChoosePoint"),
  149. NodeItem("UtilityKDChooseXForm"),
  150. ]
  151. matrix_category = [
  152. NodeItem("UtilityMetaRig"),
  153. NodeItem("UtilityMatrixFromCurve"),
  154. NodeItem("UtilityMatricesFromCurve"),
  155. NodeItem("UtilityNumberOfCurveSegments"),
  156. NodeItem("UtilityMatrixFromCurveSegment"),
  157. NodeItem("UtilityPointFromCurve"),
  158. NodeItem("UtilityGetCurvePoint"),
  159. NodeItem("UtilityNumberOfSplines"),
  160. NodeItem("UtilityPointFromBoneMatrix"),
  161. NodeItem("UtilitySetBoneLength"),
  162. NodeItem("UtilityGetBoneLength"),
  163. NodeItem("UtilityBoneMatrixHeadTailFlip"),
  164. NodeItem("UtilityMatrixSetLocation"),
  165. NodeItem("UtilityMatrixFromXForm"),
  166. NodeItem("UtilityAxesFromMatrix"),
  167. NodeItem("UtilityMatrixTransform"),
  168. NodeItem("UtilityMatrixInvert"),
  169. NodeItem("UtilityMatrixCompose"),
  170. NodeItem("UtilityMatrixAlignRoll"),
  171. NodeItem("UtilityTransformationMatrix"),
  172. NodeItem("UtilitySetBoneMatrixTail"),
  173. ]
  174. groups_category = [
  175. NodeItem("MantisNodeGroup"),
  176. NodeItem("MantisSchemaGroup"),
  177. ]
  178. group_interface_category = [
  179. NodeItem("NodeGroupInput"),
  180. NodeItem("NodeGroupOutput"),
  181. ]
  182. node_categories = [
  183. # identifier, label, items list
  184. MantisNodeCategory('INPUT', "Input", items=input_category),
  185. MantisNodeCategory('LINK_TRANSFORM', "Link (Transform)", items=link_transform_category),
  186. MantisNodeCategory('LINK_TRACKING', "Link (Tracking)", items=link_tracking_category),
  187. MantisNodeCategory('LINK_RELATIONSHIP', "Link (Inheritance)", items=link_relationship_category),
  188. MantisNodeCategory('DEFORMER', "Deformer", items=deformer_category),
  189. MantisNodeCategory('XFORM', "Transform", items=xForm_category),
  190. MantisNodeCategory('DRIVER', "Driver", items=driver_category),
  191. MantisNodeCategory('GEOMETRY', "Geometry", items =geometry_category),
  192. MantisNodeCategory('UTILITIES', "Utility", items=utility_category),
  193. MantisNodeCategory('MATRIX', "Matrix", items=matrix_category),
  194. MantisNodeCategory('GROUPS', "Groups", items=groups_category),
  195. MantisGroupCategory('GROUP_INTERFACE', "Group In/Out", items=group_interface_category),
  196. ]
  197. schema_category=[NodeItem(cls.bl_idname) for cls in schema_nodes_ui.TellClasses()]
  198. schema_categories = [
  199. SchemaNodeCategory('SCHEMA_SCHEMA', "Schema", items=schema_category),
  200. ]
  201. import bpy
  202. def init_keymaps():
  203. kc = bpy.context.window_manager.keyconfigs.addon
  204. km = kc.keymaps.new(name="Node Generic", space_type='NODE_EDITOR')
  205. kmi = [
  206. # Normal operation
  207. km.keymap_items.new("mantis.group_nodes", 'G', 'PRESS', ctrl=True),
  208. km.keymap_items.new("mantis.edit_group", 'TAB', 'PRESS'),
  209. km.keymap_items.new("mantis.execute_node_tree", 'E', 'PRESS'),
  210. km.keymap_items.new("mantis.mute_node", 'M', 'PRESS'),
  211. km.keymap_items.new("mantis.nodes_cleanup", "C", 'PRESS', shift=True,),
  212. # Testing
  213. km.keymap_items.new("mantis.query_sockets", 'Q', 'PRESS'),
  214. km.keymap_items.new("mantis.test_operator", 'T', 'PRESS'),
  215. km.keymap_items.new("mantis.visualize_output", 'V', 'PRESS'),
  216. # Saving, Loading, Reloading, etc.
  217. km.keymap_items.new("mantis.export_save_choose", "S", 'PRESS', alt=True,),
  218. km.keymap_items.new("mantis.export_save_as", "S", 'PRESS', alt=True, shift=True),
  219. km.keymap_items.new("mantis.reload_tree", "R", 'PRESS', alt=True,),
  220. km.keymap_items.new("mantis.import_tree", "O", 'PRESS', ctrl=True,),
  221. ]
  222. return km, kmi
  223. addon_keymaps = []
  224. # handlers! these have to be persistent
  225. from bpy.app.handlers import persistent
  226. from .base_definitions import hash_tree
  227. @persistent
  228. def update_handler(scene):
  229. # return
  230. context=bpy.context
  231. if context.space_data:
  232. if not hasattr(context.space_data, "path"):
  233. return
  234. trees = [p.node_tree for p in context.space_data.path]
  235. if not trees: return
  236. if (node_tree := trees[0]).bl_idname in ['MantisTree']:
  237. if node_tree.is_exporting:
  238. return
  239. if node_tree.prevent_next_exec : pass
  240. elif node_tree.do_live_update and not (node_tree.is_executing):
  241. node_tree.update_tree(context)
  242. @persistent
  243. def execute_handler(scene):
  244. context = bpy.context
  245. if context.space_data:
  246. if not hasattr(context.space_data, "path"):
  247. return
  248. trees = [p.node_tree for p in context.space_data.path]
  249. if not trees: return
  250. if (node_tree := trees[0]).bl_idname in ['MantisTree']:
  251. # check here instead of in execute_tree because these values can be
  252. # modified at weird times and checking from the handler is more consistent
  253. if ( node_tree.tree_valid) and ( node_tree.do_live_update ):
  254. node_tree.execute_tree(context)
  255. node_tree.tree_valid=False
  256. from .versioning import versioning_tasks
  257. def node_version_update(node, do_once):
  258. from .xForm_nodes_ui import xFormNode
  259. for bl_idname, task, required_kwargs in versioning_tasks:
  260. arg_map = {}
  261. if 'node' in required_kwargs:
  262. arg_map['node']=node
  263. if 'tree' in required_kwargs or 'node_tree' in required_kwargs:
  264. arg_map['tree']=node.id_data; arg_map['node_tree']=node.id_data
  265. # we'll match all, or categories, or specific bl_idname as needed.
  266. if ('ALL' in bl_idname) or \
  267. ('XFORM' in bl_idname) and isinstance(node, xFormNode) or\
  268. node.bl_idname in bl_idname:
  269. if do_once:
  270. print (f"Updating tree {node.id_data.name} to "
  271. f"{MANTIS_VERSION_MAJOR}.{MANTIS_VERSION_MINOR}.{MANTIS_VERSION_SUB}")
  272. task(**arg_map)
  273. def do_version_update(node_tree):
  274. # set updating status for dynamic nodes to prevent bugs in socket remapping
  275. do_once = True
  276. for node in node_tree.nodes:
  277. if hasattr(node, 'is_updating'):
  278. node.is_updating = True
  279. # start by doing tree versioning tasks
  280. for affected_bl_idnames, task, arguments_needed in versioning_tasks:
  281. if node_tree.bl_idname not in affected_bl_idnames: continue # this is a node task.
  282. arguments = {}
  283. if 'tree' in arguments_needed:
  284. arguments['tree']=node_tree
  285. task(**arguments)
  286. # run the updates that have no prerequisites
  287. for node in node_tree.nodes:
  288. node_version_update(node, do_once)
  289. do_once = False
  290. # NOTE: if future versoning tasks have prerequisites, resolve them here and update again
  291. # reset the updating status for dynamic nodes
  292. for node in node_tree.nodes:
  293. if hasattr(node, 'is_updating'):
  294. node.is_updating = False
  295. # increment the version at the end
  296. node_tree.mantis_version[0] = MANTIS_VERSION_MAJOR
  297. node_tree.mantis_version[1] = MANTIS_VERSION_MINOR
  298. node_tree.mantis_version[2] = MANTIS_VERSION_SUB
  299. @persistent
  300. def version_update_handler(filename):
  301. for node_tree in bpy.data.node_groups: # ensure it can update again after file load.
  302. if node_tree.bl_idname in ["MantisTree", "SchemaTree"]:
  303. node_tree.is_exporting=False; node_tree.is_executing=False
  304. for node_tree in bpy.data.node_groups:
  305. if node_tree.bl_idname in ["MantisTree", "SchemaTree"]:
  306. if (node_tree.mantis_version[0] < MANTIS_VERSION_MAJOR) or \
  307. (node_tree.mantis_version[1] < MANTIS_VERSION_MINOR) or \
  308. (node_tree.mantis_version[2] < MANTIS_VERSION_SUB):
  309. do_version_update(node_tree)
  310. @persistent
  311. def autoload_components(filename):
  312. # this should not be blocking or slow!
  313. print("Auto-loading components")
  314. from os import path as os_path
  315. from .utilities.utilities import get_component_library_items, get_default_collection
  316. from .utilities.i_o import do_import
  317. from .preferences import get_bl_addon_object
  318. import json
  319. from bpy import context, data
  320. bl_addon_object = get_bl_addon_object()
  321. unlink_curves = True
  322. unlink_armatures = True
  323. if data.collections.get(bl_addon_object.preferences.CurveDefaultCollection):
  324. unlink_curves=False
  325. if data.collections.get(bl_addon_object.preferences.MetaArmatureDefaultCollection):
  326. unlink_armatures=False
  327. base_path = bl_addon_object.preferences.ComponentsAutoLoadFolder
  328. components = get_component_library_items(path='AUTOLOAD')
  329. for autoload_component in components:
  330. path = os_path.join(base_path, autoload_component[0])
  331. with open(path, 'r', encoding='utf-8') as f:
  332. json_data = json.load(f)
  333. do_import(json_data, context,
  334. search_multi_files=True, filepath=path,
  335. skip_existing=True)
  336. # let's get the node trees and assign a fake user
  337. for tree_name in json_data.keys():
  338. tree = data.node_groups.get(tree_name)
  339. tree.use_fake_user = True
  340. # now we need to unlink the collections, and add fake users to them
  341. curves_collection = get_default_collection(collection_type="CURVE")
  342. armature_collection = get_default_collection(collection_type="ARMATURE")
  343. if unlink_curves and (curves_collection := data.collections.get(
  344. bl_addon_object.preferences.CurveDefaultCollection)):
  345. context.scene.collection.children.unlink(curves_collection)
  346. if unlink_armatures and (armature_collection := data.collections.get(
  347. bl_addon_object.preferences.MetaArmatureDefaultCollection)):
  348. context.scene.collection.children.unlink(armature_collection)
  349. # This has to be done after file load because the file load clears the timers
  350. @persistent
  351. def begin_selection_sync_timer(filename):
  352. # And here I will register any timers used by Mantis.
  353. from .timers import timer_update_selection_sync, ENABLED, SELECTION_POLL_RATE
  354. from .preferences import get_bl_addon_object
  355. bl_mantis_addon = get_bl_addon_object()
  356. if bl_mantis_addon and bl_mantis_addon.preferences:
  357. ENABLED = bl_mantis_addon.preferences.EnableSelectionSync
  358. SELECTION_POLL_RATE = bl_mantis_addon.preferences.SelectionSyncPollRate
  359. bpy.app.timers.register(timer_update_selection_sync)
  360. # I'll need to do some fiddling here when it comes time to try
  361. # and make rig definitions animatable.
  362. @persistent
  363. def on_animation_playback_pre_handler(scene,depsgraph):
  364. for t in bpy.data.node_groups:
  365. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  366. t.is_executing = True
  367. @persistent
  368. def on_animation_playback_post_handler(scene,depsgraph):
  369. for t in bpy.data.node_groups:
  370. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  371. t.is_executing = False
  372. @persistent
  373. def on_undo_post_handler(scene): # the undo will trigger a depsgraph update
  374. for t in bpy.data.node_groups: # so we enable prevent_next_exec.
  375. if t.bl_idname in ['MantisTree', 'SchemaTree']:
  376. t.prevent_next_exec = True
  377. t.hash=""
  378. # set the tree to invalid to trigger a tree update
  379. # since the context data is wiped by an undo.
  380. from .menu_classes import (node_context_menu_draw, node_add_menu_draw,
  381. armature_add_menu_draw, import_menu_draw)
  382. from .socket_definitions import generate_custom_interface_types
  383. generated_classes = generate_custom_interface_types()
  384. classes.extend(generated_classes)
  385. def register():
  386. from bpy.utils import register_class
  387. for cls in classes:
  388. try:
  389. register_class(cls)
  390. except RuntimeError as e:
  391. prRed(f"Registration error for class: {cls.__name__}")
  392. raise e
  393. nodeitems_utils.register_node_categories('MantisNodeCategories', node_categories)
  394. nodeitems_utils.register_node_categories('SchemaNodeCategories', schema_categories)
  395. bpy.types.NODE_MT_context_menu.append(node_context_menu_draw)
  396. bpy.types.NODE_MT_add.append(node_add_menu_draw)
  397. bpy.types.VIEW3D_MT_armature_add.append(armature_add_menu_draw)
  398. bpy.types.TOPBAR_MT_file_import.append(import_menu_draw)
  399. km, kmi = init_keymaps()
  400. for k in kmi:
  401. k.active = True
  402. addon_keymaps.append((km, k))
  403. # add the handlers
  404. bpy.app.handlers.depsgraph_update_pre.insert(0, update_handler)
  405. bpy.app.handlers.depsgraph_update_post.insert(0, execute_handler)
  406. bpy.app.handlers.load_post.insert(0, begin_selection_sync_timer)
  407. bpy.app.handlers.load_post.insert(0, autoload_components)
  408. bpy.app.handlers.load_post.insert(0, version_update_handler)
  409. bpy.app.handlers.animation_playback_pre.insert(0, on_animation_playback_pre_handler)
  410. bpy.app.handlers.animation_playback_post.insert(0, on_animation_playback_post_handler)
  411. bpy.app.handlers.undo_post.insert(0, on_undo_post_handler)
  412. # I'm adding mine in first to ensure other addons don't mess up mine
  413. # but I am a good citizen! so my addon won't mess up yours! probably...
  414. def unregister():
  415. bpy.types.NODE_MT_context_menu.remove(node_context_menu_draw)
  416. bpy.types.NODE_MT_add.remove(node_add_menu_draw)
  417. bpy.types.VIEW3D_MT_armature_add.remove(armature_add_menu_draw)
  418. bpy.types.TOPBAR_MT_file_import.remove(import_menu_draw)
  419. for tree in bpy.data.node_groups: # ensure it doesn't try to update while quitting.
  420. if tree.bl_idname in ['MantisTree, SchemaTree']:
  421. tree.is_exporting=True; tree.is_executing=True
  422. nodeitems_utils.unregister_node_categories('MantisNodeCategories')
  423. nodeitems_utils.unregister_node_categories('SchemaNodeCategories')
  424. from bpy.utils import unregister_class
  425. for cls in reversed(classes):
  426. unregister_class(cls)
  427. for km, kmi in addon_keymaps:
  428. km.keymap_items.remove(kmi)
  429. addon_keymaps.clear()