versioning.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. #Versioning Tasks
  2. # this will be the new versioning system, and will deprecate the old SOCKETS_ADDED and such
  3. from bpy.types import Node, NodeSocket
  4. from bpy.app import version as bpy_version
  5. from .utilities.utilities import (prRed, prGreen, prPurple, prWhite,
  6. prOrange,
  7. wrapRed, wrapGreen, wrapPurple, wrapWhite,
  8. wrapOrange,
  9. get_socket_maps, do_relink, )
  10. # CHECKLIST FOR DUMMIES:
  11. # Did you make sure to turn off and re-enable tree updates?
  12. # Did you restore connections to the node socket after changing things?
  13. # Did you test FUNCTIONALITY in your test rigs instead of just checking if the tree
  14. # would generate? CHANGED FUNCTIONALITY IS STILL A BUG!!
  15. # Did you make sure to toggle the is_updating flag for ANY node that is touched by
  16. # the edits you are doing to the current node (example: removing a socket causes
  17. # linked group and schema nodes to update)
  18. # (add more whenever a weird or difficult to debug problem occurs)
  19. # Did you check the update script on a tree that doesn't need it?
  20. def version_upgrade_very_old(*args, **kwargs):
  21. node = kwargs['node']
  22. current_major_version = node.id_data.mantis_version[0]
  23. current_minor_version = node.id_data.mantis_version[1]
  24. if current_major_version > 0: return# major version must be 0
  25. if current_minor_version > 11: return# minor version must be 12 or less
  26. # this is the old node update, very inneficient and strange and badly organized
  27. NODES_REMOVED=["xFormRootNode"]
  28. # Node bl_idname, # Socket Name
  29. SOCKETS_REMOVED=[("UtilityDriverVariable", "Transform Channel"),
  30. ("xFormRootNode","World Out"),
  31. ("UtilitySwitch","xForm"),
  32. ("LinkDrivenParameter", "Enable")]
  33. # Node Class #Prior bl_idname # prior name # new bl_idname # new name, # Multi
  34. SOCKETS_RENAMED=[ ("LinkDrivenParameter", "DriverSocket", "Driver", "FloatSocket", "Value", False),
  35. ("DeformerHook", "IntSocket", "Index", "UnsignedIntSocket", "Point Index", False),
  36. ("SchemaConstOutput", "IntSocket", "Expose when N==", "UnsignedIntSocket", "Expose at Index", False),]
  37. # NODE CLASS NAME IN_OUT SOCKET TYPE SOCKET NAME INDEX MULTI DEFAULT
  38. SOCKETS_ADDED=[("DeformerMorphTargetDeform", 'INPUT', 'BooleanSocket', "Use Shape Key", 1, False, False),
  39. ("DeformerMorphTargetDeform", 'INPUT', 'BooleanSocket', "Use Offset", 2, False, True),
  40. ("UtilityFCurve", 'INPUT', "eFCrvExtrapolationMode", "Extrapolation Mode", 0, False, 'CONSTANT'),
  41. ("LinkCopyScale", 'INPUT', "BooleanSocket", "Additive", 3, False, False),
  42. ("DeformerHook", 'INPUT', "FloatFactorSocket", "Influence",3, False, 1.0),
  43. ("DeformerHook", 'INPUT', "UnsignedIntSocket", "Spline Index", 2, False, 0),
  44. ("DeformerHook", 'INPUT', "BooleanSocket", "Auto-Bezier", 5, False, True),
  45. ("UtilityCompare", 'INPUT', "EnumCompareOperation", "Comparison", 0, False, 'EQUAL'),
  46. ("UtilityMatrixFromCurve", 'INPUT', "UnsignedIntSocket", "Spline Index", 1, False, 0),
  47. ("UtilityMatricesFromCurve", 'INPUT', "UnsignedIntSocket", "Spline Index", 1, False, 0),
  48. ("UtilityPointFromCurve", 'INPUT', "UnsignedIntSocket", "Spline Index", 1, False, 0),
  49. ("LinkCopyScale", 'INPUT', "FloatFactorSocket", "Power", 5, False, 1.0),
  50. ]
  51. rename_jobs = []
  52. node_tree = kwargs['node_tree']
  53. try:
  54. if node.bl_idname in NODES_REMOVED:
  55. print(f"INFO: removing node {node.name} of type {node.bl_idname} because it has been deprecated.")
  56. node.inputs.remove(socket)
  57. return
  58. for i, socket in enumerate(node.inputs.values()):
  59. if (node.bl_idname, socket.identifier) in SOCKETS_REMOVED:
  60. print(f"INFO: removing socket {socket.identifier} of node {node.name} of type {node.bl_idname} because it has been deprecated.")
  61. node.inputs.remove(socket)
  62. for old_class, old_bl_idname, old_name, new_bl_idname, new_name, multi in SOCKETS_RENAMED:
  63. if (node.bl_idname == old_class and socket.bl_idname == old_bl_idname and socket.name == old_name):
  64. rename_jobs.append((socket, i, new_bl_idname, new_name, multi))
  65. for i, socket in enumerate(node.outputs.values()):
  66. if (node.bl_idname, socket.identifier) in SOCKETS_REMOVED:
  67. print(f"INFO: removing socket {socket.identifier} of node {node.name} of type {node.bl_idname} because it has been deprecated.")
  68. node.outputs.remove(socket)
  69. for old_class, old_bl_idname, old_name, new_bl_idname, new_name, multi in SOCKETS_RENAMED:
  70. if (node.bl_idname == old_class and socket.bl_idname == old_bl_idname and socket.name == old_name):
  71. rename_jobs.append((socket, i, new_bl_idname, new_name, multi))
  72. for bl_idname, in_out, socket_type, socket_name, index, use_multi_input, default_val in SOCKETS_ADDED:
  73. if node.bl_idname != bl_idname:
  74. continue
  75. if in_out == 'INPUT' and node.inputs.get(socket_name) is None:
  76. print(f"INFO: adding socket \"{socket_name}\" of type {socket_type} to node {node.name} of type {node.bl_idname}.")
  77. s = node.inputs.new(socket_type, socket_name, use_multi_input=use_multi_input)
  78. try:
  79. s.default_value = default_val
  80. except AttributeError:
  81. pass # the socket is read-only
  82. node.inputs.move(len(node.inputs)-1, index)
  83. socket_map = None
  84. if rename_jobs:
  85. socket_maps = get_socket_maps(node)
  86. for socket, socket_index, new_bl_idname, new_name, multi in rename_jobs:
  87. old_id = socket.identifier
  88. print (f"Renaming socket {socket.identifier} to {new_name} in node {node.name}")
  89. if socket.is_output:
  90. index = 1
  91. in_out = "OUTPUT"
  92. node.outputs.remove(socket)
  93. s = node.outputs.new(new_bl_idname, new_name, identifier=new_name, use_multi_input=multi)
  94. node.outputs.move(len(node.outputs)-1, socket_index)
  95. socket_map = socket_maps[1]
  96. else:
  97. index = 0
  98. in_out = "INPUT"
  99. node.inputs.remove(socket)
  100. s = node.inputs.new(new_bl_idname, new_name, identifier=new_name, use_multi_input=multi)
  101. node.inputs.move(len(node.inputs)-1, socket_index)
  102. socket_map = socket_maps[0]
  103. socket_map[new_name] = socket_map[old_id]
  104. if new_name != old_id: del socket_map[old_id] # sometimes rename just changes the socket type or multi
  105. do_relink(node, s, socket_map)
  106. except Exception as e:
  107. prRed(f"Error updating version in node: {node.id_data.name}::{node.name}; see error:")
  108. print(e)
  109. def version_upgrade_bone_0_12_0_from_older(*args, **kwargs):
  110. # we need to check if it has an array collection input and a color input
  111. # then we need to solve each task
  112. node = kwargs['node']
  113. live_updates = node.id_data.do_live_update
  114. node.id_data.do_live_update = False
  115. current_major_version = node.id_data.mantis_version[0]
  116. current_minor_version = node.id_data.mantis_version[1]
  117. if current_major_version > 0: # major version must be 0
  118. return
  119. if current_minor_version >= 12: # minor version must be 11 or less
  120. return
  121. # sub version doesn't matter since any subversion of 11 should trigger this task
  122. collection_input_is_array = False
  123. try:
  124. collection_input_is_array = node.inputs['Bone Collection'].is_multi_input
  125. except KeyError: # I suppose this happens in very, very old trees
  126. pass # but it is extremely unlikely
  127. toggle_updating = []
  128. was_updating = {}
  129. try:
  130. if not collection_input_is_array: # it must be made into an array!
  131. prPurple(f"Updating \"Bone Collection\" Socket in {node.name}")
  132. from .utilities.utilities import get_socket_maps
  133. socket_maps = get_socket_maps(node)
  134. socket_map = socket_maps[0]
  135. for i, socket in enumerate(node.inputs):
  136. if socket.name == 'Bone Collection': break
  137. # Always guard socket removal in case of connection to e.g. schema
  138. for socket_name, links in socket_map.items():
  139. if isinstance(links, list):
  140. for link in links:
  141. if hasattr(link, 'node') and hasattr(link.node, 'is_updating'):
  142. toggle_updating.append(link.node)
  143. was_updating[link.node.name] = link.node.is_updating
  144. link.node.is_updating = True
  145. node.inputs.remove(socket)
  146. s = node.inputs.new('BoneCollectionSocket', 'Bone Collection',
  147. identifier='Bone Collection', use_multi_input=True)
  148. node.inputs.move(len(node.inputs)-1, i)
  149. do_relink(node, s, socket_map, in_out='INPUT')
  150. if node.inputs.get('Color') is None:
  151. prPurple(f"Adding \"Color\" Socket to {node.name}")
  152. s = node.inputs.new('ColorSetSocket', 'Color',)
  153. node.inputs.move(len(node.inputs)-1, 22)
  154. except Exception as e:
  155. prRed(f"Error updating version in node: {node.id_data.name}::{node.name}; see error:")
  156. print(e)
  157. finally:
  158. # Now we have to clean up by removing the unneeded sockets and repositioning.
  159. for other_node in toggle_updating:
  160. other_node.is_updating = was_updating[other_node.name]
  161. node.id_data.do_live_update = live_updates
  162. def up_0_12_1_add_inherit_color(*args, **kwargs):
  163. # add an inherit color input.
  164. node = kwargs['node']
  165. current_major_version = node.id_data.mantis_version[0]
  166. current_minor_version = node.id_data.mantis_version[1]
  167. current_sub_version = node.id_data.mantis_version[2]
  168. if current_major_version > 0: return# major version must be 0
  169. if current_minor_version > 12: return# minor version must be 12 or less
  170. if current_minor_version == 12 and current_sub_version > 9: return # sub version must be 8 or less
  171. # I am having it do 8 or less because there was a bug in this function prior to 9
  172. # sub version doesn't matter since any subversion of 11 should trigger this task
  173. prPurple(f"Adding \"Inherit Color\" socket to {node.name}")
  174. try:
  175. inh_color = node.inputs.get('Inherit Color')
  176. if inh_color and inh_color.bl_idname != 'BooleanSocket':
  177. node.inputs.remove(inh_color)
  178. inh_color = None
  179. if inh_color is None:
  180. s = node.inputs.new('BooleanSocket', 'Inherit Color',)
  181. node.inputs.move(len(node.inputs)-1, 23)
  182. s.default_value=True
  183. except Exception as e:
  184. prRed(f"Error updating version in node: {node.id_data.name}::{node.name}; see error:")
  185. print(e)
  186. def up_0_12_13_add_widget_scale(*args, **kwargs):
  187. node = kwargs['node']
  188. current_major_version = node.id_data.mantis_version[0]
  189. current_minor_version = node.id_data.mantis_version[1]
  190. current_sub_version = node.id_data.mantis_version[2]
  191. if current_major_version > 0: return# major version must be 0
  192. if current_minor_version > 12: return# minor version must be 12 or less
  193. if current_minor_version == 12 and current_sub_version > 12: return
  194. # sub version must be 12 or less
  195. prPurple(f"Adding \"Scale\" socket to {node.name}")
  196. try:
  197. scale = node.inputs.get('Scale')
  198. if scale is None:
  199. s = node.inputs.new('VectorScaleSocket', 'Scale',)
  200. s.default_value=[1.0,1.0,1.0]
  201. node.inputs.move(len(node.inputs)-1, 1)
  202. except Exception as e:
  203. prRed(f"Error updating version in node: {node.id_data.name}::{node.name}; see error:")
  204. print(e)
  205. def up_0_12_25_replace_floor_offset_type(*args, **kwargs):
  206. node = kwargs['node']
  207. current_major_version = node.id_data.mantis_version[0]
  208. current_minor_version = node.id_data.mantis_version[1]
  209. current_sub_version = node.id_data.mantis_version[2]
  210. if current_major_version > 0: return# major version must be 0
  211. if current_minor_version > 12: return# minor version must be 12 or less
  212. if current_minor_version == 12 and current_sub_version > 24: return
  213. socket_maps = get_socket_maps(node)
  214. prPurple(f"Fixing \"Offset\" socket in {node.name}")
  215. try:
  216. offset = node.inputs["Offset"]
  217. node.inputs.remove(offset)
  218. s = node.inputs.new('FloatSocket', 'Offset',)
  219. node.inputs.move(len(node.inputs)-1, 2)
  220. do_relink(node, s, socket_maps[0])
  221. except Exception as e:
  222. prRed(f"Error updating version in node: {node.id_data.name}::{node.name}; see error:")
  223. print(e)
  224. def get_absolute_location(node): # using this for version compatibility
  225. location = node.location.copy() # FUTURE: deprecate old blenders and use absolute_location
  226. while(node.parent):
  227. node = node.parent
  228. location+= node.location
  229. return location
  230. def up_0_13_0_new_custom_prop_node(*args, **kwargs):
  231. tree, node = kwargs['node_tree'], kwargs['node']
  232. current_major_version = tree.mantis_version[0]
  233. if current_major_version > 0: return# major version must be 0
  234. current_minor_version = tree.mantis_version[1]
  235. if current_minor_version >= 13: return# minor version must be 12 or less
  236. remove_me, prop_nodes = [], []
  237. from .xForm_nodes_ui import xFormBoneNode
  238. socket_map_in, socket_map_out = get_socket_maps(node)
  239. if isinstance(node, xFormBoneNode):
  240. if node.inputs.get('Custom Properties'):
  241. return # already done here
  242. for custom_input in reversed(list(node.inputs)):
  243. if 'Parameter' not in custom_input.bl_idname:
  244. continue
  245. custom_prop_node = tree.nodes.new('UtilityCustomProperty')
  246. prop_type = None
  247. if custom_input.bl_idname == 'ParameterBoolSocket':
  248. prop_type = 'BOOL'
  249. custom_prop_node.inputs['Default (Bool)'].default_value = getattr(custom_input, "default_value")
  250. elif custom_input.bl_idname == 'ParameterIntSocket':
  251. prop_type = 'INT'
  252. custom_prop_node.inputs['Default (Int)'].default_value = int( getattr(custom_input, "default_value") )
  253. custom_prop_node.inputs['Min (Int)'].default_value = int( getattr(custom_input, "min") )
  254. custom_prop_node.inputs['Max (Int)'].default_value = int( getattr(custom_input, "max") )
  255. custom_prop_node.inputs['Soft Min (Int)'].default_value = int( getattr(custom_input, "soft_min") )
  256. custom_prop_node.inputs['Soft Max (Int)'].default_value = int( getattr(custom_input, "soft_max") )
  257. elif custom_input.bl_idname == 'ParameterFloatSocket':
  258. prop_type = 'FLOAT'
  259. custom_prop_node.inputs['Default (Float)'].default_value = getattr(custom_input, "default_value")
  260. custom_prop_node.inputs['Min (Float)'].default_value = getattr(custom_input, "min")
  261. custom_prop_node.inputs['Max (Float)'].default_value = getattr(custom_input, "max")
  262. custom_prop_node.inputs['Soft Min (Float)'].default_value = getattr(custom_input, "soft_min")
  263. custom_prop_node.inputs['Soft Max (Float)'].default_value = getattr(custom_input, "soft_max")
  264. elif custom_input.bl_idname == 'ParameterVectorSocket':
  265. prop_type = 'VECTOR'
  266. custom_prop_node.inputs['Default (Vector)'].default_value = getattr(custom_input, "default_value")
  267. try:
  268. custom_prop_node.inputs['Min (Float)'].default_value = getattr(custom_input, "min")
  269. custom_prop_node.inputs['Max (Float)'].default_value = getattr(custom_input, "max")
  270. custom_prop_node.inputs['Soft Min (Float)'].default_value = getattr(custom_input, "soft_min")
  271. custom_prop_node.inputs['Soft Max (Float)'].default_value = getattr(custom_input, "soft_max")
  272. except AttributeError: # I don't know if I just never implemented these or if it is version specific
  273. pass # anyways this isn't critical and should not trigger even a warning
  274. elif custom_input.bl_idname == 'ParameterStringSocket':
  275. prop_type = 'STRING'
  276. custom_prop_node.inputs['Default (String)'].default_value = getattr(custom_input, "default_value")
  277. custom_prop_node.inputs['Name'].default_value = custom_input.name
  278. custom_prop_node.inputs['Type'].default_value = prop_type
  279. prop_nodes.append(custom_prop_node)
  280. remove_me.append(custom_input)
  281. # now we need to relink things, because the custom property socket could have had an
  282. # input supplying the default value
  283. relink_value = socket_map_in.get(custom_input.identifier, None)
  284. if isinstance(relink_value, list): # this indicates it is a list of links
  285. # CRITICALLY, we need to force display update before doing this.
  286. custom_prop_node.display_update({}, None) # parsed_tree and context, not needed
  287. input_socket = None
  288. match prop_type:
  289. case 'BOOL':
  290. input_socket = "Default (Bool)"
  291. case 'INT':
  292. input_socket = "Default (Int)"
  293. case 'FLOAT':
  294. input_socket = "Default (Float)"
  295. case 'VECTOR':
  296. input_socket = "Default (Vector)"
  297. case 'STRING':
  298. input_socket = "Default (String)"
  299. case _: # Should never never happen
  300. raise RuntimeError("Unexpected Code Path Reached, this is a bug.")
  301. do_relink(custom_prop_node, custom_prop_node.inputs[input_socket],
  302. {input_socket:relink_value})
  303. while remove_me:
  304. custom_input = remove_me.pop()
  305. node.inputs.remove(custom_input)
  306. new_input = node.inputs.new("CustomPropSocket", "Custom Properties", use_multi_input=True)
  307. from mathutils import Vector
  308. for i, prop_node in enumerate(prop_nodes):
  309. tree.links.new(input=prop_node.outputs[0], output=new_input)
  310. prop_node.location = get_absolute_location(node)
  311. prop_node.location = prop_node.location - Vector((180, -260*i))
  312. prop_node.select = False # it is annoying to select them all by default
  313. else: # just need to add the socket.
  314. if node.inputs.get('Custom Properties'):
  315. return # already done here
  316. new_input = node.inputs.new("CustomPropSocket", "Custom Properties", use_multi_input=True)
  317. def schema_enable_custom_interface_types(*args, **kwargs):
  318. tree = kwargs['tree']
  319. current_major_version = tree.mantis_version[0]
  320. current_minor_version = tree.mantis_version[1]
  321. current_sub_version = tree.mantis_version[2]
  322. if current_major_version > 0: return# major version must be 0
  323. if current_minor_version >= 13: return# minor version must be 12 or less
  324. # we need to set the new interface values on the schema interface stuff
  325. prGreen(f"Updating Schema tree {tree.name} to support new, improved UI!")
  326. tree.do_live_update = False
  327. for n in tree.nodes:
  328. if hasattr(n, "is_updating"):
  329. n.is_updating = True
  330. try:
  331. for item in tree.interface.items_tree:
  332. if item.item_type == 'PANEL':
  333. continue
  334. parent_name = 'Constant'
  335. if item.parent:
  336. parent_name=item.parent.name
  337. if hasattr(item, "is_array"):
  338. # if is_array exists we're in the custom interface class
  339. # so we'll assume the other attributes exist
  340. if parent_name == 'Array':
  341. item.is_array = True
  342. if parent_name == 'Connection':
  343. item.is_array = False
  344. item.is_connection=True
  345. item.connected_to=item.name
  346. # since heretofore it has been a requirement that the names match
  347. except Exception as e:
  348. prRed(f"Error updating version in tree: {tree.name}; see error:")
  349. print(e)
  350. finally:
  351. for n in tree.nodes:
  352. if hasattr(n, "is_updating"):
  353. n.is_updating = False
  354. tree.do_live_update = True
  355. def update_fcurve_and_armature_node_to_multi_socket(*args, **kwargs):
  356. from .base_definitions import SchemaUINode
  357. node = kwargs['node']
  358. live_updates = node.id_data.do_live_update
  359. node.id_data.do_live_update = False
  360. # First we have to get the socket maps and re-init the sockets
  361. convert_keys = {'UtilityFCurve' : [ 'Keyframe', ],
  362. 'LinkArmature' : [ 'Target', 'Weight', ], }
  363. my_convert_keys = convert_keys[node.bl_idname]
  364. sockets_in, _sockets_out = get_socket_maps(node,)
  365. # NOTE IMPORTANT BUG INFO
  366. # I was using node.inputs.clear() here before unguarded...
  367. # this caused connected Schema nodes to update and mutate the socket map
  368. # which, in turn, connected the new socket to the wildcard and extended the schema
  369. # resulting in trees that fail to run. This was particularly bad because it was
  370. # so hard to debug (due to spooky action at a distance mutation)
  371. # So we have to mark the connected nodes as "updating" before we modify the tree.
  372. # TODO: should I just mark all nodes as updating during versioning?
  373. toggle_updating = []
  374. was_updating = {}
  375. for socket_name, links in sockets_in.items():
  376. if isinstance(links, list):
  377. for link in links:
  378. if hasattr(link, 'node') and hasattr(link.node, 'is_updating'):
  379. toggle_updating.append(link.node)
  380. was_updating[link.node.name] = link.node.is_updating
  381. link.node.is_updating = True
  382. socket_templates_original = node.socket_templates
  383. node.inputs.clear() # this is VERY DANGEROUS without the above
  384. add_me_sockets = [st for st in node.socket_templates if st.is_input == True]
  385. node.init_sockets(add_me_sockets)
  386. node.socket_templates = socket_templates_original
  387. try:
  388. new_sockets_in = {}
  389. for convert_key in my_convert_keys:
  390. for socket_name, links in sockets_in.items():
  391. if links is None: continue
  392. if convert_key+'.' in socket_name:
  393. if new_sockets_in.get(convert_key+'s'):
  394. # has to be in this order to come back alright.
  395. # assuming, that is, that the keys are sorted. they should be.
  396. new_sockets_in[convert_key+'s'] = sockets_in[socket_name] + new_sockets_in[convert_key+'s']
  397. else:
  398. new_sockets_in[convert_key+'s'] = sockets_in[socket_name]
  399. if new_sockets_in:
  400. do_relink(node, node.inputs[convert_key+'s'], new_sockets_in, in_out="INPUT",)
  401. for socket_name, links in sockets_in.items():
  402. proceed = True
  403. for convert_key in my_convert_keys:
  404. if convert_key in socket_name:
  405. proceed = False
  406. if proceed:
  407. do_relink(node, node.inputs[socket_name], sockets_in, in_out='INPUT')
  408. finally:
  409. # Now we have to clean up by removing the unneeded sockets and repositioning.
  410. for other_node in toggle_updating:
  411. other_node.is_updating = was_updating[other_node.name]
  412. node.id_data.do_live_update = live_updates
  413. # These BBone Scale-In, Scale-Out properties had the wrong defaults
  414. # now that they are implemented properly,
  415. # since they were not implemented before, we'll do all of them at once.
  416. # Normally it is wrong to set things directly like this, but they didn't
  417. # do anything before. Oh well.
  418. def fix_bbone_default_scale_in_and_out(*args, **kwargs):
  419. tree = kwargs['tree']
  420. current_major_version = tree.mantis_version[0]
  421. current_minor_version = tree.mantis_version[1]
  422. current_sub_version = tree.mantis_version[2]
  423. if current_major_version > 0: return# major version must be 0
  424. if current_minor_version >= 13: return# minor version must be 12 or less
  425. if current_minor_version == 13 and current_sub_version >= 5: return# sub version must be 4 or less
  426. prPurple(f"Fixing BBone Settings for {tree.name}")
  427. live_updates = tree.do_live_update
  428. tree.do_live_update = False
  429. bones = []
  430. for node in tree.nodes:
  431. if hasattr(node, 'is_updating'):
  432. node.is_updating = True
  433. if node.bl_idname == 'xFormBoneNode':
  434. bones.append(node)
  435. try:
  436. for bone_node in bones:
  437. bone_node.inputs['BBone Scale-In'].default_value = (1,1,1)
  438. bone_node.inputs['BBone Scale-Out'].default_value = (1,1,1)
  439. finally:
  440. for node in tree.nodes:
  441. if hasattr(node, 'is_updating'):
  442. node.is_updating = False
  443. tree.do_live_update = live_updates
  444. # New display features, Display Type, new Custom Object gizmo/pivot stuff
  445. def add_new_display_features_v0_13_5(*args, **kwargs):
  446. tree = kwargs['tree']
  447. current_major_version = tree.mantis_version[0]
  448. current_minor_version = tree.mantis_version[1]
  449. current_sub_version = tree.mantis_version[2]
  450. if current_major_version > 0: return# major version must be 0
  451. if current_minor_version >= 13: return# minor version must be 12 or less
  452. if current_minor_version == 13 and current_sub_version >= 5: return# sub version must be 4 or less
  453. prPurple(f"Adding new Display Features to {tree.name}")
  454. live_updates = tree.do_live_update
  455. tree.do_live_update = False
  456. live_updates = tree.do_live_update
  457. bones = []
  458. armatures = []
  459. for node in tree.nodes:
  460. if hasattr(node, 'is_updating'):
  461. node.is_updating = True
  462. if node.bl_idname == 'xFormBoneNode':
  463. bones.append(node)
  464. if node.bl_idname == 'xFormArmatureNode':
  465. armatures.append(node)
  466. try:
  467. for bone_node in bones:
  468. # we'll just try this...
  469. from .xForm_socket_templates import (BoneDisplayType,
  470. CustomObjectWireWidth,
  471. UseTransformAtCustomShape,
  472. UseTransformAroundCustomShape,
  473. xFormBoneSockets)
  474. input_templates = ( BoneDisplayType,
  475. CustomObjectWireWidth,
  476. UseTransformAroundCustomShape,
  477. UseTransformAtCustomShape, )
  478. bone_node.init_sockets(input_templates)
  479. bone_node.socket_templates = xFormBoneSockets
  480. for i, inp in enumerate(bone_node.inputs):
  481. if inp.name == 'Custom Object xForm Override':
  482. # As confusing as this is, it is the least terrible way to do this
  483. # We add the sockets to the end, then move them from the end to the right place
  484. bone_node.inputs.move(len(bone_node.inputs)-1, i+1)
  485. bone_node.inputs.move(len(bone_node.inputs)-1, i+2)
  486. bone_node.inputs.move(len(bone_node.inputs)-1, i+3)
  487. bone_node.inputs.move(len(bone_node.inputs)-1, i+4)
  488. break
  489. for armature_node in armatures:
  490. # we'll just try this...
  491. from .xForm_socket_templates import (ArmatureDisplayType,
  492. xFormArmatureSockets)
  493. input_templates = ( ArmatureDisplayType, )
  494. armature_node.init_sockets(input_templates)
  495. armature_node.socket_templates = xFormArmatureSockets
  496. for i, inp in enumerate(armature_node.inputs):
  497. if inp.name == 'Relationship':
  498. armature_node.inputs.move(len(armature_node.inputs)-1, i+1)
  499. break
  500. finally:
  501. for node in tree.nodes:
  502. if hasattr(node, 'is_updating'):
  503. node.is_updating = False
  504. tree.do_live_update = live_updates
  505. def up_0_13_5_modes_for_matrix_from_curve_and_compose_matrix(*args, **kwargs):
  506. node = kwargs['node']
  507. if 'Mode' in node.inputs:
  508. return # done already
  509. tree = node.id_data
  510. current_major_version = tree.mantis_version[0]
  511. current_minor_version = tree.mantis_version[1]
  512. current_sub_version = tree.mantis_version[2]
  513. if current_major_version > 0: return# major version must be 0
  514. if current_minor_version >= 13: return# minor version must be 12 or less
  515. if current_minor_version == 13 and current_sub_version >= 5: return# sub version must be 4 or less
  516. live_updates = tree.do_live_update
  517. tree.do_live_update = False
  518. for other_node in tree.nodes:
  519. if hasattr(other_node, 'is_updating'):
  520. other_node.is_updating = True
  521. try:
  522. socket_templates = node.socket_templates
  523. if node.bl_idname == 'UtilityMatrixFromCurve':
  524. from .misc_nodes_socket_templates import (MatrixFromCurveMode,
  525. MatrixFromCurveFactor,
  526. MatrixFromCurveTailFactor, )
  527. input_templates = ( MatrixFromCurveMode, MatrixFromCurveFactor,
  528. MatrixFromCurveTailFactor, )
  529. node.init_sockets(input_templates)
  530. node.inputs.move(len(node.inputs)-3, 0) # move Mode to first place
  531. elif node.bl_idname == 'UtilityMatrixCompose':
  532. from .misc_nodes_socket_templates import (ComposeMatrixBoneLength,
  533. MatrixComposeMode,
  534. ComposeMatrixRotation,)
  535. input_templates = ( ComposeMatrixBoneLength, MatrixComposeMode,
  536. ComposeMatrixRotation,)
  537. node.init_sockets(input_templates)
  538. node.inputs.move(len(node.inputs)-1, 0) # These go in the top, so make em in order
  539. node.inputs.move(len(node.inputs)-1, 0) # and move 'em one at a time in reverse order
  540. node.socket_templates = socket_templates
  541. finally:
  542. for other_node in tree.nodes:
  543. if hasattr(other_node, 'is_updating'):
  544. other_node.is_updating = False
  545. tree.do_live_update = live_updates
  546. # versioning tasks that involve Blender versions rather than Mantis versions:
  547. error_description_4_5_0_LTS = 'There is a bug in Blender 4.5.0 LTS, that is why these sockets are blue.'\
  548. ' This will be fixed in future Blender versions.'
  549. def cleanup_4_5_0_LTS_interface_workaround(*args, **kwargs):
  550. # this is a function for cleaning up the workaround up above
  551. tree = kwargs['tree']
  552. if bpy_version == (4,5,0): return
  553. if not hasattr(tree, "interface_helper"): return
  554. import json
  555. try:
  556. interface_helper = json.loads(tree.interface_helper)
  557. except:
  558. return # this should mean it was never a problem to begin with.
  559. prPurple(f"Restoring Tree Interface for {tree.name}.")
  560. for interface_item in tree.interface.items_tree:
  561. if interface_item.item_type == 'PANEL': continue
  562. # now we need to restore the socket types, which are in the interface helper
  563. # keep the interface stuff around, I'll use it for marking arrays in the future
  564. int_info = interface_helper[interface_item.identifier]
  565. socket_type = int_info['bl_socket_idname']
  566. interface_item.socket_type = socket_type
  567. if interface_item.description == error_description_4_5_0_LTS:
  568. interface_item.description = ''
  569. versioning_tasks = [
  570. # node bl_idname task required keyword arguments
  571. (['ALL'], version_upgrade_very_old, ['node_tree', 'node'],),
  572. (['xFormBoneNode'], version_upgrade_bone_0_12_0_from_older, ['node'],),
  573. (['xFormBoneNode'], up_0_12_1_add_inherit_color, ['node'],),
  574. (['MantisTree', 'SchemaTree'], cleanup_4_5_0_LTS_interface_workaround, ['tree']),
  575. (['InputWidget'], up_0_12_13_add_widget_scale, ['node']),
  576. (['LinkFloor'], up_0_12_25_replace_floor_offset_type, ['node']),
  577. (['XFORM'], up_0_13_0_new_custom_prop_node, ['node', 'node_tree']),
  578. (['SchemaTree'], schema_enable_custom_interface_types, ['tree']),
  579. (['UtilityFCurve', 'LinkArmature'],
  580. update_fcurve_and_armature_node_to_multi_socket, ['node']),
  581. (['MantisTree', 'SchemaTree'], fix_bbone_default_scale_in_and_out, ['tree']),
  582. (['MantisTree', 'SchemaTree'], add_new_display_features_v0_13_5, ['tree']),
  583. (['UtilityMatrixFromCurve', 'UtilityMatrixCompose'],
  584. up_0_13_5_modes_for_matrix_from_curve_and_compose_matrix,
  585. ['node',], ),
  586. ]
  587. # WORKAROUNDS for bugs should go here:
  588. # 4.5.0 LTS valid socket types bug:
  589. def workaround_4_5_0_interface_update(tree, name, in_out, sock_type, parent_name, do_parent=False):
  590. # TODO: dedupe this code from i_o.py
  591. prRed("There is a bug in Blender 4.5.0 regarding node-group interface sockets. Working around it.")
  592. sock = tree.interface.new_socket(name=name, in_out=in_out, socket_type="NodeSocketGeometry")
  593. import json
  594. interface_helper = {} # initialize it if it is empty
  595. if tree.interface_helper: # may be empty, check here
  596. interface_helper = json.loads(tree.interface_helper)
  597. error_message = error_description_4_5_0_LTS
  598. interface_helper[sock.identifier] = {
  599. 'name' : sock.name,
  600. 'identifier' : sock.identifier,
  601. 'in_out' : sock.in_out,
  602. 'socket_type' : sock_type,
  603. 'bl_socket_idname' : sock_type,
  604. 'mantis_socket_category' : parent_name,
  605. 'description' : error_message,
  606. }
  607. sock.description = error_message # this tells the user why the socket looks weird.
  608. tree.interface_helper = json.dumps(interface_helper)
  609. if do_parent and (parent := tree.interface.items_tree.get(parent_name)):
  610. tree.interface.move_to_parent(
  611. sock,
  612. parent,
  613. 0, # what to do here?
  614. )
  615. return sock
  616. def socket_add_workaround_for_4_5_0_LTS(item, socket_collection, multi):
  617. import json
  618. tree = item.id_data
  619. interface_helper = json.loads(tree.interface_helper)
  620. socket_info = interface_helper.get(item.identifier)
  621. if not socket_info: raise RuntimeError(f"There has been an error adding the socket {item.name}")
  622. s = socket_collection.new(
  623. type=socket_info['bl_socket_idname'],
  624. name=item.name, # in case the user has changed it
  625. identifier=item.identifier,
  626. use_multi_input=multi, )
  627. return s