i_o.py 64 KB

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