i_o.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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
  7. from .base_definitions import NODES_REMOVED, SOCKETS_REMOVED
  8. # this works but it is really ugly and probably quite inneficient
  9. # TODO: make hotkeys for export and import and reload from file
  10. # we need to give the tree a filepath attribute and update it on saving
  11. # then we need to use the filepath attribute to load from
  12. # finally we need to use a few operators to choose whether to open a menu or not
  13. # and we need a message to display on save/load so that the user knows it is happening
  14. # TODO:
  15. # Additionally export MetaRig and Curve and other referenced data
  16. # Meshes can be exported as .obj and imported via GN
  17. def TellClasses():
  18. return [ MantisExportNodeTreeSaveAs, MantisExportNodeTreeSave, MantisExportNodeTree, MantisImportNodeTree, MantisReloadNodeTree]
  19. # https://stackoverflow.com/questions/42033142/is-there-an-easy-way-to-check-if-an-object-is-json-serializable-in-python - thanks!
  20. def is_jsonable(x):
  21. import json
  22. try:
  23. json.dumps(x)
  24. return True
  25. except (TypeError, OverflowError):
  26. return False
  27. # https://stackoverflow.com/questions/295135/turn-a-stritree-into-a-valid-filename - thank you user "Sophie Gage"
  28. def remove_special_characters(name):
  29. import re; return re.sub('[^\w_.)( -]', '', name)# re = regular expressions
  30. def fix_custom_parameter(n, property_definition, ):
  31. if n.bl_idname in ['xFormNullNode', 'xFormBoneNode', 'xFormArmatureNode', 'xFormGeometryObjectNode',]:
  32. prop_name = property_definition["name"]
  33. prop_type = property_definition["bl_idname"]
  34. if prop_type in ['ParameterBoolSocket', 'ParameterIntSocket', 'ParameterFloatSocket', 'ParameterVectorSocket' ]:
  35. # is it good to make both of them?
  36. input = n.inputs.new( prop_type, prop_name)
  37. output = n.outputs.new( prop_type, prop_name)
  38. if property_definition["is_output"] == True:
  39. return output
  40. return input
  41. elif n.bl_idname in ['LinkArmature']:
  42. prop_name = property_definition["name"]
  43. prop_type = property_definition["bl_idname"]
  44. input = n.inputs.new( prop_type, prop_name)
  45. return input
  46. return None
  47. def export_to_json(trees, path="", write_file=True, only_selected=False):
  48. # ignore these because they are either unrelated python stuff or useless or borked
  49. prop_ignore = [ "__dict__", "__doc__", "__module__", "__weakref__",# "name",
  50. "bl_height_default", "bl_height_max", "bl_height_min",
  51. "bl_icon", "bl_rna", "bl_static_type", "bl_description",
  52. "bl_width_default", "bl_width_max", "bl_width_min",
  53. "__annotations__", "original", "rna_type", "view_center",
  54. "links", "nodes", "internal_links", "inputs", "outputs",
  55. "__slots__", "dimensions", "type", "interface",
  56. "library_weak_reference", "parsed_tree", "node_tree_updater",
  57. "asset_data", "preview", # blender asset stuff
  58. "object_reference", # this one is here to hold on to widgets when appending
  59. "color_tag" , # added in blender 4.4, not used by Mantis, readonly.
  60. ]
  61. # don't ignore: "bl_idname", "bl_label",
  62. # ignore the name, it's the dict - key for the node props
  63. # no that's stupid don't ignore the name good grief
  64. # I am doing this because these are interactions with other addons that cause problems and probably don't exist for any given user
  65. prop_ignore.extend(['keymesh'])
  66. export_data = {}
  67. for tree in trees:
  68. base_tree = False
  69. if tree is trees[-1]:
  70. base_tree = True
  71. tree_info, tree_in_out = {}, {}
  72. for propname in dir(tree):
  73. # if getattr(tree, propname):
  74. # pass
  75. if (propname in prop_ignore) or ( callable(getattr(tree, propname)) ):
  76. continue
  77. v = getattr(tree, propname)
  78. if isinstance(getattr(tree, propname), bpy.types.bpy_prop_array):
  79. v = tuple(getattr(tree, propname))
  80. if not is_jsonable( v ):
  81. raise RuntimeError(f"Not JSON-able: {propname}, type: {type(v)}")
  82. tree_info[propname] = v
  83. tree_info["name"] = tree.name
  84. # if only_selected:
  85. # # all in/out links, relative to the selection, should be marked and used to initialize tree properties
  86. # pass
  87. if not only_selected: # we'll handle this later with the links
  88. for sock in tree.interface.items_tree:
  89. sock_data={}
  90. if sock.item_type == 'PANEL':
  91. sock_data["name"] = sock.name
  92. sock_data["item_type"] = sock.item_type
  93. sock_data["description"] = sock.description
  94. sock_data["default_closed"] = sock.default_closed
  95. tree_in_out[sock.name] = sock_data
  96. # if it is a socket....
  97. else:
  98. sock_parent = None
  99. if sock.parent:
  100. sock_parent = sock.parent.name
  101. for propname in dir(sock):
  102. if (propname in prop_ignore) or ( callable(v) ):
  103. continue
  104. if (propname == "parent"):
  105. sock_data[propname] = sock_parent
  106. continue
  107. v = getattr(sock, propname)
  108. if isinstance(getattr(sock, propname), bpy.types.bpy_prop_array):
  109. v = tuple(getattr(sock, propname))
  110. if not is_jsonable( v ):
  111. raise RuntimeError(f"{propname}, {type(v)}")
  112. sock_data[propname] = v
  113. tree_in_out[sock.identifier] = sock_data
  114. nodes = {}
  115. for n in tree.nodes:
  116. # if this is a node-group, force it to update its interface, because it may be messed up.
  117. # can remove this HACK when I have stronger guarentees about node-group's keeping the interface
  118. from .base_definitions import node_group_update
  119. if hasattr(n, "node_tree"):
  120. node_group_update(n, force=True)
  121. if only_selected and n.select == False:
  122. continue
  123. node_props, sockets = {}, {}
  124. for propname in dir(n):
  125. v = getattr(n, propname)
  126. if propname in ['fake_fcurve_ob']:
  127. v=v.name
  128. if (propname in prop_ignore) or ( callable(v) ):
  129. continue
  130. if v.__class__.__name__ in ["Vector", "Color"]:
  131. v = tuple(v)
  132. if isinstance(v, bpy.types.NodeTree):
  133. v = v.name
  134. if isinstance(v, bpy.types.bpy_prop_array):
  135. v = tuple(v)
  136. if propname == "parent" and v:
  137. v = v.name
  138. if not is_jsonable(v):
  139. raise RuntimeError(f"Could not export... {n.name}, {propname}, {type(v)}")
  140. if v is None:
  141. continue
  142. node_props[propname] = v
  143. # so we have to accumulate the parent location because the location is not absolute
  144. if propname == "location" and n.parent is not None:
  145. location_acc = Vector((0,0))
  146. parent = n.parent
  147. while (parent):
  148. location_acc += parent.location
  149. parent = parent.parent
  150. location_acc += getattr(n, propname)
  151. node_props[propname] = tuple(location_acc)
  152. # this works!
  153. # n.parent = None
  154. # if propname == "location":
  155. # print (v, n.location)
  156. # if parent:
  157. # n.parent = parent
  158. # now we need to get the sockets...
  159. # WHY IS THIS FUNCTION DEFINED IN THIS SCOPE?
  160. def socket_data(s):
  161. socket = {}
  162. socket["name"] = s.name
  163. socket["bl_idname"] = s.bl_idname
  164. socket["is_output"] = s.is_output
  165. socket["is_multi_input"] = s.is_multi_input
  166. # if s.bl_idname == 'TransformSpaceSocket':
  167. # prGreen(s.default_value)
  168. # here is where we'll handle a socket's special data
  169. if s.bl_idname == "EnumMetaBoneSocket":
  170. socket["bone"] = s.bone
  171. if s.bl_idname in ["EnumMetaBoneSocket", "EnumMetaRigSocket", "EnumCurveSocket"]:
  172. if sp := s.get("search_prop"): # may be None
  173. socket["search_prop"] = sp.name # this is an object.
  174. #
  175. # v = s.get("default_value") # this doesn't seem to work, see below
  176. if hasattr(s, "default_value"):
  177. v = s.default_value
  178. else:
  179. v = None
  180. v_type = type(v)
  181. if v is None:
  182. return socket # we don't need to store this.
  183. if not is_jsonable(v):
  184. v = tuple(v)
  185. if not is_jsonable(v):
  186. raise RuntimeError(f"Error serializing data in {s.node.name}::{s.name} for value of type {v_type}")
  187. socket["default_value"] = v
  188. # at this point we can get the custom parameter ui hints if we want
  189. if not s.is_output:
  190. # try and get this data
  191. if v := getattr(s,'min', None):
  192. socket["min"] = v
  193. if v := getattr(s,'max', None):
  194. socket["max"] = v
  195. if v := getattr(s,'soft_min', None):
  196. socket["soft_min"] = v
  197. if v := getattr(s,'soft_max', None):
  198. socket["soft_max"] = v
  199. if v := getattr(s,'description', None):
  200. socket["description"] = v
  201. return socket
  202. #
  203. for i, s in enumerate(n.inputs):
  204. socket = socket_data(s)
  205. socket["index"]=i
  206. sockets[s.identifier] = socket
  207. for i, s in enumerate(n.outputs):
  208. socket = socket_data(s)
  209. socket["index"]=i
  210. sockets[s.identifier] = socket
  211. node_props["sockets"] = sockets
  212. nodes[n.name] = node_props
  213. links = []
  214. in_sockets = {}
  215. out_sockets = {}
  216. in_node = {"name":"MANTIS_AUTOGEN_GROUP_INPUT", "bl_idname":"NodeGroupInput", "sockets":in_sockets}
  217. out_node = {"name":"MANTIS_AUTOGEN_GROUP_OUTPUT", "bl_idname":"NodeGroupOutput", "sockets":out_sockets}
  218. add_input_node, add_output_node = False, False
  219. unique_sockets_from={}
  220. unique_sockets_to={}
  221. for l in tree.links:
  222. a, b = l.from_node.name, l.from_socket.identifier
  223. c, d = l.to_node.name, l.to_socket.identifier
  224. # get the indices of the sockets to be absolutely sure
  225. for e, outp in enumerate(l.from_node.outputs):
  226. # for some reason, 'is' does not return True no matter what...
  227. # so we are gonn compare the memory address directly, this is stupid
  228. if (outp.as_pointer() == l.from_socket.as_pointer()): break
  229. else:
  230. problem=l.from_node.name + "::" + l.from_socket.name
  231. raise RuntimeError(wrapRed(f"Error saving index of socket: {problem}"))
  232. for f, inp in enumerate(l.to_node.inputs):
  233. if (inp.as_pointer() == l.to_socket.as_pointer()): break
  234. else:
  235. problem = l.to_node.name + "::" + l.to_socket.name
  236. raise RuntimeError(wrapRed(f"Error saving index of socket: {problem}"))
  237. g, h = l.from_socket.name, l.to_socket.name
  238. # print (f"{a}:{b} --> {c}:{d})")
  239. # this data is good enough
  240. if base_tree:
  241. if (only_selected and l.from_node.select) and (not l.to_node.select):
  242. # handle an output in the tree
  243. add_output_node=True
  244. if not (sock_name := unique_sockets_to.get(l.from_socket.node.name+l.from_socket.identifier)):
  245. sock_name = l.to_socket.name; name_stub = sock_name
  246. used_names = list(tree_in_out.keys()); i=0
  247. while sock_name in used_names:
  248. sock_name=name_stub+'.'+str(i).zfill(3); i+=1
  249. unique_sockets_to[l.from_socket.node.name+l.from_socket.identifier]=sock_name
  250. out_sock = out_sockets.get(sock_name)
  251. if not out_sock:
  252. out_sock = {}; out_sockets[sock_name] = out_sock
  253. out_sock["index"]=len(out_sockets) # zero indexed, so zero length makes zero the first index and so on, this works
  254. out_sock["name"] = sock_name
  255. out_sock["identifier"] = sock_name
  256. out_sock["bl_idname"] = l.to_socket.bl_idname
  257. out_sock["is_output"] = False
  258. out_sock["source"]=[l.to_socket.node.name,l.to_socket.identifier]
  259. 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
  260. sock_data={}
  261. sock_data["name"] = sock_name
  262. sock_data["item_type"] = "SOCKET"
  263. sock_data["default_closed"] = False
  264. sock_data["socket_type"] = l.from_socket.bl_idname
  265. sock_data["identifier"] = sock_name
  266. sock_data["in_out"]="OUTPUT"
  267. sock_data["index"]=out_sock["index"]
  268. tree_in_out[sock_name] = sock_data
  269. c=out_node["name"]
  270. d=out_sock["identifier"]
  271. f=out_sock["index"]
  272. h=out_sock["name"]
  273. elif (only_selected and (not l.from_node.select)) and l.to_node.select:
  274. add_input_node=True
  275. # we need to get a unique name for this
  276. # use the Tree IN/Out because we are dealing with Group in/out
  277. if not (sock_name := unique_sockets_from.get(l.from_socket.node.name+l.from_socket.identifier)):
  278. sock_name = l.from_socket.name; name_stub = sock_name
  279. used_names = list(tree_in_out.keys()); i=0
  280. while sock_name in used_names:
  281. sock_name=name_stub+'.'+str(i).zfill(3); i+=1
  282. unique_sockets_from[l.from_socket.node.name+l.from_socket.identifier]=sock_name
  283. in_sock = in_sockets.get(sock_name)
  284. if not in_sock:
  285. in_sock = {}; in_sockets[sock_name] = in_sock
  286. in_sock["index"]=len(in_sockets) # zero indexed, so zero length makes zero the first index and so on, this works
  287. #
  288. in_sock["name"] = sock_name
  289. in_sock["identifier"] = sock_name
  290. in_sock["bl_idname"] = l.from_socket.bl_idname
  291. in_sock["is_output"] = True
  292. 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
  293. in_sock["source"] = [l.from_socket.node.name,l.from_socket.identifier]
  294. sock_data={}
  295. sock_data["name"] = sock_name
  296. sock_data["item_type"] = "SOCKET"
  297. sock_data["default_closed"] = False
  298. sock_data["socket_type"] = l.from_socket.bl_idname
  299. sock_data["identifier"] = sock_name
  300. sock_data["in_out"]="INPUT"
  301. sock_data["index"]=in_sock["index"]
  302. tree_in_out[sock_name] = sock_data
  303. a=in_node.get("name")
  304. b=in_sock["identifier"]
  305. e=in_sock["index"]
  306. g=in_node.get("name")
  307. # parentheses matter here...
  308. elif (only_selected and not (l.from_node.select and l.to_node.select)):
  309. continue
  310. elif only_selected and not (l.from_node.select and l.to_node.select):
  311. continue # pass if both links are not selected
  312. links.append( (a,b,c,d,e,f,g,h) ) # it's a tuple
  313. if add_input_node or add_output_node:
  314. all_nodes_bounding_box=[Vector((float("inf"),float("inf"))), Vector((-float("inf"),-float("inf")))]
  315. for n in nodes.values():
  316. if n["location"][0] < all_nodes_bounding_box[0].x:
  317. all_nodes_bounding_box[0].x = n["location"][0]
  318. if n["location"][1] < all_nodes_bounding_box[0].y:
  319. all_nodes_bounding_box[0].y = n["location"][1]
  320. #
  321. if n["location"][0] > all_nodes_bounding_box[1].x:
  322. all_nodes_bounding_box[1].x = n["location"][0]
  323. if n["location"][1] > all_nodes_bounding_box[1].y:
  324. all_nodes_bounding_box[1].y = n["location"][1]
  325. if add_input_node:
  326. 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))
  327. nodes["MANTIS_AUTOGEN_GROUP_INPUT"]=in_node
  328. if add_output_node:
  329. 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))
  330. nodes["MANTIS_AUTOGEN_GROUP_OUTPUT"]=out_node
  331. export_data[tree.name] = (tree_info, tree_in_out, nodes, links,) # f_curves)
  332. import json
  333. if not write_file:
  334. return export_data # gross to have a different type of return value... but I don't care
  335. with open(path, "w") as file:
  336. print(wrapWhite("Writing mantis tree data to: "), wrapGreen(file.name))
  337. file.write( json.dumps(export_data, indent = 4) )
  338. # I'm gonna do this in a totally naive way, because this should already be sorted properly
  339. # for the sake of dependency satisfaction. So the current "tree" should be the "main" tree
  340. tree.filepath = path
  341. def do_import_from_file(filepath, context):
  342. import json
  343. all_trees = [n_tree for n_tree in bpy.data.node_groups if n_tree.bl_idname in ["MantisTree", "SchemaTree"]]
  344. for tree in all_trees:
  345. tree.is_exporting = True
  346. tree.do_live_update = False
  347. with open(filepath, 'r', encoding='utf-8') as f:
  348. data = json.load(f)
  349. do_import(data,context)
  350. for tree in all_trees:
  351. tree.do_live_update = True
  352. tree = bpy.data.node_groups[list(data.keys())[-1]]
  353. try:
  354. context.space_data.node_tree = tree
  355. except AttributeError: # not hovering over the Node Editor
  356. pass
  357. return {'FINISHED'}
  358. # otherwise:
  359. # repeat this because we left the with, this is bad and ugly but I don't care
  360. for tree in all_trees:
  361. tree.is_exporting = False
  362. tree.do_live_update = True
  363. tree.prevent_next_exec = True
  364. return {'CANCELLED'}
  365. def do_import(data, context):
  366. trees = []
  367. tree_sock_id_maps = {}
  368. # First: init the interface of the node graph
  369. for tree_name, tree_data in data.items():
  370. tree_info = tree_data[0]
  371. tree_in_out = tree_data[1]
  372. # need to make a new tree; first, try to get it:
  373. tree = bpy.data.node_groups.get(tree_info["name"])
  374. if tree is None:
  375. tree = bpy.data.node_groups.new(tree_info["name"], tree_info["bl_idname"])
  376. tree.nodes.clear(); tree.links.clear(); tree.interface.clear()
  377. # this may be a bad bad thing to do without some kind of warning TODO TODO
  378. tree.is_executing = True
  379. tree.do_live_update = False
  380. trees.append(tree)
  381. tree_sock_id_map = {}
  382. tree_sock_id_maps[tree.name] = tree_sock_id_map
  383. interface_parent_me = {}
  384. # I need to guarantee that the interface items are in the right order.
  385. interface_sockets = [] # I'll just sort them afterwards so I hold them here.
  386. default_position=0 # We'll use this if the position attribute is not set when e.g. making groups.
  387. for s_name, s_props in tree_in_out.items():
  388. if s_props["item_type"] == 'SOCKET':
  389. if s_props["socket_type"] == "LayerMaskSocket":
  390. continue
  391. if (socket_type := s_props["socket_type"]) == "NodeSocketColor":
  392. socket_type = "VectorSocket"
  393. sock = tree.interface.new_socket(s_props["name"], in_out=s_props["in_out"], socket_type=socket_type)
  394. tree_sock_id_map[s_name] = sock.identifier
  395. if not (socket_position := s_props.get('position')):
  396. socket_position=default_position; default_position+=1
  397. interface_sockets.append( (sock, socket_position) )
  398. # TODO: set whatever properties are needed (default, etc)
  399. if panel := s_props.get("parent"): # this get is just to maintain compatibility with an older form of this script... and it is harmless
  400. interface_parent_me[sock] = (panel, s_props["position"])
  401. else: # it's a panel
  402. panel = tree.interface.new_panel(s_props["name"], description=s_props.get("description"), default_closed=s_props.get("default_closed"))
  403. for socket, (panel, index) in interface_parent_me.items():
  404. tree.interface.move_to_parent(
  405. socket,
  406. tree.interface.items_tree.get(panel),
  407. index,
  408. )
  409. # Go BACK through and set the index/position now that all items exist.
  410. interface_sockets.sort(key=lambda a : a[1])
  411. for (socket, position) in interface_sockets:
  412. print (socket.name, position)
  413. tree.interface.move(socket, position)
  414. # Now go and do nodes and links
  415. for tree_name, tree_data in data.items():
  416. print ("Importing sub-graph: %s with %s nodes" % (wrapGreen(tree_name), wrapPurple(len(tree_data[2]))) )
  417. tree_info = tree_data[0]
  418. nodes = tree_data[2]
  419. links = tree_data[3]
  420. parent_me = []
  421. tree = bpy.data.node_groups.get(tree_info["name"])
  422. tree.is_executing = True
  423. tree.do_live_update = False
  424. trees.append(tree)
  425. tree_sock_id_map=tree_sock_id_maps[tree.name]
  426. interface_parent_me = {}
  427. # from mantis.utilities import prRed, prWhite, prOrange, prGreen
  428. for name, propslist in nodes.items():
  429. bl_idname = propslist["bl_idname"]
  430. if bl_idname in NODES_REMOVED:
  431. prWhite(f"INFO: Ignoring import of node {name} of type {bl_idname}; it has been removed.")
  432. continue
  433. n = tree.nodes.new(bl_idname)
  434. if bl_idname in ["DeformerMorphTargetDeform"]:
  435. n.inputs.remove(n.inputs[-1]) # get rid of the wildcard
  436. if n.bl_idname in [ "SchemaArrayInput",
  437. "SchemaArrayInputGet",
  438. "SchemaArrayOutput",
  439. "SchemaConstInput",
  440. "SchemaConstOutput",
  441. "SchemaOutgoingConnection",
  442. "SchemaIncomingConnection",]:
  443. n.update()
  444. if sub_tree := propslist.get("node_tree"):
  445. n.node_tree = bpy.data.node_groups.get(sub_tree)
  446. from .base_definitions import node_group_update
  447. node_group_update(n, force = True)
  448. sockets_removed = []
  449. for i, (s_id, s_val) in enumerate(propslist["sockets"].items()):
  450. for socket_removed in SOCKETS_REMOVED:
  451. if n.bl_idname == socket_removed[0] and s_id == socket_removed[1]:
  452. prWhite(f"INFO: Ignoring import of socket {s_id}; it has been removed.")
  453. sockets_removed.append(s_val["index"])
  454. sockets_removed.sort()
  455. continue
  456. try:
  457. if s_val["is_output"]: # for some reason it thinks the index is a string?
  458. # try:
  459. if n.bl_idname == "MantisSchemaGroup":
  460. socket = n.outputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id)
  461. else:
  462. socket = n.outputs[int(s_val["index"])]
  463. else:
  464. for removed_index in sockets_removed:
  465. if s_val["index"] > removed_index:
  466. s_val["index"]-=1
  467. if s_val["index"] >= len(n.inputs):
  468. if n.bl_idname == "UtilityDriver":
  469. with bpy.context.temp_override(**{'node':n}):
  470. bpy.ops.mantis.driver_node_add_variable()
  471. socket = n.inputs[int(s_val["index"])]
  472. elif n.bl_idname == "UtilityFCurve":
  473. with bpy.context.temp_override(**{'node':n}):
  474. bpy.ops.mantis.fcurve_node_add_kf()
  475. socket = n.inputs[int(s_val["index"])]
  476. elif n.bl_idname == "MantisSchemaGroup":
  477. socket = n.inputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id, use_multi_input=s_val["is_multi_input"])
  478. # for k,v in s_val.items():
  479. # print(f"{k}:{v}")
  480. # print (s_id)
  481. # raise NotImplementedError(s_val["is_multi_input"])
  482. elif n.bl_idname in ["NodeGroupOutput"]:
  483. # print (len(n.inputs), len(n.outputs))
  484. pass
  485. elif n.bl_idname == "LinkArmature":
  486. with bpy.context.temp_override(**{'node':n}):
  487. bpy.ops.mantis.link_armature_node_add_target()
  488. socket = n.inputs[int(s_val["index"])]
  489. elif n.bl_idname == "DeformerMorphTargetDeform": # this one doesn't use an operator since I figure out how to do dynamic node stuff
  490. socket = n.inputs.new(s_val["bl_idname"], s_val["name"], identifier=s_id)
  491. else:
  492. prWhite(n.name, s_val["name"], s_id)
  493. for k,v in propslist["sockets"].items():
  494. print(k,v)
  495. prRed(s_val["index"], len(n.inputs))
  496. raise NotImplementedError(wrapRed(f"{n.bl_idname} needs to be handled in JSON load."))
  497. # if n.bl_idname in ['']
  498. else: # most of the time
  499. socket = n.inputs[int(s_val["index"])]
  500. except IndexError:
  501. socket = fix_custom_parameter(n, propslist["sockets"][s_id])
  502. if socket is None:
  503. is_output = "output" if {s_val["is_output"]} else "input"
  504. prRed(s_val, type(s_val))
  505. raise RuntimeError(is_output, n.name, s_val["name"], s_id, len(n.inputs))
  506. # if propslist["bl_idname"] == "UtilityMetaRig":#and i == 0:
  507. # pass#prRed (i, s_id, s_val)
  508. # if propslist["bl_idname"] == "UtilityMetaRig":# and i > 0:
  509. # prRed("Not Found: %s" % (s_id))
  510. # prOrange(propslist["sockets"][s_id])
  511. # socket = fix_custom_parameter(n, propslist["sockets"][s_id]
  512. for s_p, s_v in s_val.items():
  513. if s_p not in ["default_value"]:
  514. if s_p == "search_prop" and n.bl_idname == 'UtilityMetaRig':
  515. socket.node.armature= s_v
  516. socket.search_prop=bpy.data.objects.get(s_v)
  517. if s_p == "search_prop" and n.bl_idname in ['UtilityMatrixFromCurve', 'UtilityMatricesFromCurve']:
  518. socket.search_prop=bpy.data.objects.get(s_v)
  519. elif s_p == "bone" and socket.bl_idname == 'EnumMetaBoneSocket':
  520. socket.bone = s_v
  521. socket.node.pose_bone = s_v
  522. continue # not editable and NOT SAFE
  523. #
  524. if socket.bl_idname in ["BooleanThreeTupleSocket"]:
  525. value = bool(s_v[0]), bool(s_v[1]), bool(s_v[2]),
  526. s_v = value
  527. try:
  528. setattr(socket, s_p , s_v)
  529. except TypeError as e:
  530. prRed("Can't set socket due to type mismatch: ", socket, s_p, s_v)
  531. # raise e
  532. except ValueError as e:
  533. prRed("Can't set socket due to type mismatch: ", socket, s_p, s_v)
  534. # raise e
  535. except AttributeError as e:
  536. prWhite("Tried to write a read-only property, ignoring...")
  537. prWhite(f"{socket.node.name}[{socket.name}].{s_p} is read only, cannot set value to {s_v}")
  538. # raise e
  539. # not sure if this is true:
  540. # this can find properties that aren't node in/out
  541. # we should also be checking those above actually
  542. # TODO:
  543. # find out why "Bone hide" not being found
  544. for p, v in propslist.items():
  545. if p == "sockets": # it's the sockets dict
  546. continue
  547. if p == "node_tree":
  548. continue # we've already done this # v = bpy.data.node_groups.get(v)
  549. # will throw AttributeError if read-only
  550. # will throw TypeError if wrong type...
  551. if n.bl_idname == "NodeFrame" and p in ["width, height, location"]:
  552. continue
  553. if p == "parent" and v is not None:
  554. parent_me.append( (n.name, v) )
  555. v = None # for now) #TODO
  556. try:
  557. setattr(n, p, v)
  558. except Exception as e:
  559. print (p)
  560. raise e
  561. # raise NotImplementedError
  562. # for k,v in tree_sock_id_map.items():
  563. # print (wrapGreen(k), " ", wrapPurple(v))
  564. for l in links:
  565. id1 = l[1]
  566. id2 = l[3]
  567. #
  568. name1=l[6]
  569. name2=l[7]
  570. # prWhite(l[0], l[1], " --> ", l[2], l[3])
  571. # l has...
  572. # node 1
  573. # identifier 1
  574. # node 2
  575. # identifier 2
  576. # if the from/to socket or node has been removed, continue
  577. from_node = tree.nodes.get(l[0])
  578. if not from_node:
  579. prWhite(f"INFO: cannot create link {l[0]}:{l[1]} --> {l[2]}:{l[3]}")
  580. continue
  581. if hasattr(from_node, "node_tree"): # now we have to map by name actually
  582. try:
  583. id1 = from_node.outputs[l[4]].identifier
  584. except IndexError:
  585. prRed ("Index incorrect")
  586. id1 = None
  587. elif from_node.bl_idname in ["NodeGroupInput"]:
  588. id1 = tree_sock_id_map.get(l[1])
  589. if id1 is None:
  590. prRed(l[1])
  591. # prOrange (l[1], id1)
  592. elif from_node.bl_idname in ["SchemaArrayInput", "SchemaConstInput", "SchemaIncomingConnection"]:
  593. # try the index instead
  594. id1 = from_node.outputs[l[4]].identifier
  595. for from_sock in from_node.outputs:
  596. if from_sock.identifier == id1: break
  597. else: # we can raise a runtime error here actually
  598. from_sock = None
  599. to_node = tree.nodes[l[2]]
  600. if hasattr(to_node, "node_tree"):
  601. try:
  602. id2 = to_node.inputs[l[5]].identifier
  603. except IndexError:
  604. prRed ("Index incorrect")
  605. id2 = None
  606. elif to_node.bl_idname in ["NodeGroupOutput"]:
  607. id2 = tree_sock_id_map.get(l[3])
  608. # prPurple(to_node.name)
  609. # for inp in to_node.inputs:
  610. # prPurple(inp.name, inp.identifier)
  611. # prOrange (l[3], id2)
  612. elif to_node.bl_idname in ["SchemaArrayOutput", "SchemaConstOutput", "SchemaOutgoingConnection"]:
  613. # try the index instead
  614. id2 = to_node.inputs[l[5]].identifier
  615. # try to get by name
  616. #id2 = to_node.inputs[name2]
  617. for to_sock in to_node.inputs:
  618. if to_sock.identifier == id2: break
  619. else:
  620. to_sock = None
  621. try:
  622. link = tree.links.new(from_sock, to_sock)
  623. except TypeError:
  624. if ((id1 is not None) and ("Layer Mask" in id1)) or ((id2 is not None) and ("Layer Mask" in id2)):
  625. pass
  626. else:
  627. prWhite(f"looking for... {name1}:{id1}, {name2}:{id2}")
  628. prRed (f"Failed: {l[0]}:{l[1]} --> {l[2]}:{l[3]}")
  629. prRed (f" got node: {from_node.name}, {to_node.name}")
  630. prRed (f" got socket: {from_sock}, {to_sock}")
  631. if from_sock is None:
  632. prOrange ("Candidates...")
  633. for out in from_node.outputs:
  634. prOrange(" %s, id=%s" % (out.name, out.identifier))
  635. for k, v in tree_sock_id_map.items():
  636. print (wrapOrange(k), wrapPurple(v))
  637. if to_sock is None:
  638. prOrange ("Candidates...")
  639. for inp in to_node.inputs:
  640. prOrange(" %s, id=%s" % (inp.name, inp.identifier))
  641. for k, v in tree_sock_id_map.items():
  642. print (wrapOrange(k), wrapPurple(v))
  643. raise RuntimeError
  644. # if at this point it doesn't work... we need to fix
  645. for name, p in parent_me:
  646. if (n := tree.nodes.get(name)) and (p := tree.nodes.get(p)):
  647. n.parent = p
  648. # otherwise the frame node is missing because it was not included in the data e.g. when grouping nodes.
  649. tree.is_executing = False
  650. tree.do_live_update = True
  651. # try:
  652. # tree=context.space_data.path[0].node_tree
  653. # tree.update_tree(context)
  654. # except: #update tree can cause all manner of errors
  655. # pass
  656. import bpy
  657. from bpy_extras.io_utils import ImportHelper, ExportHelper
  658. from bpy.props import StringProperty, BoolProperty, EnumProperty
  659. from bpy.types import Operator
  660. # Save As
  661. class MantisExportNodeTreeSaveAs(Operator, ExportHelper):
  662. """Export a Mantis Node Tree by filename."""
  663. bl_idname = "mantis.export_save_as"
  664. bl_label = "Export Mantis Tree as ...(JSON)"
  665. # ExportHelper mix-in class uses this.
  666. filename_ext = ".rig"
  667. filter_glob: StringProperty(
  668. default="*.rig",
  669. options={'HIDDEN'},
  670. maxlen=255, # Max internal buffer length, longer would be clamped.
  671. )
  672. @classmethod
  673. def poll(cls, context):
  674. return hasattr(context.space_data, 'path')
  675. def execute(self, context):
  676. # we need to get the dependent trees from self.tree...
  677. # there is no self.tree
  678. # how do I choose a tree?
  679. base_tree=context.space_data.path[-1].node_tree
  680. from .utilities import all_trees_in_tree
  681. trees = all_trees_in_tree(base_tree)[::-1]
  682. prGreen("Exporting node graph with dependencies...")
  683. for t in trees:
  684. prGreen ("Node graph: \"%s\"" % (t.name))
  685. base_tree.is_exporting = True
  686. export_to_json(trees, self.filepath)
  687. base_tree.is_exporting = False
  688. base_tree.prevent_next_exec = True
  689. return {'FINISHED'}
  690. # Save
  691. class MantisExportNodeTreeSave(Operator):
  692. """Save a Mantis Node Tree to disk."""
  693. bl_idname = "mantis.export_save"
  694. bl_label = "Export Mantis Tree (JSON)"
  695. @classmethod
  696. def poll(cls, context):
  697. return hasattr(context.space_data, 'path')
  698. def execute(self, context):
  699. base_tree=context.space_data.path[-1].node_tree
  700. from .utilities import all_trees_in_tree
  701. trees = all_trees_in_tree(base_tree)[::-1]
  702. prGreen("Exporting node graph with dependencies...")
  703. for t in trees:
  704. prGreen ("Node graph: \"%s\"" % (t.name))
  705. base_tree.is_exporting = True
  706. export_to_json(trees, self.filepath)
  707. base_tree.is_exporting = False
  708. base_tree.prevent_next_exec = True
  709. return {'FINISHED'}
  710. # Save Choose:
  711. class MantisExportNodeTree(Operator):
  712. """Save a Mantis Node Tree to disk."""
  713. bl_idname = "mantis.export_save_choose"
  714. bl_label = "Export Mantis Tree (JSON)"
  715. @classmethod
  716. def poll(cls, context):
  717. return hasattr(context.space_data, 'path')
  718. def execute(self, context):
  719. base_tree=context.space_data.path[-1].node_tree
  720. if base_tree.filepath:
  721. prRed(base_tree.filepath)
  722. return bpy.ops.mantis.export_save()
  723. else:
  724. return bpy.ops.mantis.export_save_as('INVOKE_DEFAULT')
  725. # here is what needs to be done...
  726. # - modify this to work with a sort of parsed-tree instead (sort of)
  727. # - this needs to treat each sub-graph on its own
  728. # - is this a problem? do I need to reconsider how I treat the graph data in mantis?
  729. # - I should learn functional programming / currying
  730. # - then the parsed-tree this builds must be executed as Blender nodes
  731. # - I think... this is not important right now. not yet.
  732. # - KEEP IT SIMPLE, STUPID
  733. class MantisImportNodeTree(Operator, ImportHelper):
  734. """Import a Mantis Node Tree."""
  735. bl_idname = "mantis.import_tree"
  736. bl_label = "Import Mantis Tree (JSON)"
  737. # ImportHelper mixin class uses this
  738. filename_ext = ".rig"
  739. filter_glob : StringProperty(
  740. default="*.rig",
  741. options={'HIDDEN'},
  742. maxlen=255, # Max internal buffer length, longer would be clamped.
  743. )
  744. def execute(self, context):
  745. return do_import_from_file(self.filepath, context)
  746. # this is useful:
  747. # https://blender.stackexchange.com/questions/73286/how-to-call-a-confirmation-dialog-box
  748. # class MantisReloadConfirmMenu(bpy.types.Panel):
  749. # bl_label = "Confirm?"
  750. # bl_idname = "OBJECT_MT_mantis_reload_confirm"
  751. # def draw(self, context):
  752. # layout = self.layout
  753. # layout.operator("mantis.reload_tree")
  754. class MantisReloadNodeTree(Operator):
  755. # """Import a Mantis Node Tree."""
  756. # bl_idname = "mantis.reload_tree"
  757. # bl_label = "Import Mantis Tree"
  758. """Reload Mantis Tree"""
  759. bl_idname = "mantis.reload_tree"
  760. bl_label = "Confirm reload tree?"
  761. bl_options = {'REGISTER', 'INTERNAL'}
  762. @classmethod
  763. def poll(cls, context):
  764. if hasattr(context.space_data, 'path'):
  765. return True
  766. return False
  767. def invoke(self, context, event):
  768. return context.window_manager.invoke_confirm(self, event)
  769. def execute(self, context):
  770. base_tree=context.space_data.path[-1].node_tree
  771. if not base_tree.filepath:
  772. self.report({'ERROR'}, "Tree has not been saved - so it cannot be reloaded.")
  773. return {'CANCELLED'}
  774. self.report({'INFO'}, "reloading tree")
  775. return do_import_from_file(base_tree.filepath, context)
  776. # todo:
  777. # - export metarig and option to import it
  778. # - same with controls
  779. # - it would be nice to have a library of these that can be imported alongside the mantis graph