i_o.py 46 KB

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