i_o.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  1. # this is the I/O part of mantis. I eventually intend to make this a markup language. not right now tho lol
  2. from .utilities import (prRed, prGreen, prPurple, prWhite,
  3. prOrange,
  4. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  5. wrapOrange,)
  6. from mathutils import Vector, Matrix
  7. NODES_REMOVED=["xFormRootNode"]
  8. # Node bl_idname, # Socket Name
  9. SOCKETS_REMOVED=[("UtilityDriverVariable", "Transform Channel"),
  10. ("xFormRootNode","World Out"),
  11. ("UtilitySwitch","xForm"),
  12. ("LinkDrivenParameter", "Enable")]
  13. # Node Class #Prior bl_idname # prior name # new bl_idname # new name, # Multi
  14. # Debugging values.
  15. print_read_only_warning = False
  16. print_link_failure = False
  17. # ignore these because they are either unrelated python stuff or useless or borked
  18. prop_ignore = [ "__dict__", "__doc__", "__module__", "__weakref__",# "name",
  19. "bl_height_default", "bl_height_max", "bl_height_min",
  20. "bl_icon", "bl_rna", "bl_static_type", "bl_description",
  21. "bl_width_default", "bl_width_max", "bl_width_min",
  22. "__annotations__", "original", "rna_type", "view_center",
  23. "links", "nodes", "internal_links", "inputs", "outputs",
  24. "__slots__", "dimensions", "type", "interface",
  25. "library_weak_reference", "parsed_tree", "node_tree_updater",
  26. "asset_data", "preview", # blender asset stuff
  27. "object_reference", # this one is here to hold on to widgets when appending
  28. "color_tag" , # added in blender 4.4, not used by Mantis, readonly.
  29. # more blender properties...
  30. "bl_use_group_interface", "default_group_node_width", "id_type",
  31. # blender runtime stuff
  32. "animation_data", "description", "grease_pencil", "is_editable",
  33. "is_embedded_data", "is_evaluated", "is_library_indirect", "is_missing",
  34. "is_runtime_data", "library", "name_full", "override_library",
  35. "session_uid", "tag", "use_extra_user", "use_fake_user", "users",
  36. # some Mantis stuff I don't need to save
  37. "do_live_update", "is_executing", "is_exporting", "hash", "filepath",
  38. "prevent_next_exec", "execution_id", "num_links", "tree_valid",
  39. "interface_helper",
  40. # node stuff
  41. "mantis_node_class_name", "color", "height", "initialized", "select",
  42. "show_options", "show_preview", "show_texture", "use_custom_color",
  43. "warning_propagation",
  44. # these are in Bone
  45. "socket_count", "display_bb_settings", "display_def_settings",
  46. "display_ik_settings", "display_vp_settings",
  47. ]
  48. # don't ignore: "bl_idname", "bl_label",
  49. # ignore the name, it's the dict - key for the node props
  50. # no that's stupid don't ignore the name good grief
  51. # I am doing this because these are interactions with other addons that cause problems and probably don't exist for any given user
  52. prop_ignore.extend(['keymesh'])
  53. # trees
  54. prop_ignore_tree = prop_ignore.copy()
  55. prop_ignore_tree.extend(["bl_label", "name"])
  56. prop_ignore_interface = prop_ignore.copy()
  57. # Geometry Nodes stuff that Mantis doesn't use
  58. prop_ignore_interface.extend( [ "attribute_domain",
  59. "default_attribute_name",
  60. "default_input",
  61. "force_non_field",
  62. "hide_in_modifier",
  63. "hide_value",
  64. # no idea what this is, also don't care
  65. "is_inspect_output",
  66. "is_panel_toggle",
  67. "layer_selection_field",
  68. "structure_type", ] )
  69. from bpy.app import version
  70. if version >= (4,5,0):
  71. SOCKETS_REMOVED.append( ("LinkSplineIK", "Use Original Scale"))
  72. add_inputs_bl_idnames = [
  73. "UtilityDriver", "UtilityFCurve", "DeformerMorphTargetDeform",
  74. "LinkArmature",
  75. "xFormBoneNode"
  76. # for custom properties, right?
  77. # For a long time this wasn't in here and I guess there weren't problems
  78. # I really don't know if adding it here is right...
  79. ]
  80. # this works but it is really ugly and probably quite inneficient
  81. # TODO: make hotkeys for export and import and reload from file
  82. # we need to give the tree a filepath attribute and update it on saving
  83. # then we need to use the filepath attribute to load from
  84. # finally we need to use a few operators to choose whether to open a menu or not
  85. # and we need a message to display on save/load so that the user knows it is happening
  86. # TODO:
  87. # Additionally export MetaRig and Curve and other referenced data
  88. # Meshes can be exported as .obj and imported via GN
  89. def TellClasses():
  90. return [ MantisExportNodeTreeSaveAs, MantisExportNodeTreeSave, MantisExportNodeTree, MantisImportNodeTree, MantisReloadNodeTree]
  91. # https://stackoverflow.com/questions/42033142/is-there-an-easy-way-to-check-if-an-object-is-json-serializable-in-python - thanks!
  92. def is_jsonable(x):
  93. import json
  94. try:
  95. json.dumps(x)
  96. return True
  97. except (TypeError, OverflowError):
  98. return False
  99. # https://stackoverflow.com/questions/295135/turn-a-stritree-into-a-valid-filename - thank you user "Sophie Gage"
  100. def remove_special_characters(name):
  101. import re; return re.sub('[^\w_.)( -]', '', name)# re = regular expressions
  102. def fix_custom_parameter(n, property_definition, ):
  103. if n.bl_idname in ['xFormNullNode', 'xFormBoneNode', 'xFormArmatureNode', 'xFormGeometryObjectNode',]:
  104. prop_name = property_definition["name"]
  105. prop_type = property_definition["bl_idname"]
  106. if prop_type in ['ParameterBoolSocket', 'ParameterIntSocket', 'ParameterFloatSocket', 'ParameterVectorSocket' ]:
  107. # is it good to make both of them?
  108. input = n.inputs.new( prop_type, prop_name)
  109. output = n.outputs.new( prop_type, prop_name)
  110. if property_definition["is_output"] == True:
  111. return output
  112. return input
  113. elif n.bl_idname in ['LinkArmature']:
  114. prop_name = property_definition["name"]
  115. prop_type = property_definition["bl_idname"]
  116. input = n.inputs.new( prop_type, prop_name)
  117. return input
  118. return None
  119. # def scan_tree_for_objects(base_tree, current_tree):
  120. # # goal: find all referenced armature and curve objects
  121. # # return [set(armatures), set(curves)]
  122. # armatures = set()
  123. # curves = set()
  124. # for node in base_tree.parsed_tree.values():
  125. # from .utilities import get_node_prototype
  126. # if node.ui_signature is None:
  127. # continue
  128. # ui_node = get_node_prototype(node.ui_signature, node.base_tree)
  129. # if ui_node is None or ui_node.id_data != current_tree:
  130. # continue
  131. # if hasattr(node, "bGetObject"):
  132. # ob = node.bGetObject()
  133. # print(node, ob)
  134. # if ob is None:
  135. # continue
  136. # if not hasattr(node, "type"):
  137. # continue
  138. # if ob.type == 'ARMATURE':
  139. # armatures.add(ob)
  140. # if ob.type == 'CURVE':
  141. # curves.add(ob)
  142. # return (armatures, curves)
  143. # Currently this isn't very robust and doesn't seek backwards
  144. # to see if a dependency is created by node connections.
  145. # TODO it remains to be seen if that is even a desirable behaviour.
  146. def scan_tree_for_objects(base_tree, current_tree):
  147. from bpy import data
  148. armatures, curves = set(), set()
  149. for node in current_tree.nodes:
  150. match node.bl_idname:
  151. case "UtilityMetaRig":
  152. if node.inputs[0].is_linked:
  153. continue
  154. if (armature := node.inputs[0].search_prop) is not None:
  155. armatures.add(armature)
  156. case "InputExistingGeometryObjectNode":
  157. if node.inputs["Name"].is_linked:
  158. continue
  159. ob_name = node.inputs["Name"].default_value
  160. if ob := data.objects.get(ob_name):
  161. if ob.type == "ARMATURE":
  162. armatures.add(ob)
  163. elif ob.type == "CURVE":
  164. curves.add(ob)
  165. case "xFormArmatureNode":
  166. if node.inputs["Name"].is_linked:
  167. continue
  168. armature_name = node.inputs["Name"].default_value
  169. armature = data.objects.get(armature_name)
  170. if armature:
  171. armatures.add(armature)
  172. case "xFormGeometryObjectNode":
  173. if node.inputs["Name"].is_linked:
  174. continue
  175. ob_name = node.inputs["Name"].default_value
  176. if ob := data.objects.get(ob_name):
  177. if ob.type == "ARMATURE":
  178. armatures.add(ob)
  179. elif ob.type == "CURVE":
  180. curves.add(ob)
  181. for input in node.inputs:
  182. if input.bl_idname in ["EnumCurveSocket"]:
  183. if input.search_prop is not None:
  184. curves.add(input.search_prop)
  185. # NOW check the parsed_tree and see if it is possible to find any other
  186. # objects referred to/provided by the tree
  187. return (curves, armatures )
  188. from dataclasses import dataclass, field, asdict
  189. # some basic classes to define curve point types
  190. @dataclass
  191. class crv_pnt_data():
  192. co : tuple[float, float, float] = field(default=(0,0,0,))
  193. handle_left : tuple[float, float, float] = field(default=(0,0,0,))
  194. handle_right : tuple[float, float, float] = field(default=(0,0,0,))
  195. handle_left_type : str = field(default="ALIGNED")
  196. handle_right_type : str = field(default="ALIGNED")
  197. radius : float = field(default=0.0)
  198. tilt : float = field(default=0.0)
  199. w : float = field(default=0.0)
  200. @dataclass
  201. class spline_data():
  202. type : str = field(default='POLY')
  203. points : list[dict] = field(default_factory=[])
  204. order_u : int = field(default=4)
  205. radius_interpolation : str = field(default="LINEAR")
  206. tilt_interpolation : str = field(default="LINEAR")
  207. resolution_u : int = field(default=12)
  208. use_bezier_u : bool = field(default=False)
  209. use_cyclic_u : bool = field(default=False)
  210. use_endpoint_u : bool = field(default=False)
  211. index : int = field(default=0)
  212. object_name : str = field(default='Curve')
  213. def get_curve_for_pack(object):
  214. splines = []
  215. for i, spline in enumerate(object.data.splines):
  216. points = []
  217. if spline.type == 'BEZIER':
  218. for point in spline.bezier_points:
  219. export_pnt = crv_pnt_data(
  220. co = tuple(point.co),
  221. radius = point.radius,
  222. tilt = point.tilt,
  223. handle_left = tuple(point.handle_left),
  224. handle_right = tuple(point.handle_right),
  225. handle_left_type = point.handle_left_type,
  226. handle_right_type = point.handle_right_type,
  227. )
  228. points.append(asdict(export_pnt))
  229. else:
  230. for point in spline.points:
  231. export_pnt = crv_pnt_data(
  232. co = point.co[:3], # exclude the w value
  233. radius = point.radius,
  234. tilt = point.tilt,
  235. w = point.co[3],
  236. )
  237. points.append(export_pnt)
  238. export_spl = spline_data(
  239. type = spline.type,
  240. points = points,
  241. order_u = spline.order_u,
  242. radius_interpolation = spline.radius_interpolation,
  243. tilt_interpolation = spline.tilt_interpolation,
  244. resolution_u = spline.resolution_u,
  245. use_bezier_u = spline.use_bezier_u,
  246. use_cyclic_u = spline.use_cyclic_u,
  247. use_endpoint_u = spline.use_endpoint_u,
  248. index = i,
  249. object_name = object.name,)
  250. splines.append(asdict(export_spl))
  251. return splines
  252. def matrix_as_tuple(matrix):
  253. return ( matrix[0][0], matrix[0][1], matrix[0][2], matrix[0][3],
  254. matrix[1][0], matrix[1][1], matrix[1][2], matrix[1][3],
  255. matrix[2][0], matrix[2][1], matrix[2][2], matrix[2][3],
  256. matrix[3][0], matrix[3][1], matrix[3][2], matrix[3][3], )
  257. @dataclass
  258. class metabone_data:
  259. object_name : str = field(default='')
  260. name : str = field(default=''),
  261. type : str = field(default='BONE'),
  262. matrix : tuple[float] = field(default=()),
  263. parent : str = field(default=''),
  264. length : float = field(default=-1.0),
  265. children : list[str] = field(default_factory=[]),
  266. # keep it really simple for now. I'll add BBone and envelope later on
  267. # when I make them accessible from the meta-rig
  268. def get_armature_for_pack(object):
  269. metarig_data = {}
  270. armature_data = metabone_data( object_name = object.name,
  271. name=object.name, type='ARMATURE',
  272. matrix=matrix_as_tuple(object.matrix_world),
  273. parent="", # NOTE that this is not always a fair assumption!
  274. length = -1.0, children =[],)
  275. metarig_data[object.name] = asdict(armature_data)
  276. metarig_data["MANTIS_RESERVED"] = asdict(armature_data) # just in case a bone is named the same as the armature
  277. for bone in object.data.bones:
  278. parent_name = ''
  279. if bone.parent is None:
  280. armature_data.children.append(bone.name)
  281. else:
  282. parent_name=bone.parent.name
  283. children=[]
  284. for c in bone.children:
  285. children.append(c.name)
  286. bone_data = metabone_data( object_name = object.name,
  287. name=bone.name, type='BONE',
  288. matrix=matrix_as_tuple(bone.matrix_local),
  289. parent=parent_name, length = bone.length, children = children,
  290. )
  291. metarig_data[bone.name]=asdict(bone_data)
  292. return metarig_data
  293. def get_socket_data(socket, ignore_if_default=False):
  294. # TODO: don't get stuff in the socket templates
  295. # PROBLEM: I don't have easy access to this from the ui class (or mantis class)
  296. socket_data = {}
  297. socket_data["name"] = socket.name
  298. socket_data["bl_idname"] = socket.bl_idname
  299. socket_data["is_output"] = socket.is_output
  300. socket_data["is_multi_input"] = socket.is_multi_input
  301. # here is where we'll handle a socket_data'socket special data
  302. if socket.bl_idname == "EnumMetaBoneSocket":
  303. socket_data["bone"] = socket.bone
  304. if socket.bl_idname in ["EnumMetaBoneSocket", "EnumMetaRigSocket", "EnumCurveSocket"]:
  305. if sp := socket.get("search_prop"): # may be None
  306. socket_data["search_prop"] = sp.name # this is an object.
  307. #
  308. if hasattr(socket, "default_value"):
  309. value = socket.default_value
  310. else:
  311. value = None
  312. return socket_data # we don't need to store any more.
  313. if not is_jsonable(value): # FIRST try and make a tuple out of it because JSON doesn't like mutables
  314. value = tuple(value)
  315. if not is_jsonable(value): # now see if it worked and crash out if it didn't
  316. raise RuntimeError(f"Error serializing data in {socket.node.name}::{socket.name} for value of type {type(value)}")
  317. socket_data["default_value"] = value
  318. # TODO TODO implement "ignore if default" feature here
  319. # at this point we can get the custom parameter ui hints if we want
  320. if not socket.is_output:
  321. # try and get this data
  322. if value := getattr(socket,'min', None):
  323. socket_data["min"] = value
  324. if value := getattr(socket,'max', None):
  325. socket_data["max"] = value
  326. if value := getattr(socket,'soft_min', None):
  327. socket_data["soft_min"] = value
  328. if value := getattr(socket,'soft_max', None):
  329. socket_data["soft_max"] = value
  330. if value := getattr(socket,'description', None):
  331. socket_data["description"] = value
  332. return socket_data
  333. #
  334. def get_node_data(ui_node):
  335. # if this is a node-group, force it to update its interface, because it may be messed up.
  336. # can remove this HACK when I have stronger guarentees about node-group's keeping the interface
  337. from .base_definitions import node_group_update
  338. if hasattr(ui_node, "node_tree"):
  339. ui_node.is_updating = True
  340. try: # HERE BE DANGER
  341. node_group_update(ui_node, force=True)
  342. finally: # ensure this line is run even if there is an error
  343. ui_node.is_updating = False
  344. node_props, inputs, outputs = {}, {}, {}
  345. for propname in dir(ui_node):
  346. value = getattr(ui_node, propname)
  347. if propname in ['fake_fcurve_ob']:
  348. value=value.name
  349. if (propname in prop_ignore) or ( callable(value) ):
  350. continue
  351. if value.__class__.__name__ in ["Vector", "Color"]:
  352. value = tuple(value)
  353. if isinstance(value, bpy.types.NodeTree):
  354. value = value.name
  355. if isinstance(value, bpy.types.bpy_prop_array):
  356. value = tuple(value)
  357. if propname == "parent" and value:
  358. value = value.name
  359. if not is_jsonable(value):
  360. raise RuntimeError(f"Could not export... {ui_node.name}, {propname}, {type(value)}")
  361. if value is None:
  362. continue
  363. node_props[propname] = value
  364. # so we have to accumulate the parent location because the location is not absolute
  365. if propname == "location" and ui_node.parent is not None:
  366. location_acc = Vector((0,0))
  367. parent = ui_node.parent
  368. while (parent):
  369. location_acc += parent.location
  370. parent = parent.parent
  371. location_acc += getattr(ui_node, propname)
  372. node_props[propname] = tuple(location_acc)
  373. # this works!
  374. if ui_node.bl_idname in ['RerouteNode']:
  375. return node_props # we don't need to get the socket information.
  376. for i, ui_socket in enumerate(ui_node.inputs):
  377. socket = get_socket_data(ui_socket)
  378. socket["index"]=i
  379. inputs[ui_socket.identifier] = socket
  380. for i, ui_socket in enumerate(ui_node.outputs):
  381. socket = get_socket_data(ui_socket)
  382. socket["index"]=i
  383. outputs[ui_socket.identifier] = socket
  384. node_props["inputs"] = inputs
  385. node_props["outputs"] = outputs
  386. return node_props
  387. def get_tree_data(tree):
  388. tree_info = {}
  389. for propname in dir(tree):
  390. # if getattr(tree, propname):
  391. # pass
  392. if (propname in prop_ignore_tree) or ( callable(getattr(tree, propname)) ):
  393. continue
  394. v = getattr(tree, propname)
  395. if isinstance(getattr(tree, propname), bpy.types.bpy_prop_array):
  396. v = tuple(getattr(tree, propname))
  397. if not is_jsonable( v ):
  398. raise RuntimeError(f"Not JSON-able: {propname}, type: {type(v)}")
  399. tree_info[propname] = v
  400. tree_info["name"]=tree.name
  401. return tree_info
  402. def get_interface_data(tree, tree_in_out):
  403. for sock in tree.interface.items_tree:
  404. sock_data={}
  405. if sock.item_type == 'PANEL':
  406. sock_data["name"] = sock.name
  407. sock_data["item_type"] = sock.item_type
  408. sock_data["description"] = sock.description
  409. sock_data["default_closed"] = sock.default_closed
  410. tree_in_out[sock.name] = sock_data
  411. # if it is a socket....
  412. else:
  413. # we need to get the socket class from the bl_idname
  414. bl_socket_idname = sock.bl_socket_idname
  415. # try and import it
  416. from . import socket_definitions
  417. # WANT an attribute error if this fails.
  418. socket_class = getattr(socket_definitions, bl_socket_idname)
  419. sock_parent = None
  420. if sock.parent:
  421. sock_parent = sock.parent.name
  422. for propname in dir(sock):
  423. if propname in prop_ignore_interface:
  424. continue
  425. if (propname == "parent"):
  426. sock_data[propname] = sock_parent
  427. continue
  428. v = getattr(sock, propname)
  429. if (propname in prop_ignore) or ( callable(v) ):
  430. continue
  431. if isinstance(getattr(sock, propname), bpy.types.bpy_prop_array):
  432. v = tuple(getattr(sock, propname))
  433. if not is_jsonable( v ):
  434. raise RuntimeError(f"{propname}, {type(v)}")
  435. sock_data[propname] = v
  436. # this is a property. pain.
  437. sock_data["socket_type"] = socket_class.interface_type.fget(socket_class)
  438. tree_in_out[sock.identifier] = sock_data
  439. def export_to_json(trees, base_tree=None, path="", write_file=True, only_selected=False, ):
  440. export_data = {}
  441. for tree in trees:
  442. current_tree_is_base_tree = False
  443. if tree is trees[-1]:
  444. current_tree_is_base_tree = True
  445. tree_info, tree_in_out = {}, {}
  446. tree_info = get_tree_data(tree)
  447. curves, metarig_data = {}, {}
  448. embed_metarigs=True
  449. if base_tree and embed_metarigs:
  450. curves_in_tree, metarigs_in_tree = scan_tree_for_objects(base_tree, tree)
  451. for crv in curves_in_tree:
  452. curves[crv.name] = get_curve_for_pack(crv)
  453. for mr in metarigs_in_tree:
  454. metarig_data[mr.name] = get_armature_for_pack(mr)
  455. # if only_selected:
  456. # # all in/out links, relative to the selection, should be marked and used to initialize tree properties
  457. if not only_selected: # we'll handle this later with the links
  458. for sock in tree.interface.items_tree:
  459. get_interface_data(tree, tree_in_out) # it concerns me that this one modifies
  460. # the collection instead of getting the data and returning it. TODO refactor this
  461. nodes = {}
  462. for node in tree.nodes:
  463. if only_selected and node.select == False:
  464. continue
  465. nodes[node.name] = get_node_data(node)
  466. links = []
  467. in_sockets, out_sockets = {}, {}
  468. unique_sockets_from, unique_sockets_to = {}, {}
  469. in_node = {"name":"MANTIS_AUTOGEN_GROUP_INPUT", "bl_idname":"NodeGroupInput", "inputs":in_sockets}
  470. out_node = {"name":"MANTIS_AUTOGEN_GROUP_OUTPUT", "bl_idname":"NodeGroupOutput", "outputs":out_sockets}
  471. add_input_node, add_output_node = False, False
  472. for link in tree.links:
  473. from_node_name, from_socket_id = link.from_node.name, link.from_socket.identifier
  474. to_node_name, to_socket_id = link.to_node.name, link.to_socket.identifier
  475. from_socket_name, to_socket_name = link.from_socket.name, link.to_socket.name
  476. # get the indices of the sockets to be absolutely sure
  477. for from_outoput_index, outp in enumerate(link.from_node.outputs):
  478. # for some reason, 'is' does not return True no matter what...
  479. # so we are gonn compare the memory address directly, this is stupid
  480. if (outp.as_pointer() == link.from_socket.as_pointer()): break
  481. else:
  482. problem=link.from_node.name + "::" + link.from_socket.name
  483. raise RuntimeError(wrapRed(f"Error saving index of socket: {problem}"))
  484. for to_input_index, inp in enumerate(link.to_node.inputs):
  485. if (inp.as_pointer() == link.to_socket.as_pointer()): break
  486. else:
  487. problem = link.to_node.name + "::" + link.to_socket.name
  488. raise RuntimeError(wrapRed(f"Error saving index of socket: {problem}"))
  489. if current_tree_is_base_tree:
  490. if (only_selected and link.from_node.select) and (not link.to_node.select):
  491. # handle an output in the tree
  492. add_output_node=True
  493. if not (sock_name := unique_sockets_to.get(link.from_socket.node.name+link.from_socket.identifier)):
  494. sock_name = link.to_socket.name; name_stub = sock_name
  495. used_names = list(tree_in_out.keys()); i=0
  496. while sock_name in used_names:
  497. sock_name=name_stub+'.'+str(i).zfill(3); i+=1
  498. unique_sockets_to[link.from_socket.node.name+link.from_socket.identifier]=sock_name
  499. out_sock = out_sockets.get(sock_name)
  500. if not out_sock:
  501. out_sock = {}; out_sockets[sock_name] = out_sock
  502. out_sock["index"]=len(out_sockets) # zero indexed, so zero length makes zero the first index and so on, this works
  503. # what in the bad word is happening here?
  504. # why?
  505. # why no de-duplication?
  506. # what was I thinking?
  507. # TODO REFACTOR THIS SOON
  508. out_sock["name"] = sock_name
  509. out_sock["identifier"] = sock_name
  510. out_sock["bl_idname"] = link.to_socket.bl_idname
  511. out_sock["is_output"] = False
  512. out_sock["source"]=[link.to_socket.node.name,link.to_socket.identifier]
  513. out_sock["is_multi_input"] = False # this is not something I can even set on tree interface items, and this code is not intended for making Schema
  514. sock_data={}
  515. sock_data["name"] = sock_name
  516. sock_data["item_type"] = "SOCKET"
  517. sock_data["default_closed"] = False
  518. # record the actual bl_idname and the proper interface type.
  519. sock_data["socket_type"] = link.from_socket.interface_type
  520. sock_data["bl_socket_idname"] = link.from_socket.bl_idname
  521. sock_data["identifier"] = sock_name
  522. sock_data["in_out"]="OUTPUT"
  523. sock_data["index"]=out_sock["index"]
  524. tree_in_out[sock_name] = sock_data
  525. to_node_name=out_node["name"]
  526. to_socket_id=out_sock["identifier"]
  527. to_input_index=out_sock["index"]
  528. to_socket_name=out_sock["name"]
  529. elif (only_selected and (not link.from_node.select)) and link.to_node.select:
  530. add_input_node=True
  531. # we need to get a unique name for this
  532. # use the Tree IN/Out because we are dealing with Group in/out
  533. if not (sock_name := unique_sockets_from.get(link.from_socket.node.name+link.from_socket.identifier)):
  534. sock_name = link.from_socket.name; name_stub = sock_name
  535. used_names = list(tree_in_out.keys()); i=0
  536. while sock_name in used_names:
  537. sock_name=name_stub+'.'+str(i).zfill(3); i+=1
  538. unique_sockets_from[link.from_socket.node.name+link.from_socket.identifier]=sock_name
  539. in_sock = in_sockets.get(sock_name)
  540. if not in_sock:
  541. in_sock = {}; in_sockets[sock_name] = in_sock
  542. in_sock["index"]=len(in_sockets) # zero indexed, so zero length makes zero the first index and so on, this works
  543. #
  544. in_sock["name"] = sock_name
  545. in_sock["identifier"] = sock_name
  546. in_sock["bl_idname"] = link.from_socket.bl_idname
  547. in_sock["is_output"] = True
  548. in_sock["is_multi_input"] = False # this is not something I can even set on tree interface items, and this code is not intended for making Schema
  549. in_sock["source"] = [link.from_socket.node.name,link.from_socket.identifier]
  550. sock_data={}
  551. sock_data["name"] = sock_name
  552. sock_data["item_type"] = "SOCKET"
  553. sock_data["default_closed"] = False
  554. # record the actual bl_idname and the proper interface type.
  555. sock_data["socket_type"] = link.from_socket.interface_type
  556. sock_data["bl_socket_idname"] = link.from_socket.bl_idname
  557. sock_data["identifier"] = sock_name
  558. sock_data["in_out"]="INPUT"
  559. sock_data["index"]=in_sock["index"]
  560. tree_in_out[sock_name] = sock_data
  561. from_node_name=in_node.get("name")
  562. from_socket_id=in_sock["identifier"]
  563. from_outoput_index=in_sock["index"]
  564. from_socket_name=in_node.get("name")
  565. # parentheses matter here...
  566. elif (only_selected and not (link.from_node.select and link.to_node.select)):
  567. continue
  568. elif only_selected and not (link.from_node.select and link.to_node.select):
  569. continue # pass if both links are not selected
  570. links.append( (from_node_name,
  571. from_socket_id,
  572. to_node_name,
  573. to_socket_id,
  574. from_outoput_index,
  575. to_input_index,
  576. from_socket_name,
  577. to_socket_name) ) # it's a tuple
  578. if add_input_node or add_output_node:
  579. all_nodes_bounding_box=[Vector((float("inf"),float("inf"))), Vector((-float("inf"),-float("inf")))]
  580. for n in nodes.values():
  581. if n["location"][0] < all_nodes_bounding_box[0].x:
  582. all_nodes_bounding_box[0].x = n["location"][0]
  583. if n["location"][1] < all_nodes_bounding_box[0].y:
  584. all_nodes_bounding_box[0].y = n["location"][1]
  585. #
  586. if n["location"][0] > all_nodes_bounding_box[1].x:
  587. all_nodes_bounding_box[1].x = n["location"][0]
  588. if n["location"][1] > all_nodes_bounding_box[1].y:
  589. all_nodes_bounding_box[1].y = n["location"][1]
  590. if add_input_node:
  591. in_node["location"] = Vector((all_nodes_bounding_box[0].x-400, all_nodes_bounding_box[0].lerp(all_nodes_bounding_box[1], 0.5).y))
  592. nodes["MANTIS_AUTOGEN_GROUP_INPUT"]=in_node
  593. if add_output_node:
  594. out_node["location"] = Vector((all_nodes_bounding_box[1].x+400, all_nodes_bounding_box[0].lerp(all_nodes_bounding_box[1], 0.5).y))
  595. nodes["MANTIS_AUTOGEN_GROUP_OUTPUT"]=out_node
  596. export_data[tree.name] = (tree_info, tree_in_out, nodes, links, curves, metarig_data,) # f_curves)
  597. return export_data
  598. def write_json_data(data, path):
  599. import json
  600. with open(path, "w") as file:
  601. print(wrapWhite("Writing mantis tree data to: "), wrapGreen(file.name))
  602. file.write( json.dumps(data, indent = 4) )
  603. def get_link_sockets(link, tree, tree_socket_id_map):
  604. from_node_name = link[0]
  605. from_socket_id = link[1]
  606. to_node_name = link[2]
  607. to_socket_id = link[3]
  608. from_output_index = link[4]
  609. to_input_index = link[5]
  610. from_socket_name = link[6]
  611. to_socket_name = link[7]
  612. # TODO: make this a loop and swap out the in/out stuff
  613. # this is OK but I want to avoid code-duplication, which this almost is.
  614. from_node = tree.nodes.get(from_node_name)
  615. # first try and get by name. we'll use this if the ID and the name do not match.
  616. # from_sock = from_node.outputs.get(from_socket_name)
  617. id1 = from_socket_id
  618. if hasattr(from_node, "node_tree") or \
  619. from_node.bl_idname in ["SchemaArrayInput",
  620. "SchemaArrayInputGet",
  621. "SchemaArrayInputAll",
  622. "SchemaConstInput",
  623. "SchemaIncomingConnection", ]: # now we have to map by something else
  624. try:
  625. id1 = from_node.outputs[from_socket_name].identifier
  626. except KeyError: # we'll try index if nothing else works
  627. try:
  628. id1 = from_node.outputs[from_output_index].identifier
  629. except IndexError as e:
  630. prRed("failed to create link: "
  631. f"{from_node_name}:{from_socket_id} --> {to_node_name}:{to_socket_id}")
  632. return (None, None)
  633. elif from_node.bl_idname in ["NodeGroupInput"]:
  634. id1 = tree_socket_id_map.get(from_socket_id)
  635. for from_sock in from_node.outputs:
  636. if from_sock.identifier == id1: break
  637. else:
  638. from_sock = None
  639. id2 = to_socket_id
  640. to_node = tree.nodes[to_node_name]
  641. if hasattr(to_node, "node_tree") or \
  642. to_node.bl_idname in ["SchemaArrayOutput",
  643. "SchemaConstOutput",
  644. "SchemaOutgoingConnection", ]: # now we have to map by something else
  645. try:
  646. id2 = to_node.inputs[to_socket_name].identifier
  647. except KeyError: # we'll try index if nothing else works
  648. try: # nesting try/except is ugly but it is right...
  649. id2 = to_node.inputs[to_input_index].identifier
  650. except IndexError as e:
  651. prRed("failed to create link: "
  652. f"{from_node_name}:{from_socket_id} --> {to_node_name}:{to_socket_id}")
  653. return (None, None)
  654. elif to_node.bl_idname in ["NodeGroupOutput"]:
  655. id2 = tree_socket_id_map.get(to_socket_id)
  656. for to_sock in to_node.inputs:
  657. if to_sock.identifier == id2: break
  658. else:
  659. to_sock = None
  660. return from_sock, to_sock
  661. def setup_sockets(node, propslist, in_out="inputs"):
  662. sockets_removed = []
  663. for i, (s_id, s_val) in enumerate(propslist[in_out].items()):
  664. if node.bl_idname in ['NodeReroute']:
  665. break # Reroute Nodes do not have anything I can set or modify.
  666. for socket_removed in SOCKETS_REMOVED:
  667. if node.bl_idname == socket_removed[0] and s_id == socket_removed[1]:
  668. prWhite(f"INFO: Ignoring import of socket {s_id}; it has been removed.")
  669. sockets_removed.append(s_val["index"])
  670. sockets_removed.sort()
  671. continue
  672. if s_val["is_output"]:
  673. if node.bl_idname in "MantisSchemaGroup":
  674. node.is_updating = True
  675. try:
  676. socket = node.outputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id)
  677. finally:
  678. node.is_updating=False
  679. elif s_val["index"] >= len(node.outputs):
  680. if node.bl_idname in add_inputs_bl_idnames:
  681. socket = node.outputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, )
  682. else: # first try to get by ID AND name. ID's switch around a bit so we need both to match.
  683. for socket in node.outputs:
  684. if socket.identifier == s_id and socket.name == s_val['name']:
  685. break
  686. # this often fails for group outputs and such
  687. # because the socket ID may not be the same when it is re-generated
  688. else: # otherwise try to get the index
  689. # IT IS NOT CLEAR but this is what throws the index error below BAD
  690. # try to get by name
  691. socket = node.outputs.get(s_val['name'])
  692. if not socket:
  693. try:
  694. socket = node.outputs[int(s_val["index"])]
  695. except IndexError as e:
  696. print (node.id_data.name)
  697. print (propslist['name'])
  698. print (s_id, s_val['name'], s_val['index'])
  699. raise e
  700. if socket.name != s_val["name"]:
  701. right_name = s_val['name']
  702. prRed( "There has been an error getting a socket while importing data."
  703. f"found name: {socket.name}; should have found: {right_name}.")
  704. else:
  705. for removed_index in sockets_removed:
  706. if s_val["index"] > removed_index:
  707. s_val["index"]-=1
  708. if s_val["index"] >= len(node.inputs):
  709. if node.bl_idname in add_inputs_bl_idnames:
  710. socket = node.inputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, use_multi_input=s_val["is_multi_input"])
  711. elif node.bl_idname in ["MantisSchemaGroup"]:
  712. node.is_updating = True
  713. try:
  714. socket = node.inputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, use_multi_input=s_val["is_multi_input"])
  715. finally:
  716. node.is_updating=False
  717. elif node.bl_idname in ["NodeGroupOutput"]:
  718. pass # this is dealt with separately
  719. else:
  720. prWhite("Not found: ", propslist['name'], s_val["name"], s_id)
  721. prRed("Index: ", s_val["index"], "Number of inputs", len(node.inputs))
  722. for thing1, thing2 in zip(propslist[in_out].keys(), getattr(node, in_out).keys()):
  723. print (thing1, thing2)
  724. raise NotImplementedError(wrapRed(f"{node.bl_idname} in {node.id_data.name} needs to be handled in JSON load."))
  725. else: # first try to get by ID AND name. ID's switch around a bit so we need both to match.
  726. for socket in node.inputs:
  727. if socket.identifier == s_id and socket.name == s_val['name']:
  728. break
  729. # failing to find the socket by ID is less common for inputs than outputs.
  730. # it usually isn't a problem.
  731. else: # otherwise try to get the index
  732. # IT IS NOT CLEAR but this is what throws the index error below BAD
  733. socket = node.inputs.get(s_val["name"])
  734. if not socket:
  735. socket = node.inputs[int(s_val["index"])]
  736. # finally we need to check that the name matches.
  737. if socket.name != s_val["name"]:
  738. right_name = s_val['name']
  739. prRed( "There has been an error getting a socket while importing data."
  740. f"found name: {socket.name}; should have found: {right_name}.")
  741. # set the value
  742. for s_p, s_v in s_val.items():
  743. if s_p not in ["default_value"]:
  744. if s_p == "search_prop" and node.bl_idname == 'UtilityMetaRig':
  745. socket.node.armature= s_v
  746. socket.search_prop=bpy.data.objects.get(s_v)
  747. if s_p == "search_prop" and node.bl_idname in ['UtilityMatrixFromCurve', 'UtilityMatricesFromCurve']:
  748. socket.search_prop=bpy.data.objects.get(s_v)
  749. elif s_p == "bone" and socket.bl_idname == 'EnumMetaBoneSocket':
  750. socket.bone = s_v
  751. socket.node.pose_bone = s_v
  752. continue # not editable and NOT SAFE
  753. #
  754. if socket.bl_idname in ["BooleanThreeTupleSocket"]:
  755. value = bool(s_v[0]), bool(s_v[1]), bool(s_v[2]),
  756. s_v = value
  757. try:
  758. setattr(socket, s_p , s_v)
  759. except TypeError as e:
  760. prRed("Can't set socket due to type mismatch: ", node.name, socket.name, s_p, s_v)
  761. # raise e
  762. except ValueError as e:
  763. prRed("Can't set socket due to type mismatch: ", node.name, socket.name, s_p, s_v)
  764. # raise e
  765. except AttributeError as e:
  766. if print_read_only_warning == True:
  767. prWhite("Tried to write a read-only property, ignoring...")
  768. prWhite(f"{socket.node.name}[{socket.name}].{s_p} is read only, cannot set value to {s_v}")
  769. def do_import_from_file(filepath, context):
  770. import json
  771. all_trees = [n_tree for n_tree in bpy.data.node_groups if n_tree.bl_idname in ["MantisTree", "SchemaTree"]]
  772. for tree in all_trees:
  773. tree.is_exporting = True
  774. tree.do_live_update = False
  775. def do_cleanup(tree):
  776. tree.is_exporting = False
  777. tree.do_live_update = True
  778. tree.prevent_next_exec = True
  779. with open(filepath, 'r', encoding='utf-8') as f:
  780. data = json.load(f)
  781. do_import(data,context)
  782. for tree in all_trees:
  783. do_cleanup(tree)
  784. tree = bpy.data.node_groups[list(data.keys())[-1]]
  785. try:
  786. context.space_data.node_tree = tree
  787. except AttributeError: # not hovering over the Node Editor
  788. pass
  789. return {'FINISHED'}
  790. # otherwise:
  791. # repeat this because we left the with, this is bad and ugly but I don't care
  792. for tree in all_trees:
  793. do_cleanup(tree)
  794. return {'CANCELLED'}
  795. def do_import(data, context):
  796. trees = []
  797. tree_sock_id_maps = {}
  798. # First: init the interface of the node graph
  799. for tree_name, tree_data in data.items():
  800. tree_info = tree_data[0]
  801. tree_in_out = tree_data[1]
  802. # need to make a new tree; first, try to get it:
  803. tree = bpy.data.node_groups.get(tree_info["name"])
  804. if tree is None:
  805. tree = bpy.data.node_groups.new(tree_info["name"], tree_info["bl_idname"])
  806. tree.nodes.clear(); tree.links.clear(); tree.interface.clear()
  807. # this may be a bad bad thing to do without some kind of warning TODO TODO
  808. tree.is_executing = True
  809. tree.do_live_update = False
  810. trees.append(tree)
  811. tree_sock_id_map = {}
  812. tree_sock_id_maps[tree.name] = tree_sock_id_map
  813. interface_parent_me = {}
  814. # I need to guarantee that the interface items are in the right order.
  815. interface_sockets = [] # I'll just sort them afterwards so I hold them here.
  816. default_position=0 # We'll use this if the position attribute is not set when e.g. making groups.
  817. for s_name, s_props in tree_in_out.items():
  818. if s_props["item_type"] == 'SOCKET':
  819. if s_props["socket_type"] == "LayerMaskSocket":
  820. continue
  821. if (socket_type := s_props["socket_type"]) == "NodeSocketColor":
  822. socket_type = "VectorSocket"
  823. if bpy.app.version != (4,5,0):
  824. sock = tree.interface.new_socket(s_props["name"], in_out=s_props["in_out"], socket_type=socket_type)
  825. else: # blender 4.5.0 LTS, have to workaround a bug!
  826. from .versioning import workaround_4_5_0_interface_update
  827. sock = workaround_4_5_0_interface_update(tree=tree, name=s_props["name"], in_out=s_props["in_out"],
  828. sock_type=socket_type, parent_name=s_props.get("parent", ''))
  829. tree_sock_id_map[s_name] = sock.identifier
  830. if not (socket_position := s_props.get('position')):
  831. socket_position=default_position; default_position+=1
  832. interface_sockets.append( (sock, socket_position) )
  833. # TODO: set whatever properties are needed (default, etc)
  834. if panel := s_props.get("parent"): # this get is just to maintain compatibility with an older form of this script... and it is harmless
  835. interface_parent_me[sock] = (panel, s_props["position"])
  836. else: # it's a panel
  837. panel = tree.interface.new_panel(s_props["name"], description=s_props.get("description"), default_closed=s_props.get("default_closed"))
  838. for socket, (panel, index) in interface_parent_me.items():
  839. tree.interface.move_to_parent(
  840. socket,
  841. tree.interface.items_tree.get(panel),
  842. index,
  843. )
  844. # BUG this was screwing up the order of things
  845. # so I want to fix it and re-enable it
  846. if True:
  847. # Go BACK through and set the index/position now that all items exist.
  848. interface_sockets.sort(key=lambda a : a[1])
  849. for (socket, position) in interface_sockets:
  850. tree.interface.move(socket, position)
  851. # Now go and do nodes and links
  852. for tree_name, tree_data in data.items():
  853. print ("Importing sub-graph: %s with %s nodes" % (wrapGreen(tree_name), wrapPurple(len(tree_data[2]))) )
  854. tree_info = tree_data[0]
  855. nodes = tree_data[2]
  856. links = tree_data[3]
  857. parent_me = []
  858. tree = bpy.data.node_groups.get(tree_info["name"])
  859. tree.is_executing = True
  860. tree.do_live_update = False
  861. trees.append(tree)
  862. tree_sock_id_map=tree_sock_id_maps[tree.name]
  863. interface_parent_me = {}
  864. # from mantis.utilities import prRed, prWhite, prOrange, prGreen
  865. for name, propslist in nodes.items():
  866. bl_idname = propslist["bl_idname"]
  867. if bl_idname in NODES_REMOVED:
  868. prWhite(f"INFO: Ignoring import of node {name} of type {bl_idname}; it has been removed.")
  869. continue
  870. n = tree.nodes.new(bl_idname)
  871. if bl_idname in ["DeformerMorphTargetDeform"]:
  872. n.inputs.remove(n.inputs[-1]) # get rid of the wildcard
  873. if n.bl_idname in [ "SchemaArrayInput",
  874. "SchemaArrayInputGet",
  875. "SchemaArrayInputAll",
  876. "SchemaArrayOutput",
  877. "SchemaConstInput",
  878. "SchemaConstOutput",
  879. "SchemaOutgoingConnection",
  880. "SchemaIncomingConnection",]:
  881. n.update()
  882. if sub_tree := propslist.get("node_tree"):
  883. n.node_tree = bpy.data.node_groups.get(sub_tree)
  884. from .base_definitions import node_group_update
  885. n.is_updating = True
  886. try:
  887. node_group_update(n, force = True)
  888. finally:
  889. n.is_updating=False
  890. # set up sockets
  891. setup_sockets(n, propslist, in_out="inputs")
  892. setup_sockets(n, propslist, in_out="outputs")
  893. for p, v in propslist.items():
  894. if p in ["node_tree",
  895. "sockets",
  896. "inputs",
  897. "outputs",
  898. "warning_propagation",
  899. "socket_idname"]:
  900. continue
  901. # will throw AttributeError if read-only
  902. # will throw TypeError if wrong type...
  903. if n.bl_idname == "NodeFrame" and p in ["width, height, location"]:
  904. continue
  905. if version < (4,4,0) and p == 'location_absolute':
  906. continue
  907. if p == "parent" and v is not None:
  908. parent_me.append( (n.name, v) )
  909. v = None # for now) #TODO
  910. try:
  911. setattr(n, p, v)
  912. except Exception as e:
  913. print (p)
  914. raise e
  915. for l in links:
  916. from_socket_name = l[6]
  917. to_socket_name = l[7]
  918. name1=l[0]
  919. name2=l[2]
  920. from_sock, to_sock = get_link_sockets(l, tree, tree_sock_id_map)
  921. try:
  922. link = tree.links.new(from_sock, to_sock)
  923. except TypeError:
  924. prPurple (from_sock)
  925. prOrange (to_sock)
  926. if print_link_failure:
  927. from_node_name = link[0]; from_socket_id = link[1]
  928. to_node_name = link[2]; to_socket_id = link[3]
  929. prWhite(f"looking for... {from_node_name}:{from_socket_id}, {to_node_name}:{to_socket_id}")
  930. prRed (f"Failed: {l[0]}:{l[1]} --> {l[2]}:{l[3]}")
  931. prRed (f" got node: {from_node_name}, {to_node_name}")
  932. prRed (f" got socket: {from_sock}, {to_sock}")
  933. raise RuntimeError
  934. else:
  935. prRed(f"Failed to add link in {tree.name}: {name1}:{from_socket_name}, {name2}:{to_socket_name}")
  936. # if at this point it doesn't work... we need to fix
  937. for name, p in parent_me:
  938. if (n := tree.nodes.get(name)) and (p := tree.nodes.get(p)):
  939. n.parent = p
  940. # otherwise the frame node is missing because it was not included in the data e.g. when grouping nodes.
  941. # TODO: IMPORT THIS DATA HERE!!!
  942. # try:
  943. # curves = tree_data[4]
  944. # armatures = tree_data[5]
  945. # except KeyError: # shouldn't happen but maybe someone has an old file
  946. # curves = {}
  947. # armatures = {}
  948. # for curve_name, curve_data in curves.items():
  949. # from .utilities import import_curve_data_to_object
  950. # import_curve_data_to_object(curve_name, curve_data)
  951. tree.is_executing = False
  952. tree.do_live_update = True
  953. import bpy
  954. from bpy_extras.io_utils import ImportHelper, ExportHelper
  955. from bpy.props import StringProperty, BoolProperty, EnumProperty
  956. from bpy.types import Operator
  957. # Save As
  958. class MantisExportNodeTreeSaveAs(Operator, ExportHelper):
  959. """Export a Mantis Node Tree by filename."""
  960. bl_idname = "mantis.export_save_as"
  961. bl_label = "Export Mantis Tree as ...(JSON)"
  962. # ExportHelper mix-in class uses this.
  963. filename_ext = ".rig"
  964. filter_glob: StringProperty(
  965. default="*.rig",
  966. options={'HIDDEN'},
  967. maxlen=255, # Max internal buffer length, longer would be clamped.
  968. )
  969. @classmethod
  970. def poll(cls, context):
  971. return hasattr(context.space_data, 'path')
  972. def execute(self, context):
  973. # we need to get the dependent trees from self.tree...
  974. # there is no self.tree
  975. # how do I choose a tree?
  976. base_tree=context.space_data.path[-1].node_tree
  977. from .utilities import all_trees_in_tree
  978. trees = all_trees_in_tree(base_tree)[::-1]
  979. prGreen("Exporting node graph with dependencies...")
  980. for t in trees:
  981. prGreen ("Node graph: \"%s\"" % (t.name))
  982. base_tree.is_exporting = True
  983. export_data = export_to_json(trees, base_tree, self.filepath)
  984. write_json_data(export_data, self.filepath)
  985. base_tree.is_exporting = False
  986. base_tree.prevent_next_exec = True
  987. base_tree.filepath = self.filepath
  988. return {'FINISHED'}
  989. # Save
  990. class MantisExportNodeTreeSave(Operator):
  991. """Save a Mantis Node Tree to disk."""
  992. bl_idname = "mantis.export_save"
  993. bl_label = "Export Mantis Tree (JSON)"
  994. @classmethod
  995. def poll(cls, context):
  996. return hasattr(context.space_data, 'path')
  997. def execute(self, context):
  998. base_tree=context.space_data.path[-1].node_tree
  999. from .utilities import all_trees_in_tree
  1000. trees = all_trees_in_tree(base_tree)[::-1]
  1001. prGreen("Exporting node graph with dependencies...")
  1002. for t in trees:
  1003. prGreen ("Node graph: \"%s\"" % (t.name))
  1004. base_tree.is_exporting = True
  1005. export_to_json(trees, base_tree, base_tree.filepath)
  1006. write_json_data(export_data, base_tree.filepath)
  1007. base_tree.is_exporting = False
  1008. base_tree.prevent_next_exec = True
  1009. return {'FINISHED'}
  1010. # Save Choose:
  1011. class MantisExportNodeTree(Operator):
  1012. """Save a Mantis Node Tree to disk."""
  1013. bl_idname = "mantis.export_save_choose"
  1014. bl_label = "Export Mantis Tree (JSON)"
  1015. @classmethod
  1016. def poll(cls, context):
  1017. return hasattr(context.space_data, 'path')
  1018. def execute(self, context):
  1019. base_tree=context.space_data.path[-1].node_tree
  1020. if base_tree.filepath:
  1021. prRed(base_tree.filepath)
  1022. return bpy.ops.mantis.export_save()
  1023. else:
  1024. return bpy.ops.mantis.export_save_as('INVOKE_DEFAULT')
  1025. # here is what needs to be done...
  1026. # - modify this to work with a sort of parsed-tree instead (sort of)
  1027. # - this needs to treat each sub-graph on its own
  1028. # - is this a problem? do I need to reconsider how I treat the graph data in mantis?
  1029. # - I should learn functional programming / currying
  1030. # - then the parsed-tree this builds must be executed as Blender nodes
  1031. # - I think... this is not important right now. not yet.
  1032. # - KEEP IT SIMPLE, STUPID
  1033. class MantisImportNodeTree(Operator, ImportHelper):
  1034. """Import a Mantis Node Tree."""
  1035. bl_idname = "mantis.import_tree"
  1036. bl_label = "Import Mantis Tree (JSON)"
  1037. # ImportHelper mixin class uses this
  1038. filename_ext = ".rig"
  1039. filter_glob : StringProperty(
  1040. default="*.rig",
  1041. options={'HIDDEN'},
  1042. maxlen=255, # Max internal buffer length, longer would be clamped.
  1043. )
  1044. def execute(self, context):
  1045. return do_import_from_file(self.filepath, context)
  1046. # this is useful:
  1047. # https://blender.stackexchange.com/questions/73286/how-to-call-a-confirmation-dialog-box
  1048. # class MantisReloadConfirmMenu(bpy.types.Panel):
  1049. # bl_label = "Confirm?"
  1050. # bl_idname = "OBJECT_MT_mantis_reload_confirm"
  1051. # def draw(self, context):
  1052. # layout = self.layout
  1053. # layout.operator("mantis.reload_tree")
  1054. class MantisReloadNodeTree(Operator):
  1055. # """Import a Mantis Node Tree."""
  1056. # bl_idname = "mantis.reload_tree"
  1057. # bl_label = "Import Mantis Tree"
  1058. """Reload Mantis Tree"""
  1059. bl_idname = "mantis.reload_tree"
  1060. bl_label = "Confirm reload tree?"
  1061. bl_options = {'REGISTER', 'INTERNAL'}
  1062. @classmethod
  1063. def poll(cls, context):
  1064. if hasattr(context.space_data, 'path'):
  1065. return True
  1066. return False
  1067. def invoke(self, context, event):
  1068. return context.window_manager.invoke_confirm(self, event)
  1069. def execute(self, context):
  1070. base_tree=context.space_data.path[-1].node_tree
  1071. if not base_tree.filepath:
  1072. self.report({'ERROR'}, "Tree has not been saved - so it cannot be reloaded.")
  1073. return {'CANCELLED'}
  1074. self.report({'INFO'}, "reloading tree")
  1075. return do_import_from_file(base_tree.filepath, context)
  1076. # todo:
  1077. # - export metarig and option to import it
  1078. # - same with controls
  1079. # - it would be nice to have a library of these that can be imported alongside the mantis graph