i_o.py 39 KB

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